Author SHA1 Message Date
gloamxun 4f4a4567ea Emit native PDF page resources and named transparency states 2026-11-21 00:53:46 +08:00
gloamxun 2bced813a2 Record original Elsevier double-column first output 2026-11-20 23:48:25 +08:00
gloamxun 6d54af5350 Expand deferred TeX input without recursive dispatch frames 2026-11-20 23:40:14 +08:00
gloamxun ebbc9e2c17 Implement native automatic font expansion for paragraphs 2026-11-20 23:29:37 +08:00
gloamxun 1dd745afcb Prioritize feature implementation before consolidated acceptance 2026-11-20 23:08:30 +08:00
gloamxun 4777d66fc8 Apply native font protrusion during line breaking and packing 2026-11-20 17:18:25 +08:00
gloamxun 361e8d070f Reuse decoded Type 1 fonts across native revisions 2026-11-20 16:55:48 +08:00
gloamxun 6e573dc1ce Run cancellable pdfTeX matching in native frontends 2026-11-20 16:43:48 +08:00
gloamxun 091458d329 Verify schema 28 format round trips and rejection gates 2026-11-20 16:21:19 +08:00
gloamxun 4eeb5686b8 Implement native text accents for unmodified LaTeX jobs 2026-11-20 16:15:30 +08:00
gloamxun ca60c66a17 Reuse the active edit line within the checkpoint budget 2026-11-20 16:08:36 +08:00
gloamxun 600160f624 Record edit-line latency and text accent evidence 2026-11-20 15:48:44 +08:00
gloamxun e4a265ca6c Reuse valid checkpoints across auxiliary file changes 2026-11-20 15:17:28 +08:00
gloamxun 3a3913a385 Verify earlier checkpoints on original CVPR edits 2026-11-20 14:29:50 +08:00
gloamxun 0a21eb27a7 Reuse session-verified source versions in native source maps 2026-11-20 14:18:42 +08:00
gloamxun 225736ce80 Measure the A4 edit-to-paint critical path 2026-11-20 14:04:20 +08:00
gloamxun 4575150f92 Record native source-map reuse and CVPR invalidation evidence 2026-11-20 13:23:44 +08:00
gloamxun 592d1ef2a3 Reuse byte-verified source versions after checkpoint resume 2026-11-20 13:02:50 +08:00
gloamxun 0ff8597ab4 Verify live edits on official IEEE and CVPR projects 2026-11-20 12:39:35 +08:00
gloamxun ae59cc1cc1 Record live source-version reuse across complete paired edits 2026-11-20 12:19:14 +08:00
gloamxun 1038fcf709 Record sharded binding timings and source hash call chains 2026-11-20 09:37:34 +08:00
gloamxun ae6ddb47d0 Record command binding checkpoint and live preview comparisons 2026-11-20 09:20:29 +08:00
gloamxun a1ed9498bc Verify file-revision checkpoints across browser and publisher corpus 2026-11-20 08:59:13 +08:00
gloamxun 1ba46a9f61 Record live file-edit and original A3 verification 2026-11-20 08:31:34 +08:00
gloamxun 287d4a7cf0 Validate live checkpoint reuse across atomic project file changes 2026-11-20 08:26:44 +08:00
gloamxun e77b15d8bd Record paired upstream and browser preview timings 2026-11-19 22:46:59 +08:00
gloamxun da277611e8 Record complete workspace validation for live file identity 2026-11-19 22:43:15 +08:00
gloamxun 45455c4cc0 Measure upstream preamble reuse on publisher templates 2026-11-19 22:41:07 +08:00
gloamxun 6438c3475d Record upstream reuse and editor cancellation experiments 2026-11-19 22:35:20 +08:00
gloamxun 50bd410574 Document live TeX priorities and verified publisher results 2026-11-19 22:20:28 +08:00
63 changed files with 4445 additions and 330 deletions

No files matched your search

Generated
+1
View File
@@ -1431,6 +1431,7 @@ version = "0.1.0"
dependencies = [
"flate2",
"hyphenate",
"libc",
"lopdf",
"rusttype",
"serde",
+21 -18
View File
@@ -1,18 +1,22 @@
# texrra engine
Rust-native, Typst-inspired incremental LaTeX engine with a live preview
server. Typesetting is implemented in Rust; the engine does not invoke XeLaTeX,
LuaLaTeX, or pdfLaTeX. The web frontend is a separate repository,
[`texrra-web`](https://git.iloveuulove.me/gloamxun/texrra-web), served by this
engine as static files.
Texrra is building a TeX engine for live editing of existing LaTeX projects.
It tracks inputs and compilation state, reuses eligible work after edits,
and publishes updated pages with source locations. The delivery targets are
a library, a CLI, and editor integration. The current Route-D implementation
is the development baseline. Upstream TeX components are candidates for reuse
where their state, file effects, and cancellation can be verified.
The [product goal](docs/NATIVE_PRODUCT_GOAL.md) defines compatibility and live
preview acceptance. The [publisher matrix](docs/PUBLISHER_TEMPLATE_MATRIX.md)
covers original journals, two-column journals, conferences, and arXiv.
## Native execution bootstrap
Route-D's native token/state kernel has a strict developer entry. Its target is
portable, complete LaTeX execution and real-time compilation; the web interface
is a test client. The full [P2-M1 stage](docs/NATIVE_FORMAT_ARTICLE_STAGE.md)
is active and incomplete; [current progress](docs/P2_M1_PROGRESS.md) records the
accepted components and remaining work.
The current Route-D entry is available through the developer CLI and the native
editor example. Its implementation and remaining work are tracked in the
[stage progress](docs/P2_M1_PROGRESS.md). The separate frontend repository
is [texrra-web](https://git.iloveuulove.me/gloamxun/texrra-web).
Native fonts come from an explicit resource World. For the checked-in examples,
configure the actual TFM/PFB directories and an installed font-map directory:
@@ -40,8 +44,8 @@ canvas does not certify native pagination. There is no automatic fallback
between these targets. See [native pages and remaining device work](docs/NATIVE_PAGES.md).
INITEX starts with actual nullfont and zero layout dimensions. Non-INITEX
bootstrap also loads its initial cmr10 through World. Missing resources fail;
the kernel does not silently use bundled fonts or run an external TeX process.
bootstrap loads its initial cmr10 through World. The current native job reports
missing resources directly.
Use `--texmf-root`, resource search environment variables and `--input-policy`
for distribution/project resources; `--resource-manifest` records actual reads,
versions and negative lookups, including failed jobs. The CLI defaults to TeX
@@ -54,13 +58,12 @@ or source preprocessing. It now carries actual sized FontId resources through
text, math, geometry, SVG and PDF. Live fontdimen and em/ex affect their real
consumers; output uses actual map/encoding/PFB resources. See
[native font execution and boundaries](docs/NATIVE_FONT_EXECUTION.md).
HTTP/project routes still use the older implementation and have not migrated
to this kernel.
The native editor example exercises the shared compile session and page
updates. The production HTTP routes still use the older implementation.
Format boot, active compatibility gaps, and whole-project results are tracked
in the [stage progress](docs/P2_M1_PROGRESS.md).
The e-TeX profile remains partial. Unmodified latex.ltx currently stops at
657:3, tracinggroups, using the actual native job target; the complete
pdflatex.ini entry now enters latex.ltx and stops at the same boundary. Neither
is a successful format boot. [Streaming TFM keep/pass/boundary execution](docs/NATIVE_FONT_PROGRAMS.md) is
[Streaming TFM keep/pass/boundary execution](docs/NATIVE_FONT_PROGRAMS.md) is
connected to actual lists. [Owned discretionary branches and actual ligature
hyphenation/reconstitution](docs/NATIVE_DISCRETIONARIES.md) now feed line breaking,
packing, diagnostics and output. [Two-pass mathematical noad ligature/kern and
+3
View File
@@ -13,3 +13,6 @@ serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = "1.0"
sha2 = "=0.10.9"
hyphenate = { path = "../../vendor/hyphenate" }
[target.'cfg(all(target_os = "linux", target_env = "gnu"))'.dependencies]
libc = "0.2"
@@ -332,6 +332,8 @@ impl NativeBox {
}
TextNode::Indent(w)
| TextNode::MathBoundary { width: w, .. }
| TextNode::AccentKern(w)
| TextNode::MarginKern { width: w, .. }
| TextNode::Kern { width: w, .. } => HorizontalItem::Box(HorizontalBox {
width: *w as i64,
..HorizontalBox::default()
@@ -612,6 +614,8 @@ pub(super) fn hpack(
}
TextNode::Indent(w)
| TextNode::MathBoundary { width: w, .. }
| TextNode::AccentKern(w)
| TextNode::MarginKern { width: w, .. }
| TextNode::Kern { width: w, .. } => width += *w as i64,
TextNode::Glue(g) | TextNode::NamedGlue(g, _) => {
width += g.width as i64;
@@ -25,9 +25,15 @@ 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 = "pdf_resource_entries_empty")]
pub(super) pdf_resource_entries: Arc<[u8]>,
#[serde(default, skip_serializing_if = "crate::pdf_device::links::PageLinks::is_empty")]
pub(super) pdf_links: crate::pdf_device::links::PageLinks,
}
fn pdf_resource_entries_empty(entries: &Arc<[u8]>) -> bool {
entries.is_empty()
}
impl NativeShipout {
pub fn display_list(&self) -> Result<crate::render::DisplayList, String> {
let mut page = crate::render::DisplayList {
@@ -37,6 +43,10 @@ impl NativeShipout {
units: crate::render::DisplayUnits::TeX,
pdf: self.device.pdf.clone(),
pdf_links: self.pdf_links.clone(),
pdf_resources: crate::pdf_device::page_resources::PageResources {
entries: self.pdf_resource_entries.clone(),
..Default::default()
},
..Default::default()
};
use crate::{math_engine_tex::MathItem, render::DisplayItem};
@@ -7,6 +7,8 @@ pub enum DiagnosticNode {
Character {
font: FontId,
slot: u8,
#[serde(default, skip_serializing_if = "crate::native_font::unexpanded")]
expansion: i32,
ligature: Option<String>,
},
Box(DiagnosticBox),
@@ -50,6 +52,8 @@ pub enum DiagnosticNode {
},
Output(OutputNode),
Unsupported(String),
AccentKern(i32),
MarginKern { width: i32, right: bool },
}
/// A semantic view, without recursively copying the box's painted contents.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -149,6 +153,7 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
TextNode::Language(l) => DiagnosticNode::Language(*l),
TextNode::Glyph {
font,
glyph,
slot,
original,
ligature,
@@ -158,6 +163,13 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
} => DiagnosticNode::Character {
font: *font,
slot: *slot,
expansion: glyph.math_geometry.as_ref()
.and_then(|geometry| geometry.items.first())
.and_then(|paint| match &paint.item {
crate::math_engine_tex::MathItem::NativeGlyph { font, .. } => Some(font.expansion),
_ => None,
})
.unwrap_or(0),
ligature: ligature.then(|| {
format!(
"{}{original}{}",
@@ -180,6 +192,7 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
DiagnosticNode::Character {
font: font.id,
slot: *slot,
expansion: font.expansion,
ligature: None,
}
} else {
@@ -209,6 +222,11 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
name: None,
},
TextNode::Leaders(leader) => leader_node(leader),
TextNode::AccentKern(width) => DiagnosticNode::AccentKern(*width),
TextNode::MarginKern { width, right, .. } => DiagnosticNode::MarginKern {
width: *width,
right: *right,
},
TextNode::Kern { width, explicit } => DiagnosticNode::Kern {
width: *width,
explicit: *explicit,
@@ -331,9 +349,12 @@ impl Printer<'_> {
self.flex(g.shrink.amount, g.shrink.order);
}
}
fn character(&mut self, font: FontId, slot: u8) -> Result<(), String> {
fn character(&mut self, font: FontId, slot: u8, expansion: i32) -> Result<(), String> {
let name = self.state.fonts.font(font)?.identifier_text();
self.command(&name);
if expansion != 0 {
self.literal(&format!(" ({expansion:+})"));
}
self.literal(" ");
self.ascii(slot);
Ok(())
@@ -436,9 +457,10 @@ impl Printer<'_> {
DiagnosticNode::Character {
font,
slot,
expansion,
ligature,
} => {
self.character(*font, *slot)?;
self.character(*font, *slot, *expansion)?;
if let Some(s) = ligature {
self.literal(" (ligature ");
for c in s.chars() {
@@ -471,6 +493,17 @@ impl Printer<'_> {
&format!("{prefix}."),
)?;
}
DiagnosticNode::MarginKern { width, right } => {
self.command("kern");
self.number(i64::from(*width));
self.literal(if *right { " (right margin)" } else { " (left margin)" });
}
DiagnosticNode::AccentKern(width) => {
self.command("kern");
self.literal(" ");
self.number(i64::from(*width));
self.literal(" (for accent)");
}
DiagnosticNode::Kern { width, explicit } => {
self.command("kern");
if *explicit {
@@ -563,6 +596,10 @@ impl Printer<'_> {
self.literal(&format!(" {{{}}}", program.literal()));
}
}
OutputOperation::PdfObject(number) => {
self.command("pdfrefobj");
self.literal(&format!(" {number}"));
}
OutputOperation::PdfImage { image, .. } => {
self.command("pdfrefximage");
self.literal(&format!(" {}", image.id));
+121 -20
View File
@@ -25,7 +25,10 @@ mod pdf_catalog;
mod pdf_color;
mod pdf_graphics;
mod pdf_image;
mod pdf_objects;
mod pdf_links;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub(super) mod pdf_match;
mod quantities;
mod restores;
mod scanning;
@@ -215,6 +218,8 @@ pub struct Executor {
io: IoState,
pdf_colors: crate::pdf_device::PdfColorStacks,
pdf_link_stack: Vec<pdf_links::ActiveLink>,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: Option<Arc<pdf_match::PdfMatch>>,
pdf_catalog_tokens: Vec<Token>,
pdf_outlines: Vec<crate::pdf_device::catalog::PdfOutline<Vec<Token>>>,
pdf_outline_payload: usize,
@@ -377,6 +382,8 @@ impl Executor {
io: IoState::default(),
pdf_colors: Default::default(),
pdf_link_stack: Vec::new(),
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pdf_last_match: None,
pdf_catalog_tokens: Vec::new(),
pdf_outlines: Vec::new(),
pdf_outline_payload: 0,
@@ -688,36 +695,54 @@ impl Executor {
return self.fail("native expansion nesting limit exceeded");
}
self.expansion_depth += 1;
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),
}
};
let result = self.expand_with_pending_tokens(input, files, definition_context);
self.expansion_depth -= 1;
result
}
// Keep the recursive path outside the expansion dispatch frame.
fn expand_after(
fn expand_with_pending_tokens(
&mut self,
token: &Token,
mut input: InputToken,
files: &mut impl SourceProvider,
mut definition_context: bool,
) -> 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)? {
let mut pending = Vec::new();
let mut first = None;
let result = loop {
if input.frozen {
break Some(input);
}
let meaning = self.meaning(&input.token);
if !matches!(meaning, Meaning::Primitive(Primitive::Expandafter)) {
break self.expand_one_inner(input, meaning, files, definition_context)?;
}
if self.read_parameter(Parameter::Tracingcommands).width() > 1 {
self.trace_command(&input.token, files)?;
}
// Expanding the second token is the same dispatch with deferred
// input. Only a re-entry from a scanner needs a new expansion frame.
if let Some(outer) = first.replace(self.required_raw(files)?) {
if pending.len() >= self.limits.input_depth {
return self.fail("native input stack limit exceeded");
}
pending.push(outer);
}
input = self.required_raw(files)?;
definition_context = false;
};
let Some(first) = first else {
return Ok(result);
};
if let Some(second) = result {
self.unread(second)?;
}
self.unread(first)?;
for token in pending.into_iter().rev() {
self.unread(token)?;
}
Ok(None)
}
fn expand_one_inner(
&mut self,
input: InputToken,
@@ -844,6 +869,13 @@ impl Executor {
};
self.print_tokens(result, token)?;
}
Pdfmatch | Pdflastmatch => {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
self.expand_pdf_match(primitive, token, files)?;
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
return self
.fail("pdfTeX regular expressions are unavailable on this host");
}
Pdfcolorstackinit => {
let stack = self.init_pdf_color_stack(files)?;
self.print_tokens(&stack.to_string(), token)?;
@@ -1975,6 +2007,16 @@ impl Executor {
Ok(())
}
fn font_character_target(
&mut self, files: &mut impl SourceProvider,
) -> Result<(FontId, u8), Error> {
let font = self.font_identifier(files)?;
let slot = self.integer(files)?;
let slot = u8::try_from(slot).map_err(|_| {
self.error("font character code must be in 0..255", self.current)
})?;
Ok((font, slot))
}
fn internal_integer_from(
&mut self,
next: InputToken,
@@ -1999,6 +2041,15 @@ impl Executor {
}
Ok(value.width())
}
Meaning::Primitive(Primitive::Efcode) => {
let (font, slot) = self.font_character_target(files)?;
self.reads.insert(Dependency::FontResources);
Ok(self.state.fonts.expansion_code(font, slot))
}
Meaning::Primitive(p @ (Primitive::Lpcode | Primitive::Rpcode)) => {
let (font, slot) = self.font_character_target(files)?;
Ok(self.state.fonts.protrusion_code(font, slot, p == Primitive::Rpcode))
}
Meaning::Primitive(p @ (Primitive::Hyphenchar | Primitive::Skewchar)) => {
let font = self.font_identifier(files)?;
let values = self.state.font_integers(font);
@@ -2047,6 +2098,10 @@ impl Executor {
Meaning::Primitive(Primitive::Interactionmode) => Ok(self.interaction_mode_value()),
Meaning::Primitive(Primitive::Pdftexversion) => Ok(Self::PDFTEX_VERSION),
Meaning::Primitive(Primitive::Pdfshellescape) => Ok(Self::SHELL_ESCAPE),
Meaning::Primitive(Primitive::Pdflastobj) => {
self.reads.insert(Dependency::PdfObjects);
Ok(self.state.pdf_objects.as_deref().map_or(0, |objects| objects.last()))
}
Meaning::Primitive(
p @ (Primitive::Pdflastximage
| Primitive::Pdflastximagepages
@@ -2614,6 +2669,7 @@ impl Executor {
if immediate {
let next = self.required_expanded(files)?;
match self.primitive(&next.token) {
Some(Primitive::Pdfobj) => return self.scan_pdf_object(true, files),
Some(Primitive::Pdfximage) => return self.scan_pdf_image(&next.token, true, files),
Some(p @ (Primitive::Openout | Primitive::Closeout | Primitive::Write)) => {
primitive = p
@@ -2691,6 +2747,7 @@ impl Executor {
self.current = node.span;
self.tick()?;
match &node.operation {
OutputOperation::PdfObject(number) => return self.write_pdf_object(*number),
OutputOperation::PdfImage { image, .. } => {
return self.declare_pdf_image(image.id);
}
@@ -3393,6 +3450,7 @@ impl Executor {
)) | Meaning::CharGiven(_)
| Meaning::Primitive(
Primitive::Char
| Primitive::Accent
| Primitive::Hskip
| Primitive::Hfil
| Primitive::Hfill
@@ -3565,6 +3623,7 @@ impl Executor {
}
Unskip | Unkern | Unpenalty => self.delete_last(primitive)?,
ItalicCorrection => self.append_italic_correction()?,
Accent => self.text_accent(&token, files)?,
Shipout => self.scan_box(boxes::Destination::Shipout, files)?,
Leaders | Cleaders | Xleaders => self.scan_leaders(primitive, files)?,
Vrule => {
@@ -3656,6 +3715,8 @@ impl Executor {
Pdfstartlink | Pdfendlink | Pdfdest => {
self.scan_pdf_link(primitive, token.span, files)?;
}
Pdfobj => self.scan_pdf_object(false, files)?,
Pdfrefobj => self.scan_pdf_object_reference(token.span, files)?,
Pdfcatalog => self.scan_pdf_catalog(files)?,
Pdfoutline => self.scan_pdf_outline(files)?,
Pdfinfo => self.scan_pdf_info(files)?,
@@ -3741,13 +3802,23 @@ impl Executor {
key: Option<Key>,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.assignment_inner(primitive, key, files)?;
self.assignment_with_box_policy(primitive, key, true, files)
}
fn assignment_with_box_policy(
&mut self,
primitive: Option<Primitive>,
key: Option<Key>,
allow_setbox: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.assignment_inner(primitive, key, allow_setbox, files)?;
self.finish_assignment()
}
fn assignment_inner(
&mut self,
mut primitive: Option<Primitive>,
mut key: Option<Key>,
allow_setbox: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
use Primitive::*;
@@ -3822,6 +3893,33 @@ impl Executor {
matches!(primitive, Some(Edef | Xdef)),
files,
)?,
Some(Pdffontexpand) => {
let font = self.font_identifier(files)?;
self.optional_equals(files)?;
let stretch = self.integer(files)?;
let shrink = self.integer(files)?;
let step = self.integer(files)?;
let automatic = self.keyword("autoexpand", files)?;
if automatic {
self.optional_space(files)?;
}
self.state
.fonts
.configure_expansion(font, stretch, shrink, step, automatic)
.map_err(|message| self.error(message, self.current))?;
}
Some(Efcode) => {
let (font, slot) = self.font_character_target(files)?;
self.optional_equals(files)?;
let code = self.integer(files)?;
self.state.fonts.set_expansion_code(font, slot, code);
}
Some(Lpcode | Rpcode) => {
let (font, slot) = self.font_character_target(files)?;
self.optional_equals(files)?;
let code = self.integer(files)?;
self.state.fonts.set_protrusion_code(font, slot, primitive == Some(Rpcode), code);
}
Some(Hyphenchar | Skewchar) => {
let font = self.font_identifier(files)?;
self.optional_equals(files)?;
@@ -3918,6 +4016,9 @@ impl Executor {
}
Some(Parshape) => self.scan_paragraph_shape(global, files)?,
Some(Setbox) => {
if !allow_setbox {
return self.fail("improper native setbox in an assignment prefix");
}
let n = self.register_index(files)?;
self.optional_equals(files)?;
if self
@@ -276,7 +276,7 @@ impl Executor {
};
}
if self.meaning(&t.token) == Meaning::Parameter(Parameter::Tabskip) {
self.assignment_inner(None, Some(Key::Parameter(Parameter::Tabskip)), files)?;
self.assignment_inner(None, Some(Key::Parameter(Parameter::Tabskip)), true, files)?;
} else {
return Ok(t);
}
@@ -165,7 +165,9 @@ impl Executor {
.as_mut()
.expect("unhbox starts an actual paragraph")
.nodes
.extend(nodes),
.extend(
nodes.into_iter().filter(|node| !matches!(node, TextNode::MarginKern { .. })),
),
BoxContent::Vertical(nodes) => self.append_unboxed_vertical(nodes),
}
Ok(())
@@ -249,6 +251,7 @@ impl Executor {
n,
TextNode::Glyph { .. }
| TextNode::Kern { .. }
| TextNode::AccentKern(_)
| TextNode::Box(_)
| TextNode::Indent(_)
| TextNode::Rule(_)
@@ -312,7 +312,7 @@ impl Executor {
self.display.as_mut().unwrap().alignment = Some(list);
// fin_align's do_assignments runs in the empty display math list. In
// particular, the second closing shift is expanded before pop_nest.
let close = self.display_assignments(files)?;
let close = self.assignments_before_content(true, files)?;
if !matches!(
self.meaning(&close.token),
Meaning::Character(TokenKind::Character(_, CatCode::MathShift))
@@ -353,14 +353,19 @@ impl Executor {
self.display.take().unwrap();
self.resume_after_display(span, files)
}
fn display_assignments(
pub(super) fn assignments_before_content(
&mut self,
allow_setbox: bool,
files: &mut impl SourceProvider,
) -> Result<InputToken, Error> {
use Primitive::*;
loop {
let t = self.expanded_non_space(files)?;
match self.meaning(&t.token) {
let meaning = self.meaning(&t.token);
if !allow_setbox && Self::suppresses_meaning(&t, &meaning) {
continue;
}
match meaning {
Meaning::Primitive(Relax) => continue,
Meaning::Primitive(p)
if p.page_dimension().is_some()
@@ -402,6 +407,10 @@ impl Executor {
| Font
| Fontdimen
| Hyphenchar
| Lpcode
| Rpcode
| Efcode
| Pdffontexpand
| Skewchar
| Textfont
| Scriptfont
@@ -431,7 +440,7 @@ impl Executor {
| Insertpenalties
) =>
{
self.assignment(Some(p), None, files)?
self.assignment_with_box_policy(Some(p), None, allow_setbox, files)?
}
Meaning::Count(n) => self.assignment(None, Some(Key::Count(n)), files)?,
Meaning::Toks(n) => self.assignment(None, Some(Key::Toks(n)), files)?,
@@ -20,8 +20,9 @@ impl Tail {
TextNode::Glue(g)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) => Self::Glue(*g, false),
TextNode::Kern { width, .. } => Self::Kern(*width),
TextNode::Kern { width, .. } | TextNode::AccentKern(width) => Self::Kern(*width),
TextNode::Penalty(n) => Self::Penalty(*n),
TextNode::MarginKern { .. } => Self::Other(15),
TextNode::Glyph { ligature, .. } => Self::Other(if *ligature { 7 } else { 0 }),
TextNode::MathChar(_) => Self::Other(0),
TextNode::Box(b) => Self::Other(b.native_box.as_ref().map_or(1, |b| {
@@ -783,7 +783,8 @@ impl Executor {
| Lccode | Uccode | Lowercase | Uppercase | Hyphenation | Patterns | Mathcode
| Delcode | Count | Countdef | Dimen | Dimendef | Skip | Skipdef | Muskip
| Muskipdef | Toks | Toksdef | Advance | Multiply | Divide | Read | Readline
| Font | Fontdimen | Hyphenchar | Skewchar | Textfont | Scriptfont
| Font | Fontdimen | Hyphenchar | Skewchar | Lpcode | Rpcode | Efcode | Pdffontexpand
| Textfont | Scriptfont
| Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time
| Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage
| Endinput | Showbox | Show | Showthe | Discretionary | DiscretionaryHyphen
@@ -264,6 +264,17 @@ impl Executor {
};
self.trace_shipout(&b, files)?;
let current = self.current;
let pdf_resource_entries = if device.pdf.is_some() {
let parameter = TokenParameter::Pdfpageresources;
self.reads.insert(Dependency::TokenParameter(parameter));
if let Some(tokens) = self.state.token_parameter(parameter).cloned() {
self.pdf_token_bytes(&tokens)?.into()
} else {
Default::default()
}
} else {
Default::default()
};
let pdf_color_start = if device.pdf.is_some() {
self.pdf_colors.start_page()
} else {
@@ -367,6 +378,7 @@ impl Executor {
pdf_color_start,
pdf_color_steps,
pdf_graphics_steps,
pdf_resource_entries,
pdf_links,
})));
self.statistics_after_shipout(before, files)?;
@@ -1,5 +1,128 @@
use super::*;
use crate::provenance::{Derivation, PaintSource};
fn accent_glyph(state: &State, font: FontId, slot: u8, token: &Token, accent: bool) -> TextNode {
let origin = TokenOrigin::from(token);
let source = PaintSource::token(origin);
let source = if accent {
source.derived(Derivation::Accent)
} else {
source
};
let glyph = super::super::fonts::text_glyph(state, font, slot, source.clone());
TextNode::Glyph {
font,
glyph,
slot,
original: char::from(slot).to_string(),
ligature: false,
left_boundary: false,
right_boundary: false,
origins: vec![origin.span],
component_sources: vec![source],
hyphen_char: state.hyphen_character(font),
}
}
impl Executor {
pub(super) fn text_accent(
&mut self,
token: &Token,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
use super::super::boxes::{PackSpec, hpack};
if !self.math.is_empty() {
return self.fail("a text accent in math mode requires a math accent");
}
let span = token.invocation.unwrap_or(token.span);
self.reads.insert(Dependency::ParagraphMode);
self.reads.insert(Dependency::TextFont);
self.reads.insert(Dependency::FontResources);
let slot = self.integer(files)?;
let slot = u8::try_from(slot)
.map_err(|_| self.error("native accent character must be in 0..255", span))?;
let font = self.state.text_font();
if !self.state.font_has_slot(font, slot) {
return self.missing_glyph(font, slot, span, files);
}
let accent_font = self
.state
.fonts
.font(font)
.map_err(|error| self.error(error, span))?;
let x_height = i64::from(accent_font.x_height());
let accent_slant = f64::from(accent_font.parameters()[0]) / 65_536.0;
let mut accent = accent_glyph(&self.state, font, slot, token, true);
let base = self.assignments_before_content(false, files)?;
let base_slot = match self.meaning(&base.token) {
Meaning::Character(TokenKind::Character(c, CatCode::Letter | CatCode::Other)) => {
Some(i32::try_from(u32::from(c)).expect("a Unicode scalar fits i32"))
}
Meaning::CharGiven(c) => Some(i32::from(c)),
Meaning::Primitive(Primitive::Char) => Some(self.integer(files)?),
_ => None,
};
let mut assembled = Vec::with_capacity(4);
if let Some(base_slot) = base_slot {
let base_span = base.token.invocation.unwrap_or(base.token.span);
let base_slot = u8::try_from(base_slot).map_err(|_| {
self.error("native accent base character must be in 0..255", base_span)
})?;
let base_font = self.state.text_font();
if self.state.font_has_slot(base_font, base_slot) {
let font = self
.state
.fonts
.font(base_font)
.map_err(|error| self.error(error, base_span))?;
let base_slant = f64::from(font.parameters()[0]) / 65_536.0;
let base_node = accent_glyph(&self.state, base_font, base_slot, &base.token, false);
let TextNode::Glyph { glyph: mark, .. } = &accent else {
unreachable!("a text accent begins with its character");
};
let TextNode::Glyph { glyph: base, .. } = &base_node else {
unreachable!("an accent base is an unshaped character");
};
let shift = x_height - base.height;
let left = (((base.width - mark.width) as f64) / 2.0
+ base.height as f64 * base_slant
- x_height as f64 * accent_slant)
.round() as i64;
let right = -mark.width - left;
let kern = |width| {
i32::try_from(width)
.map(TextNode::AccentKern)
.map_err(|_| self.error("native accent kern exceeds capacity", span))
};
let left = kern(left)?;
let right = kern(right)?;
if shift != 0 {
self.reads.insert(Dependency::BoxPackState);
let mut shifted = hpack(vec![accent], PackSpec::Natural, span, &self.state)
.map_err(|error| self.error(error, span))?;
self.state.last_badness = shifted.badness;
shifted.shift = shift;
accent = TextNode::Box(shifted.horizontal_item());
}
assembled.extend([left, accent, right, base_node]);
} else {
self.missing_glyph(base_font, base_slot, base_span, files)?;
assembled.push(accent);
}
} else {
self.unread(base)?;
assembled.push(accent);
}
let paragraph = self
.paragraph
.as_mut()
.expect("the text accent starts horizontal mode");
paragraph.nodes.extend(assembled);
paragraph.space_factor = 1000;
Ok(())
}
pub(super) fn append_italic_correction(&mut self) -> Result<(), Error> {
self.reads.insert(Dependency::ParagraphMode);
self.reads.insert(Dependency::BoxPackState);
@@ -26,7 +26,7 @@ impl Executor {
Ok(number)
}
fn pdf_token_bytes(&mut self, tokens: &[Token]) -> Result<Vec<u8>, Error> {
pub(super) fn pdf_token_bytes(&mut self, tokens: &[Token]) -> Result<Vec<u8>, Error> {
let text = self.token_list_text(tokens);
if text.len() > self.limits.tokens {
return self.fail("native PDF token output limit exceeded");
@@ -44,7 +44,7 @@ impl Executor {
}
}
fn scan_pdf_bytes(&mut self, files: &mut impl SourceProvider) -> Result<Vec<u8>, Error> {
pub(super) fn scan_pdf_bytes(&mut self, files: &mut impl SourceProvider) -> Result<Vec<u8>, Error> {
let tokens = self.scan_pdf_tokens(files)?;
self.pdf_token_bytes(&tokens)
}
@@ -0,0 +1,218 @@
use super::*;
use std::ffi::{CString, c_int};
use std::mem::MaybeUninit;
use std::ops::Range;
use std::ptr;
pub(super) struct PdfMatch {
input: Vec<u8>,
captures: Vec<Option<Range<usize>>>,
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct RegexRequest {
pub pattern: Vec<u8>,
pub input: Vec<u8>,
pub count: usize,
pub insensitive: bool,
}
#[derive(serde::Serialize, serde::Deserialize)]
pub enum RegexOutcome {
Match(Vec<Option<Range<usize>>>),
NoMatch,
InvalidPattern(String),
}
pub fn match_pdf_regex(request: &RegexRequest) -> Result<RegexOutcome, String> {
match search(
request.pattern.clone(),
request.input.clone(),
request.count,
request.insensitive,
) {
Ok(Some(matched)) => Ok(RegexOutcome::Match(matched.captures)),
Ok(None) => Ok(RegexOutcome::NoMatch),
Err(SearchError::Pattern(message)) => Ok(RegexOutcome::InvalidPattern(message)),
Err(SearchError::Runtime(message)) => Err(message),
}
}
impl Executor {
pub(super) fn expand_pdf_match(
&mut self,
primitive: Primitive,
origin: &Token,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if primitive == Primitive::Pdflastmatch {
let index = usize::try_from(self.integer(files)?)
.map_err(|_| self.error("Bad match number", self.current))?;
let text = self
.pdf_last_match
.as_ref()
.and_then(|last| {
let range = last.captures.get(index)?.as_ref()?;
let mut text = format!("{}->", range.start);
text.extend(last.input[range.clone()].iter().copied().map(char::from));
Some(text)
})
.unwrap_or_else(|| String::from("-1->"));
return self.print_tokens(&text, origin);
}
let insensitive = self.keyword("icase", files)?;
let count = if self.keyword("subcount", files)? {
usize::try_from(self.integer(files)?).unwrap_or(10)
} else {
10
};
let pattern = self.scan_pdf_bytes(files)?;
let input = self.scan_pdf_bytes(files)?;
self.check_cancellation()?;
let request = RegexRequest {
pattern,
input,
count,
insensitive,
};
let result = files.match_pdf_regex(&request, self.cancellation.as_ref());
self.check_cancellation()?;
let text = match result.map_err(|message| self.error(message, origin.span))? {
RegexOutcome::Match(captures) => {
let input = as_c_string(request.input).into_bytes();
if captures
.iter()
.flatten()
.any(|range| range.start > range.end || range.end > input.len())
{
return self.fail("regex backend supplied invalid captures");
}
self.pdf_last_match = Some(Arc::new(PdfMatch { input, captures }));
"1"
}
RegexOutcome::NoMatch => {
self.pdf_last_match = None;
"0"
}
RegexOutcome::InvalidPattern(message) => {
files
.observe_diagnostic(
WriteDestination::TerminalAndLog,
&format!("pdfTeX warning: pdftex: \\pdfmatch: {message}\n"),
)
.map_err(|error| self.error(error, origin.span))?;
"-1"
}
};
self.print_tokens(text, origin)
}
}
enum SearchError {
Pattern(String),
Runtime(String),
}
struct CLocale {
active: libc::locale_t,
previous: libc::locale_t,
}
impl CLocale {
fn enter() -> Result<Self, SearchError> {
// The reference engine treats matching as C-locale byte processing.
// Changing only this thread leaves concurrent jobs and the host alone.
let active = unsafe { libc::newlocale(libc::LC_ALL_MASK, c"C".as_ptr(), ptr::null_mut()) };
if active.is_null() {
return Err(SearchError::Runtime("cannot create pdfTeX C locale".into()));
}
let previous = unsafe { libc::uselocale(active) };
if previous.is_null() {
unsafe { libc::freelocale(active) };
return Err(SearchError::Runtime("cannot enter pdfTeX C locale".into()));
}
Ok(Self { active, previous })
}
}
impl Drop for CLocale {
fn drop(&mut self) {
// previous is the still-live locale returned by uselocale above.
unsafe {
libc::uselocale(self.previous);
libc::freelocale(self.active);
}
}
}
struct CompiledRegex(libc::regex_t);
impl Drop for CompiledRegex {
fn drop(&mut self) {
// This wrapper is created only after successful regcomp.
unsafe { libc::regfree(&mut self.0) };
}
}
fn regex_error(code: c_int) -> String {
// An error code can be described without referring to a compiled regex.
let length = unsafe { libc::regerror(code, ptr::null(), ptr::null_mut(), 0) };
let mut message = vec![0u8; length];
unsafe { libc::regerror(code, ptr::null(), message.as_mut_ptr().cast(), length) };
message.pop();
String::from_utf8_lossy(&message).into_owned()
}
fn as_c_string(mut bytes: Vec<u8>) -> CString {
// pdfTeX's makecstring passes the prefix through the first NUL.
if let Some(end) = bytes.iter().position(|&byte| byte == 0) {
bytes.truncate(end);
}
CString::new(bytes).expect("regex bytes were truncated at the first NUL")
}
fn search(
pattern: Vec<u8>,
input: Vec<u8>,
requested: usize,
insensitive: bool,
) -> Result<Option<PdfMatch>, SearchError> {
let _locale = CLocale::enter()?;
let pattern = as_c_string(pattern);
let input = as_c_string(input);
let flags = libc::REG_EXTENDED | if insensitive { libc::REG_ICASE } else { 0 };
let mut regex = MaybeUninit::uninit();
// regcomp initializes the regex storage on success. The pattern is
// NUL-terminated and valid throughout the call.
let status = unsafe { libc::regcomp(regex.as_mut_ptr(), pattern.as_ptr(), flags) };
if status != 0 {
return Err(SearchError::Pattern(regex_error(status)));
}
let regex = CompiledRegex(unsafe { regex.assume_init() });
// Group starts cannot outnumber pattern bytes. Requests beyond that
// bound are observable only as missing captures.
let count = requested.min(pattern.as_bytes().len() + 1);
let mut ranges = vec![
libc::regmatch_t {
rm_so: -1,
rm_eo: -1
};
count
];
// Both C strings and the initialized regex live through the call.
// A zero count asks regexec to skip writing capture positions.
let status = unsafe { libc::regexec(&regex.0, input.as_ptr(), count, ranges.as_mut_ptr(), 0) };
if status != 0 {
return Ok(None);
}
let input = input.into_bytes();
let captures = ranges
.into_iter()
.map(|range| {
let start = usize::try_from(range.rm_so).ok()?;
let end = usize::try_from(range.rm_eo).ok()?;
(start <= end && end <= input.len()).then_some(start..end)
})
.collect();
Ok(Some(PdfMatch { input, captures }))
}
@@ -0,0 +1,113 @@
use super::*;
use crate::pdf_device::page_resources::ObjectBody;
impl Executor {
pub(super) fn scan_pdf_object(
&mut self,
immediate: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.read_parameter(Parameter::Pdfoutput).width() <= 0 {
return self.fail("\\pdfobj not allowed in DVI mode");
}
self.reads.insert(Dependency::PdfObjects);
if self.keyword("reserveobjnum", files)? {
self.optional_space(files)?;
if immediate {
return self.fail("\\pdfobj reserveobjnum cannot be used with \\immediate");
}
return self
.state
.pdf_objects
.get_or_insert_with(Default::default)
.reserve(self.limits.tokens)
.map(|_| ())
.map_err(|error| self.error(error, self.current));
}
let requested = if self.keyword("useobjnum", files)? {
let number = self.integer(files)?;
let reserved = u32::try_from(number).ok().filter(|number| {
self.state
.pdf_objects
.as_deref()
.is_some_and(|objects| objects.is_reserved(*number))
});
if reserved.is_none() {
let warning = "pdfTeX warning (\\pdfobj): invalid object number being ignored\n";
files
.observe_message(warning)
.map_err(|error| self.error(error, self.current))?;
self.events.push(Event::Message {
text: warning.into(),
span: self.current,
});
}
reserved
} else {
None
};
let attributes = if self.keyword("stream", files)? {
Some(if self.keyword("attr", files)? {
self.scan_pdf_bytes(files)?
} else {
Vec::new()
})
} else {
None
};
if self.keyword("file", files)? {
return self.fail("file-backed \\pdfobj payloads are unsupported in native PDF output");
}
let bytes = self.scan_pdf_bytes(files)?;
let value = match attributes {
Some(attributes) => ObjectBody::Stream { attributes, bytes },
None => ObjectBody::Direct(bytes),
};
let number = self
.state
.pdf_objects
.get_or_insert_with(Default::default)
.define(requested, value, self.limits.tokens)
.map_err(|error| self.error(error, self.current))?;
if immediate {
self.pdf_page_data(files)?;
self.write_pdf_object(number)?;
}
Ok(())
}
pub(super) fn scan_pdf_object_reference(
&mut self,
span: Span,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
if self.read_parameter(Parameter::Pdfoutput).width() <= 0 {
return self.fail("\\pdfrefobj not allowed in DVI mode");
}
self.reads.insert(Dependency::PdfObjects);
let number = self.positive_pdf_number("object reference", files)? as u32;
if !self
.state
.pdf_objects
.as_deref()
.is_some_and(|objects| objects.contains(number))
{
return self.fail("cannot find referenced PDF object");
}
self.defer_output(OutputNode {
span,
operation: OutputOperation::PdfObject(number),
})
}
pub(super) fn write_pdf_object(&mut self, number: u32) -> Result<(), Error> {
self.reads.insert(Dependency::PdfObjects);
self.state
.pdf_objects
.as_deref_mut()
.ok_or_else(|| String::from("unknown native PDF object"))
.and_then(|objects| objects.write(number))
.map_err(|error| self.error(error, self.current))
}
}
@@ -207,6 +207,7 @@ impl Executor {
| Primitive::Month
| Primitive::Year
| Primitive::Inputlineno
| Primitive::Pdflastobj
| Primitive::Pdflastximage
| Primitive::Pdflastximagepages
| Primitive::Pdflastximagecolordepth
@@ -223,6 +224,9 @@ impl Executor {
| Primitive::Prevgraf
| Primitive::Spacefactor
| Primitive::Hyphenchar
| Primitive::Lpcode
| Primitive::Rpcode
| Primitive::Efcode
| Primitive::Skewchar
)
)
@@ -274,7 +278,7 @@ impl Executor {
}
Ok(n as i32)
}
fn optional_space(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
pub(super) fn optional_space(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
if let Some(t) = self.expanded(files)?
&& !t.token.kind.is_space()
{
@@ -6,7 +6,7 @@ use crate::{
tfm::{FontSize, TfmMetrics},
};
use sha2::{Digest, Sha256};
use std::sync::Arc;
use std::{collections::BTreeMap, sync::Arc};
#[derive(
Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
@@ -51,7 +51,7 @@ impl FontInstance {
self.metrics().map_or(0, TfmMetrics::size_sp)
}
pub fn metrics(&self) -> Option<&TfmMetrics> {
self.glyph_font.as_ref().map(|f| &f.metrics)
self.glyph_font.as_ref().map(|f| f.metrics())
}
pub fn parameters(&self) -> &[i32] {
&self.parameters
@@ -138,12 +138,25 @@ impl Default for FontLimits {
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub(super) struct FontExpansion {
pub stretch: i32,
pub shrink: i32,
pub step: i32,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct FontCatalog {
fonts: Vec<FontInstance>,
resources: Vec<FontResource>,
parameter_words: usize,
limits: FontLimits,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
protrusion: BTreeMap<FontId, BTreeMap<u8, [i16; 2]>>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
expansion: BTreeMap<FontId, FontExpansion>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
expansion_codes: BTreeMap<FontId, BTreeMap<u8, u16>>,
}
impl Default for FontCatalog {
fn default() -> Self {
@@ -173,6 +186,9 @@ impl FontCatalog {
resources: Vec::new(),
parameter_words: 7,
limits,
protrusion: BTreeMap::new(),
expansion: BTreeMap::new(),
expansion_codes: BTreeMap::new(),
})
}
pub fn fonts(&self) -> &[FontInstance] {
@@ -268,8 +284,9 @@ impl FontCatalog {
let glyph_font = Arc::new(crate::native_font::NativeFont {
id,
name: name.into(),
metrics,
metrics: Arc::new(metrics),
resource: self.resources[resource].clone(),
expansion: 0,
});
self.fonts.push(FontInstance {
name: name.into(),
@@ -316,6 +333,74 @@ impl FontCatalog {
self.fonts[id.0 as usize].parameters[index] = value;
Ok(())
}
pub(super) fn protrusion_code(&self, font: FontId, slot: u8, right: bool) -> i32 {
self.protrusion.get(&font).and_then(|font| font.get(&slot))
.map_or(0, |codes| i32::from(codes[usize::from(right)]))
}
pub(super) fn set_protrusion_code(
&mut self, font: FontId, slot: u8, right: bool, code: i32,
) {
let code = code.clamp(-1000, 1000) as i16;
if code != 0 || self.protrusion.get(&font).is_some_and(|font| font.contains_key(&slot)) {
self.protrusion.entry(font).or_default().entry(slot).or_default()[usize::from(right)] = code;
}
}
pub(super) fn configure_expansion(
&mut self,
font: FontId,
stretch: i32,
shrink: i32,
step: i32,
automatic: bool,
) -> Result<(), String> {
self.glyph_font(font)?;
let step = step.clamp(0, 100);
if step == 0 {
return Err("invalid font expansion step".into());
}
let stretch = stretch.clamp(0, 1000) / step * step;
let shrink = shrink.clamp(0, 500) / step * step;
if stretch == 0 && shrink == 0 {
return Err("invalid font expansion limits".into());
}
if !automatic {
return Err("native font expansion requires autoexpand; external expanded metrics are unsupported".into());
}
let config = FontExpansion { stretch, shrink, step };
if self.expansion.get(&font).is_some_and(|old| *old != config) {
return Err("font has already been configured with different expansion settings".into());
}
self.expansion.insert(font, config);
Ok(())
}
pub(super) fn has_expansion(&self) -> bool {
!self.expansion.is_empty()
}
pub(super) fn expansion(&self, font: FontId) -> Option<FontExpansion> {
self.expansion.get(&font).copied()
}
pub(super) fn expansion_code(&self, font: FontId, slot: u8) -> i32 {
self.expansion_codes
.get(&font)
.and_then(|codes| codes.get(&slot))
.map_or(1000, |code| i32::from(*code))
}
pub(super) fn set_expansion_code(&mut self, font: FontId, slot: u8, code: i32) {
let code = code.clamp(0, 1000);
if code < 1000 {
self.expansion_codes.entry(font).or_default().insert(slot, code as u16);
} else if let Some(codes) = self.expansion_codes.get_mut(&font) {
codes.remove(&slot);
if codes.is_empty() {
self.expansion_codes.remove(&font);
}
}
}
pub fn set_integers(&mut self, id: FontId, integers: FontIntegers) -> Result<(), String> {
self.font(id)?;
self.fonts[id.0 as usize].integers = integers;
@@ -49,7 +49,7 @@ pub(super) fn text_glyph_from_font(
) -> HorizontalBox {
let f = face.metrics();
let c = char::from(slot);
let (width, height, depth, italic) = (f.width(c), f.height(c), f.depth(c), f.italic(c));
let (width, height, depth, italic) = (face.advance(slot), f.height(c), f.depth(c), f.italic(c));
HorizontalBox {
width,
height,
@@ -8,7 +8,8 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 27;
const SCHEMA: u32 = 34;
const COMPATIBLE_SCHEMAS: [u32; 6] = [27, 28, 31, 32, 33, SCHEMA];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
#[derive(serde::Serialize, serde::Deserialize)]
@@ -105,16 +106,16 @@ impl FormatImage {
schema: u32,
engine: String,
}
// Check identity before decoding state: old schemas can lack fields
// which the current kernel must own, even with a valid checksum.
// The new schemas add primitive or node variants. Previously
// published state fields and variants retain their meanings.
let identity: Identity =
serde_json::from_str(&envelope.payload).map_err(|error| error.to_string())?;
if identity.schema != SCHEMA || identity.engine != ENGINE {
if !COMPATIBLE_SCHEMAS.contains(&identity.schema) || identity.engine != ENGINE {
return Err("incompatible native format image".into());
}
let image: Self =
serde_json::from_str(&envelope.payload).map_err(|error| error.to_string())?;
if image.schema != SCHEMA
if image.schema != identity.schema
|| image.engine != ENGINE
|| image.state.is_initex()
|| image.state.group_depth() != 0
@@ -15,6 +15,7 @@ pub enum TokenParameter {
Output,
Errhelp,
Everycr,
Pdfpageresources,
}
impl TokenParameter {
pub const ALL: &'static [Self] = &[
@@ -28,6 +29,7 @@ impl TokenParameter {
Self::Output,
Self::Errhelp,
Self::Everycr,
Self::Pdfpageresources,
];
pub fn name(self) -> String {
format!("{self:?}").to_ascii_lowercase()
@@ -228,6 +228,7 @@ pub enum OutputOperation {
stack: usize,
action: crate::pdf_device::PdfColorStackAction,
},
PdfObject(u32),
PdfSave,
PdfSetMatrix(Vec<Token>),
PdfRestore,
@@ -7,6 +7,8 @@ mod context;
mod device;
mod diagnostics;
mod engine;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub use engine::pdf_match::{RegexOutcome, RegexRequest, match_pdf_regex};
mod font_catalog;
mod fonts;
mod format_image;
@@ -210,6 +212,15 @@ pub struct GeneratedInput {
/// File lookup belongs to the host. Execution never shells out to TeX or
/// searches a different engine when a file/primitive is absent.
pub trait SourceProvider {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn match_pdf_regex(
&mut self,
request: &RegexRequest,
_cancellation: Option<&Cancellation>,
) -> Result<RegexOutcome, String> {
match_pdf_regex(request)
}
/// Change the TeX diagnostic selector. Mode zero suppresses the terminal.
fn set_interaction_mode(&mut self, _mode: u8) -> Result<(), String> {
Ok(())
@@ -356,6 +367,7 @@ pub enum Dependency {
MagnificationState,
PdfFileState,
PdfCatalogState,
PdfObjects,
PdfImages,
GlyphUnicode,
ResourceStatistics,
@@ -663,6 +675,7 @@ impl Execution {
})?);
}
}
self.resolve_page_graphics_resources(&mut pages)?;
if let Some(first) = pages.first_mut() {
first.items.extend(
image_objects
@@ -672,6 +685,28 @@ impl Execution {
}
Ok(pages)
}
fn resolve_page_graphics_resources(
&self,
pages: &mut [crate::render::DisplayList],
) -> Result<(), Error> {
use crate::pdf_device::page_resources::{PdfObjects, PageResources};
use crate::render::DisplayItem;
let empty = PdfObjects::default();
let objects = self.state.pdf_objects.as_deref().unwrap_or(&empty);
for page in pages {
let states = page.items.iter().filter_map(|item| match item {
DisplayItem::PdfColor(program) => Some(&program.graphics_states),
_ => None,
}).flatten().cloned().collect();
page.pdf_resources = PageResources::from_page(
page.pdf_resources.entries.clone(), &states, objects,
).map_err(|message| Error::at(
&self.sources, self.state.input_profile(), message, Span::default(),
))?;
}
Ok(())
}
/// Export the paragraphs already measured during token execution. No text
/// concatenation, source parser or final-state restyling participates.
pub fn document(&self) -> Result<crate::Document, Error> {
@@ -4,6 +4,8 @@ use crate::{HorizontalBox, Paragraph, ParagraphFont};
use std::collections::BTreeMap;
mod break_cache;
mod expansion;
mod protrusion;
use break_cache::BreakNode;
pub use break_cache::{LineBreakCache, LineBreakWork};
@@ -70,6 +72,9 @@ pub enum TextNode {
post_break: Vec<TextNode>,
replacement_count: u8,
},
/// Spacing owned by a text accent and protected from leading discard.
AccentKern(i32),
MarginKern { width: i32, right: bool, font: FontId, slot: u8 },
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct NativeParagraph {
@@ -383,6 +388,8 @@ fn width(n: &TextNode) -> i64 {
TextNode::Rule(r) => r.dimensions().0,
TextNode::Output(node) => node.dimensions().map_or(0, |(width, _, _)| width),
TextNode::Kern { width: n, .. }
| TextNode::AccentKern(n)
| TextNode::MarginKern { width: n, .. }
| TextNode::MathBoundary { width: n, .. }
| TextNode::Indent(n) => *n as i64,
_ => 0,
@@ -550,6 +557,8 @@ fn metrics(nodes: &[TextNode], left: Glue, right: Glue) -> (i64, [i64; 4], i64)
fn break_lines(
nodes: &[TextNode],
projected: &[BreakNode],
margins: Option<&protrusion::Search>,
expansion: Option<&expansion::Search>,
p: &BTreeMap<Parameter, ParameterValue>,
shape: &[ParagraphShapeLine],
pass: u8,
@@ -584,6 +593,7 @@ fn break_lines(
&& matches!(
projected[i - 1],
BreakNode::Content(_)
| BreakNode::AccentKern(_)
| BreakNode::Discretionary { .. }
| BreakNode::Kern {
explicit: false,
@@ -728,7 +738,17 @@ fn break_lines(
if target < 0 && shape.is_empty() {
return Err("negative native paragraph measure".into());
}
let delta = target - natural;
let hanging = margins.map_or(0, |margins| {
// The active paragraph still ends in parfillskip. A nonzero
// fill stops the right search at the terminal breakpoint.
let right_visible = !final_break
|| p[&Parameter::Parfillskip].glue().canonical_zero;
margins.width(a.start, b.end, a.post_break, b.pre_break, right_visible)
});
let shortfall = target - natural + hanging;
let delta = expansion.map_or(shortfall, |expansion| {
expansion.residual(shortfall, a.start, b.end, a.post_break, b.pre_break)
});
let infinite = stretch[1..].iter().any(|n| *n != 0);
let bad = if delta >= 0 {
if infinite {
@@ -914,17 +934,32 @@ fn pack(
p: &BTreeMap<Parameter, ParameterValue>,
(indent, target): (i64, i64),
last: bool,
terminal_marker: bool,
ends_in_pre_break: bool,
state: &State,
span: Span,
) -> Result<(Paragraph, NativeBox, super::marks::MigratingMaterial), String> {
) -> Result<(Paragraph, NativeBox, super::marks::MigratingMaterial, bool), String> {
let left = p[&Parameter::Leftskip].glue();
let mut material = Vec::new();
if left != Glue::default() {
material.push(TextNode::NamedGlue(left, Parameter::Leftskip));
}
material.extend_from_slice(nodes);
let enabled = p[&Parameter::Pdfprotrudechars].width() > 0;
if enabled && let Some(kern) = protrusion::margin_kern(state, nodes, false, false) {
material.push(kern);
}
let right_end = nodes.len() - usize::from(terminal_marker);
material.extend_from_slice(&nodes[..right_end]);
if last {
material.push(TextNode::Penalty(10000));
}
if enabled
&& let Some(kern) = protrusion::margin_kern(state, &nodes[..right_end], true, ends_in_pre_break)
{
material.push(kern);
}
material.extend_from_slice(&nodes[right_end..]);
if last {
material.push(TextNode::NamedGlue(
p[&Parameter::Parfillskip].glue(),
Parameter::Parfillskip,
@@ -934,7 +969,11 @@ fn pack(
p[&Parameter::Rightskip].glue(),
Parameter::Rightskip,
));
let (material, adjustments) = super::marks::extract(material);
let (mut material, adjustments) = super::marks::extract(material);
if p[&Parameter::Pdfadjustspacing].width() > 0 && state.fonts.has_expansion() {
expansion::pack(state, &mut material, target)?;
}
let shrinking = material.iter().map(width).sum::<i64>() > target;
let mut b = super::boxes::hpack(
material,
super::boxes::PackSpec::To(
@@ -958,7 +997,7 @@ fn pack(
centered: false,
right_aligned: false,
};
Ok((paragraph, b, adjustments))
Ok((paragraph, b, adjustments, shrinking))
}
// TeX init_math scans natural widths and visible nodes, independently of
// rounded glue-setting coordinates. Stretch/shrink before the last visible
@@ -1081,6 +1120,7 @@ pub(super) fn finish(
if let Some(path) = break_cache::solve(
&b.nodes,
&parameters,
state,
shape,
pass,
&mut work,
@@ -1110,13 +1150,6 @@ pub(super) fn finish(
let mut packed_shrinking = Vec::new();
let mut pre_display_size = -1073741823;
for (i, (point, bad)) in path.iter().enumerate() {
let left = parameters[&Parameter::Leftskip].glue();
let mut right = parameters[&Parameter::Rightskip].glue();
if i + 1 == path.len() {
right = right
.add(parameters[&Parameter::Parfillskip].glue())
.map_err(str::to_owned)?;
}
let material = line_material(
&b.nodes,
start,
@@ -1126,23 +1159,26 @@ pub(super) fn finish(
true,
point.zero_tail,
);
let (natural, stretch, shrink) = metrics(&material, left, right);
let dimensions = geometry(&parameters, shape, i + b.previous_lines);
let target = dimensions.1;
let (set, packed_bad, excess) =
super::boxes::setting(target - natural, stretch, [shrink, 0, 0, 0], true);
packed_diagnostic.push(target != natural && set.order == 0);
packed_shrinking.push(target < natural);
packed_badness.push(packed_bad);
packed_excess.push(excess);
let (line, line_box, adjustments) = pack(
let terminal_marker = point.zero_tail.is_some()
|| matches!(b.nodes.get(point.end), Some(TextNode::Penalty(_)));
let ends_in_pre_break = point.pre_break.is_some_and(|index| {
matches!(&b.nodes[index], TextNode::Discretionary { pre_break, .. } if !pre_break.is_empty())
});
let (line, line_box, adjustments, shrinking) = pack(
&material,
&parameters,
dimensions,
i + 1 == path.len(),
terminal_marker,
ends_in_pre_break,
state,
b.span,
)?;
packed_diagnostic.push(line_box.diagnostic_eligible);
packed_shrinking.push(shrinking);
packed_badness.push(line_box.badness);
packed_excess.push(line_box.excess);
if i + 1 == path.len() {
let BoxContent::Horizontal(material) = &line_box.content else {
unreachable!()
@@ -1316,6 +1352,7 @@ fn add_hyphens(
| TextNode::NamedGlue(_, _)
| TextNode::Leaders(_)
| TextNode::Penalty(_)
| TextNode::AccentKern(_)
| TextNode::Kern { explicit: true, .. }
)
})
@@ -47,6 +47,8 @@ type Path = Option<Vec<(Break, i32)>>;
struct Entry {
hash: u64,
nodes: Vec<BreakNode>,
margins: Option<protrusion::Search>,
expansion: Option<expansion::Search>,
parameters: BTreeMap<Parameter, ParameterValue>,
shape: Vec<ParagraphShapeLine>,
previous_lines: usize,
@@ -57,7 +59,10 @@ struct Entry {
impl Entry {
fn retained_nodes(&self) -> usize {
self.nodes.len() + self.shape.len()
self.nodes.len()
+ self.shape.len()
+ self.margins.as_ref().map_or(0, protrusion::Search::len)
+ self.expansion.as_ref().map_or(0, expansion::Search::len)
}
}
@@ -128,6 +133,7 @@ pub(super) enum BreakNode {
post_break: Option<Widths>,
replacement_count: u8,
},
AccentKern(i32),
}
impl BreakNode {
@@ -146,6 +152,8 @@ impl BreakNode {
TextNode::Glue(glue)
| TextNode::NamedGlue(glue, _)
| TextNode::Leaders(LeaderGlue { glue, .. }) => Self::Glue(*glue),
TextNode::AccentKern(width) => Self::AccentKern(*width),
TextNode::MarginKern { width, .. } => Self::Content(i64::from(*width)),
TextNode::Kern { width, explicit } => Self::Kern {
width: *width,
explicit: *explicit,
@@ -178,7 +186,9 @@ impl BreakNode {
natural,
..Default::default()
},
Self::Kern { width, .. } | Self::MathBoundary { width, .. } => Widths {
Self::Kern { width, .. }
| Self::AccentKern(width)
| Self::MathBoundary { width, .. } => Widths {
natural: i64::from(width),
..Default::default()
},
@@ -255,6 +265,7 @@ pub(super) fn candidate_widths(
pub(super) fn solve(
source: &[TextNode],
parameters: &BTreeMap<Parameter, ParameterValue>,
state: &State,
shape: &[ParagraphShapeLine],
pass: u8,
work: &mut usize,
@@ -263,14 +274,23 @@ pub(super) fn solve(
cache: Option<&LineBreakCache>,
) -> Result<Path, String> {
let nodes: Vec<_> = source.iter().map(BreakNode::project).collect();
let retained = nodes.len() + shape.len();
let margins = (parameters[&Parameter::Pdfprotrudechars].width() > 1)
.then(|| protrusion::Search::new(state, source));
let expansion = (parameters[&Parameter::Pdfadjustspacing].width() > 1
&& state.fonts.has_expansion())
.then(|| expansion::Search::new(state, source))
.transpose()?;
let retained = nodes.len()
+ shape.len()
+ margins.as_ref().map_or(0, protrusion::Search::len)
+ expansion.as_ref().map_or(0, expansion::Search::len);
let mut hash = None;
if let Some(cache) = cache
&& retained <= RETAINED_NODES
&& parameters[&Parameter::Tracingparagraphs].width() <= 0
{
let mut hasher = DefaultHasher::new();
(&nodes, parameters, shape, pass, previous_lines).hash(&mut hasher);
(&nodes, &margins, &expansion, parameters, shape, pass, previous_lines).hash(&mut hasher);
let key = hasher.finish();
hash = Some(key);
let mut cache = cache
@@ -284,6 +304,8 @@ pub(super) fn solve(
&& entry.parameters == *parameters
&& entry.shape == shape
&& entry.nodes == nodes
&& entry.margins == margins
&& entry.expansion == expansion
}) {
let entry = cache.entries.remove(index).unwrap();
*work += entry.edges;
@@ -302,6 +324,8 @@ pub(super) fn solve(
let result = break_lines(
source,
&nodes,
margins.as_ref(),
expansion.as_ref(),
parameters,
shape,
pass,
@@ -331,6 +355,8 @@ pub(super) fn solve(
cache.entries.push_back(Entry {
hash,
nodes,
margins,
expansion,
parameters: parameters.clone(),
shape: shape.to_vec(),
previous_lines,
@@ -0,0 +1,301 @@
//! pdfTeX expansion uses each live font's stretch and shrink limits. Paragraph
//! search budgets the quantization error; packing applies a font to each glyph.
use super::{State, TextNode, metrics};
use crate::{math_engine_tex::MathItem, native_font::NativeFont, pdf_device};
use std::{collections::BTreeMap, ops::AddAssign, sync::Arc};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
struct Capacity {
stretch: i64,
shrink: i64,
}
impl AddAssign for Capacity {
fn add_assign(&mut self, other: Self) {
self.stretch += other.stretch;
self.shrink += other.shrink;
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
struct Limits {
stretch: i32,
shrink: i32,
step: i32,
}
impl Limits {
fn include(&mut self, font: super::super::font_catalog::FontExpansion) -> Result<(), String> {
for (current, next) in [
(&mut self.step, font.step),
(&mut self.stretch, font.stretch),
(&mut self.shrink, font.shrink),
] {
if next != 0 {
if *current != 0 && *current != next {
return Err(
"inconsistent font expansion steps or limits in a native paragraph".into(),
);
}
*current = next;
}
}
Ok(())
}
fn residual(self, shortfall: i64, capacity: Capacity) -> i64 {
let (direction, limit, available) = if shortfall < 0 {
(-1, self.shrink, capacity.shrink)
} else {
(1, self.stretch, capacity.stretch)
};
if available <= 0 || shortfall == 0 {
return shortfall;
}
if available > shortfall.abs() {
direction * (available / i64::from(limit / self.step)) / 2
} else {
shortfall - direction * available
}
}
}
struct Character<'a> {
font: &'a Arc<NativeFont>,
slot: u8,
width: i64,
}
fn character(node: &TextNode) -> Option<Character<'_>> {
let TextNode::Glyph { glyph, slot, .. } = node else {
return None;
};
let geometry = glyph.math_geometry.as_ref()?;
let MathItem::NativeGlyph { font, .. } = &geometry.items.first()?.item else {
return None;
};
Some(Character {
font,
slot: *slot,
width: glyph.width,
})
}
fn pair(nodes: &[TextNode], at: usize) -> Option<(Character<'_>, Character<'_>)> {
let left = character(nodes.get(at.checked_sub(1)?)?)?;
let right = character(nodes.get(at + 1)?)?;
(left.font.id == right.font.id && left.font.expansion == 0 && right.font.expansion == 0)
.then_some((left, right))
}
fn capacity(
state: &State,
nodes: &[TextNode],
at: usize,
limits: Option<&mut Limits>,
) -> Result<Capacity, String> {
let measure = |font: &NativeFont, slot, width, kern| {
let Some(config) = state.fonts.expansion(font.id) else {
return Capacity::default();
};
if font.expansion != 0 {
return Capacity::default();
}
let code = state.fonts.expansion_code(font.id, slot);
let scale = |value| pdf_device::magnify(value, code);
let stretch = pdf_device::magnify(width, 1000 + config.stretch) - width;
let shrink = width - pdf_device::magnify(width, 1000 - config.shrink);
Capacity {
stretch: scale(if kern { stretch } else { stretch.max(0) }),
shrink: scale(if kern { shrink } else { shrink.max(0) }),
}
};
if let Some(glyph) = character(&nodes[at]) {
if glyph.font.expansion == 0
&& let Some(limits) = limits
&& let Some(config) = state.fonts.expansion(glyph.font.id)
{
limits.include(config)?;
}
return Ok(measure(glyph.font, glyph.slot, glyph.width, false));
}
if let TextNode::Kern {
width,
explicit: false,
} = nodes[at]
&& let Some((left, right)) = pair(nodes, at)
{
let kern = left
.font
.metrics()
.kern(char::from(left.slot), char::from(right.slot));
// A boundary kern and a TFM kern between two characters have the same
// node type. Only use the font program's actual kerning pair here.
if kern == i64::from(width) {
return Ok(measure(left.font, left.slot, kern, true));
}
}
Ok(Capacity::default())
}
fn sum(
state: &State,
nodes: &[TextNode],
mut limits: Option<&mut Limits>,
) -> Result<Capacity, String> {
let mut total = Capacity::default();
for i in 0..nodes.len() {
total += capacity(state, nodes, i, limits.as_deref_mut())?;
}
Ok(total)
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub(super) struct Search {
limits: Limits,
prefix: Vec<Capacity>,
discretionary: BTreeMap<usize, [Capacity; 2]>,
}
impl Search {
pub(super) fn new(state: &State, nodes: &[TextNode]) -> Result<Self, String> {
let mut limits = Limits::default();
let mut total = Capacity::default();
let mut prefix = Vec::with_capacity(nodes.len() + 1);
let mut discretionary = BTreeMap::new();
prefix.push(total);
for (i, node) in nodes.iter().enumerate() {
total += capacity(state, nodes, i, Some(&mut limits))?;
prefix.push(total);
if let TextNode::Discretionary {
pre_break,
post_break,
..
} = node
{
let pre = sum(state, pre_break, Some(&mut limits))?;
let post = sum(state, post_break, Some(&mut limits))?;
if pre != Capacity::default() || post != Capacity::default() {
discretionary.insert(i, [pre, post]);
}
}
}
Ok(Self {
limits,
prefix,
discretionary,
})
}
pub(super) fn len(&self) -> usize {
self.prefix.len() + 2 * self.discretionary.len()
}
pub(super) fn residual(
&self,
shortfall: i64,
start: usize,
end: usize,
post: Option<usize>,
pre: Option<usize>,
) -> i64 {
let mut total = Capacity {
stretch: self.prefix[end].stretch - self.prefix[start].stretch,
shrink: self.prefix[end].shrink - self.prefix[start].shrink,
};
if let Some(branches) = post.and_then(|i| self.discretionary.get(&i)) {
total += branches[1];
}
if let Some(branches) = pre.and_then(|i| self.discretionary.get(&i)) {
total += branches[0];
}
self.limits.residual(shortfall, total)
}
}
fn glyph_ratio(state: &State, glyph: &Character<'_>, line_ratio: i32) -> i32 {
let Some(config) = state.fonts.expansion(glyph.font.id) else {
return 0;
};
if glyph.font.expansion != 0 {
return 0;
}
let max = if line_ratio < 0 {
config.shrink
} else {
config.stretch
};
let code = state.fonts.expansion_code(glyph.font.id, glyph.slot);
let magnitude = i64::from(line_ratio.abs()) * i64::from(code) * i64::from(max) / 1_000_000;
let step = i64::from(config.step);
(magnitude + step / 2).div_euclid(step) as i32 * config.step * line_ratio.signum()
}
pub(super) fn pack(state: &State, material: &mut [TextNode], target: i64) -> Result<(), String> {
let (natural, stretch, _) = metrics(material, Default::default(), Default::default());
let shortfall = target - natural;
if shortfall == 0 || (shortfall > 0 && stretch[1..].iter().any(|width| *width != 0)) {
return Ok(());
}
let capacity = sum(state, material, None)?;
let available = if shortfall < 0 {
capacity.shrink
} else {
capacity.stretch
};
if available <= 0 {
return Ok(());
}
let ratio =
pdf_device::divide_scaled(shortfall.clamp(-available, available), available, 3).0 as i32;
let mut fonts = BTreeMap::new();
for i in 0..material.len() {
if let TextNode::Kern {
width,
explicit: false,
} = material[i]
&& let Some((left, right)) = pair(material, i)
&& let kern = left
.font
.metrics()
.kern(char::from(left.slot), char::from(right.slot))
&& kern == i64::from(width)
{
let amount = glyph_ratio(state, &left, ratio);
if let TextNode::Kern { width, .. } = &mut material[i] {
*width = i32::try_from(pdf_device::magnify(kern, 1000 + amount))
.map_err(|_| "expanded native font kern exceeds the scaled point range")?;
}
}
}
for node in material {
let Some(glyph) = character(node) else {
continue;
};
let amount = glyph_ratio(state, &glyph, ratio);
if amount == 0 {
continue;
}
let face = fonts.entry((glyph.font.id, amount)).or_insert_with(|| {
Arc::new(NativeFont {
expansion: amount,
..glyph.font.as_ref().clone()
})
});
let TextNode::Glyph { glyph, .. } = node else {
unreachable!()
};
glyph.width = pdf_device::magnify(glyph.width, 1000 + amount);
glyph.italic = pdf_device::magnify(glyph.italic, 1000 + amount);
let geometry = glyph
.math_geometry
.as_mut()
.expect("native character geometry");
geometry.metrics.width = glyph.width;
let MathItem::NativeGlyph { font, .. } = &mut geometry.items[0].item else {
unreachable!()
};
*font = face.clone();
}
Ok(())
}
@@ -0,0 +1,205 @@
//! The same font-slot widths drive break search and the owned margin kerns.
use super::*;
#[derive(Clone, Copy)]
enum Edge {
Skip,
Solid,
Glyph(FontId, u8),
}
impl Edge {
fn character(node: &TextNode) -> Self {
match node {
TextNode::Glyph { font, slot, .. } => Self::Glyph(*font, *slot),
TextNode::MathChar(glyph) => {
use crate::math_engine_tex::MathItem;
match glyph
.math_geometry
.as_deref()
.map(|geometry| geometry.items.as_slice())
{
Some([item]) => match &item.item {
MathItem::NativeGlyph { font, slot, .. } => Self::Glyph(font.id, *slot),
_ => Self::Solid,
},
_ => Self::Solid,
}
}
_ => Self::Solid,
}
}
fn node(node: &TextNode, right: bool) -> Self {
match node {
TextNode::Box(boxed) => match boxed.native_box.as_deref() {
Some(NativeBox {
content: BoxContent::Horizontal(nodes),
..
}) if !nodes.is_empty() => Self::list(nodes, right),
Some(NativeBox {
content: BoxContent::Horizontal(_),
..
}) if boxed.width == 0 && boxed.height == 0 && boxed.depth == 0 => Self::Skip,
_ => Self::Solid,
},
TextNode::Language(_)
| TextNode::Mark(_)
| TextNode::Adjustment(_)
| TextNode::Insertion(_)
| TextNode::Penalty(_)
| TextNode::Indent(0)
| TextNode::AccentKern(0)
| TextNode::MathBoundary { width: 0, .. }
| TextNode::Kern {
explicit: false, ..
}
| TextNode::Kern { width: 0, .. } => Self::Skip,
TextNode::Output(node) if node.dimensions().is_none() => Self::Skip,
TextNode::Glue(glue)
| TextNode::NamedGlue(glue, _)
| TextNode::Leaders(LeaderGlue { glue, .. })
if glue.canonical_zero =>
{
Self::Skip
}
TextNode::Discretionary {
pre_break,
post_break,
replacement_count: 0,
..
} if pre_break.is_empty() && post_break.is_empty() => Self::Skip,
_ => Self::character(node),
}
}
fn list(nodes: &[TextNode], right: bool) -> Self {
let mut nodes = nodes.iter();
while let Some(node) = if right {
nodes.next_back()
} else {
nodes.next()
} {
let edge = Self::node(node, right);
if !matches!(edge, Self::Skip) {
return edge;
}
}
Self::Skip
}
fn width(self, state: &State, right: bool) -> i32 {
let Self::Glyph(font, slot) = self else {
return 0;
};
let code = state.fonts.protrusion_code(font, slot, right);
if code == 0 {
return 0;
}
let quad = state
.fonts
.font(font)
.expect("marginal glyph's font is live")
.quad();
let scaled = i64::from(quad) * i64::from(code);
// Round to the nearest sp, taking half a unit away from zero.
(scaled.signum() * ((scaled.abs() + 500) / 1000)) as i32
}
}
pub(super) fn margin_kern(
state: &State,
nodes: &[TextNode],
right: bool,
direct: bool,
) -> Option<TextNode> {
let edge = if direct {
nodes.last().map_or(Edge::Solid, Edge::character)
} else {
Edge::list(nodes, right)
};
let Edge::Glyph(font, slot) = edge else {
return None;
};
let width = -edge.width(state, right);
(width != 0).then_some(TextNode::MarginKern {
width,
right,
font,
slot,
})
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
struct Projected {
left: Option<(usize, i32)>,
right: Option<(usize, i32)>,
pre: Option<i32>,
post: Option<i32>,
}
#[derive(Debug, PartialEq, Eq, Hash)]
pub(super) struct Search(Vec<Projected>);
impl Search {
pub(super) fn new(state: &State, nodes: &[TextNode]) -> Self {
let mut widths = vec![Projected::default(); nodes.len() + 1];
for (i, node) in nodes.iter().enumerate() {
let edge = Edge::node(node, true);
widths[i + 1].right = if matches!(edge, Edge::Skip) {
widths[i].right
} else {
Some((i, edge.width(state, true)))
};
if let TextNode::Discretionary {
pre_break,
post_break,
..
} = node
{
widths[i].pre = pre_break
.last()
.map(|node| Edge::character(node).width(state, true));
widths[i].post = post_break
.first()
.map(|node| Edge::character(node).width(state, false));
}
}
for (i, node) in nodes.iter().enumerate().rev() {
let edge = Edge::node(node, false);
widths[i].left = if matches!(edge, Edge::Skip) {
widths[i + 1].left
} else {
Some((i, edge.width(state, false)))
};
}
Self(widths)
}
pub(super) fn len(&self) -> usize {
self.0.len()
}
pub(super) fn width(
&self,
start: usize,
end: usize,
post: Option<usize>,
pre: Option<usize>,
right_visible: bool,
) -> i64 {
let left = post.and_then(|i| self.0[i].post).or_else(|| {
self.0[start]
.left
.filter(|(i, _)| *i < end)
.map(|(_, width)| width)
});
let right = pre.and_then(|i| self.0[i].pre).or_else(|| {
self.0[end]
.right
.filter(|(i, _)| right_visible && *i >= start)
.map(|(_, width)| width)
});
i64::from(left.unwrap_or(0)) + i64::from(right.unwrap_or(0))
}
}
@@ -230,7 +230,8 @@ impl<'a> Tracer<'a> {
self.short(post_break, out)?;
i += usize::from(*replacement_count);
}
TextNode::Kern { .. } | TextNode::Penalty(_) => {}
TextNode::Kern { .. } | TextNode::AccentKern(_) | TextNode::Penalty(_)
| TextNode::MarginKern { .. } => {}
}
i += 1;
}
@@ -111,6 +111,8 @@ pub enum Parameter {
Baselineskip,
Lineskip,
Tabskip,
Pdfprotrudechars,
Pdfadjustspacing,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue {
@@ -225,6 +227,8 @@ impl Parameter {
Self::Baselineskip,
Self::Lineskip,
Self::Tabskip,
Self::Pdfprotrudechars,
Self::Pdfadjustspacing,
];
pub fn name(self) -> String {
format!("{self:?}").to_ascii_lowercase()
@@ -41,13 +41,38 @@ impl RevisionExecution {
revision: u64,
execution: Execution,
resources: Option<crate::resources::ResourceTrace>,
) -> Self {
Self::with_previous_sources(revision, execution, resources, None)
}
fn with_previous_sources(
revision: u64,
execution: Execution,
resources: Option<crate::resources::ResourceTrace>,
previous: Option<&Self>,
) -> Self {
let source_versions = execution
.sources
.iter()
.map(|source| SourceVersion {
sha256: format!("{:x}", Sha256::digest(&source.data)),
bytes: source.data.len() as u64,
.enumerate()
.map(|(id, source)| {
// The previous result was built by this session. Match the
// scanned bytes, including generated and stream input.
previous
.and_then(|old| {
old.execution
.sources
.get(id)
.zip(old.source_versions.get(id))
})
.filter(|(old_source, _)| *old_source == source)
.map_or_else(
|| SourceVersion {
sha256: format!("{:x}", Sha256::digest(&source.data)),
bytes: source.data.len() as u64,
},
|(_, version)| version.clone(),
)
})
.collect();
Self {
@@ -127,6 +152,19 @@ impl NativeSession {
commit().map(Some)
}
/// Build a source map for a completed execution. The current result
/// already has byte-verified sources owned by this session.
pub fn source_map(
&self,
revision: &Arc<RevisionExecution>,
pages: &[crate::render::DisplayList],
) -> Result<crate::source_map::SourceMap, String> {
let current = self
.latest()
.is_some_and(|latest| Arc::ptr_eq(&latest, revision));
crate::source_map::SourceMap::from_revision_checked(revision, pages, !current)
}
/// Last successfully published result, with its own revision identity.
pub fn latest(&self) -> Option<Arc<RevisionExecution>> {
self.state
@@ -166,7 +204,7 @@ impl RevisionJob {
let executed = executor
.with_cancellation(self.cancellation.clone())
.run_detailed(source, files);
self.finish_execution(executed, files)
self.finish_execution(executed, files, None)
}
/// Capture selected entry continuations while running the full revision.
@@ -181,7 +219,7 @@ impl RevisionJob {
let executed = executor
.with_cancellation(self.cancellation.clone())
.run_capturing_entries(source, files, select, capture);
self.finish_execution(executed, files)
self.finish_execution(executed, files, None)
}
/// Resume after the host has validated prefix dependencies and replayed
@@ -192,9 +230,10 @@ impl RevisionJob {
source: SourceFile,
files: &mut impl SourceProvider,
) -> Option<Result<Arc<RevisionExecution>, RevisionFailure>> {
let previous = self.session.latest();
let executed =
checkpoint.resume_after_host_replay(source, files, self.cancellation.clone())?;
Some(self.finish_execution(executed, files))
Some(self.finish_execution(executed, files, previous.as_deref()))
}
/// Resume a verified prefix and observe new boundaries in the executed suffix.
@@ -217,22 +256,24 @@ impl RevisionJob {
select,
capture,
)?;
Some(self.finish_execution(executed, files))
Some(self.finish_execution(executed, files, previous.as_deref()))
}
fn finish_execution(
self,
executed: Result<Execution, ExecutionFailure>,
files: &impl SourceProvider,
previous: Option<&RevisionExecution>,
) -> Result<Arc<RevisionExecution>, RevisionFailure> {
// Host observations can themselves supersede the revision. Do not
// invoke the host while holding the session publication lock.
let resources = files.execution_resource_trace().cloned();
let result = executed.map(|execution| {
Arc::new(RevisionExecution::from_execution(
Arc::new(RevisionExecution::with_previous_sources(
self.revision,
execution,
resources.clone(),
previous,
))
});
let mut state = self
@@ -312,6 +312,16 @@ pub enum Primitive {
Overwithdelims,
Atopwithdelims,
Abovewithdelims,
Accent,
Pdfmatch,
Pdflastmatch,
Lpcode,
Rpcode,
Efcode,
Pdffontexpand,
Pdfobj,
Pdfrefobj,
Pdflastobj,
}
impl Primitive {
@@ -362,6 +372,8 @@ impl Primitive {
| Pdfcreationdate
| Pdftexrevision
| Pdfstrcmp
| Pdfmatch
| Pdflastmatch
| Pdfcolorstackinit
| Csname
| Unless
@@ -602,6 +614,8 @@ pub struct State {
pub(super) pdf_file_options: Option<crate::pdf_device::PdfFileOptions>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_catalog: Option<Box<crate::pdf_device::catalog::PdfCatalog>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(super) pdf_objects: Option<Box<crate::pdf_device::page_resources::PdfObjects>>,
pub(super) pdf_info: Vec<u8>,
pub(super) glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap,
pub(super) hyphenation: super::hyphenation::HyphenationData,
@@ -703,6 +717,7 @@ impl Default for State {
output_mode_set: None,
pdf_file_options: None,
pdf_catalog: None,
pdf_objects: None,
pdf_info: Vec::new(),
glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap::default(),
hyphenation: super::hyphenation::HyphenationData::default(),
@@ -722,6 +737,7 @@ impl Default for State {
("radical", Radical),
("left", Left),
("right", Right),
("accent", Accent),
("mathaccent", Mathaccent),
("mathchoice", Mathchoice),
("overline", Overline),
@@ -729,6 +745,10 @@ impl Default for State {
("eqno", Eqno),
("leqno", Leqno),
("hyphenchar", Hyphenchar),
("lpcode", Lpcode),
("rpcode", Rpcode),
("efcode", Efcode),
("pdffontexpand", Pdffontexpand),
("fontname", Fontname),
("fontdimen", Fontdimen),
("skewchar", Skewchar),
@@ -918,7 +938,14 @@ impl Default for State {
("pdfcreationdate", Pdfcreationdate),
("pdfshellescape", Pdfshellescape),
("pdfstrcmp", Pdfstrcmp),
#[cfg(all(target_os = "linux", target_env = "gnu"))]
("pdfmatch", Pdfmatch),
#[cfg(all(target_os = "linux", target_env = "gnu"))]
("pdflastmatch", Pdflastmatch),
("pdfcolorstackinit", Pdfcolorstackinit),
("pdfobj", Pdfobj),
("pdfrefobj", Pdfrefobj),
("pdflastobj", Pdflastobj),
("pdfcolorstack", Pdfcolorstack),
("pdfsave", Pdfsave),
("pdfstartlink", Pdfstartlink),
@@ -1316,6 +1343,7 @@ impl State {
self.output_mode_set = None;
self.pdf_file_options = None;
self.pdf_catalog = None;
self.pdf_objects = None;
self.pdf_info.clear();
self
}
@@ -1330,6 +1358,7 @@ impl State {
generate_unicode: self.parameter(Parameter::Pdfgentounicode).width(),
glyph_unicode: &self.glyph_unicode,
catalog: self.pdf_catalog.as_deref(),
objects: self.pdf_objects.as_deref(),
info: crate::pdf_device::PdfInfo {
entries: &self.pdf_info,
date: (self.parameter(Parameter::Pdfinfoomitdate).width() == 0)
+125 -32
View File
@@ -3,9 +3,15 @@
//! master from a font name, Unicode label, or the current execution state.
use crate::{
execution::{FontId, FontResource},
resources::{LoadedResource, ResourceVersion},
tfm::TfmMetrics,
type1::Type1Font,
type1_outline::Type1Outlines,
};
use std::{
collections::{BTreeMap, VecDeque},
sync::{Arc, Mutex},
};
use std::collections::BTreeMap;
mod virtual_paint;
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -48,9 +54,17 @@ impl NativeFontProgram {
pub struct NativeFont {
pub id: FontId,
pub name: String,
pub metrics: TfmMetrics,
pub metrics: Arc<TfmMetrics>,
pub resource: FontResource,
/// Horizontal font adjustment in thousandths. The backing TFM and
/// outline program are the original font at the original point size.
#[serde(default, skip_serializing_if = "unexpanded")]
pub expansion: i32,
}
pub(crate) fn unexpanded(amount: &i32) -> bool {
*amount == 0
}
impl NativeFont {
pub fn metrics(&self) -> &TfmMetrics {
&self.metrics
@@ -58,6 +72,22 @@ impl NativeFont {
pub fn size_sp(&self) -> i64 {
self.metrics.size_sp()
}
pub fn advance(&self, slot: u8) -> i64 {
let width = self.metrics.width(char::from(slot));
if self.expansion == 0 {
return width;
}
crate::pdf_device::magnify(width, 1000 + self.expansion)
}
pub(crate) fn same_base(&self, other: &Self) -> bool {
std::ptr::eq(self, other)
|| (self.id == other.id
&& self.name == other.name
&& (Arc::ptr_eq(&self.metrics, &other.metrics) || self.metrics == other.metrics)
&& self.resource.version == other.resource.version
&& (Arc::ptr_eq(&self.resource.data, &other.resource.data)
|| self.resource.data == other.resource.data))
}
pub fn has_slot(&self, slot: u8) -> bool {
self.metrics.has_slot(slot)
}
@@ -186,6 +216,85 @@ fn verify_resource(
Ok(resource)
}
const MAX_TYPE1_PROGRAMS: usize = 16;
const MAX_CACHED_PFB_BYTES: usize = 256 * 1024;
/// Decoded Type 1 programs shared across revisions in one compiler.
#[derive(Default)]
pub struct NativeFontCache {
type1: Mutex<VecDeque<(ResourceVersion, Arc<DecodedType1>)>>,
}
struct DecodedType1 {
program: Type1Font,
outlines: Type1Outlines,
bbox: [i32; 4],
stem_v: i32,
}
impl DecodedType1 {
fn from_pfb(resource: &LoadedResource) -> Result<Self, String> {
let program = Type1Font::from_pfb(&resource.data).ok_or_else(|| {
format!(
"invalid Type1 PFB program: {}",
resource.version.path.display()
)
})?;
let outlines = Type1Outlines::parse(&program)?;
let bbox = outlines.normalized_bbox(program.bbox);
let stem_v = outlines.stem_v();
Ok(Self {
program,
outlines,
bbox,
stem_v,
})
}
}
impl NativeFontCache {
// The caller reads the actual resource and verifies its bytes on this
// revision before asking for the decoded representation.
fn type1(&self, resource: &LoadedResource) -> Result<Arc<DecodedType1>, String> {
if resource.data.len() > MAX_CACHED_PFB_BYTES {
return DecodedType1::from_pfb(resource).map(Arc::new);
}
let mut entries = self.type1.lock().expect("native Type 1 cache poisoned");
if let Some(index) = entries
.iter()
.position(|(version, _)| *version == resource.version)
{
let entry = entries.remove(index).expect("cached Type 1 index exists");
let decoded = entry.1.clone();
entries.push_back(entry);
return Ok(decoded);
}
let decoded = Arc::new(DecodedType1::from_pfb(resource)?);
if entries.len() == MAX_TYPE1_PROGRAMS {
entries.pop_front();
}
entries.push_back((resource.version.clone(), decoded.clone()));
Ok(decoded)
}
/// Resolve the current revision's fonts and record its actual reads.
pub fn resolve(
&self,
pages: &mut [crate::render::DisplayList],
files: &mut impl crate::execution::SourceProvider,
) -> Result<(), String> {
if let Some(mut expanded) = virtual_paint::expand_pages(pages, files)? {
resolve_physical_fonts(&mut expanded, files, self)?;
for (original, resolved) in pages.iter_mut().zip(expanded) {
*original = resolved;
}
Ok(())
} else {
resolve_physical_fonts(pages, files, self)
}
}
}
/// Resolve only fonts used by actual output lists. TFM-only execution and
/// unshipped boxes do not require any font program. Errors leave lists intact.
/// SVG executes the requested glyph programs; PDF embeds the same actual PFB.
@@ -193,22 +302,15 @@ pub fn resolve_native_fonts(
pages: &mut [crate::render::DisplayList],
files: &mut impl crate::execution::SourceProvider,
) -> Result<(), String> {
if let Some(mut expanded) = virtual_paint::expand_pages(pages, files)? {
resolve_physical_fonts(&mut expanded, files)?;
for (original, resolved) in pages.iter_mut().zip(expanded) {
*original = resolved;
}
Ok(())
} else {
resolve_physical_fonts(pages, files)
}
NativeFontCache::default().resolve(pages, files)
}
fn resolve_physical_fonts(
pages: &mut [crate::render::DisplayList],
files: &mut impl crate::execution::SourceProvider,
font_cache: &NativeFontCache,
) -> Result<(), String> {
use crate::{render::DisplayItem, resources::ResourceKind, type1::Type1Font};
use std::{collections::BTreeSet, sync::Arc};
use crate::{render::DisplayItem, resources::ResourceKind};
use std::collections::BTreeSet;
let mut used: BTreeMap<FontId, (Arc<NativeFont>, BTreeSet<u8>)> = BTreeMap::new();
for page in pages.iter() {
for item in &page.items {
@@ -216,7 +318,7 @@ fn resolve_physical_fonts(
let entry = used
.entry(font.id)
.or_insert_with(|| (font.clone(), BTreeSet::new()));
if entry.0.as_ref() != font.as_ref() {
if !Arc::ptr_eq(&entry.0, font) && !entry.0.same_base(font) {
return Err("native font ids from different jobs cannot share output".into());
}
entry.1.insert(*slot);
@@ -238,10 +340,7 @@ fn resolve_physical_fonts(
.iter()
.find_map(|p| p.pdf.as_ref())
.map(|p| p.file.clone());
let mut cache: BTreeMap<
(String, Option<String>),
(NativeFontPaint, crate::type1_outline::Type1Outlines),
> = BTreeMap::new();
let mut cache: BTreeMap<_, (NativeFontPaint, Arc<DecodedType1>)> = BTreeMap::new();
for (id, (font, slots)) in used {
let entry = map_entry(&map.data, &font.name)?;
let Some(entry) = entry else {
@@ -317,12 +416,8 @@ fn resolve_physical_fonts(
&file,
&map.version.path.to_string_lossy(),
)?;
let program = Type1Font::from_pfb(&resource.data).ok_or_else(|| {
format!(
"invalid Type1 PFB program: {}",
resource.version.path.display()
)
})?;
let decoded = font_cache.type1(&resource)?;
let program = &decoded.program;
let mut resources = vec![map.version.clone(), resource.version];
let encoding = if let Some(name) = entry.encoding {
let enc = actual_resource(
@@ -339,25 +434,23 @@ fn resolve_physical_fonts(
.map(|slot| program.name_for_code(slot).unwrap_or(".notdef").to_owned())
.collect()
};
let outlines = crate::type1_outline::Type1Outlines::parse(&program)?;
let bbox = outlines.normalized_bbox(program.bbox);
let stem_v = outlines.stem_v();
cache.insert(
key.clone(),
(
NativeFontPaint {
program: NativeFontProgram::Type1(program),
program: NativeFontProgram::Type1(program.clone()),
encoding,
glyph_paths: BTreeMap::new(),
bbox,
stem_v,
bbox: decoded.bbox,
stem_v: decoded.stem_v,
resources,
},
outlines,
decoded,
),
);
}
let (paint, outlines) = cache.get_mut(&key).unwrap();
let (paint, decoded) = cache.get_mut(&key).unwrap();
let outlines = &decoded.outlines;
for slot in slots {
if paint.glyph_paths.contains_key(&slot) {
continue;
@@ -18,6 +18,7 @@ struct Expansion<'a, F> {
files: &'a mut F,
virtuals: BTreeMap<FontId, (Arc<NativeFont>, Option<Arc<LoadedVirtual>>)>,
local_fonts: BTreeMap<(String, String, i64), Arc<NativeFont>>,
expanded_fonts: BTreeMap<(FontId, i32), Arc<NativeFont>>,
last_id: u32,
commands: usize,
}
@@ -46,7 +47,7 @@ fn offset(point: i64, delta: i64) -> Result<i64, String> {
impl<'a, F: SourceProvider> Expansion<'a, F> {
fn lookup(&mut self, font: &Arc<NativeFont>) -> Result<Option<Arc<LoadedVirtual>>, String> {
if let Some((old, vf)) = self.virtuals.get(&font.id) {
if !Arc::ptr_eq(old, font) && old != font {
if !Arc::ptr_eq(old, font) && !old.same_base(font) {
return Err("native font ids from different jobs cannot share output".into());
}
return Ok(vf.clone());
@@ -104,7 +105,8 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
let font = Arc::new(NativeFont {
id: FontId::for_device(self.last_id),
name: local.name.clone(),
metrics,
metrics: Arc::new(metrics),
expansion: 0,
resource: FontResource {
version: file.version,
data: Arc::new(file.data),
@@ -164,7 +166,18 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
font.name
));
}
let width = font.metrics.width(char::from(slot));
let font = if glyph.font.expansion == 0 {
font
} else {
self.expanded_fonts
.entry((font.id, glyph.font.expansion))
.or_insert_with(|| Arc::new(NativeFont {
expansion: glyph.font.expansion,
..font.as_ref().clone()
}))
.clone()
};
let width = font.advance(slot);
let size = font.size_sp();
self.expand(
Glyph {
@@ -255,6 +268,7 @@ pub(super) fn expand_pages(
files,
virtuals: BTreeMap::new(),
local_fonts: BTreeMap::new(),
expanded_fonts: BTreeMap::new(),
last_id: 0x7fff_ffff,
commands: 0,
};
@@ -278,6 +292,7 @@ pub(super) fn expand_pages(
magnification: page.magnification,
units: page.units,
pdf: page.pdf.clone(),
pdf_resources: page.pdf_resources.clone(),
images: page.images.clone(),
..DisplayList::default()
};
+70 -20
View File
@@ -441,6 +441,7 @@ fn native_pdf_font_size(size: i64) -> i64 {
struct NativeTextRun {
font: crate::execution::FontId,
expansion: i32,
size: i64,
y: i64,
cursor: f64,
@@ -451,7 +452,11 @@ impl NativeTextRun {
fn flush(run: &mut Option<Self>, content: &mut String) {
if let Some(run) = run.take() {
content.push_str(&run.text);
content.push_str("] TJ ET\n");
if run.expansion == 0 {
content.push_str("] TJ ET\n");
} else {
content.push_str("] TJ 100 Tz ET\n");
}
}
}
fn push(&mut self, x: f64, slot: u8, face: &crate::native_font::NativeFont) {
@@ -682,7 +687,7 @@ fn page_content(
}
if let Some(run) = &native_text {
if run.point_size == 0.0
|| !matches!(item,DisplayItem::NativeGlyph{font,size,y,..}if font.id==run.font && *size==run.size && *y==run.y)
|| !matches!(item,DisplayItem::NativeGlyph{font,size,y,..}if font.id==run.font && font.expansion==run.expansion && *size==run.size && *y==run.y)
{
NativeTextRun::flush(&mut native_text, &mut content);
}
@@ -704,14 +709,22 @@ fn page_content(
let run = native_text.get_or_insert_with(|| {
let point_size =
native_font_units(font.size_sp(), 6_578_176, 1_000_000) as f64 / 10_000.0;
let spacing = if font.expansion == 0 {
String::new()
} else {
format!("{} Tz ", crate::pdf_device::print_decimal(
i64::from(1000 + font.expansion), 1,
))
};
NativeTextRun {
font: font.id,
expansion: font.expansion,
size: *size,
y: *y,
cursor: pt(*x).parse().unwrap(),
point_size,
point_size: point_size * f64::from(1000 + font.expansion) / 1000.0,
text: format!(
"BT /N{} {point_size:.4} Tf 1 0 0 1 {} {} Tm [",
"BT /N{} {point_size:.4} Tf {spacing}1 0 0 1 {} {} Tm [",
font.id.index(),
pt(*x),
pt(height - *y)
@@ -1085,6 +1098,7 @@ pub fn display_lists_to_pdf_with_paper(
&PdfMetadata::default(),
None,
None,
None,
&mut Vec::new(),
)
}
@@ -1117,6 +1131,7 @@ pub fn display_lists_to_pdf_with_cm_type1(
&PdfMetadata::default(),
None,
None,
None,
&mut Vec::new(),
)
}
@@ -1218,7 +1233,7 @@ fn native_pdf(
return Err(format!("native font {} has no output encoding for slot {slot}",font.name));
}
if let Some((old_font,old_paint))=fonts.insert(font.id,(font,paint)) {
if old_font != font || old_paint != paint {
if !old_font.same_base(font) || old_paint != paint {
return Err("inconsistent native font snapshots or programs in PDF output".into());
}
}
@@ -1236,6 +1251,24 @@ fn native_pdf(
{
return Err("invalid native PDF final stream compression level".into());
}
let raw_objects = unicode.and_then(|options| options.objects);
let resources = if raw_objects.is_some()
|| pages.iter().any(|page| !page.pdf_resources.entries.is_empty())
{
let (catalog, info) = if raw_objects.is_some() {
(
unicode.and_then(|options| options.catalog).map(|catalog| catalog.entries.as_slice()),
unicode.map(|options| options.info.entries),
)
} else {
(None, None)
};
Some(crate::pdf_device::page_resources::ResourceOutput::prepare(
pages, raw_objects, catalog, info,
)?)
} else {
None
};
let mut diagnostics = Vec::new();
let bytes = write_pdf(
pages,
@@ -1246,6 +1279,7 @@ fn native_pdf(
&PdfMetadata::default(),
final_compression,
unicode,
resources,
&mut diagnostics,
);
Ok(NativePdfDocument { bytes, diagnostics })
@@ -1268,6 +1302,7 @@ pub fn display_lists_to_pdf_with_truetype_and_metadata(
metadata,
None,
None,
None,
&mut Vec::new(),
)
}
@@ -1289,6 +1324,7 @@ pub fn display_lists_to_pdf_with_cm_type1_and_metadata(
metadata,
None,
None,
None,
&mut Vec::new(),
)
}
@@ -1732,6 +1768,7 @@ fn write_pdf(
metadata: &PdfMetadata,
final_compression: Option<i32>,
unicode: Option<crate::pdf_unicode::PdfFinalOptions<'_>>,
resources: Option<crate::pdf_device::page_resources::ResourceOutput>,
diagnostics: &mut Vec<String>,
) -> Vec<u8> {
let width = page_width;
@@ -1794,9 +1831,8 @@ fn write_pdf(
}
(font.clone(), paint.clone(), BTreeMap::new())
});
assert_eq!(
entry.0.as_ref(),
font.as_ref(),
assert!(
entry.0.same_base(font),
"native font ids from different jobs cannot share a PDF"
);
entry.2.insert(*slot, *character);
@@ -1979,6 +2015,7 @@ fn write_pdf(
font_ids[slot] = write_type0_font(&mut objects, face, slot, &used_chars[slot]);
}
let remapped = resources.map(|resources| resources.append(&mut objects));
let mut kids = Vec::new();
let mut page_ids: Vec<usize> = Vec::new();
let mut destinations = BTreeMap::new();
@@ -2005,7 +2042,7 @@ fn write_pdf(
}
}
}
for list in pages {
for (page_index, list) in pages.iter().enumerate() {
let width = if final_compression.is_some() {
list.width
} else {
@@ -2106,14 +2143,21 @@ fn write_pdf(
};
page_ids.push(page_id);
kids.push(format!("{page_id} 0 R"));
objects.push(
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources {resources}{annots} /Contents {content_id} 0 R >>",
physical(width),
physical(height)
)
.into_bytes(),
);
let mut page = format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources ",
physical(width), physical(height),
).into_bytes();
if let Some(additional) = remapped.as_ref().map(|resources| &resources.pages[page_index])
&& !additional.is_empty()
{
page.extend_from_slice(&resources.as_bytes()[..resources.len() - 2]);
page.extend_from_slice(additional);
page.extend_from_slice(b" >>");
} else {
page.extend_from_slice(resources.as_bytes());
}
page.extend_from_slice(format!("{annots} /Contents {content_id} 0 R >>").as_bytes());
objects.push(page);
let mut names = BTreeMap::new();
for (index, slot) in &used {
@@ -2340,9 +2384,11 @@ fn write_pdf(
}
let mut catalog = catalog.into_bytes();
if let Some(extra) = extra {
if !extra.entries.is_empty() {
let entries = remapped.as_ref().and_then(|resources| resources.catalog.as_deref())
.unwrap_or(&extra.entries);
if !entries.is_empty() {
catalog.push(b'\n');
catalog.extend_from_slice(&extra.entries);
catalog.extend_from_slice(entries);
catalog.push(b'\n');
}
if let Some(id) = action {
@@ -2354,7 +2400,11 @@ fn write_pdf(
if let Some(level) = final_compression {
let info = match unicode {
Some(options) => native_information_dictionary(options.info),
Some(options) => native_information_dictionary(crate::pdf_device::PdfInfo {
entries: remapped.as_ref().and_then(|resources| resources.info.as_deref())
.unwrap_or(options.info.entries),
date: options.info.date,
}),
None => metadata_object(metadata)
.map(String::into_bytes)
.unwrap_or_else(|| b"<< /Producer (texrra Route-D native) >>".to_vec()),
+3
View File
@@ -82,3 +82,6 @@ pub(crate) use graphics::Affine;
pub use graphics::{PdfGraphics, PdfMatrix};
pub mod catalog;
pub mod links;
#[doc(hidden)]
pub mod page_resources;
+13 -2
View File
@@ -9,6 +9,7 @@ pub struct PdfColorProgram {
literal: String,
pub(crate) fill: Option<[u8; 3]>,
pub(crate) stroke: Option<[u8; 3]>,
pub(crate) graphics_states: Vec<Vec<u8>>,
}
impl PdfColorProgram {
@@ -16,8 +17,16 @@ impl PdfColorProgram {
let mut fill = None;
let mut stroke = None;
let mut operands = Vec::with_capacity(4);
let mut graphics_states = Vec::new();
let mut name = None;
for token in literal.split_ascii_whitespace() {
if matches!(token, "g" | "G" | "rg" | "RG" | "k" | "K") {
if token == "gs" && operands.is_empty() {
graphics_states.push(name.take().ok_or("PDF gs requires a resource name")?);
} else if name.is_some() {
return Err("PDF resource name must be followed by gs".into());
} else if token.starts_with('/') && operands.is_empty() {
name = Some(super::page_resources::parse_name(token.as_bytes())?);
} else if matches!(token, "g" | "G" | "rg" | "RG" | "k" | "K") {
let rgb = match (token, operands.as_slice()) {
("g" | "G", [gray]) => [*gray; 3],
("rg" | "RG", [r, g, b]) => [*r, *g, *b],
@@ -53,13 +62,14 @@ impl PdfColorProgram {
operands.push(number.clamp(0.0, 1.0));
}
}
if !operands.is_empty() {
if !operands.is_empty() || name.is_some() {
return Err("PDF color program ends with unconsumed operands".into());
}
Ok(Self {
literal,
fill,
stroke,
graphics_states,
})
}
@@ -108,6 +118,7 @@ impl Default for PdfColorStacks {
literal: "0 g 0 G".into(),
fill: Some([0; 3]),
stroke: Some([0; 3]),
graphics_states: Vec::new(),
}),
saved: Vec::new(),
}])
@@ -0,0 +1,422 @@
//! Native PDF objects and extra resources captured at page shipout.
use lopdf::{
Dictionary, Object, Stream,
content::{Content, Operation},
};
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, BTreeSet},
sync::Arc,
};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) enum ObjectBody {
Direct(Vec<u8>),
Stream { attributes: Vec<u8>, bytes: Vec<u8> },
}
impl ObjectBody {
fn len(&self) -> usize {
match self {
Self::Direct(bytes) => bytes.len(),
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
}
}
fn parse(&self) -> Result<Object, String> {
match self {
Self::Direct(bytes) => parse_value(bytes),
Self::Stream { attributes, bytes } => {
let mut dictionary = parse_entries(attributes)?;
if dictionary.has(b"Length") {
return Err("native PDF stream attributes supply their own Length".into());
}
dictionary.set("Length", bytes.len() as i64);
Ok(Object::Stream(Stream::new(dictionary, bytes.clone())))
}
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct PdfObjects {
values: Vec<Option<Arc<ObjectBody>>>,
written: BTreeSet<u32>,
last: i32,
bytes: usize,
}
impl PdfObjects {
pub(crate) fn last(&self) -> i32 {
self.last
}
pub(crate) fn contains(&self, number: u32) -> bool {
number > 0 && number as usize <= self.values.len()
}
pub(crate) fn is_reserved(&self, number: u32) -> bool {
self.contains(number) && self.values[number as usize - 1].is_none()
}
pub(crate) fn reserve(&mut self, limit: usize) -> Result<u32, String> {
if self.values.len() >= limit.min(i32::MAX as usize) {
return Err("native PDF object capacity exceeded".into());
}
self.values.push(None);
self.last = self.values.len() as i32;
Ok(self.last as u32)
}
pub(crate) fn define(
&mut self,
requested: Option<u32>,
value: ObjectBody,
limit: usize,
) -> Result<u32, String> {
let bytes = self.bytes.saturating_add(value.len());
if bytes > limit {
return Err("native PDF object payload capacity exceeded".into());
}
let number = match requested {
Some(number) if self.is_reserved(number) => number,
Some(_) => return Err("native PDF object was already defined".into()),
None => self.reserve(limit)?,
};
self.values[number as usize - 1] = Some(Arc::new(value));
self.bytes = bytes;
self.last = number as i32;
Ok(number)
}
pub(crate) fn write(&mut self, number: u32) -> Result<(), String> {
self.body(number)?;
self.written.insert(number);
Ok(())
}
fn written_body(&self, number: u32) -> Result<&ObjectBody, String> {
if !self.written.contains(&number) {
return Err(format!(
"PDF reference uses object {number} before it was written"
));
}
self.body(number)
}
fn body(&self, number: u32) -> Result<&ObjectBody, String> {
number
.checked_sub(1)
.and_then(|index| self.values.get(index as usize))
.and_then(Option::as_deref)
.ok_or_else(|| format!("undefined native PDF object {number}"))
}
}
fn check_pdf_nesting(bytes: &[u8]) -> Result<(), String> {
let mut input = bytes.iter().copied().peekable();
let mut depth = 0usize;
let mut literal = 0usize;
let mut hexadecimal = false;
while let Some(byte) = input.next() {
if literal != 0 {
match byte {
b'\\' => {
input.next();
}
b'(' => literal += 1,
b')' => literal -= 1,
_ => {}
}
} else if hexadecimal {
hexadecimal = byte != b'>';
} else {
match byte {
b'%' => while input.next().is_some_and(|c| !matches!(c, b'\n' | b'\r')) {},
b'(' => literal = 1,
b'<' if input.next_if_eq(&b'<').is_some() => depth += 1,
b'<' => hexadecimal = true,
b'>' if input.next_if_eq(&b'>').is_some() => depth = depth.saturating_sub(1),
b'[' => depth += 1,
b']' => depth = depth.saturating_sub(1),
_ => {}
}
}
if depth.saturating_add(literal) > 64 {
return Err("native PDF object nesting limit exceeded".into());
}
}
Ok(())
}
fn parse_value(bytes: &[u8]) -> Result<Object, String> {
check_pdf_nesting(bytes)?;
// The content parser accepts complete PDF arrays, including references
// inside them. Requiring the final operator also rejects a partially
// parsed object or extra syntax after the value.
let mut wrapped = b"[ ".to_vec();
wrapped.extend_from_slice(bytes);
wrapped.extend_from_slice(b"\n] EndValue");
let Content { operations } =
Content::decode(&wrapped).map_err(|_| "invalid native PDF object syntax")?;
if let [operation] = operations.as_slice()
&& operation.operator == "EndValue"
&& let [Object::Array(values)] = operation.operands.as_slice()
&& let [value] = values.as_slice()
{
return Ok(value.clone());
}
Err("expected one native PDF object value".into())
}
pub(crate) fn parse_name(bytes: &[u8]) -> Result<Vec<u8>, String> {
match parse_value(bytes)? {
Object::Name(name) => Ok(name),
_ => Err("expected a PDF resource name".into()),
}
}
fn parse_entries(bytes: &[u8]) -> Result<Dictionary, String> {
let mut wrapped = b"<< ".to_vec();
wrapped.extend_from_slice(bytes);
wrapped.extend_from_slice(b"\n>>");
match parse_value(&wrapped)? {
Object::Dictionary(dictionary) => Ok(dictionary),
_ => Err("invalid native PDF resource dictionary".into()),
}
}
fn encode_value(object: Object) -> Result<Vec<u8>, String> {
if let Object::Stream(stream) = object {
let mut output = encode_value(Object::Dictionary(stream.dict))?;
output.extend_from_slice(b"\nstream\n");
output.extend_from_slice(&stream.content);
output.extend_from_slice(b"\nendstream");
return Ok(output);
}
let mut bytes = Content {
operations: [Operation::new("", vec![object])],
}
.encode()
.map_err(|error| format!("cannot encode native PDF object: {error}"))?;
bytes.truncate(bytes.len() - 2);
Ok(bytes)
}
/// Referenced names affect SVG painting only when they are used by the page.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PageResources {
pub(crate) entries: Arc<[u8]>,
pub(crate) opacity: BTreeMap<Vec<u8>, Transparency>,
pub(crate) needs_pdf_for_preview: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Transparency {
pub fill: Option<String>,
pub stroke: Option<String>,
}
fn resolve_dictionary(entry: Object, objects: &PdfObjects) -> Result<Dictionary, String> {
let mut entry = entry;
let mut seen = BTreeSet::new();
loop {
match entry {
Object::Dictionary(dictionary) => return Ok(dictionary),
Object::Reference((number, 0)) if seen.insert(number) => {
entry = objects.written_body(number)?.parse()?;
}
_ => return Err("PDF resource must refer to a dictionary".into()),
}
}
}
fn alpha(dictionary: &Dictionary, key: &[u8]) -> Result<Option<String>, String> {
let Ok(value) = dictionary.get(key) else {
return Ok(None);
};
let n = match value {
Object::Integer(n) => *n as f64,
Object::Real(n) => *n,
_ => return Err("PDF alpha must be numeric".into()),
};
if !(0.0..=1.0).contains(&n) {
return Err("PDF alpha must be between zero and one".into());
}
Ok(Some(n.to_string()))
}
impl PageResources {
pub(crate) fn from_page(
bytes: Arc<[u8]>,
names: &BTreeSet<Vec<u8>>,
objects: &PdfObjects,
) -> Result<Self, String> {
if names.is_empty() {
return Ok(Self {
entries: bytes,
..Self::default()
});
}
let entries = parse_entries(&bytes)?;
let definitions = entries
.get(b"ExtGState")
.map_err(|_| "PDF graphics state used without an ExtGState resource")?;
let definitions = resolve_dictionary(definitions.clone(), objects)?;
let mut resources = Self {
entries: bytes,
..Self::default()
};
for name in names {
let definition = definitions.get(name).map_err(|_| {
format!(
"undefined PDF graphics state /{}",
String::from_utf8_lossy(name)
)
})?;
let attributes = resolve_dictionary(definition.clone(), objects)?;
resources.needs_pdf_for_preview |= attributes.iter().any(|(key, value)| {
!matches!(key.as_slice(), b"Type" | b"ca" | b"CA")
&& !(key == b"BM" && value.as_name().is_ok_and(|name| name == b"Normal"))
});
resources.opacity.insert(
name.clone(),
Transparency {
fill: alpha(&attributes, b"ca")?,
stroke: alpha(&attributes, b"CA")?,
},
);
}
Ok(resources)
}
}
/// Validated values prior to choosing the exporter's physical object numbers.
pub(crate) struct ResourceOutput {
values: BTreeMap<u32, Object>,
page_entries: Vec<Dictionary>,
catalog: Option<Dictionary>,
info: Option<Dictionary>,
}
pub(crate) struct RemappedResources {
pub pages: Vec<Vec<u8>>,
pub catalog: Option<Vec<u8>>,
pub info: Option<Vec<u8>>,
}
impl ResourceOutput {
pub(crate) fn prepare(
pages: &[crate::render::DisplayList],
objects: Option<&PdfObjects>,
catalog: Option<&[u8]>,
info: Option<&[u8]>,
) -> Result<Self, String> {
let empty = PdfObjects::default();
let objects = objects.unwrap_or(&empty);
let page_entries = pages
.iter()
.map(|page| {
let entries = parse_entries(&page.pdf_resources.entries)?;
if entries.has(b"Font") || entries.has(b"XObject") {
return Err(
"additional PDF resources overlap generated Font or XObject entries".into(),
);
}
Ok(entries)
})
.collect::<Result<Vec<_>, String>>()?;
let catalog = catalog.map(parse_entries).transpose()?;
let info = info.map(parse_entries).transpose()?;
let mut pending = objects.written.clone();
for dictionary in page_entries.iter().chain(catalog.iter()).chain(info.iter()) {
for (_, entry) in dictionary.iter() {
references(entry, &mut pending)?;
}
}
let mut values = BTreeMap::new();
while let Some(number) = pending.pop_first() {
if values.contains_key(&number) {
continue;
}
let value = objects.written_body(number)?.parse()?;
references(&value, &mut pending)?;
values.insert(number, value);
}
Ok(Self {
values,
page_entries,
catalog,
info,
})
}
pub(crate) fn append(self, output: &mut Vec<Vec<u8>>) -> RemappedResources {
let ids: BTreeMap<_, _> = self
.values
.keys()
.copied()
.enumerate()
.map(|(i, number)| (number, (output.len() + i + 1) as u32))
.collect();
for (_, mut object) in self.values {
remap(&mut object, &ids);
output.push(encode_value(object).expect("valid PDF object in memory"));
}
let encode = |dictionary: Dictionary| {
if dictionary.is_empty() {
return Vec::new();
}
let mut object = Object::Dictionary(dictionary);
remap(&mut object, &ids);
let bytes = encode_value(object).expect("valid PDF resource dictionary in memory");
bytes[2..bytes.len() - 2].to_vec()
};
RemappedResources {
pages: self.page_entries.into_iter().map(&encode).collect(),
catalog: self.catalog.map(&encode),
info: self.info.map(encode),
}
}
}
fn references(object: &Object, pending: &mut BTreeSet<u32>) -> Result<(), String> {
match object {
Object::Reference((number, 0)) if *number > 0 => {
pending.insert(*number);
}
Object::Reference(_) => return Err("unsupported native PDF object generation".into()),
Object::Array(values) => {
for value in values {
references(value, pending)?;
}
}
Object::Dictionary(dictionary) => {
for (_, value) in dictionary.iter() {
references(value, pending)?;
}
}
Object::Stream(stream) => {
for (_, value) in stream.dict.iter() {
references(value, pending)?;
}
}
_ => {}
}
Ok(())
}
fn remap(object: &mut Object, ids: &BTreeMap<u32, u32>) {
match object {
Object::Reference((number, _)) => *number = ids[number],
Object::Array(values) => values.iter_mut().for_each(|value| remap(value, ids)),
Object::Dictionary(dictionary) => dictionary
.iter_mut()
.for_each(|(_, value)| remap(value, ids)),
Object::Stream(stream) => stream
.dict
.iter_mut()
.for_each(|(_, value)| remap(value, ids)),
_ => {}
}
}
+25 -2
View File
@@ -7,6 +7,7 @@ use crate::{
pub(super) struct NativeText {
font: Option<FontId>,
effective_size: i64,
expansion: i32,
v: i64,
start_h: i64,
delta_h: i64,
@@ -30,6 +31,7 @@ impl NativeText {
Self {
font: None,
effective_size: 0,
expansion: 0,
v: height,
start_h: 0,
delta_h: 0,
@@ -47,8 +49,21 @@ impl NativeText {
print_decimal(number, 4)
));
}
if state.expansion != font.expansion {
state.close_string(out);
state.expansion = font.expansion;
out.push_str(&format!(
"{} Tz\n",
print_decimal(i64::from(1000 + font.expansion), 1)
));
}
let horizontal_size = if font.expansion == 0 {
state.effective_size
} else {
crate::pdf_device::magnify(state.effective_size, 1000 + font.expansion)
};
let (mut shift, shift_out) =
divide_scaled(x - state.start_h - state.delta_h, state.effective_size, 3);
divide_scaled(x - state.start_h - state.delta_h, horizontal_size, 3);
let minimum = divide_scaled(6_578_176, 10i64.pow(u32::from(digits) + 2), 0).0;
let (v, v_out) = if (state.v - y).abs() >= minimum {
divide_scaled(state.v - y, 6_578_176, digits + 2)
@@ -77,7 +92,7 @@ impl NativeText {
state.delta_h += shift_out;
}
out.push_str(&format!("<{slot:02X}>"));
state.delta_h += match &paint.program {
let advance = match &paint.program {
crate::native_font::NativeFontProgram::Pk(pk) => pk.advances[&slot],
crate::native_font::NativeFontProgram::Type1(_) => {
divide_scaled(
@@ -88,6 +103,11 @@ impl NativeText {
.1
}
};
state.delta_h += if font.expansion == 0 {
advance
} else {
crate::pdf_device::magnify(advance, 1000 + font.expansion)
};
}
fn close_string(&mut self, out: &mut String) {
if self.opened {
@@ -98,6 +118,9 @@ impl NativeText {
pub(super) fn finish(text: &mut Option<Self>, out: &mut String) {
if let Some(mut text) = text.take() {
text.close_string(out);
if text.expansion != 0 {
out.push_str("100 Tz\n");
}
out.push_str("ET\n");
}
}
@@ -129,6 +129,7 @@ pub struct PdfFinalOptions<'a> {
pub generate_unicode: i32,
pub glyph_unicode: &'a GlyphUnicodeMap,
pub catalog: Option<&'a crate::pdf_device::catalog::PdfCatalog>,
pub objects: Option<&'a crate::pdf_device::page_resources::PdfObjects>,
pub info: crate::pdf_device::PdfInfo<'a>,
}
+90 -17
View File
@@ -135,6 +135,7 @@ pub enum DisplayItem {
struct NativeSvgGlyph<'a> {
position: [i64; 2],
size: i64,
expansion: i32,
slot: u8,
font: &'a str,
glyph: &'a str,
@@ -173,6 +174,7 @@ impl DisplayItem {
Ok(NativeSvgGlyph {
position: [*x, *y],
size: *size,
expansion: font.expansion,
slot: *slot,
font: paint.program.name(),
glyph: &paint.encoding[usize::from(*slot)],
@@ -245,6 +247,7 @@ pub struct DisplayList {
pub units: DisplayUnits,
pub pdf: Option<crate::pdf_device::PdfPageData>,
pub pdf_links: crate::pdf_device::links::PageLinks,
pub pdf_resources: crate::pdf_device::page_resources::PageResources,
}
impl Default for DisplayList {
fn default() -> Self {
@@ -258,6 +261,35 @@ impl Default for DisplayList {
units: DisplayUnits::PostScript,
pdf: None,
pdf_links: Default::default(),
pdf_resources: Default::default(),
}
}
}
#[derive(Clone, Default)]
struct SvgTransparency {
fill: String,
stroke: String,
rule_stroke: String,
image: String,
}
impl SvgTransparency {
fn apply(&mut self, transparency: &crate::pdf_device::page_resources::Transparency) {
let attribute = |name, alpha: &str| {
if alpha == "1" {
String::new()
} else {
format!(" {name}=\"{alpha}\"")
}
};
if let Some(alpha) = &transparency.fill {
self.fill = attribute("fill-opacity", alpha);
self.image = attribute("opacity", alpha);
}
if let Some(alpha) = &transparency.stroke {
self.stroke = attribute("stroke-opacity", alpha);
self.rule_stroke = attribute("fill-opacity", alpha);
}
}
}
@@ -265,9 +297,11 @@ impl Default for DisplayList {
impl DisplayList {
/// Whether this page needs the complete PDF device output for SVG preview.
pub fn has_embedded_pdf(&self) -> bool {
self.items
.iter()
.any(|item| matches!(item, DisplayItem::PdfImage { .. }))
self.pdf_resources.needs_pdf_for_preview
|| self
.items
.iter()
.any(|item| matches!(item, DisplayItem::PdfImage { .. }))
}
/// Compare the inputs consumed by SVG rendering. Font data for glyphs not
@@ -278,6 +312,8 @@ impl DisplayList {
&& self.units == other.units
&& self.magnification == other.magnification
&& self.images == other.images
&& self.pdf_resources.opacity == other.pdf_resources.opacity
&& self.pdf_resources.needs_pdf_for_preview == other.pdf_resources.needs_pdf_for_preview
&& self.items.len() == other.items.len()
&& self.items.iter().zip(&other.items).all(|(left, right)| {
match (left.native_svg_glyph(), right.native_svg_glyph()) {
@@ -355,9 +391,17 @@ impl DisplayList {
if !(1..=32768).contains(&self.magnification) {
return Err("invalid display-list magnification".into());
}
if self.has_embedded_pdf() {
return Err("this page requires a PDF renderer".into());
}
for item in &self.items {
if matches!(item, DisplayItem::PdfImage { .. }) {
return Err("embedded PDF page requires a PDF renderer".into());
if let DisplayItem::PdfColor(program) = item
&& program
.graphics_states
.iter()
.any(|name| !self.pdf_resources.opacity.contains_key(name))
{
return Err("unresolved PDF graphics state in SVG page".into());
}
if let Some(glyph) = item.native_svg_glyph() {
glyph?;
@@ -403,14 +447,18 @@ impl DisplayList {
let mut fill = [0u8, 0, 0];
let mut rule_fill = [0u8; 3];
let mut stroke = [0u8; 3];
let mut transparency = SvgTransparency::default();
let mut graphics = Vec::new();
let mut open_transforms = 0;
for item in &self.items {
let fill_opacity = &transparency.fill;
let stroke_opacity = &transparency.stroke;
match item {
DisplayItem::NativeGlyph { .. } => {
let NativeSvgGlyph {
position: [x, y],
size,
expansion,
slot,
font,
glyph,
@@ -423,12 +471,17 @@ impl DisplayList {
let x = x as f64 / 65_536.0;
let y = y as f64 / 65_536.0;
let scale = size as f64 / 65_536_000.0;
let horizontal_scale = if expansion == 0 {
scale
} else {
scale * f64::from(1000 + expansion) / 1000.0
};
let label = if type1 {
crate::type1::glyph_unicode_text(glyph).unwrap_or_default()
} else {
String::new()
};
out.push_str(&format!("<g data-font=\"{}\" data-glyph=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><path d=\"{}\" transform=\"translate({x:.5} {y:.5}) scale({scale:.8} -{scale:.8})\" fill=\"#{:02x}{:02x}{:02x}\"/></g>\n", escape(font), escape(glyph), escape(&label), path, fill[0],fill[1],fill[2]));
out.push_str(&format!("<g data-font=\"{}\" data-glyph=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><path d=\"{}\" transform=\"translate({x:.5} {y:.5}) scale({horizontal_scale:.8} -{scale:.8})\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}/></g>\n", escape(font), escape(glyph), escape(&label), path, fill[0],fill[1],fill[2]));
}
DisplayItem::MathGlyph {
x,
@@ -442,7 +495,7 @@ impl DisplayList {
let y = *y as f64 / 65_536.0;
let scale = *size as f64 / 65_536_000.0;
out.push_str(&format!(
"<g data-font=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><use href=\"#math-{}-{slot}\" transform=\"translate({x:.5} {y:.5}) scale({scale:.8} -{scale:.8})\" fill=\"#{:02x}{:02x}{:02x}\"/><text x=\"{x:.5}\" y=\"{y:.5}\" opacity=\"0\" aria-hidden=\"true\">{}</text></g>\n",
"<g data-font=\"{}\" data-slot=\"{slot}\" aria-label=\"{}\"><use href=\"#math-{}-{slot}\" transform=\"translate({x:.5} {y:.5}) scale({scale:.8} -{scale:.8})\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}/><text x=\"{x:.5}\" y=\"{y:.5}\" opacity=\"0\" aria-hidden=\"true\">{}</text></g>\n",
face.name(), escape(&character.to_string()), face.0,
fill[0], fill[1], fill[2], escape(&character.to_string())
));
@@ -507,7 +560,7 @@ impl DisplayList {
format!(" fill=\"#{:02x}{:02x}{:02x}\"", fill[0], fill[1], fill[2])
};
out.push_str(&format!(
"<text x=\"{x:.3}\" y=\"{y:.3}\" font-size=\"{size:.3}\" font-family=\"{family}\"{weight}{style}{fill_attr}>{}</text>\n",
"<text x=\"{x:.3}\" y=\"{y:.3}\" font-size=\"{size:.3}\" font-family=\"{family}\"{weight}{style}{fill_attr}{fill_opacity}>{}</text>\n",
escape(text)
));
}
@@ -519,7 +572,7 @@ impl DisplayList {
color,
} => {
out.push_str(&format!(
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"#{:02x}{:02x}{:02x}\"/>\n",
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}/>\n",
*x as f64 / 65_536.0,
*y as f64 / 65_536.0,
*width as f64 / 65_536.0,
@@ -539,14 +592,21 @@ impl DisplayList {
let y = *y as f64 / 65_536.0;
let width = *width as f64 / 65_536.0;
let height = *height as f64 / 65_536.0;
let color = if rule_fill == [0; 3] {
let stroked = self.units == DisplayUnits::TeX
&& (height <= 65_782.0 / 65_536.0 || width <= 65_782.0 / 65_536.0);
let (rgb, rule_alpha) = if stroked {
(stroke, &transparency.rule_stroke)
} else {
(rule_fill, fill_opacity)
};
let color = if rgb == [0; 3] {
"black".to_owned()
} else {
let [r, g, b] = rule_fill;
let [r, g, b] = rgb;
format!("#{r:02x}{g:02x}{b:02x}")
};
out.push_str(&format!(
"<rect x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" fill=\"{color}\"/>\n"
"<rect x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" fill=\"{color}\"{rule_alpha}/>\n"
));
}
// Link annotations are PDF metadata; the SVG preview omits them.
@@ -559,7 +619,7 @@ impl DisplayList {
thickness,
} => {
out.push_str(&format!(
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"none\" stroke=\"#{:02x}{:02x}{:02x}\" stroke-width=\"{:.3}\"/>\n",
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"none\" stroke=\"#{:02x}{:02x}{:02x}\" stroke-width=\"{:.3}\"{stroke_opacity}/>\n",
*x as f64 / 65_536.0,
(*y - *height) as f64 / 65_536.0,
*width as f64 / 65_536.0,
@@ -586,12 +646,21 @@ impl DisplayList {
if let Some(rgb) = program.stroke {
stroke = rgb;
}
for name in &program.graphics_states {
transparency.apply(&self.pdf_resources.opacity[name]);
}
}
DisplayItem::PdfGraphics { x, y, operation } => {
use crate::pdf_device::PdfGraphics;
match operation {
PdfGraphics::Save => {
graphics.push((open_transforms, fill, rule_fill, stroke));
graphics.push((
open_transforms,
fill,
rule_fill,
stroke,
transparency.clone(),
));
}
PdfGraphics::Matrix(matrix) => {
let [a, b, c, d, e, f] = matrix
@@ -603,12 +672,15 @@ impl DisplayList {
open_transforms += 1;
}
PdfGraphics::Restore { shift: [dx, dy] } => {
if let Some((depth, old_fill, old_rule, old_stroke)) = graphics.pop() {
if let Some((depth, old_fill, old_rule, old_stroke, old_alpha)) =
graphics.pop()
{
for _ in depth..open_transforms {
out.push_str("</g>\n");
}
(open_transforms, fill, rule_fill, stroke) =
(depth, old_fill, old_rule, old_stroke);
transparency = old_alpha;
}
if *dx != 0 || *dy != 0 {
let dx = *dx as f64 / 65_536.0;
@@ -633,7 +705,7 @@ impl DisplayList {
let width = *width as f64 / 65_536.0;
let [r, g, b] = stroke;
out.push_str(&format!(
"<line x1=\"{x1:.3}\" y1=\"{y1:.3}\" x2=\"{x2:.3}\" y2=\"{y2:.3}\" stroke=\"#{r:02x}{g:02x}{b:02x}\" stroke-width=\"{width:.3}\"/>\n"
"<line x1=\"{x1:.3}\" y1=\"{y1:.3}\" x2=\"{x2:.3}\" y2=\"{y2:.3}\" stroke=\"#{r:02x}{g:02x}{b:02x}\" stroke-width=\"{width:.3}\"{stroke_opacity}/>\n"
));
}
DisplayItem::PdfImage { .. } => unreachable!("checked before SVG export"),
@@ -653,8 +725,9 @@ impl DisplayList {
&& image.width as u64 * image.height as u64 <= 4_000_000
{
let uri = png_data_uri(image);
let image_opacity = &transparency.image;
out.push_str(&format!(
"<image x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" href=\"{uri}\"/>\n"
"<image x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" href=\"{uri}\"{image_opacity}/>\n"
));
} else {
out.push_str(&format!(
@@ -109,10 +109,7 @@ impl ProjectSnapshot {
revision: u64,
edits: BTreeMap<PathBuf, Arc<[u8]>>,
) -> Result<Arc<Self>, String> {
self.validate()?;
let mut next = self.clone();
next.version.revision = revision;
next.validated = OnceLock::new();
let mut next = self.next_revision(revision)?;
for (path, data) in edits {
let previous = next.files.get_mut(&path).ok_or_else(|| {
format!("atomic edit requires an immutable file: {}", path.display())
@@ -124,6 +121,44 @@ impl ProjectSnapshot {
next.seal()
}
/// Set or remove immutable files in a single revision. New files require
/// a declared parent directory. Replacing a file preserves its captured
/// modification time, and removing a file discards it.
pub fn with_file_changes(
&self,
revision: u64,
changes: BTreeMap<PathBuf, Option<Arc<[u8]>>>,
) -> Result<Arc<Self>, String> {
let mut next = self.next_revision(revision)?;
for (path, data) in changes {
if let Some(data) = data {
if !next
.file(&path)
.is_some_and(|previous| Arc::ptr_eq(&previous.data, &data))
{
next.files.insert(path.clone(), Self::capture(path, data));
}
} else {
if next.files.remove(&path).is_none() {
return Err(format!(
"atomic removal requires an immutable file: {}",
path.display()
));
}
next.file_modifications.remove(&path);
}
}
next.seal()
}
fn next_revision(&self, revision: u64) -> Result<Self, String> {
self.validate()?;
let mut next = self.clone();
next.version.revision = revision;
next.validated = OnceLock::new();
Ok(next)
}
fn capture(path: PathBuf, data: Arc<[u8]>) -> SnapshotFile {
SnapshotFile {
version: ResourceVersion {
@@ -161,6 +196,12 @@ impl ProjectSnapshot {
/// Whether both snapshots give lookups the same configuration, names,
/// aliases and roles. The bytes and captured times are separate inputs.
pub fn same_lookup_namespace(&self, next: &Self) -> Result<bool, String> {
Ok(self.same_lookup_configuration(next)? && self.files.keys().eq(next.files.keys()))
}
/// Whether search settings, directories, aliases and generated roles agree.
/// File creation and removal can still change lookup results.
pub fn same_lookup_configuration(&self, next: &Self) -> Result<bool, String> {
self.validate()?;
next.validate()?;
Ok(self.configuration == next.configuration
@@ -168,8 +209,7 @@ impl ProjectSnapshot {
&& self.directories == next.directories
&& self.aliases == next.aliases
&& self.generated_roots == next.generated_roots
&& self.generated == next.generated
&& self.files.keys().eq(next.files.keys()))
&& self.generated == next.generated)
}
pub fn generated(&self) -> impl Iterator<Item = &Path> {
self.generated.iter().map(PathBuf::as_path)
+17 -3
View File
@@ -94,7 +94,12 @@ impl Bounds {
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum PaintKind {
Glyph { font: u32, slot: u8 },
Glyph {
font: u32,
slot: u8,
#[serde(default, skip_serializing_if = "crate::native_font::unexpanded")]
expansion: i32,
},
Rule,
PdfImage { page: usize },
}
@@ -196,6 +201,13 @@ impl SourceMap {
pub fn from_revision(
revision: &RevisionExecution,
pages: &[DisplayList],
) -> Result<Self, String> {
Self::from_revision_checked(revision, pages, true)
}
pub(crate) fn from_revision_checked(
revision: &RevisionExecution,
pages: &[DisplayList],
verify_source_hashes: bool,
) -> Result<Self, String> {
let execution = &revision.execution;
if revision.source_versions.len() != execution.sources.len() {
@@ -208,7 +220,8 @@ impl SourceMap {
.enumerate()
.map(|(id, (file, version))| {
if version.bytes != file.data.len() as u64
|| version.sha256 != format!("{:x}", Sha256::digest(&file.data))
|| (verify_source_hashes
&& version.sha256 != format!("{:x}", Sha256::digest(&file.data)))
{
return Err(format!("source map version mismatch for source {id}"));
}
@@ -333,12 +346,13 @@ impl SourceMap {
PaintKind::Glyph {
font: font.id.index(),
slot: *slot,
expansion: font.expansion,
},
Bounds {
x: *x,
y: y.checked_sub(h)
.ok_or("source map glyph position overflow")?,
width: scale(metrics.width(c))?,
width: scale(font.advance(*slot))?,
height: h
.checked_add(d)
.ok_or("source map glyph height overflow")?,
@@ -1,4 +1,6 @@
//! Actual native box/list displays against independent INITEX diagnostics.
#[path = "support/dvi_shipout.rs"]
mod dvi_shipout;
#[path = "support/font_world.rs"]
mod font_world;
use std::{fs, process::Command};
@@ -301,3 +303,160 @@ fn errmessage_uses_scoped_unexpanded_error_help() {
.unwrap_err();
assert_eq!(error.help, None);
}
#[test]
fn text_accents_preserve_font_metrics_kerns_and_paint_positions() {
let case = directory("text-accent");
let source = r"\catcode123=1 \catcode125=2
\font\regular=cmr10
\font\slanted=cmti10
\font\smaller=cmr7
\regular
\showboxbreadth=99 \showboxdepth=99
\setbox1=\hbox{\regular\accent19 A}
\setbox2=\hbox{\regular\accent19\slanted\char84}
\setbox3=\hbox{\regular\accent19\relax}
\setbox4=\hbox{\regular\accent255 Z}
\setbox5=\hbox{\regular\accent19\let\letter=a\letter}
\setbox6=\hbox{\regular\accent19\count0=731 \smaller\char97\message{ACCENT-ASSIGNMENT:\the\count0}}
\setbox7=\vbox{\hsize=50pt \baselineskip=12pt \parfillskip=0pt plus1fil
\noindent W\hfil\penalty-10000 \accent19 A\par}
\setbox8=\vbox{\hsize=50pt \parfillskip=0pt plus1fil
\everypar{\global\count2=197}\accent19 A\par}
\message{ACCENT-EVERYPAR:\the\count2}
\showbox1 \showbox2 \showbox3 \showbox4 \showbox5 \showbox6 \showbox7 \showbox8
\shipout\vbox{\box1\box2\box3\box4\box5\box6\box7\box8}
\end
";
let log = dvi_shipout::run_reference_with_showboxes(&case, source, 8);
assert!(log.contains("ACCENT-ASSIGNMENT:731"));
assert!(log.contains("ACCENT-EVERYPAR:197"));
let actual = Executor::new(State::initex().with_etex(), Limits::default())
.with_native_pages()
.run(
SourceFile {
name: "text-accent.tex".into(),
data: source.as_bytes().to_vec(),
},
&mut Host::default(),
)
.unwrap_or_else(|error| panic!("{case:?}: {error}"));
assert_eq!(actual.state.count(2), 197);
let lists = reports(&actual);
assert_eq!(lists.len(), 8);
for report in lists {
assert!(
log.contains(&report.text),
"{case:?}\nnative:\n{}\nreference:\n{log}",
report.text
);
}
let pages = dvi_shipout::compare_shipouts(&case, &actual)
.unwrap_or_else(|error| panic!("{case:?}: {error}"));
assert_eq!(pages.len(), 1);
assert_eq!(pages[0]["glyphs"].as_u64(), Some(15));
assert!(pages[0]["max_coordinate_error_sp"].as_i64().unwrap() <= 1);
}
#[test]
fn margin_protrusion_uses_font_slots_in_break_search_and_shipout() {
let case = directory("margin-protrusion");
let source = r"\catcode123=1 \catcode125=2
\font\roman=cmr10 \roman
\hsize=38pt \baselineskip=12pt \parskip=0pt
\parfillskip=0pt plus 1fil
\rightskip=0pt plus 1fil
\pretolerance=100 \tolerance=200
\linepenalty=10
\showboxbreadth=99 \showboxdepth=99
\begingroup \lpcode\roman65=120 \endgroup
\message{GROUP-CODE:\the\lpcode\roman65}
\lpcode\roman65=100 \rpcode\roman46=500
\message{LEFT-CODE:\the\lpcode\roman65}
\message{RIGHT-CODE:\the\rpcode\roman46}
\setbox0=\vbox{\pdfprotrudechars=0 \noindent AA. AA.\par}
\setbox1=\vbox{\pdfprotrudechars=1 \noindent AA. AA.\par}
\setbox2=\vbox{\pdfprotrudechars=2 \noindent AA. AA.\par}
\setbox3=\vbox{\pdfprotrudechars=1 \noindent\hbox{A}A.\par}
\lpcode\roman65=-100 \rpcode\roman46=-125
\setbox4=\vbox{\pdfprotrudechars=1 \noindent AA.\par}
\pdfprotrudechars=1 \lpcode\roman65=100 \rpcode\roman46=500
\setbox7=\vbox{\noindent AA.\par\global\setbox8=\lastbox}
\setbox5=\hbox{\unhcopy8\unskip\unskip\message{COPIED-TAIL:\the\lastnodetype,\the\lastkern}}
\setbox6=\hbox{\unhbox8\unskip\unskip\message{MOVED-TAIL:\the\lastnodetype,\the\lastkern}}
\showbox0 \showbox1 \showbox2 \showbox3 \showbox4 \showbox5 \showbox6
\shipout\vbox{\box0\kern3pt\box1\kern3pt\box2\kern3pt\box3\kern3pt\box4\kern3pt\box5\kern3pt\box6}
\end
";
let log = dvi_shipout::run_reference_with_showboxes(&case, source, 7);
assert!(log.contains("GROUP-CODE:120 LEFT-CODE:100 RIGHT-CODE:500"));
for marker in ["COPIED-TAIL:13,0.0pt", "MOVED-TAIL:13,0.0pt"] {
assert!(log.contains(marker));
}
let actual = Executor::new(State::initex().with_etex(), Limits::default())
.with_native_pages()
.run(
SourceFile {
name: "margin-protrusion.tex".into(),
data: source.as_bytes().to_vec(),
},
&mut Host::default(),
)
.unwrap_or_else(|error| panic!("{case:?}: {error}"));
let lists = reports(&actual);
assert_eq!(lists.len(), 7);
for (report, line_count) in lists.into_iter().zip([2, 2, 1, 1, 1, 0, 0]) {
assert!(log.contains(&report.text), "{case:?}\nnative:\n{}\nreference:\n{log}", report.text);
assert_eq!(
report.text.lines().filter(|line| line.starts_with(r".\hbox(")).count(),
line_count,
);
}
let page = dvi_shipout::compare_shipout(&case, actual)
.unwrap_or_else(|error| panic!("{case:?}: {error}"));
assert_eq!(page["glyphs"].as_u64(), Some(30));
assert!(page["max_coordinate_error_sp"].as_i64().unwrap() <= 1);
}
#[test]
fn font_expansion_codes_invalidate_cached_break_geometry() {
let source = r"\catcode123=1 \catcode125=2
\font\roman=cmr10 \roman
\pdfoutput=1
\pdffontexpand\roman 100 100 10 autoexpand
\hsize=30pt \parfillskip=0pt plus1fil \rightskip=0pt plus1fil
\pretolerance=100 \tolerance=200 \linepenalty=10 \baselineskip=12pt
\showboxbreadth=99 \showboxdepth=99
\setbox0=\vbox{\pdfadjustspacing=1 \noindent AA AA\par}
\setbox1=\vbox{\pdfadjustspacing=2 \noindent AA AA\par}
\setbox2=\vbox{\pdfadjustspacing=2 \noindent AA AA\par}
\begingroup \efcode\roman65=0 \endgroup
\ifnum\efcode\roman65=0\else\errmessage{Expansion codes are global}\fi
\setbox3=\vbox{\pdfadjustspacing=2 \noindent AA AA\par}
\showbox0 \showbox1 \showbox2 \showbox3
\end
";
let cache = std::sync::Arc::new(LineBreakCache::default());
let executed = Executor::new(State::initex().with_etex(), Limits::default())
.with_line_break_cache(cache.clone())
.run(
SourceFile {
name: "font-expansion.tex".into(),
data: source.as_bytes().to_vec(),
},
&mut Host::default(),
)
.unwrap();
let lists = reports(&executed);
assert_eq!(lists.len(), 4);
assert!(cache.work().reused_passes > 0);
for (report, expected_lines) in lists.iter().zip([2, 1, 1, 2]) {
assert_eq!(
report.text.lines().filter(|line| line.starts_with(r".\hbox(")).count(),
expected_lines,
"{}",
report.text
);
assert_eq!(report.text.contains(r"\roman (-100) A"), expected_lines == 1);
}
}
@@ -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"], 27);
assert_eq!(payload["schema"], 34);
let state = State::initex().with_etex();
let loaded = FormatImage::decode(&bytes)
.unwrap()
@@ -0,0 +1,155 @@
#![cfg(all(target_os = "linux", target_env = "gnu"))]
use std::{fs, process::Command};
use texrra_tex_core::execution::*;
const SOURCE: &str = r#"
\catcode123=1 \catcode125=2 \catcode35=6 \catcode94=7
\def\probe#1{\message{!pdfmatch:#1:end!}}
\probe{before=[\pdflastmatch0]}
\def\dimpat{^([0-9]+([.,][0-9]+)?|[.,][0-9]+)(em|ex|cm|mm|in|pc|pt|dd|cc|bp|sp|nd|nc|px)? *$}
\def\value{12.5pt}
\probe{dim=[\pdfmatch{\dimpat}{\value}]/[\pdflastmatch0]/[\pdflastmatch1]/[\pdflastmatch2]/[\pdflastmatch3]}
\probe{dim-fail=[\pdfmatch{\dimpat}{wd0}]/[\pdflastmatch0]}
\probe{longest=[\pdfmatch{(a|ab)}{cab}]/[\pdflastmatch0]/[\pdflastmatch1]}
\probe{leftmost=[\pdfmatch{(a|bcde)}{abcde}]/[\pdflastmatch0]}
\probe{case=[\pdfmatch icase subcount 2{(a)(B)}{xAb}]/[\pdflastmatch0]/[\pdflastmatch1]/[\pdflastmatch2]}
\probe{invalid=[\pdfmatch{[}{x}]/[\pdflastmatch0]/[\pdflastmatch1]}
\probe{zero=[\pdfmatch subcount 0{(a)}{xax}]/[\pdflastmatch0]}
\probe{negative=[\pdfmatch subcount -2{(a)}{xax}]/[\pdflastmatch0]/[\pdflastmatch1]}
\probe{optional=[\pdfmatch{(a)?(b*)}{x}]/[\pdflastmatch0]/[\pdflastmatch1]/[\pdflastmatch2]}
\begingroup \edef\inside{\pdfmatch{(c)}{abc}}\endgroup
\probe{group=[\pdflastmatch0]/[\pdflastmatch1]}
\begingroup\escapechar=-1 \xdef\bs{\string\\}\endgroup
\probe{gnu-backref=[\pdfmatch{^(a)\bs1$}{aa}]/[\pdflastmatch1]}
\probe{gnu-class=[\pdfmatch{^\bs w+$}{a01}]/[\pdflastmatch0]}
\probe{byte-offset=[\pdfmatch{(q)}{^^c3^^a9q}]/[\pdflastmatch1]}
\def\capturedbyte#1->#2{\number`#2}
\edef\status{\pdfmatch{(.)}{^^ffq}}
\edef\capture{\pdflastmatch0}
\probe{nonutf8=[\status]/[\expandafter\capturedbyte\capture]}
\catcode0=12 \catcode10=12
\probe{nul-text=[\pdfmatch{c}{ab^^00cd}]/[\pdflastmatch0]}
\probe{nul-pattern=[\pdfmatch{a^^00b}{xa}]/[\pdflastmatch0]}
\probe{newline=[\pdfmatch{a.b}{a^^0ab}]}
\end
"#;
fn file(source: &str) -> SourceFile {
SourceFile {
name: "probe.tex".into(),
data: source.as_bytes().to_vec(),
}
}
#[test]
fn pdf_regex_matches_reference_bytes_and_retains_job_local_captures() {
let dir = std::env::temp_dir().join(format!("texrra-pdfmatch-{}", std::process::id()));
fs::create_dir(&dir).unwrap();
fs::write(dir.join("probe.tex"), SOURCE).unwrap();
let reference = Command::new("pdftex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
])
.env("LC_ALL", "C")
.env("max_print_line", "1000")
.current_dir(&dir)
.output()
.unwrap();
assert!(
reference.status.success(),
"{}",
String::from_utf8_lossy(&reference.stdout)
);
let log = fs::read(dir.join("probe.log")).unwrap();
let reference: String = log.into_iter().map(char::from).collect();
let expected: Vec<_> = reference
.split("!pdfmatch:")
.skip(1)
.map(|part| part.split_once(":end!").unwrap().0)
.collect();
assert_eq!(expected.len(), 18);
let native = Executor::new(
State::initex()
.with_etex()
.with_input_profile(InputProfile::TeX8Bit),
Limits::default(),
)
.run(file(SOURCE), &mut NoFiles)
.unwrap();
let actual: Vec<_> = native
.events
.iter()
.filter_map(|event| match event {
Event::Message { text, .. } => text.strip_prefix("!pdfmatch:")?.strip_suffix(":end!"),
_ => None,
})
.collect();
assert_eq!(actual, expected);
let fresh = Executor::new(native.state, Limits::default())
.run(file(r"\message{\pdflastmatch0}\end"), &mut NoFiles)
.unwrap();
assert!(
fresh
.events
.iter()
.any(|event| { matches!(event, Event::Message { text, .. } if text == "-1->") })
);
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_negative_capture_index_is_a_scan_error() {
let error = Executor::new(
State::initex()
.with_etex()
.with_input_profile(InputProfile::TeX8Bit),
Limits::default(),
)
.run(
file(r"\catcode123=1 \catcode125=2 \message{\pdflastmatch-1}\end"),
&mut NoFiles,
)
.unwrap_err();
assert!(error.message.contains("Bad match number"));
}
#[test]
fn capture_is_restored_after_editing_the_unread_suffix() {
let initial = r"\catcode123=1 \catcode125=2
\edef\status{\pdfmatch{(ab)}{zab}}
\message{original=[\pdflastmatch1]}
\end";
let edited = initial.replace("original", "edited");
let frontier = initial.find("\n\\message").unwrap();
let state = State::initex()
.with_etex()
.with_input_profile(InputProfile::TeX8Bit);
let (original, captured) = Executor::new(state.clone(), Limits::default()).run_capturing_entry(
file(initial),
&mut NoFiles,
frontier,
|_| (),
);
original.unwrap();
let (checkpoint, ()) = captured.expect("capture after scanning the match");
let resumed = checkpoint
.resume_after_host_replay(file(&edited), &mut NoFiles, Cancellation::default())
.expect("edited suffix is beyond the checkpoint")
.unwrap();
let full = Executor::new(state, Limits::default())
.run(file(&edited), &mut NoFiles)
.unwrap();
assert_eq!(resumed.events, full.events);
assert!(
resumed
.events
.iter()
.any(|event| matches!(event, Event::Message { text, .. } if text == "edited=[1->ab]"))
);
}
@@ -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"], 27);
assert_eq!(original["schema"], 34);
for (schema, expected) in [
(1, "incompatible native format"),
(2, "incompatible native format"),
@@ -363,6 +363,11 @@ fn old_schema_and_missing_unicode_state_are_rejected_even_with_valid_checksums()
(25, "incompatible native format"),
(26, "incompatible native format"),
(27, "glyph_unicode"),
(28, "glyph_unicode"),
(29, "incompatible native format"),
(30, "incompatible native format"),
(31, "glyph_unicode"),
(32, "glyph_unicode"),
] {
let mut payload = original.clone();
payload["schema"] = schema.into();
@@ -150,13 +150,22 @@ fn invalid_quantities_overflows_units_and_readonly_positions_fail() {
for source in [
format!("\\number{}0", "\\count".repeat(130)),
format!("\\number{}0", "\\dimen".repeat(130)),
format!("{}\\relax", "\\expandafter\\relax".repeat(130)),
] {
let error = Executor::default()
.run(file(&source), &mut FontFiles)
.unwrap_err();
assert!(error.message.contains("nesting limit"), "{}", error.message);
}
let chain = "\\expandafter A".repeat(64);
let source = format!("\\message{{CHAIN:{chain}\\number 17}}");
assert_eq!(messages(&run(&source)), [format!("CHAIN:{}17", "A".repeat(64))]);
let limits = Limits { input_depth: 32, ..Limits::default() };
let error = Executor::new(State::default(), limits)
.run(file(&source), &mut FontFiles)
.unwrap_err();
assert!(error.message.contains("input stack limit"), "{}", error.message);
}
struct Files(BTreeMap<String, String>);
@@ -283,6 +283,43 @@ fn generated_input_has_its_own_bytes_version_and_real_parent_origin() {
.starts_with(b"AB")
);
}
#[test]
fn verified_source_versions_require_the_sessions_exact_execution_result() {
let session = NativeSession::default();
let revision = session
.start()
.run(
Executor::new(State::initex(), Limits::default()).with_native_pages(),
SourceFile {
name: "main.tex".into(),
data: br"\catcode123=1 \catcode125=2 \shipout\hbox{\vrule width4pt height1pt}\end"
.to_vec(),
},
&mut NoFiles,
)
.unwrap();
let pages = revision.execution.shipout_display_lists().unwrap();
assert_eq!(
session.source_map(&revision, &pages).unwrap(),
SourceMap::from_revision(&revision, &pages).unwrap(),
);
let mut versions = revision.source_versions.clone();
versions[0].sha256 = "invalid".into();
let copied = Arc::new(RevisionExecution {
revision: revision.revision,
execution: revision.execution.clone(),
source_versions: versions,
execution_resources: None,
});
assert!(
session
.source_map(&copied, &pages)
.unwrap_err()
.contains("version mismatch")
);
}
#[test]
fn malformed_versions_spans_generated_parents_and_paint_indices_are_rejected() {
let source = format!(r"{HEADER}\shipout\hbox{{\scantokens{{A}}}}\end");
@@ -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"], 27);
assert_eq!(payload["schema"], 34);
let executor = FormatImage::decode(&bytes)
.unwrap()
.new_job(
+26 -4
View File
@@ -2,7 +2,28 @@
本文件记录用户重申的最终目标,是短期 goal、实现优先级和验收标准的上位约束。
## 2026-11-19 产品优先级
## 2026-11-20 先实现功能,再统一验收
后续迭代优先补齐 LaTeX 和实时编译功能。实时会话的状态、依赖和布局复用
随内核功能一起接入。按实际差异和共有依赖推进以下工作:
1. 补齐 pdfTeX 通用行为。先实现字宽伸缩的断行、字形前进距离及绘制,
处理 arXiv、ACL 和 NeurIPS 的共同阻塞。接着解决 Elsevier CAS 两款的
宏展开递归边界及 ACM 三类样例的 PDF 颜色程序。
2. 补齐两种兼容 profile 的共有排版和作业能力,包括数学、表格、浮动与
插入、输出例程、图形、引用和文献。完成 XeTeX profile 的真实
Unicode/OpenType 字体选择、shaping、度量和导出,接入原样 XeLaTeX。
3. 接齐实时编译的实际依赖失效、检查点恢复、执行及布局复用、取消和页差量。
关键状态随新增功能进入会话。优先缩短仍重复执行的部分与页面交付耗时,
准备让库、CLI 和编辑器都消费同一内核结果。
日常开发沿用已有的最小对照,只运行定位差异或核对改动结果所需的检查。
功能接齐后冻结同一实现和资源,集中完成原 W0–W7、全工作区回归、
pdfTeX/XeTeX profile 对照及原样出版模板矩阵,覆盖 arXiv、期刊、多个双栏
期刊及多类会议。增量结果逐修订对照独立全量;正式性能按原冻结预算、机型
和样本量验收。通过统一验收后完成产品切换并移除 v1。
## 2026-11-19 产品优先级(历史记录)
产品主体是**面向编辑会话的实时 TeX 编译和渲染内核**。一次实际编辑触发
可追踪的失效和局部更新,返回可见页面、诊断及来源。稳定后的页面、字形、
@@ -25,14 +46,15 @@ Tectonic 的 XeTeX 入口在进程级锁内运行,桥接层能提供输入输
[Tectonic 桥接层](https://github.com/tectonic-typesetting/tectonic/blob/master/crates/bridge_core/src/lib.rs#L271-L288)
原样 A4 在连续子文件编辑中,取消旧作业的浏览器观测 p95 已低于100 ms。
新编辑到可见页面的 p95 仍高于250 ms。接下来分解编译准备、执行复用和页面
交付,继续按固定预算及逐版本全量一致性验收。
当前两轮原样 A4 主文件编辑的可见 p95 为224.0和208.6 ms,仍需达到100 ms
门禁。评估上游执行入口时,分别测量编辑到可见页面、可恢复的状态范围与
全量一致性,并记录完整重新执行的成本作为基线。
[阶段测量与回执](P2_M1_PROGRESS.md)
## 2026-11-11 总目标重新确认
用户明确要求设置并持续执行完整目标:**完整 LaTeX 引擎,加上类 Typst 的实时
编译与渲染能力**。总目标现为 active,持续覆盖下文 P0–P5;P2-M1、单个原语或
编译与渲染能力**。总目标覆盖下文 P0–P5;P2-M1、单个原语或
某个项目通过都不构成总目标完成。
兼容性与实时性同时验收:真实格式/类/包和原样项目迁移;有状态的安全增量执行、
+17
View File
@@ -66,6 +66,23 @@ profile、入口和执行限制仍是显式请求参数。没有单独的编辑
下一步仍需完整I/O效果/物理alias/句柄恢复契约、checkpoint、失效传播、执行/布局
复用和局部页面发布。当前仍为全量执行,不代表完整 LaTeX 或实时性能已经通过。
## 原子文件增删与检查点
`ProjectSnapshot::with_file_changes` 接收一组同版本的绝对逻辑路径,`Some`
提交字节,`None` 删除已存在的不可变文件。新增文件使用已声明的父目录,
由快照校验资源覆盖范围、别名和生成角色。旧快照继续持有原字节。
替换现有文件沿用已捕获的修改时间,删除同时清除对应时间记录。
检查点选择要求查找配置、目录、别名和生成角色仍相同,并核对实际读取的版本。
文件集合变化时,准备新作业后重放前缀,然后逐项核对实际查找记录。这样即使
`\pdffilesize` 返回值相同,候选顺序和最终来源变化也能使检查点失效。
重放发生在原有暂存作业中,失效后按新快照全量执行。
`examples/native_editor` 的 `/preview` 接受 `files` 里的 JSON 字符串和 `null`。
启动参数可以声明当前缺失的可编辑文件,其父目录需在项目下存在。入口文件受保护,
`/project` 返回当前版本存在的可编辑文件。原字符串写入和 `source` 请求继续使用
同一共享编译接口。
## 2026-11-16:真实TeX流效果与清理(阶段未完成)
[流效果契约](NATIVE_STREAM_EFFECTS.md)记录实际顺序、唯一句柄、snapshot/file身份、
+648 -4
View File
@@ -2,8 +2,8 @@
2026-11-02:用户已授权完整执行 [阶段目标](NATIVE_FORMAT_ARTICLE_STAGE.md),
并要求 **G1 的全部退出条件为 W1 必选门禁**。整体状态:**执行中,未完成**。
最近可复现的完整工作区回归为 **1564 tests / 0 failed**,覆盖已推广的公式编号
和 `\mathchoice`。前序显示数学对齐正式验收为 1553/0。P2-M1 总验收仍按原 W0–W7 门槛执行。
最近一次完整工作区回归为 **1628 项通过、零失败**,覆盖来源映射指纹复用。
之后的检查点和文本重音变更使用定向回归及原样项目对照。P2-M1 总验收仍按原 W0–W7 门槛执行。
## 工作包状态
@@ -655,7 +655,12 @@ SHA-256 为 `d2fa1a80f378445e1dccc29378cfc1546d94e823a49f460bffda827ba5790b0d`
回执 `a3-shared/test.log` 与 `a3-manual/test.log` SHA-256 为
`34fd27652fb0afb59deaee5b68c0dcede8bd2d8e38460746031f134d698683f6`、
`f4c65f08d98a2c15544dde3f3bd82cc57f7f139fbd50782541a04e65cc407d03`。
完整工作区和原样模板复验在同一补丁上运行。
同一优化程序已完成14项原样模板复验。原版工具生成14份 PDF,原生生成
5份,成功项的页数、词框和逐轮 aux 与各自前次结果一致。逐项回执见
[出版模板矩阵](PUBLISHER_TEMPLATE_MATRIX.md)。同一补丁的全工作区结果为
1626项通过、零失败,两项标记为单独运行的 A3 已使用优化二进制通过。
`target/p4-alias-scan-identity/workspace.log` 的 SHA-256 为
`127a150974936c12a2545f26ca8c21b9f1c0327416d2b53d807e3ae25af0a0cd`。
为验证可停止的匹配方式,用 GNU 正则子进程独立测量管道往返。6个对照
覆盖最长选择、反向引用、字节位置、大小写、无匹配和模式错误。60次
@@ -663,7 +668,646 @@ SHA-256 为 `d2fa1a80f378445e1dccc29378cfc1546d94e823a49f460bffda827ba5790b0d`
耗时1.360 ms,旧作业未产生匹配答复,随后新的 helper 返回实际匹配。
`target/p3-pdfmatch-worker-probe/receipt.json` 的 SHA-256 为
`492bd9a411e6547b41bf294061e45c8c79567107e4f8d959e92a2843a5cf170a`。
目前只完成独立进程探针,编译会话接线仍待验收。
另将旧候选真实编译 arXiv、ACL 与 NeurIPS 时的165次请求原样重放至
独立进程,三个样稿各55次。匹配状态、每个捕获及其字节位置全部一致。
`target/p3-pdfmatch-worker-probe/publisher/receipt.json` 的 SHA-256 为
`df24011752225937af162b6faa8c6f9bd8a35e609653dd472f50d4004adafc3c`。
隔离候选已用真实原生 CLI 各运行 arXiv、ACL 与 NeurIPS,三个样稿
均实际委托 GNU 子进程处理55次,完整调用记录与旧进程内实现逐字节一致,
继续执行到 `\MT@protrudechars`。真实编辑会话的受控测试中,旧作业在
匹配期间被新编辑取消,收到409响应并回收阻塞子进程,单次观察为89.3 ms。
新版本复用824404 / 904155步并正常发布。PDF、SVG、来源映射和 aux 均与
独立零复用全量一致。3项 pdfTeX 语义与检查点对照通过。
回执见 `target/p3-pdfmatch-cancellable-worker`,`publisher/receipt.json`
和 `editor-cancel-v2/receipt.json` 的 SHA-256 分别为
`4953d4b0d89952f79168011232d0319837228661226d8b6fefebac29e544ea4b`、
`998b6c49c4a5adde83921ae6501a6780d53e27b2756a9282a0f1971870891a37`。
候选需配置 GNU 辅助进程路径。已推送隔离分支
`experiment/cancellable-pdftex-regex` 的 `31bf508`,主线格式版本是27。
### 上游 pdfTeX 的实时预览边界
固定 pdfTeX 1.40.29、原样 A4 和已核对的 LaTeX 格式,用同样的正文
编辑序列分别做30次主文件、30次子文件修改。pdfTeX 每次执行并生成含
SyncTeX 的 PDF,再经 Poppler 生成真实 SVG。逐次核对文本和 aux,最后
一次与独立全量的词框、SVG 和 aux 一致。此轮与旧工作区编译并行,
I/O 压力较高,时延仅保留为有负载的记录。记录没有浏览器时间和
可恢复执行状态,不能作为实时门禁结果。
`target/p4-upstream-preview-boundary/warm-reference/receipt.json` 的
SHA-256 为 `154d1266ab6ea6c8f9be22f783384f57411f0efeea8e9d6c1576c9eebfb8249e`。
采用 TeX Live 发布的 `mylatexformat` 对原样 A4 实际保存导言区并恢复。
源文件字节保持原样,恢复后正文、分文件输入和 SyncTeX 均进入真正的
pdfTeX 作业。相同方法在14份原样项目中有10份成功,共58页。成功项的
灰度页面、字词位置、嵌入字体、项目文件来源和 aux 均与全量一致;
四份的失败位置在[出版模板矩阵](PUBLISHER_TEMPLATE_MATRIX.md)。
[CTAN 的 mylatexformat](https://ctan.org/pkg/mylatexformat)
在专门的导言区依赖样例中,未找到的 `settings.tex` 缺席于 `.fls`。
新增它后,复用旧图像保留旧标签,标准全量得到新标签,重新保存格式后
再次一致。Kpathsea 实际搜索日志能看见同一请求从无结果到相对文件,
需把它与配置、文件版本和效果一起纳入复用检查。回执
`snapshot-missing-dependency/receipt.json` 的 SHA-256 为
`2a0ded450e801191b66a7bd222bd3262180ffa17932e758b8b985a478cc93594`,
原始查找记录在 `negative-lookup-trace`。
[Kpathsea 查找入口](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/kpathsea/tex-file.c#L939-L959)
### A4 配对时延与页面交付
上游标准编译与导言区恢复分别做30次主文件、30次子文件正文编辑。
每次核对真实 PDF 文本、SVG、aux 和项目文件 SyncTeX。复验在浏览器
实验退出后独立运行,记录从提交 pdfTeX 到真实 SVG 生成的台架耗时。
| 编辑文件 | 标准 p50 / p95 (ms) | 恢复 p50 / p95 (ms) |
| --- | ---: | ---: |
| 主文件 | 154.9 / 178.2 | 145.8 / 233.0 |
| 子文件 | 150.5 / 189.9 | 148.2 / 229.3 |
逐版本等价。独立轮 p50 略减,p95 上升。较高 I/O 压力下的首轮得到
不同的 p95 方向。两轮均测量 SVG 就绪时间,覆盖上游执行与输出阶段。
`target/p4-upstream-preview-boundary/paired-a4{,-alone}/receipt.json`
的 SHA-256 分别为
`52d0ca5a24a6cc53b011b7610bff6e23e233b35413c275d5d763d6a081c12f48`、
`1bf495a1bfe54de5a16d9c2993bc3e295808e968b3232745b80ba63319ce0a00`。
另用两套 Edge 会话、同一个优化二进制和原样 A4 做连接选项对照。
每套各30次主文件与30次子文件编辑,逐次核对实际执行/复用步数、
PDF、SVG、来源和最终 aux。实测24个基线 TCP 连接保持 TCP_NODELAY=0,
候选21个 TCP 连接均从0切到1。浏览器请求剩余时延 p50 在主文件
为80.0 → 78.8 ms,子文件为75.1 → 75.0 ms。可见 p95 两类方向不同,
因此现有数据不支持据此改动编辑端传输。回执
`target/p4-http-nodelay/run-1/receipt.json` 的 SHA-256 为
`879cb3ab850209eae3558558011391d9880d281073febe2fff16a934691e9cb3`。
### 原子文件增删和实际查找
在隔离的上游导言区实验中,通过结构化 Kpathsea 调用核对了10个版本。
正文和无关文件变更继续复用。前缀依赖新增、同名高优先级替换、改字节、
删除回退或恢复缺失均触发重建。每版 SVG、aux 和项目内 SyncTeX 与
全量一致。只读范围以外,实际在导言区创建并关闭输出的样例被探针标为
不可复用。上游回执 `target/p4-upstream-lookup-contract/synthetic-session/receipt.json`
的 SHA-256 为 `9232c1558faed10fc7fe8206be990f25ae4fee590bc8f7c045ec41828a6f79f8`。
原生 Route-D 已接入原子文件增删。10次版本对照覆盖未知变已知、查找
优先级、按路径删除后回落、已读字节变化,以及同尺寸文件改变来源。
三次增删无关文件各复用162步并重放6项真实宿主调用。所有版本 PDF、
SVG、来源映射、TeX 执行和 aux 与零复用一致。3项定向检查点测试通过。
日志 `target/p4-checkpoint-file-changes/guard-tests-v2.log` 的 SHA-256 为
`0619f4200c17f8d58f23b84bbad6a18c8fd622730bb45cbe0bbf31dc0b87a252`。
同一优化版编辑端对带真实 LaTeX 格式的 A4 派生项目运行6次文件提交。
无关文件增删各复用589138 / 645020步,页面更新列表为空。新增依赖及
删除后重建触发全量。已有依赖改写和删除分别从依赖读取前的检查点
复用212230步。四次依赖变动均更新第1页。每次 PDF、SVG、归一化
来源映射和真实 aux 与独立零复用版本一致。编辑端还核对了未声明路径、
移除入口和删除不存在文件的拒绝结果。回执
`target/p4-checkpoint-file-changes/editor-run-v2/receipt.json` 的 SHA-256 为
`aeb8f77618438d2272bdd501e618e1969ee682b49035626997cbc343e9b94d8e`。
同一源码的两项原样 A3 单独通过。共享会话两次编辑复用
794348 / 870724步,重放61项宿主调用,各更新第7页。手动重放跳过
770678 / 870728步,重放59项调用,两次编辑的8页、PDF 和 aux 各与
独立全量一致。记录 `target/p4-checkpoint-file-changes/a3/{shared,manual}.log`。
完整工作区1627项通过、零失败,两项标记的真实 A3 已单独通过。
完整日志 `target/p4-checkpoint-file-changes/workspace.log` 的 SHA-256 为
`2078770f89397c8a08a4beedad4ebd6ba9c73cd605ba4f1b8341149605bdea87`。
原样模板参考14份、原生5份。Springer Nature 首次超时后用同一输入重跑
成功,arXiv 和 APS 也通过同日词框对照。
[出版模板矩阵](PUBLISHER_TEMPLATE_MATRIX.md)
原样 A4 两版分别用 Edge 测量30次主文件和30次子文件编辑。每轮
执行与复用步数、页更新、PDF、SVG、来源映射以及最终 aux 一致。
最后版编辑缓冲区在独立会话用同一优化版零复用编译,再次核对输出相同。
| 原样 A4 编辑 | 基线可见 p50 / p95 (ms) | 新版可见 p50 / p95 (ms) |
| --- | ---: | ---: |
| 主文件正文 | 210.6 / 391.7 | 209.9 / 335.4 |
| 子文件正文 | 186.0 / 260.0 | 188.2 / 274.6 |
两类可见 p95 方向不同,100 ms门禁仍待通过。峰值 RSS 为601864与
602268 KiB。浏览器回执 `edge/run-1/receipt.json` 的 SHA-256 为
`98a9a49bc43b18e5b4b45bdae083d8fd1b3e6ee6f27cf40f9e719877de66f7cb`,
独立全量回执 `full-equivalence/receipt.json` 为
`abd248f1f2ba863c4c5e939460c83cae90d94698abd7728c890feea3731288e1`。
均在 `target/p4-checkpoint-file-changes` 下。
[项目快照与编辑接口](NATIVE_PROJECT_INPUTS.md)
### 检查点命令绑定的复制成本
当前原样 A4 的24次主文件热编辑共采集554个进程 CPU 样本。完整状态
指纹及资源内容处理仍占较大比例,主要符号包括55个 SipHash 写入、
48个 SHA-256 压缩块、42个宏替换列表哈希、26个状态统计、24个
`statx`,以及14个命令绑定树复制。采样回执
`target/p4-command-table-live-profile/original-a4/symbolized.json` 的 SHA-256 为
`752873ed167f168240cbcddf6936692266e6818a5dff597375ed23981cee330c`。
隔离候选在检查点共享完整命令绑定树,定义变化时才复制。481项核心
测试通过。两版的 schema 27 小格式文件逐字节相同,能双向加载,且
产出相同的 PDF。固定时钟的原样 A4 派生故障探针从旧实际格式执行
591745步,两版的进出状态指纹完全一致。记录
`target/p4-cow-command-table/wire-equivalence/receipt.json` 的 SHA-256 为
`14ae21c48752680b0d5dca3b6d788d8b3cc36cf5abf26173d0c51349667f55cd`。
同规格的候选 CPU 采样共546个样本,其中16个命令绑定树复制,执行
p50 为60.5 ms,基线为61.1 ms。候选采样回执 SHA-256 为
`8a44ef16a6f72493209f464e1bd63372ded4539456ed65a5504c846cc3e07fd8`。
两轮 Edge 对照交换两版的测量顺序,每版每轮各测30次不同主文件和
30次不同子文件编辑,逐次核对执行与复用步数、页面、PDF、SVG、
来源映射和最终 aux。
| 轮次 | 原样 A4 编辑 | 基线可见 p50 / p95 (ms) | 整表共享可见 p50 / p95 (ms) |
| --- | --- | ---: | ---: |
| 1 | 主文件正文 | 200.4 / 261.7 | 204.4 / 234.3 |
| 1 | 子文件正文 | 184.8 / 237.4 | 186.6 / 221.5 |
| 2 | 主文件正文 | 248.1 / 516.6 | 248.9 / 433.3 |
| 2 | 子文件正文 | 220.7 / 506.2 | 217.4 / 470.0 |
两个最终编辑缓冲区都用各自独立启动的会话、同一候选二进制全量
编译,复用步数为零。PDF、SVG、来源映射和 aux 均与各自增量结果
一致。两份 `target/p4-cow-command-table/full-equivalence-{1,2}/receipt.json`
同为 SHA-256 `421c2505e10f98d3356b75e651be680ca6825cc0756e914c35fd4f07a8835b5f`。
两轮可见 p95 均下降,中位数变化小。系统 I/O 等待显著,两轮
进入时的 I/O pressure some avg10 分别为28.21%和62.33%。
100 ms 正式门禁仍待达到。CPU 采样未观察到整树复制减少。整表方案
保留在隔离工作树。两轮浏览器回执
`target/p4-cow-command-table/edge/run-{1,2}/receipt.json` 的 SHA-256 分别为
`6f49f1e2a1477d8db600831dbd3f87b15e4b4c1c7f716018bcdcda587a2e2e84` 与
`0eda67d80964bfefe4fe17946e7622c00ca450520d70837347473bc950e055c6`。
隔离分桶候选按命令名有序划分绑定,只复制被写入的树。481项核心
测试通过。实际小格式逐字节保持一致并双向加载,旧 LaTeX 格式
运行同一 A4 派生探针的591745步及两条状态指纹完全一致。候选补丁
SHA-256 为 `c3caaf5432ae3f0e7c019d88e46226b1aa7266dc40c12835cb0d95eaaf74fbbb`。
回执 `target/p4-sharded-command-bindings/wire-equivalence/receipt.json`
的 SHA-256 为 `b9610fc43a21f4d8cf42ad4441998e810b909c9989f4951d64e3618c384569a3`。
该次24条热编辑的 CPU 采样中,命令树复制样本占22/1325,基线为
14/554。两次采样的运行耗时与当时负载相差明显,该比例只用于定位。
在同规格的两轮 Edge 配对中,每版每轮各30次不同主文件和30次
不同子文件编辑,逐次核对执行和复用步数、页更新、PDF、SVG、
来源映射与最终 aux。两轮最后一版各用独立会话零复用全量再次
核对一致。
| 轮次 | 原样 A4 编辑 | 基线可见 p50 / p95 (ms) | 分桶候选可见 p50 / p95 (ms) |
| --- | --- | ---: | ---: |
| 1 | 主文件正文 | 233.3 / 479.2 | 250.8 / 486.9 |
| 1 | 子文件正文 | 231.4 / 366.4 | 224.5 / 440.7 |
| 2 | 主文件正文 | 208.8 / 392.9 | 204.1 / 240.0 |
| 2 | 子文件正文 | 182.1 / 222.6 | 184.5 / 300.1 |
主文件 p95 变化方向不一致,子文件两轮均回退。峰值 RSS 各比基线
少3920和3720 KiB。分桶方案保留在隔离工作树。两轮浏览器回执
`target/p4-sharded-command-bindings/edge/run-{1,2}/receipt.json` 的 SHA-256 为
`899d4c3eeab8ecb82dd26afbcc3e0c76409ce8a17b9addfdeaeb8738cb981b64` 与
`446bc8fb666a45a01b79fb262f25221aa02ba2733ef78fea55dffab808ff2cee`。
两轮独立全量回执 `full-equivalence-{1,2}/receipt.json` 的 SHA-256
均为 `375fd7d1725e323cdc6ebd06ed02fc6d69c75c3633d9de57d6952561424404a5`。
对原样 A4 的13次热编辑定向获取 SHA-256 调用栈。捕获的12条
调用均来自自动续跑后 `RevisionExecution::from_execution` 对扫描源
计算内容指纹。该探针在捕获点暂停进程,证据用于定位调用方。
`target/p4-checkpoint-callchains/sha-blocks-a4/attribution.json`
记录12份原始栈的摘要,SHA-256 为
`69d48602bdb88f084a3ac5cf65d8b9c9b312ee717d7a39444230dcbd8fba5440`。
### 恢复检查点后复用源内容指纹
候选在同一会话恢复检查点后,源 ID、名称和实际扫描字节完全一致才
复用上一版的指纹,其他源重新计算。502项定向回归通过。两项原样 A3
单独通过,共享会话的两次编辑各跳过794348步,重放61项宿主调用,
仅更新第7页。日志 `target/p4-reuse-source-versions/a3/{shared,manual}.log`。
同规格的24次主文件热编辑采样中,基线590个 CPU 样本中有52个
SHA-256 样本,候选597个中有30个。执行 p50 为65.2与66.1 ms。
当时有原样 A3 验证运行,CPU 样本用于比较热点。基线及候选的
`target/p4-reuse-source-versions-profile{,-baseline}/original-a4/symbolized.json`
各自 SHA-256 为
`1c61b8a0b1a4349401ef493f392c41bb9bf7132e79f345138b289f0be5190c49`(基线)和
`1cc74b607766bfbd4da3fd0d7f9c3b0f15732b207e92f2e64256cf67d14e1279`(候选)。
原样 A4 两轮 Edge 配对各有30次不同主文件及30次不同子文件编辑。
第二轮按暂停前的反向配对顺序从新会话完整重跑,原中断目录保留
97次观测。逐次执行步数、复用步数、页更新、PDF、SVG、来源映射
和最终 aux 一致。两轮最后一版在各自独立的同版本会话中全量编译,
PDF、SVG、来源和 aux 与各自的增量版本一致。
| 轮次 | 原样 A4 编辑 | 基线可见 p50 / p95 (ms) | 候选可见 p50 / p95 (ms) |
| --- | --- | ---: | ---: |
| 1 | 主文件正文 | 230.6 / 353.2 | 224.7 / 335.5 |
| 1 | 子文件正文 | 205.4 / 337.7 | 199.9 / 345.1 |
| 2 | 主文件正文 | 213.7 / 312.9 | 211.1 / 242.5 |
| 2 | 子文件正文 | 195.5 / 275.4 | 184.8 / 248.4 |
候选执行 p50 在两轮主文件编辑分别下降2.5和0.6 ms,子文件分别
下降4.1和3.0 ms。两轮 I/O 负载不同,首轮部分样本与 A3 验证重叠。
主文件100 ms门禁仍待达到。第二轮候选峰值 RSS 为603156 KiB。
浏览器回执 `target/p4-reuse-source-versions/edge/{run-1,run-2-resumed}/receipt.json`
的 SHA-256 为 `b9a25ba001e7bbb6cfb863b6246590a86b8931d9a92c5e2ac6298813b95815c6`
与 `0acf05c001ac00dc927847f85ca01d049783bb22464cbd0bcdc94bdc34dac72f`。
`full-equivalence-{1,2-resumed}/receipt.json` 的 SHA-256 均为
`ec72d40ee6d2ec74a45bcad39000c2c19a9f08024713b2f5fc35c8da49bac207`。
按原补丁合入源指纹复用。完整工作区1627项通过、零失败。
暂停前完成100个测试套件,恢复后以原工作区构建配置执行剩余9个
集成套件,四个文档测试套件亦通过。两个单独运行的原样 A3 已通过。
`target/p4-reuse-source-versions/workspace-exact-resumed/receipt.json`
保存113个套件的合计及剩余工作区测试程序的哈希,回执 SHA-256 为
`2999f65936487143cb23d6da87419934403de3d79d8a4b0cb92dacae545871c7`。
同一个候选和基线分别加载固定出版格式与官方 IEEE Transactions
双栏期刊样例。原始 `bare_jrnl.tex`、`IEEEtran.cls` 和格式的指纹
匹配出版矩阵。两次正文编辑分别覆盖同长替换和不同长度替换,每次
续跑复用2060882步,从字节20465继续,重放160项宿主调用。编辑后
实际正文词框位于两栏,候选和基线每版 PDF、SVG、来源、aux 和执行
步数一致。两次编辑也分别用独立会话零复用全量确认。回执
`target/p4-reuse-source-versions/ieee-journal/receipt.json` 的 SHA-256 为
`b9fe349ec25a4f767c93a05bb5dfc4678b350d4963358e2486936438973b0d97`。
官方 CVPR 2026 的五页项目加载出版矩阵中相同的原始文件、格式和
实际 BibTeX 产物。两次改动 `sec/1_intro.tex` 时,两个二进制的输出
一致,复用步数均为零。第一处编辑令 aux 多出一条实际行号记录。
最初按冷启动生成文件做独立全量,在 PDF 比较处发现差异。随后
逐次保留编辑前的 aux、brf、out、log 和 PDF。独立会话使用同一组
初始生成文件,三次编辑的执行步数、PDF、各页 SVG、来源和 aux
均与会话结果一致。辅助文件稳定后,第三次子文件编辑执行总步数
22864610,从主文件字节1791续跑,复用11375833步,重放407项
宿主调用,只提交第1页更新。回执
`target/p4-reuse-source-versions/cvpr-generated-initial/receipt.json`
的 SHA-256 为 `9381ab9ff11c46c569f5e175ae30af4e253b562e04eea3ed7c03f6dc8485fd3f`。
这是实际项目编译及页面差量证据,浏览器延迟见原样 A4 对照。
同一候选的定向 SHA-256 调用栈又定位到来源映射。12条捕获都在
`SourceMap::from_revision` 核对源内容指纹。
`target/p4-reuse-source-versions-callchains/sha-blocks-a4/attribution.json`
的 SHA-256 为 `c21e2a6c2ee248e246955c48f64326c113254958f91e65097c68a1180bff998e`。
下一隔离候选复用会话持有的同一内核结果里的已验证源指纹,保持
来源跨度与绘制索引的校验。不同会话或传入的独立执行结果照常
逐字节计算指纹。针对相同修订号的独立结果增加验证。
### 来源映射复用同一会话的已验证结果
隔离候选用会话当前持有的确切执行结果建立来源映射。会话生成源版本
时已计算内容指纹,校验页布局和构造映射时复用这份指纹。外部传入的
执行结果仍核对其实际内容,包括相同修订号的独立结果。61项定向和
端到端测试通过。已按候选补丁和四份源文件指纹合入主线。完整工作区
1628项通过、零失败,两项保持手动验证。113组测试结果及日志记录在
`target/p4-source-map-session-identity/workspace.log`,SHA-256 为
`283d20de596e48ba3453ef887cdfcb5f17fcf82198797b61609409f7d5d6180d`。
原样 A4 各24次主文件热编辑的定向采样中,基线559个 CPU 样本中
有28个 SHA-256 样本,候选517个中有2个。布局与字体阶段中位数为
10.0 → 5.8 ms。采样回执
`target/p4-source-map-session-identity/profile-comparison.json`
的 SHA-256 为 `885d84dbd19225e48974780904dd9a9a83d71a1cd7d4ab5e7109509e4c3e7992`。
两轮 Edge 对照每版每轮各30次主文件和30次子文件编辑,第二轮交换
测量顺序。配对核对每版的执行及复用步数、页差量、PDF、SVG、来源
映射和最终 aux。两轮最终版本均独立零复用全量编译并核对一致。
| 轮次 | 编辑范围 | 基线可见 p50 / p95 (ms) | 候选可见 p50 / p95 (ms) | 布局与字体阶段 p50 (ms) |
| --- | --- | ---: | ---: | ---: |
| 1 | 主文件 | 209.3 / 269.3 | 198.8 / 246.7 | 10.3 → 6.5 |
| 1 | 子文件 | 189.2 / 240.3 | 179.4 / 241.2 | 9.8 → 6.2 |
| 2 | 主文件 | 209.0 / 247.5 | 201.4 / 411.6 | 9.9 → 6.1 |
| 2 | 子文件 | 178.3 / 319.2 | 182.6 / 354.0 | 10.0 → 6.0 |
布局与字体阶段的中位数在两轮都下降3.6至4.0 ms。可见 p95 的
变化方向有差异,两轮起始 I/O pressure some avg10 分别为19.67%和
42.62%。主文件100 ms门槛仍待达到。候选两轮峰值 RSS 为601460
和601832 KiB。浏览器回执
`target/p4-source-map-session-identity/edge/run-{1,2}/receipt.json`
的 SHA-256 分别为 `c20921e4aed4831123cf95cfd13d24472a5ea29275ad3f44199657b2a7797921`
和 `27d3cf03f10596999b9c570022e6fdab8c9dcc434c0cac99a1bdba967af5c577`。
两轮独立全量 `full-equivalence-{1,2}/receipt.json` 的 SHA-256 同为
`2c73f84608fe5b2cbaf23a2eb0e5ab2d7038078880ec4990e93af303d52c2756`。
对以上两轮各30次主文件编辑按样本拆分可见延迟。候选分别复用
558821步,剩余执行约78500步。执行阶段中位数为76.1和76.3 ms,
编译就绪中位数为101.9和102.6 ms,编译外耗时中位数为94.7和95.5 ms。
请求到首字节扣除已测排队与编译时长后的余量中位数为53.1和55.0 ms。
响应完成到观测到画面更新的中位数为32.1和31.0 ms。
按每个样本扣除执行阶段后,剩余时间的 p95 为146.2和169.5 ms。
该算术分解用于定位下一处要测量的边界。正式门禁仍用原样项目
编辑到可见页面的完整耗时。执行阶段继续区分有效 TeX 执行、
检查点恢复和再捕获。此前的独立双点记录已测得同类 A4 请求的
Linux 进程内响应残差 p50 约0.9 ms,进程外两段合计约49–51 ms。
后续独立比较本地页面交付路径。原浏览器报告逐份核对 SHA-256。
按最近秩聚合的分解回执为
`target/p4-source-map-session-identity/edge/critical-path-budget.json`,
SHA-256 为 `581a4b15a938f913be07aa4faa056ac0a1678534dd0de168d46ee144700a1914`。
原样 CVPR 的独立诊断逐版核对了同一初始输入和已验证的五页结果。
会话保留5个检查点,前两次子文件编辑的准备阶段明确报告
`main.aux` 初始版本不匹配。第三次按已稳定的辅助文件恢复,复用
11375833步,只更新第1页。下一步验证较早检查点所实际观察的
生成输入,以及在较晚检查点失效时选择较早有效检查点的范围。
诊断回执 `target/p4-source-map-session-identity/cvpr-checkpoint-diagnostics/receipt.json`
SHA-256 为 `e105a3ed13e2670507a3bdaf550ea55a3eb55489f526c626768a7c870511cc91`。
### 生成辅助文件变化后的较早检查点
隔离候选逐份核对生成文件角色与存在性。前缀实际读过或打开写入时,
继续核对该文件的初始版本。准备阶段在同一个作业锁下,按已执行步数
从高向低选取有效检查点,再重放该前缀的实际文件操作。此前已通过的
外部修改拒绝测试保持通过。首轮结果类型编译错误已修正,失败日志和
对应补丁保留。定向回归4项通过,零失败,一项手动。实际同尺寸 aux
改动将规则宽度从11 pt变为22 pt,测得宽度与 pdfTeX 对照一致。
修改后的 PDF、来源映射和执行结果与独立全量一致。回执在
`target/p4-generated-prefix-dependencies` 下,
`guard-directed-v2.log` 的 SHA-256 为
`c20e140b0d6db69c1bf1314a15de7d56751fd9dbdaa818a6851ef7325808eaae`。
CVPR 2026 使用原样项目、实际 BibTeX 输出、同一格式和字体资源。
此前需全量执行的前两次编辑现在各复用11375833步,第三次保持同一
复用步数。三次编辑分别更新第1至5页、第1和5页、第1页。每版以
编辑前保存的生成文件启动独立零复用全量编译。PDF、五页 SVG、
来源映射、aux、brf、out、仅归一工作目录的日志及总执行步数均一致。
`cvpr-earlier-checkpoint/receipt.json` 的 SHA-256 为
`500c5281a724a06ea2462e6bc09f61cbee02916ba269473f0f8cf87ddf2c06ae`。
隔离补丁 SHA-256 为
`bd28142360baa0d3a56f91ca8f1f769776fe11277bef737d04da4e8ec1f251c3`。
与主线来源映射实现组合后,4项检查点守卫和38项原生编译发布
测试通过,零失败,一项保留手动验证。按四份确切源码指纹合入
主线。组合版全工作区作业在构建时停止,保留已通过的1628项
工作区基线和本次日志。组合定向回执为
`main-directed-guard.log`、`main-directed-pipeline.log`。
CVPR 的复用步数独立于 A4 100 ms 可见延迟门禁。
### 交替编辑后的编辑行检查点
隔离候选在原有数量上限内保留最近编辑行之前的检查点。子文件变化
使依赖该文件的旧前缀失效,作业从仍有效的较早位置恢复,随后重新
捕获编辑行之前的状态。一项新定向用例通过,覆盖实际规则、来源
映射和与独立全量的等价性。构建时的首个所有权错误及修正日志均保留。
一轮原样 A4 浏览器配对,每版各30次主文件与30次子文件编辑。
共60对逐次验证 PDF、SVG、来源映射、总步数和页差量,最终 aux
及独立零复用全量一致。主文件29次增加了复用,逐对少执行的步数
中位数为22736.5。主文件复用步数中位数为558821 → 581550。
子文件复用中位数保持558821,其中一次更早恢复,少复用13451步。
| 编辑范围 | 基线可见 p50 / p95 (ms) | 候选可见 p50 / p95 (ms) | 内核执行配对中位数变化 (ms) |
| --- | ---: | ---: | ---: |
| 主文件 | 232.9 / 584.5 | 224.9 / 304.5 | -19.38 |
| 子文件 | 225.2 / 469.9 | 219.9 / 586.1 | +5.85 |
峰值 RSS 为601808 → 613300 KiB。WSL I/O pressure some avg10
从0.93%到44.20%。主文件100 ms门槛仍待达到。子文件额外执行和
内存值得进一步缩减,代码保留在隔离工作树。下一候选将一个较后的
普通字节区间快照移到编辑行前,保留较早的前缀和实际出页捕获。
首个浏览器作业因共享 Cargo 目标复用了同一个二进制而终止。保留
原日志和指纹。候选重新构建,按源码补丁和不同二进制指纹核对。
正式回执在 `target/p4-edit-line-checkpoints/edge/rebuilt-run`。
`receipt.json` 的 SHA-256 为
`412aec4acda8d7147f4e4cb00b667df1d7242aa1c50b560f6b9a238dc5df8fe7`。
独立全量回执 `rebuilt-full-equivalence/receipt.json` 的 SHA-256 为
`a7f78749b86cb9d5b8aa2c9c7fb80aa1eda1a6d2e54718ad119579a00b1a1891`。
### 编辑行检查点的快照预算
编辑行需要单独快照时,将随后一个普通字节区间的快照移到编辑行前。
保留此前较早的回退位置、真实出页捕获和原快照数量上限。定向用例
覆盖编辑行捕获、随后出页及独立全量等价,已通过。
以已测编辑行候选的同一优化二进制为基线,一轮原样 A4 配对每版各
30次主文件和30次子文件编辑。60对的总执行步数、实际页差量、PDF、
SVG 和来源映射一致。最终 aux 与使用最后编辑缓冲区的独立零复用
全量一致。主文件全部保持原复用步数,子文件仅一版多复用13017步。
| 编辑范围 | 上一候选可见 p50 / p95 (ms) | 快照预算候选可见 p50 / p95 (ms) | 执行配对中位数变化 (ms) |
| --- | ---: | ---: | ---: |
| 主文件 | 304.7 / 569.9 | 305.2 / 399.4 | -9.09 |
| 子文件 | 310.5 / 445.6 | 284.2 / 400.2 | -14.65 |
峰值 RSS 为615724 → 601592 KiB。采样期间 WSL I/O pressure some
avg10 从7.08%升至42.39%。此轮对照表明快照预算的执行时间和内存
收益,主文件可见 p50 基本不变,100 ms 可见 p95 门槛仍待达到。
同一基线二进制在上一轮多执行9步前缀,恢复位置、恢复后步数和页面
保持一致。两个轮次的延迟独立报告。
按已测源码指纹合入主线。证据在
`target/p4-edit-line-snapshot-budget`。快照预算补丁、浏览器回执、
配对统计和独立全量的 SHA-256 分别为
- 完整补丁 `2cc91c7b8d62b1b9c7479d0b42041135aee480f7494f3035d84f8d55671d590a`
- 浏览器回执 `31000162b1c84ef79db4044d36118355f3c7785d4739fe3806bc7f200aab8bef`
- 配对统计 `cad6d20b795dfe30bd504a7351c4bc49a1d9deb0694e7fca8312137e8a416fcf`
- 独立零复用全量 `0c35c2c91876fd43f216b4d1834ced44127723cf89fcd9e14a9cda9a78cb49a2`
### 文本重音与 APS 双栏样稿
原样 APS 在第一轮和真实 BibTeX 之后,第二轮从 `apssamp.bbl`
读取 OT1 的重音时停止。原诊断、生成的文献和源身份见
`target/p3-text-accent/publisher-failure-context.json`。
已在隔离候选沿用字体、水平装盒和绘制路径,实现重音的真实核
和偏移。一次定向差分核对8份原始盒、赋值、段落钩子、换行及
15个实际 DVI 字形。最大坐标差为0 sp。回执
`target/p3-text-accent/focused-paint-receipt.json`。
新写入的格式使用 schema28。已用优化候选和原样 A0 载入既有
schema27,生成单页 PDF,逐词坐标和 aux 与已验证的旧结果一致。
验证首轮误用未存档的源副本,修正后从原资源记录核对源文件指纹。
同一程序从原样 pdflatex.ini 生成 schema28,实际记录 firstaid
依赖,并在格式状态中保存原生 `\accent`。
原样 APS 使用新版格式经过四轮和一次实际 BibTeX,生成7页 PDF。
PDF 的4926个提取词及坐标、7页144 DPI灰度像素、生成文献及逐轮
aux 都与冻结的 pdfTeX 对照一致。所有页面有左右栏文字,最后
两轮 aux 收敛。首次汇总时,Poppler 的词框含 XML 禁止的字符,
保存编译产物与解析失败,通过正文词框原字节比较继续审计。
格式与新旧项目证据在 `target/p3-text-accent`。APS 回执
`aps-original/receipt.json` SHA-256 为
`8a5c885e504171e88b6dae499c3403b99ddfe9d2c09b6aff0ef2a14c07ab4c23`。
按14份候选源码指纹合入,其中一处调用按 rustfmt 换行。
原有分式、vcenter 和 PDF Unicode 三项格式回归已按新写入的
schema28 更新。schema 1至26和29仍拒绝,27与28缺少必需 Unicode
状态仍拒绝。主工作区三项定向复验通过、零失败,回执
`main-format-tests-receipt.json` SHA-256 为
`36ee67944b1b63ccb27c0646e80db19b034e898aa88f850abdd1ed720ef65d06`。
[原样模板记录](PUBLISHER_TEMPLATE_MATRIX.md#aps-revtex-原样双栏样稿)
[pdfTeX 的重音布局](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L28084-L28143)
### 原生 PDF 页面资源与透明度
`\pdfpageresources` 使用 TeX 的 token 参数和分组恢复。每次出页
捕获当时的资源字典,最后解析直接或间接的图形状态。`\pdfobj`、
`\pdflastobj` 和 `\pdfrefobj` 实际保存、写入或延迟写入对象。
对象及资源、目录、信息字典的间接引用在 PDF 写出时统一编号。
页面颜色栈保存 `gs` 命令;SVG 从相同定义分别绘制填充和描边透明度,
涉及其他图形状态的页面使用实际原生 PDF 进行合成。schema34
保存新增语义。文件型对象、用户资源和自动字体或图像资源的名称
合并,以及其他 PDF 字典入口的引用仍待接齐。
[pdfTeX 的出页资源字典](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web)
独立 pdfTeX 对照中,固定样例一页及迟定义对象样例两页的144 DPI灰度图
逐像素一致。第二个样例核对组内资源只作用于一页、细规则的描边透明度,
以及延迟流对象和目录中的实际引用。既有目录和颜色栈共17项定向检查通过。
实时编辑将第一种填充透明度从0.25改为0.5,实际复用95步并替换一页。
改后 SVG 和 PDF 与独立零复用编译完全一致;来源映射仅归一化测试目录
和会话修订号,来源及几何一致。第一次探测的编辑序号冲突、原始会话地图
差异和临时目录冲突均保留日志。这个样例只用于正确性对照。
`target/p3-pdf-page-graphics-state-native` 的回执:
- `directed/receipt.json` 为 `f9e6681b3d977aa6d784f4ae1a196264bf34ea530e19d23cd87ca05494b5d16f`。
- `late-objects/receipt.json` 为 `5921924488c3970584db61872af99961b24efb5c00487042781e71869f2640ab`。
- `regression.log` 为 `9dd038475f57182020feeb500788a81a39f92bbef53aef581496f8d3052b5c71`。
### 宏展开调度与实际浮点表达式
将 `\expandafter` 的暂存 token 留在同一次展开调度。执行第二个 token
仍使用原上下文与命令追踪,结果先回退,再按顺序恢复待处理 token。
递归重入扫描时仍核对实际展开和扫描深度,输入容量与逐 token 步数
保持原接口。64 层直接嵌套的最小样例得到同样的 pdfTeX 输出。
Elsevier CAS 图形高度和浮点舍入的冻结最小样例已能以原样源码生成
一页 PDF。实际图像高72.5539 pt,基线12 pt,浮点结果6.546157836914062,
取整7。144 DPI 灰度图逐像素一致。初次仅合并直接连续链的候选仍触发
真实浮点样例的展开上限,失败证据保留。最终定向数量和命令追踪共7项
通过。置于统一矩阵的原样全项目仍需在同一版本集中验收。
`target/p3-native-expansion-continuations` 的通过回执:
- `long-chain-candidate-v2/receipt.json` 为 `2081edb92a50bb26afafd6f5148c945c81a9fbcb6809ce16c660eb0cfdbf91c1`。
- `float-candidate-v2/receipt.json` 为 `4686b90bc415229537835459d4da502875b1ee241e6dd079f8045d55b34fd409`。
- `float-candidate-v2/render-receipt.json` 为 `6bc7cc5fdecde72879f9890821527959c5a8d23bc72ae638004cef1835bed421`。
- `directed-v2.log` 为 `cb3dcaf8a6292a40f43f30d4018f4be4a38033b216ece84153d86fef53004ec6`。
### 原生自动字宽伸缩
字宽伸缩参数进入真实字体目录和 schema33 格式。模式1在装盒时按字形
的实际度量和代码选择量化比例。模式2也按断行区间和 discretionary 内容
考虑可用伸缩量。断行缓存保存这部分度量投影。PDF 与 SVG 按比例绘制实际
字体,来源映射保留比例和伸缩后的字形度量。本阶段支持自动伸缩,外置
预伸缩 TFM 尚待接入。
[pdfTeX 的伸缩参数与量化](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L17548-L17683)
沿用冻结的 pdfTeX 四盒样例,另用同一段落对照模式1、模式2及关闭单字形
伸缩。两组共7个盒诊断相同,10个 PDF 词框的坐标偏差为0 bp。第二组按
同一顺序产生2、1、2行。一个定向回归验证同一会话的断行结果可复用,
并在代码改变后重新选择断点。独立最小格式重载实际代码500,输出中
四个字形均为+50‰,来源映射的单字形宽度为516097 sp。
`target/p3-pdf-font-expansion-native` 的证据:
- `witness-final/receipt.json` 为 `66485903072ed783283181d5b741cc75f893210821b3e7a414e564bfa34ce8e8`。
- `break-final/receipt.json` 为 `8b79955a0367271116314a27b08233c57ba7b83c9c60ad50c9f5276228a351c6`。
- `stored-expansion/receipt.json` 为 `83079cb38b9a1ced3ef8a74826abcd331ca18299d2c336678889bc8e0ad16862`。
- `targeted-test-final.log` 为 `31b28eada6e82d08f9869fc9fdbcd9a11c87c03d73b724554e7a5f2d31988d49`。
最初混用同一基础字体的伸缩变体时触发 PDF 字体身份断言。已修正资源
去重的比较规则。验证入口对预期 showbox 退出码和布局清单字段的误判
原日志已保留。原样 `pdflatex.ini` 的调试构建探测达到20分钟超时。日志保留在
`target/p3-pdf-font-expansion-native/format`。此次未进入 arXiv 作业。
统一工作区回归、原样格式与出版模板矩阵的优化构建复验,以及正式性能
采样留到功能集成。
### 原生段落边缘悬挂
`\pdfprotrudechars`、`\lpcode`、`\rpcode` 接入实际字体槽和水平
列表。模式1在装盒时加入有符号边缘 kern,模式2也在断行搜索时计算
实际边缘量。使用当前字体 quad、实际边缘字形和嵌套横盒。拆开横盒时
去掉本层边缘 kern,保留原列表其余节点。模式2的缓存键包括实际边缘
投影,字体槽或活参数改变后重新选择断点。
[pdfTeX 的边缘宽度和节点](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L19387-L19430)
[pdfTeX 的断行短缺量](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L23363-L23369)
定向列表和 DVI 7项、格式3项全部通过。新用例的7个原始盒及30个
实际字形与 pdfTeX 对齐,最大坐标差为0 sp。冻结的 PDF 文档8个词框
与实际原生输出坐标完全一致。比对脚本首轮误把正常 showbox 退出
状态当失败,使用保存的文件和完整输出继续核对。最小格式读取需要
显式 PDF 模式,从同一个此前保存的格式读回左代码100和右代码−125。
真实未修改的 pdflatex.ini 生成 schema32,继续读取已发布27/28/31。
基于原样 A4 主文件和子文件附加参考段落,实际预览修改左边缘的
字体代码后,模式2从一行改成两行。该次修改仍复用849626步,发布
PDF、SVG、来源映射和 aux 与独立零复用全量一致。更早的两个短文档
对照也得到同样的断行与输出,保留实际复用步数为零的证据。
原样 arXiv、ACL 和 NeurIPS 2025 均越过 `\MT@protrudechars`,下一处
为 `\MT@adjustspacing` 对应的 `\pdfadjustspacing`。已冻结真实
pdfTeX 字宽伸缩对照,4个盒分别显示0、+50、−50、0千分比,包含
字形 `\efcode` 为零的情形。实际 PDF 词框同样反映伸展和收缩。
[下一处上游字体伸缩](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L16327-L16385)
按20份组合代码和测试的确切指纹合入主线。发布阶段保留原样矩阵,
此次沿用已有参考,只运行受影响的三份样稿及对应定向。
回执在 `target/p3-pdf-protrusion-native`。
- 原始绘制 `paint-receipt.json` 为 `2b54c5ccab28e6cc6699f9c748761962bae04f004a32d0c1428230cc264ef034`
- 原样格式 `format/receipt.json` 为 `2ec1b3861460dad8490f030dac802d53e24e3c43547220146ccadc1f988b4b73`
- 实际 PDF `actual-pdf/receipt.json` 为 `869a6824cc1ff4348613dd802ccf463ad3c5a16f0a35265f3db4b837ab1c7e80`
- 原样样稿 `publisher/receipt.json` 为 `885c1780af905b9d7a5c22cfc0584c67f5edc8393cbbc624692746af0a55eb96`
- A4 编辑 `edited-font-codes-a4/receipt.json` 为 `57464a38938db16e0f02b1138caa7f99760b72b17f61934b6ede2f550af7263f`
- 字宽伸缩参考 `target/p3-pdf-font-expansion-reference/receipt.json` 为 `27a8757e73f54e43b865e01d463b809d60c31962467edb6466250f7b876811a2`
### 会话内复用实际 Type 1 字体解析
逐版读取并核对真实 PFB 后,以路径、字节数和 SHA-256 复用 Type 1
程序、轮廓结构和字体界限。字体地图、编码资源和当前页的字形仍按实际
作业验证。每个编译会话最多保留16个、单个输入不超过256 KiB的解析项。
原入口和当前输出的数据结构保持一致。
同一路径更换真实 PFB 的定向用例通过。PDF 和 SVG 随字体版本改变,
新版本的 PDF、SVG 和来源映射与独立全量一致,旧版仍保持原字形。
在同一真实 schema31 和固定 TeX 时钟下测量一轮原样 A4。每版各30次
主文件和30次子文件编辑,全部60对的总步数、复用步数和位置、页差量、
PDF、SVG 及来源映射一致。最终 aux 和同二进制独立零复用编译一致。
| 编辑范围 | 布局与字体阶段 p50 (ms) | 该阶段配对中位数变化 (ms) | 可见 p95 (ms) |
| --- | ---: | ---: | ---: |
| 主文件 | 11.43 → 9.11 | -2.27 | 370.6 → 391.9 |
| 子文件 | 10.48 → 9.17 | -0.57 | 384.8 → 358.1 |
峰值 RSS 为603012 → 603324 KiB。起始和结束 I/O pressure some avg10
为0.70%和42.00%。本轮用于确认字体阶段收益,可见 p95 的方向不同,
100 ms实时门槛仍待达到。按已测三个文件的指纹合入主线。回执见
`target/p4-native-type1-program-cache`。
- 浏览器配对回执 `edge/run/receipt.json` 为 `f3be954818286224a46e412cfcfef2067b2465d26cd639eb6f7bb4cec1ad0ed4`
- 独立全量 `full-equivalence/receipt.json` 为 `c0b43a9458ece8b4eebd9936865e488e0362a351fbecd4a38103a2ca6a7d5a46`
- 字体更换 `focused-retry.log` 为 `2f366efcd72f6a994f363801a0f91f9f6ac2eda8ed9887ab1c12c3ec65641634`
### 正常发布入口的可取消 pdfTeX 匹配
原生 `\pdfmatch` 和 `\pdflastmatch` 沿用已独立验证的 GNU 字节匹配。
Linux GNU 的 CLI 和预览通过正在运行的同一个可执行文件启动匹配进程,
支持以应用程序通常的入口部署。匹配结果进入当前作业,检查点保留
捕获,取消会终止并回收实际匹配进程。直接调用低层执行器由宿主
提供匹配,同平台可调用同一个 GNU 实现。
[pdfTeX 的字节匹配](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/utils.c#L762-L853)
实际未修改的 pdflatex.ini 产生 schema31,包含两项匹配原语、文本
重音和官方 firstaid 依赖。继续接受已发布的 schema27/28,保留
拒绝旧模式缺字段及未发布 schema29/30 的回归。匹配、捕获续跑、
格式和拒绝门禁共六项定向通过。只安装单个重命名 CLI 的作业也已
生成实际 PDF,正文验证了左端开始的最长匹配。
原样 arXiv 与 ACL 各55次 GNU 匹配,输入和捕获结果与已保存参考
逐字节一致。两份样稿均推进到 microtype 设置的
`\MT@protrudechars`,该控制序列指向尚待实现的原语
`\pdfprotrudechars`。使用既有 NeurIPS 分支结论,留待相关行为再次变化
或发布验收时复跑。
同一预览程序在旧作业进入真实 GNU 调用后收到新编辑,73.8 ms 后旧
请求返回409,匹配进程已经回收。新作业实际复用824330 / 904081步,
发布 PDF、SVG、来源映射和 aux 与独立的零复用全量结果一致。
一次受控取消时间独立于100 ms可见预览 p95 门禁。
完整候选及回执在 `target/p3-pdfmatch-integrated`,按19份代码、
锁文件和测试的确切指纹合入。
- 真实格式 `format/receipt.json` 为 `3d5ea7373e7a51b1289fb0d970247fc0d7efcaa564b26dea3fe1d119028f150d`
- 单程序发布 `installed-cli/receipt.json` 为 `70e04387ccbf1c76d5a7e40fe4da7fc77174ee70e900a8e60cf3a167c8e951ed`
- 原样模板 `publisher/receipt.json` 为 `40b71c04aa4a6d763c5cdd1f314381ad93ecc94154e91efd475703d3767cdc40`
- 编辑取消 `editor-cancellation/receipt.json` 为 `4a4461efd163723e65bfe814f92b1e737a268a511c008bb369b8e46065b4e0bd`
已为下一处版面能力冻结新 pdfTeX 对照。原样字体的同一段文字在
38 pt 宽度下,模式0/1各两行,模式2一行。五个实际盒包括正负
边缘 kern、嵌套盒和字体代码跨组。回执
`target/p3-pdf-protrusion-reference/frozen/receipt.json` 的 SHA-256 为
`d84266b5e2d731a06755420f7be74e598cb48b5aac4cbc876291f1368156b873`。
[pdfTeX 边缘宽度和节点](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L19387-L19430)
### TeX 输入的默认扩展名候选
+99
View File
@@ -384,6 +384,105 @@ ACL 和 NeurIPS 原生首处诊断均为 `\MT@protrudechars`,分别位于
四项复跑及分范围合并回执 `publisher-followup/receipt.json` 的 SHA-256 为
`65ee11dea157174e282033cf993a8bfd1e5e0989bab48fe73df1ab7005bd7e19`。
### 主线文件身份扫描调整后的原样复验
主线 `24ea6ef` 的同一优化程序独立复跑14项。分别使用已验证的基础、
NeurIPS、ACM 编译环境。源文件、模板归档、格式和字体映射均按对应基线
校验。14份参考 PDF 生成,全部 aux 收敛且无未定义引用告警。原生生成
Springer Nature、IEEE Transactions 双栏 starter、IEEE Conference starter、
Springer LNCS、CVPR 2026 共5份 PDF。成功项的页数、词框和逐轮 aux 与各自
上一次结果一致,其他9项的首条诊断一致。三组报告及逐项复验汇总见
`target/p4-alias-scan-identity/publisher/receipt.json`,SHA-256 为
`a8aa32d5f9ca829dd121018300cd07f9f996b3aad17b11b3549bbbe49ee8ac3b`。
### 原子文件增删后的主线复验
同一优化版复跑14份原样期刊、双栏期刊、会议和 arXiv。参考端14份全部
生成,原生仍生成5份。成功项的页数、词框和逐轮 aux 与对照一致,其余
原生样稿的首条诊断一致。Springer Nature 首次原生试验达到90秒上限,
同二进制、格式和模板重试后正常生成12页。arXiv 和 APS 的参考词框
首次跨日对照只差日期数字,同日独立生成的全部词框逐字节一致。
`target/p4-checkpoint-file-changes/publisher-recovery/receipt.json` 的 SHA-256 为
`00265ef887ae499fa3ed5164f349198dfad6fb60ce9d07310c293cfa5ef9a6fb`。
初次报告、超时记录和同日重跑均保留。
### APS REVTeX 原样双栏样稿
`apssamp.tex` 的原样 reprint 版本已通过 schema28 原生格式编译。
同一官方源码、实际 REVTeX 类、字体资源和四份 EPS 转换产物保持固定。
第一轮生成参考文献所需的 aux,独立运行 BibTeX,后续三轮实际读入
`apssamp.bbl`。通用文本 `\accent` 处理了文献中 OT1 的实际重音。
原生和冻结的 pdfTeX 参考均为7页。4926个词的顺序及坐标相同,每页的
左右两栏均有实际字框。144 DPI 灰度图逐页像素相同。生成的 BBL 与
四轮 aux 逐字节一致,最后两轮收敛且没有未定义引用告警。此次证据
为主线功能的 APS 单项对照。最近同版本全矩阵仍是14份参考、5份原生,
发布时再对整批模板做组合验收。
`target/p3-text-accent/aps-original/receipt.json` SHA-256 为
`8a5c885e504171e88b6dae499c3403b99ddfe9d2c09b6aff0ef2a14c07ab4c23`。
[APS REVTeX](https://journals.aps.org/revtex)
### arXiv 与 ACL 的原生微字体匹配
schema31 主线功能通过正常的单程序部署,在原样 arXiv 与 ACL 的
microtype 配置中分别执行55次匹配。实际 GNU 输入和捕获均与既有
pdfTeX 对照字节一致。两项编译随后在实际 `\pdfprotrudechars` 的别名
处停止。之前的 NeurIPS 官方样例在独立候选上同样推进到该边界。
本次主要核对正常部署及编辑取消,复用冻结对照。
[编译与取消证据](P2_M1_PROGRESS.md#正常发布入口的可取消-pdftex-匹配)
### arXiv、ACL 与 NeurIPS 的边缘悬挂
schema32 的正常入口继续执行三份已有官方样例。三份均越过
microtype 的边缘悬挂设置,随后停在字宽伸缩
`\MT@adjustspacing`。同一版的独立 pdfTeX 对照核对真实断点、
边缘 kern 和物理 PDF 词框。受影响样稿的源指纹及实际诊断见
`target/p3-pdf-protrusion-native/publisher/receipt.json`。
[阶段证据](P2_M1_PROGRESS.md#原生段落边缘悬挂)
### Elsevier CAS 双栏首轮输出
通用展开调度改动通过了实际图像高度与 LaTeX 浮点公式的差分。
原样 `cas-dc-sample.tex` 的30份交付文件与冻结出版基线一致。
首次探测漏用了冻结 `TEXFONTMAPS`,在出页阶段找不到实际 STIX 字体。
补回参考端读取的同一 `pdftex.map`,沿用同一程序和格式,独立首轮
生成5页 PDF,实际嵌入 Type 1 STIX。资源清单确认读取了同一映射。
文献、逐轮辅助文件及版面差分留在统一验收范围。
回执 `target/p3-native-expansion-continuations/original-cas-dc-with-map/receipt.json`
为 `2642101fee57d94538b1feee51e77e4e8134511b44fedd853b24b826ec83fdf5`。
### IEEE 双栏期刊与 CVPR 会议的实时会话对照
使用矩阵中同一原样输入、TeX 格式和已验证的字体资源,验证编辑后
的 PDF、SVG、来源映射与 aux。IEEE Transactions 的两次同长和异长
正文改动均续跑,各复用2060882步,实际正文词框覆盖左右栏。CVPR
2026 的输入包括此前官方项目实际生成的 BibTeX 产物,共5页。前两次
子文件改动为全量,aux 稳定后第三次复用11375833步,仅更新第1页。
五次编辑分别用同一初始状态的独立零复用编译核对一致。
[会话回执与阶段记录](P2_M1_PROGRESS.md#恢复检查点后复用源内容指纹)
### 上游 pdfTeX 导言区恢复对照
在同一批14项原样项目上运行固定的 pdfTeX 1.40.29,配对比较标准格式
和 TeX Live 官方 `mylatexformat` 导言区恢复。两端均沿用相同原始模板、
资源和已收敛的辅助文件。标准入口生成14份。恢复入口完成10份、58页,
各页的144 DPI 灰度图、嵌入字体、逐字词框和 aux 均一致。规范化后的
项目文件 SyncTeX 记录逐条一致,7项仍有发行版文件来源记录差异。
Springer LNCS 的格式保存遇到包对 `\openout` 的范围限制。ACM 的
单栏期刊、双栏期刊和会议案例均在保存时遇到 `acks` 环境嵌套错误。
这四项保留标准全量结果和保存失败日志。此轮只验证已收敛文档的导言区
恢复范围。用户编辑后的依赖、重用、版面和时延通过各自的会话验收判断。
对应 `target/p4-upstream-preview-boundary/snapshot-publishers` 回执如下。
- `receipt.json` 为 `4fd41bab48ea42af55a4cef3964a080531a7d542a935c3ab08ad9beb7b5347b1`
- `source-map-comparison.json` 为 `8106461bd200fcc85769f05e37773fe855ef2c2a9caa56cfe6057961cbcb0da6`
- `rendered-comparison.json` 为 `d5590af00c2e4b30b9973fa6eea8bcd5b0f3854d8f156784352bb304885f6712`
### ACM 的三类官方样例
新增 ACM acmart v2.21 的单栏期刊 `acmsmall`、双栏期刊 `acmtog` 和会议
+54 -23
View File
@@ -30,7 +30,7 @@ struct Edit {
visible_revision: Option<u64>,
source: Option<String>,
#[serde(default)]
files: BTreeMap<String, String>,
files: BTreeMap<String, Option<String>>,
#[serde(default)]
preview_draft: bool,
}
@@ -169,6 +169,9 @@ struct Queue {
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
if let Some(status) = texrra_engine::native::dispatch_pdf_regex_worker() {
std::process::exit(status);
}
let mut args = std::env::args_os().skip(1).map(PathBuf::from);
let usage = "native_editor SOURCE FORMAT FORMAT_RESOURCES NEW_RUN_DIR [PORT] [FILE ...]";
let source = args.next().ok_or(usage)?.canonicalize()?;
@@ -214,12 +217,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let file = project.file(&entry).expect("the editor owns its entry");
let files = editable
.iter()
.map(|(name, path)| {
let file = project
.file(path)
.expect("editable project files are immutable");
Ok((name, std::str::from_utf8(&file.data)?))
})
.filter_map(|(name, path)| project.file(path).map(|file| (name, file)))
.map(|(name, file)| Ok((name, std::str::from_utf8(&file.data)?)))
.collect::<Result<BTreeMap<_, _>, std::str::Utf8Error>>()?;
reply(
request,
@@ -257,18 +256,21 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let path = editable
.get(&name)
.ok_or_else(|| format!("File is not editable: {name}"))?;
Ok((path.clone(), Arc::from(value.into_bytes())))
if *path == entry && value.is_none() {
return Err("The entry file cannot be removed".into());
}
Ok((path.clone(), value.map(|text| Arc::from(text.into_bytes()))))
})
.collect::<Result<BTreeMap<_, _>, String>>();
let next = updates.and_then(|mut updates| {
if let Some(source) = edit.source
&& updates
.insert(entry.clone(), Arc::from(source.into_bytes()))
.insert(entry.clone(), Some(Arc::from(source.into_bytes())))
.is_some()
{
return Err("The entry file was edited twice".into());
}
project.with_file_edits(edit.sequence, updates)
project.with_file_changes(edit.sequence, updates)
});
project = match next {
Ok(project) => project,
@@ -399,6 +401,8 @@ fn prepare(
let mut editable = BTreeMap::from([(name.to_owned(), entry.clone())]);
let mut files = BTreeMap::<PathBuf, Arc<[u8]>>::from([(entry.clone(), Arc::from(original))]);
let source_root = source.parent().expect("the entry has a parent");
let mut declared = BTreeSet::from([entry.clone()]);
let mut directories = BTreeSet::new();
for relative in additional {
if relative.as_os_str().is_empty()
|| relative
@@ -412,23 +416,50 @@ fn prepare(
.into());
}
let logical = run.join(relative);
let physical = source_root.join(relative).canonicalize()?;
if !physical.starts_with(source_root) || files.contains_key(&logical) {
return Err(format!(
"Project file is outside the entry directory or is listed twice: {}",
relative.display()
)
.into());
if !declared.insert(logical.clone()) {
return Err(format!("Project file is listed twice: {}", relative.display()).into());
}
let data: Arc<[u8]> = Arc::from(fs::read(physical)?);
fs::create_dir_all(logical.parent().expect("project file has a parent"))?;
fs::write(&logical, &data)?;
let physical = source_root.join(relative);
let data = match physical.canonicalize() {
Ok(path) if path.starts_with(source_root) => Some(Arc::<[u8]>::from(fs::read(path)?)),
Ok(_) => {
return Err(format!(
"Project file is outside the entry directory: {}",
relative.display()
)
.into());
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let parent = physical
.parent()
.expect("project file has a parent")
.canonicalize()?;
if !parent.starts_with(source_root) || physical.symlink_metadata().is_ok() {
return Err(error.into());
}
None
}
Err(error) => return Err(error.into()),
};
let directory = logical.parent().expect("project file has a parent");
fs::create_dir_all(directory)?;
directories.extend(
directory
.ancestors()
.take_while(|path| path.starts_with(run))
.map(Path::to_owned),
);
if let Some(name) = relative.to_str()
&& std::str::from_utf8(&data).is_ok()
&& data
.as_deref()
.is_none_or(|bytes| std::str::from_utf8(bytes).is_ok())
{
editable.insert(name.into(), logical.clone());
}
files.insert(logical, data);
if let Some(data) = data {
fs::write(&logical, &data)?;
files.insert(logical, data);
}
}
let mut request = CompileRequest::new(
world.clone(),
@@ -475,7 +506,7 @@ fn prepare(
revision: 1,
roots: coverage,
files,
directories: BTreeSet::new(),
directories,
aliases: BTreeMap::new(),
generated_roots: BTreeSet::from([run.to_owned()]),
generated,
+2
View File
@@ -9,5 +9,7 @@ mod native_generated;
mod native_host;
mod native_job;
mod native_preview;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
mod native_regex;
mod native_stream;
pub mod rust_typeset;
+3
View File
@@ -17,6 +17,9 @@ mod route_d;
use texrra_engine::rust_typeset;
fn main() {
if let Some(status) = texrra_engine::native::dispatch_pdf_regex_worker() {
std::process::exit(status);
}
if let Err(error) = run() {
eprintln!("error: {error}");
process::exit(1);
+22 -24
View File
@@ -73,6 +73,16 @@ pub struct CompileRequest {
pub terminal: bool,
pub observer: Option<Arc<dyn CompileObserver>>,
}
/// Register this executable as the isolated pdfTeX matcher and handle its
/// internal worker invocation. Call before parsing application arguments, and
/// exit with the returned status when the invocation was handled.
pub fn dispatch_pdf_regex_worker() -> Option<i32> {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
return crate::native_regex::dispatch();
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
None
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CompileStage {
Prepared,
@@ -559,6 +569,7 @@ pub struct NativeCompiler {
jobs: Arc<Mutex<()>>,
draft_sync: Arc<DraftSyncQueue>,
format_cache: Arc<FormatCache>,
font_cache: Arc<texrra_tex_core::native_font::NativeFontCache>,
line_break_cache: Arc<texrra_tex_core::execution::LineBreakCache>,
entry_checkpoints: Option<Arc<CheckpointCache>>,
}
@@ -934,31 +945,20 @@ impl CompileJob {
.filter(|_| checkpoint_guard::can_stage(&request));
let format_cache = &self.compiler.format_cache;
let mut entry_checkpoint_work = EntryCheckpointWork::default();
let mut active_checkpoint =
checkpoints
.and_then(CheckpointCache::current)
.and_then(|available| match available.select(&request) {
Ok(selected) => Some(selected),
Err(error) => {
entry_checkpoint_work.rejection = Some(error);
None
}
});
let prepared = match active_checkpoint.as_ref() {
Some(candidate) => {
match candidate.prepare(&request, format_cache, &cancellation, evidence) {
Ok(prepared) => Some(prepared),
let (active_checkpoint, prepared) =
if let Some(available) = checkpoints.and_then(CheckpointCache::current) {
match available.prepare(&request, format_cache, &cancellation, evidence) {
Ok((selected, prepared)) => (Some(selected), Some(prepared)),
Err(error) => {
check(&cancellation)?;
*evidence = AttemptEvidence::new(revision);
entry_checkpoint_work.rejection = Some(error.to_string());
active_checkpoint = None;
None
(None, None)
}
}
}
None => None,
};
} else {
(None, None)
};
let PreparedJob {
executor,
format_preparation,
@@ -1080,12 +1080,11 @@ impl CompileJob {
)
};
if let Some(path) = &request.layout_manifest {
let source_map =
texrra_tex_core::source_map::SourceMap::from_revision(&execution, &pages)?;
let source_map = self.compiler.session.source_map(&execution, &pages)?;
files.write_layout_manifest(path, e, &pages, &source_map)?;
}
evidence.phase = AttemptPhase::Fonts;
let fonts = texrra_tex_core::native_font::resolve_native_fonts(&mut pages, files);
let fonts = self.compiler.font_cache.resolve(&mut pages, files);
let reported = report(files, &request);
if let Err(error) = fonts {
if let Err(report) = reported {
@@ -1094,8 +1093,7 @@ impl CompileJob {
return Err(CompileError::Host(error));
}
reported?;
let source_map =
texrra_tex_core::source_map::SourceMap::from_revision(&execution, &pages)?;
let source_map = self.compiler.session.source_map(&execution, &pages)?;
notify(
&request,
revision,
+642 -91
View File
@@ -4,7 +4,10 @@ use super::*;
#[cfg(test)]
use std::{collections::BTreeMap, fs};
use std::{collections::BTreeSet, ffi::OsString, path::Path};
use texrra_tex_core::{execution::EntryCheckpoint, resources::ResourceKind};
use texrra_tex_core::{
execution::EntryCheckpoint,
resources::{ResourceKind, ResourceLookup},
};
#[cfg(test)]
use texrra_tex_core::{execution::HostResourceUsage, resources::InputPolicy};
@@ -41,6 +44,7 @@ pub(super) struct CheckpointSet {
entries: Vec<Arc<CachedCheckpoint>>,
calls: Vec<Call>,
refresh_on_resume: bool,
edit_frontier: Option<usize>,
}
pub(super) struct SelectedCheckpoint {
@@ -58,6 +62,7 @@ struct CaptureSchedule {
seen: [bool; SOURCE_INTERVALS],
next_page: usize,
fixed_frontier: Option<usize>,
pending_edit_frontier: Option<usize>,
}
#[derive(Clone, Copy)]
@@ -65,20 +70,38 @@ struct CaptureSlots {
interval: usize,
early: bool,
page: bool,
edit: bool,
next_page: usize,
}
impl CaptureSchedule {
fn new(bytes: usize, fixed_frontier: Option<usize>) -> Self {
fn new(bytes: usize, fixed_frontier: Option<usize>, edit_frontier: Option<usize>) -> Self {
Self {
bytes,
stride: bytes.div_ceil(SOURCE_INTERVALS).max(1),
seen: [false; SOURCE_INTERVALS],
next_page: 1,
fixed_frontier,
pending_edit_frontier: edit_frontier,
}
}
fn take_edit_frontier(&mut self, frontier: usize, ordinary_capture: bool) -> bool {
let edit = self
.pending_edit_frontier
.take_if(|pending| *pending == frontier)
.is_some();
if edit && !ordinary_capture {
// Move a later byte-interval capture to the active editing line.
// Keep the earlier prefix and all shipout capture opportunities.
let next_interval = (frontier - 1) / self.stride + 1;
if let Some(seen) = self.seen.get_mut(next_interval) {
*seen = true;
}
}
edit
}
fn select(&mut self, frontier: usize, pages: usize) -> Option<CaptureSlots> {
if let Some(minimum) = self.fixed_frontier {
if self.seen[0] || frontier < minimum {
@@ -89,6 +112,7 @@ impl CaptureSchedule {
interval: 0,
early: true,
page: false,
edit: false,
next_page: self.next_page,
});
}
@@ -101,10 +125,12 @@ impl CaptureSchedule {
if page {
self.next_page = pages.saturating_add((pages / 8).max(1).next_power_of_two());
}
(early || page).then_some(CaptureSlots {
let edit = self.take_edit_frontier(frontier, early || page);
(early || page || edit).then_some(CaptureSlots {
interval,
early,
page,
edit,
next_page: self.next_page,
})
}
@@ -120,6 +146,7 @@ impl CaptureSchedule {
Some(CaptureSlots {
interval,
early,
edit: self.take_edit_frontier(frontier, early || checkpoint.slots.page),
..checkpoint.slots
})
}
@@ -131,6 +158,7 @@ struct CapturedEntries<'a> {
initial: Option<GeneratedInitialState>,
early: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
shipped: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
edit: Option<Arc<CachedCheckpoint>>,
changed: bool,
}
@@ -146,6 +174,7 @@ impl<'a> CapturedEntries<'a> {
initial: files.preparation().generated_initial.clone(),
early: Default::default(),
shipped: Default::default(),
edit: None,
changed: false,
}
}
@@ -154,6 +183,9 @@ impl<'a> CapturedEntries<'a> {
if slots.early {
self.early[slots.interval] = Some(checkpoint.clone());
}
if slots.edit {
self.edit = Some(checkpoint.clone());
}
if slots.page {
self.shipped[slots.interval] = Some(checkpoint);
}
@@ -167,8 +199,13 @@ impl<'a> CapturedEntries<'a> {
) else {
return;
};
let Ok(guard) = PrefixInputGuard::capture(self.request, path, trace, initial.clone())
else {
let Ok(guard) = PrefixInputGuard::capture(
self.request,
path,
trace,
host.generated_outputs(),
initial.clone(),
) else {
return;
};
self.retain(
@@ -191,14 +228,34 @@ impl<'a> CapturedEntries<'a> {
if !self.changed {
return None;
}
let edit_frontier = self
.edit
.as_ref()
.map(|checkpoint| checkpoint.entry.frontier());
let mut entries: Vec<_> = self
.early
.into_iter()
.chain(self.shipped)
.flatten()
.chain(self.edit)
.collect();
entries.sort_by_key(|candidate| candidate.entry.completed_steps());
entries.dedup_by(|a, b| Arc::ptr_eq(a, b));
if entries.len() > 2 * SOURCE_INTERVALS {
let edit = edit_frontier.expect("an edit checkpoint can fill the remaining slot");
// Preserve the earliest continuation and the page checkpoints.
// Displace the ordinary continuation closest to the edited line.
let (index, _) = entries
.iter()
.enumerate()
.skip(1)
.filter(|(_, checkpoint)| {
!checkpoint.slots.page && checkpoint.entry.frontier() != edit
})
.min_by_key(|(_, checkpoint)| checkpoint.entry.frontier().abs_diff(edit))
.expect("the full schedule has ordinary continuations");
entries.remove(index);
}
let replay_count = entries.iter().map(|entry| entry.replay_count).max()?;
let mut calls = recording.into_calls()?;
calls.truncate(replay_count);
@@ -206,6 +263,7 @@ impl<'a> CapturedEntries<'a> {
entries,
calls,
refresh_on_resume,
edit_frontier,
}))
}
}
@@ -283,7 +341,7 @@ impl CheckpointCache {
Result<Arc<RevisionExecution>, RevisionFailure>,
Option<Arc<CheckpointSet>>,
) {
let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier);
let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier, None);
let mut captures = CapturedEntries::new(request, files);
let mut recording = RecordingHost::new(files);
let result = job.run_capturing_entries(
@@ -303,24 +361,92 @@ impl CheckpointCache {
}
impl PublishedCheckpoints {
pub(super) fn select(&self, request: &CompileRequest) -> Result<SelectedCheckpoint, String> {
let current = self.current.clone().select(request);
let Some(previous) = &self.previous_body else {
return current;
};
let completed = current
.as_ref()
.map_or(0, SelectedCheckpoint::completed_steps);
if previous
.entries
.last()
.is_some_and(|entry| entry.entry.completed_steps() > completed)
&& let Ok(previous) = previous.clone().select(request)
&& previous.completed_steps() > completed
{
return Ok(previous);
pub(super) fn prepare(
&self,
request: &CompileRequest,
cache: &FormatCache,
cancellation: &Cancellation,
evidence: &mut AttemptEvidence,
) -> Result<(SelectedCheckpoint, PreparedJob), CompileError> {
let project = request
.project
.as_deref()
.ok_or_else(|| CompileError::Host("checkpoint requires an atomic project".into()))?;
let mut candidates: Vec<_> = self
.current
.candidates()
.chain(self.previous_body.iter().flat_map(|body| body.candidates()))
.collect();
candidates.sort_by_key(|candidate| std::cmp::Reverse(candidate.completed_steps()));
let mut candidates = candidates.into_iter();
let mut rejection = None;
let first = candidates
.by_ref()
.find(|candidate| {
let checkpoint = &candidate.set.entries[candidate.index];
match checkpoint
.accept_entry(project)
.and_then(|()| checkpoint.guard.verify_project(request))
{
Ok(_) => true,
Err(error) => {
rejection.get_or_insert(error);
false
}
}
})
.ok_or_else(|| {
CompileError::Host(
rejection.unwrap_or_else(|| "no entry checkpoint retained".into()),
)
})?;
// Host preparation observes the actual generated files while the job
// lock is held. Choose a valid prefix before replaying any effects.
let mut selected = None;
let mut prepared = prepare_checked(
request,
false,
Some(cache),
cancellation,
evidence,
Some(Box::new(|world, preparation| {
let mut rejection = None;
for candidate in std::iter::once(first).chain(candidates) {
let checkpoint = &candidate.set.entries[candidate.index];
match checkpoint
.accept_entry(project)
.and_then(|()| checkpoint.guard.verify(request, world, preparation))
{
Ok(()) => {
selected = Some(candidate);
return Ok(());
}
Err(error) => {
rejection.get_or_insert(error);
}
}
}
Err(rejection.unwrap_or_else(|| "no entry checkpoint retained".into()))
})),
EffectMode::Draft,
KernelPreparation::Resume,
)?;
let selected = selected.expect("resume preparation chose a verified checkpoint");
let checkpoint = &selected.set.entries[selected.index];
for call in &selected.set.calls[..checkpoint.replay_count] {
check(cancellation)?;
call(&mut prepared.files)?;
}
current
if !checkpoint
.guard
.project
.immutable_paths()
.eq(project.immutable_paths())
{
checkpoint.guard.verify_replayed_lookups(&prepared.files)?;
}
Ok((selected, prepared))
}
}
@@ -342,6 +468,7 @@ impl CheckpointSet {
entries,
calls: self.calls[..replay_count].to_vec(),
refresh_on_resume: self.refresh_on_resume,
edit_frontier: self.edit_frontier,
}))
}
@@ -350,27 +477,13 @@ impl CheckpointSet {
work.captured_frontier = self.entries.last().map(|entry| entry.entry.frontier());
}
pub(super) fn select(
self: Arc<Self>,
request: &CompileRequest,
) -> Result<SelectedCheckpoint, String> {
let project = request
.project
.as_deref()
.ok_or("checkpoint requires an atomic project")?;
let mut rejection = None;
for (index, checkpoint) in self.entries.iter().enumerate().rev() {
match checkpoint
.accept_entry(project)
.and_then(|()| checkpoint.guard.verify_project(request))
{
Ok(_) => return Ok(SelectedCheckpoint { set: self, index }),
Err(error) => {
rejection.get_or_insert(error);
}
}
}
Err(rejection.unwrap_or_else(|| "no entry checkpoint retained".into()))
fn candidates(self: &Arc<Self>) -> impl Iterator<Item = SelectedCheckpoint> + '_ {
(0..self.entries.len())
.rev()
.map(|index| SelectedCheckpoint {
set: Arc::clone(self),
index,
})
}
}
@@ -394,38 +507,6 @@ impl SelectedCheckpoint {
self.set.entries[self.index].entry.completed_steps()
}
pub(super) fn prepare(
&self,
request: &CompileRequest,
cache: &FormatCache,
cancellation: &Cancellation,
evidence: &mut AttemptEvidence,
) -> Result<PreparedJob, CompileError> {
let checkpoint = &self.set.entries[self.index];
let mut prepared = prepare_checked(
request,
false,
Some(cache),
cancellation,
evidence,
Some(Box::new(|world, preparation| {
checkpoint.guard.verify(request, world, preparation)?;
checkpoint.accept_entry(
world
.project()
.ok_or("checkpoint requires an atomic project")?,
)
})),
EffectMode::Draft,
KernelPreparation::Resume,
)?;
for call in &self.set.calls[..checkpoint.replay_count] {
check(cancellation)?;
call(&mut prepared.files)?;
}
Ok(prepared)
}
pub(super) fn resume(
self,
request: &CompileRequest,
@@ -455,7 +536,13 @@ impl SelectedCheckpoint {
return Ok((result, self.set));
}
let mut schedule = CaptureSchedule::new(source.data.len(), None);
let previous = checkpoint
.guard
.project
.file(&checkpoint.guard.entry)
.expect("a checkpoint records its source");
let edit = changed_line_start(&previous.data, &source.data).or(self.set.edit_frontier);
let mut schedule = CaptureSchedule::new(source.data.len(), None, edit);
let mut captures = CapturedEntries::new(request, files);
// Share only calls and continuations from the prefix just replayed.
for previous in &self.set.entries[..=self.index] {
@@ -498,12 +585,36 @@ impl SelectedCheckpoint {
}
}
fn changed_line_start(previous: &[u8], current: &[u8]) -> Option<usize> {
if previous == current {
return None;
}
let common = previous
.iter()
.zip(current)
.take_while(|(old, new)| old == new)
.count();
let mut prefix = &current[..common];
// A CR followed by LF is one physical line ending.
if prefix.ends_with(b"\r") && current.get(common) == Some(&b'\n') {
prefix = &prefix[..prefix.len() - 1];
}
Some(
prefix
.iter()
.rposition(|byte| matches!(*byte, b'\r' | b'\n'))
.map_or(0, |offset| offset + 1),
)
}
struct PrefixInputGuard {
original: AttemptRequest,
project: Arc<ProjectSnapshot>,
initial: GeneratedInitialState,
entry: PathBuf,
immutable: BTreeSet<PathBuf>,
generated: BTreeSet<PathBuf>,
lookups: Vec<ResourceLookup>,
clock_environment: Option<[Option<OsString>; 3]>,
}
@@ -516,6 +627,7 @@ impl PrefixInputGuard {
request: &CompileRequest,
entry: &Path,
trace: &ResourceTrace,
written: &BTreeSet<PathBuf>,
initial: GeneratedInitialState,
) -> Result<Self, String> {
let project = request
@@ -550,16 +662,26 @@ impl PrefixInputGuard {
.map(|item| item.target.as_path()),
);
let mut immutable = BTreeSet::new();
let mut generated = BTreeSet::new();
for path in tracked {
if project.file(path).is_some() {
immutable.insert(path.to_path_buf());
} else if !initial.files().contains_key(path) {
} else if initial.files().contains_key(path) {
generated.insert(path.to_path_buf());
} else {
return Err(format!(
"checkpoint input has no stable initial role: {}",
path.display()
));
}
}
// Opening a generated output observes its pre-write version.
generated.extend(
written
.iter()
.filter(|path| initial.files().contains_key(*path))
.cloned(),
);
for observed in &trace.file_modifications {
if project.file(&observed.path).is_none() {
return Err("checkpoint file date requires a captured immutable resource".into());
@@ -572,6 +694,8 @@ impl PrefixInputGuard {
initial,
entry: entry.to_path_buf(),
immutable,
generated,
lookups: trace.lookups.clone(),
clock_environment: (!trace.file_modifications.is_empty()).then(date_environment),
})
}
@@ -597,8 +721,8 @@ impl PrefixInputGuard {
.project
.as_deref()
.ok_or("checkpoint requires an atomic project")?;
if !self.project.same_lookup_namespace(current)? {
return Err("checkpoint lookup namespace changed".into());
if !self.project.same_lookup_configuration(current)? {
return Err("checkpoint lookup configuration changed".into());
}
for path in &self.immutable {
let old = self.project.file(path).map(|file| &file.version);
@@ -621,6 +745,19 @@ impl PrefixInputGuard {
Ok(current)
}
fn verify_replayed_lookups(&self, files: &Files) -> Result<(), CompileError> {
let trace = files.resource_trace();
if trace.lookups != self.lookups
|| !trace.read_errors.is_empty()
|| !trace.namespace_capture_failures.is_empty()
{
return Err(CompileError::Host(
"checkpoint replayed lookup changed".into(),
));
}
Ok(())
}
fn verify(
&self,
request: &CompileRequest,
@@ -635,7 +772,21 @@ impl PrefixInputGuard {
.generated_initial
.as_ref()
.ok_or("checkpoint requires generated versions observed under the job lock")?;
self.initial.check(current)
if self.initial.cwd() != current.cwd() {
return Err("generated initial workdir differs from the actual host".into());
}
for path in self.initial.files().keys().chain(current.files().keys()) {
let before = self.initial.files().get(path);
let after = current.files().get(path);
let same_presence = before.map(Option::is_some) == after.map(Option::is_some);
if !same_presence || (self.generated.contains(path) && before != after) {
return Err(format!(
"generated initial role or version mismatch: {}",
path.display()
));
}
}
Ok(())
}
}
@@ -728,10 +879,14 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
executor
.unwrap()
.run_capturing_entry(source, &mut recording, PREFIX.len() - 25, |host| {
(host.capture(), host.resource_usage().unwrap().unwrap())
(
host.capture(),
host.resource_usage().unwrap().unwrap(),
host.generated_outputs().clone(),
)
});
assert!(executed.is_ok());
let (checkpoint, (recorded, usage)) = checkpoint.unwrap();
let (checkpoint, (recorded, usage, written)) = checkpoint.unwrap();
let (calls, trace) = recorded.unwrap();
assert_eq!(usage.open_outputs, Some(1));
assert!(
@@ -740,7 +895,9 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
.iter()
.any(|lookup| lookup.name == "optional.tex" && lookup.resolved.is_none())
);
let guard = PrefixInputGuard::capture(&request, &entry, &trace, initial).unwrap();
let guard = PrefixInputGuard::capture(&request, &entry, &trace, &written, initial).unwrap();
assert!(guard.generated.contains(&aux));
assert!(!guard.generated.contains(&seed));
assert!(guard.immutable.contains(&library));
assert!(!guard.immutable.contains(&unrelated));
assert!(!guard.immutable.contains(&entry));
@@ -805,16 +962,16 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
&request.clone().with_project(changed_prefix),
"entry prefix changed",
);
let mut appeared = definition;
appeared.revision = 3;
appeared
.files
.insert(cwd.join("optional.tex"), Arc::from(b"present".as_slice()));
let mut changed_namespace = definition;
changed_namespace.revision = 3;
changed_namespace
.directories
.insert(cwd.join("new-directory"));
rejected(
&request
.clone()
.with_project(ProjectSnapshot::new(appeared).unwrap()),
"lookup namespace changed",
.with_project(ProjectSnapshot::new(changed_namespace).unwrap()),
"lookup configuration changed",
);
let mut changed_clock = request.clone();
changed_clock.time = JobTime::new(2026, 11, 18, 1001).unwrap();
@@ -1177,6 +1334,400 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
);
}
#[test]
fn immutable_file_creation_and_removal_replay_real_lookup_results() {
use texrra_tex_core::resources::SearchPath;
let cwd = std::env::temp_dir().join(format!("texrra-file-revisions-{}", std::process::id()));
fs::create_dir(&cwd).unwrap();
let cwd = cwd.canonicalize().unwrap();
let vendor = cwd.join("vendor");
let entry = cwd.join("entry.tex");
let aux = cwd.join("entry.aux");
let extra = cwd.join("unread.tex");
let settings = cwd.join("settings.tex");
let vendor_settings = vendor.join("settings.tex");
let tag = cwd.join("tag.tex");
let vendor_tag = vendor.join("tag.tex");
let prefix = concat!(
"\\catcode123=1 \\catcode125=2\n",
"\\def\\value{10}\n",
"\\openin3=settings.tex \\ifeof3\\else\\input settings.tex \\fi\\closein3\n",
"\\edef\\filesize{\\pdffilesize{tag.tex}}\n",
"\\immediate\\openout1=entry.aux\n",
"\\immediate\\write1{unchanged journal}\\relax\n",
"\\message{CHECKPOINT}\\relax\n",
);
let tail = "\\shipout\\hbox{\\vrule width\\value pt height1pt}\n\\immediate\\closeout1\\end\n";
let world = {
let mut world = WorldConfig::new(&cwd);
world.paths.insert(
ResourceKind::Tex,
vec![
SearchPath::directory(&cwd, false),
SearchPath::directory(&vendor, false),
],
);
world
};
let mut project = ProjectSnapshot::new(ProjectDefinition {
configuration: world.clone(),
revision: 1,
roots: BTreeSet::from([cwd.clone()]),
files: BTreeMap::from([
(
entry.clone(),
Arc::from(format!("{prefix}{tail}").into_bytes()),
),
(vendor_tag.clone(), Arc::from(b"42".as_slice())),
]),
directories: BTreeSet::from([vendor]),
aliases: BTreeMap::new(),
generated_roots: BTreeSet::from([cwd.clone()]),
generated: BTreeSet::from([aux.clone()]),
})
.unwrap();
assert!(
project
.with_file_changes(
2,
BTreeMap::from([(aux.clone(), Some(Arc::from(b"source collision".as_slice())))]),
)
.is_err()
);
assert!(
project
.with_file_changes(
2,
BTreeMap::from([(cwd.join("missing-parent/entry.tex"), Some(Arc::from([])))]),
)
.is_err()
);
let mut request = CompileRequest::new(
world,
"entry.tex",
"entry.pdf",
JobTime::new(2026, 11, 20, 540)
.unwrap()
.with_pdf_clock(0, 0)
.unwrap(),
)
.observe_generated_initial();
request.entry = Entry::Initex;
request.etex = true;
NativeCompiler::default()
.compile(request.clone().with_project(project.clone()))
.unwrap();
let journal = fs::read(&aux).unwrap();
let compiler = NativeCompiler::default().with_entry_checkpoints(prefix.len() - 2);
let revisions = [
("cold", None, false, None, 10),
(
"unrelated appeared",
Some((&extra, Some(b"unused".as_slice()))),
true,
None,
10,
),
("unrelated removed", Some((&extra, None)), true, None, 10),
(
"missing dependency appeared",
Some((&vendor_settings, Some(br"\def\value{20}".as_slice()))),
false,
Some("open_in changed"),
20,
),
(
"higher priority dependency appeared",
Some((&settings, Some(br"\def\value{30}".as_slice()))),
false,
Some("open_in changed"),
30,
),
(
"dependency edited",
Some((&settings, Some(br"\def\value{40}".as_slice()))),
false,
Some("observed input changed"),
40,
),
(
"removed dependency exposes fallback",
Some((&settings, None)),
false,
Some("observed input changed"),
20,
),
(
"removed fallback",
Some((&vendor_settings, None)),
false,
Some("observed input changed"),
10,
),
(
"equal-size result came from a new path",
Some((&tag, Some(b"59".as_slice()))),
false,
Some("replayed lookup changed"),
10,
),
(
"unrelated file appeared again",
Some((&extra, Some(b"new unused".as_slice()))),
true,
None,
10,
),
];
let mut pdfs = BTreeMap::new();
for (index, (label, edit, reuse, rejection, width)) in revisions.into_iter().enumerate() {
if let Some((path, bytes)) = edit {
let previous = project.clone();
project = project
.with_file_changes(
index as u64 + 1,
BTreeMap::from([(path.clone(), bytes.map(Arc::from))]),
)
.unwrap();
if label == "unrelated appeared" {
assert!(previous.file(path).is_none());
assert!(project.file(path).is_some());
}
}
let next = request.clone().with_project(project.clone());
let result = compiler.compile(next.clone()).unwrap();
let work = &result.entry_checkpoint_work;
assert_eq!(work.reused_steps > 0, reuse, "{label}: {work:?}");
if let Some(expect) = rejection {
assert!(
work.rejection
.as_deref()
.is_some_and(|e| e.contains(expect)),
"{label}: {work:?}"
);
}
assert_eq!(fs::read(&aux).unwrap(), journal, "{label}");
let full = NativeCompiler::default().compile(next).unwrap();
assert_eq!(full.entry_checkpoint_work.reused_steps, 0, "{label}");
assert_eq!(result.pdf, full.pdf, "{label}");
assert_eq!(result.source_map.pages, full.source_map.pages, "{label}");
assert_eq!(
result.source_map.sources, full.source_map.sources,
"{label}"
);
assert_eq!(
result.preview_since(None).unwrap().pages,
full.preview_since(None).unwrap().pages,
"{label}",
);
assert_eq!(
result.execution.execution, full.execution.execution,
"{label}"
);
assert_eq!(
result.resources.trace.lookups, full.resources.trace.lookups,
"{label}"
);
assert_eq!(fs::read(&aux).unwrap(), journal, "{label}");
if let Some(previous) = pdfs.insert(width, result.pdf.clone()) {
assert_eq!(previous, result.pdf, "{label}");
}
eprintln!("{label}: {work:?}");
}
assert_eq!(pdfs.values().collect::<BTreeSet<_>>().len(), 4);
}
#[test]
fn automatic_checkpoints_refresh_the_previous_edit_line_after_a_child_edit() {
let mut schedule = CaptureSchedule::new(400, None, Some(290));
assert!(schedule.select(215, 0).unwrap().early);
let edit = schedule.select(290, 0).unwrap();
assert!(edit.edit && !edit.early);
assert!(schedule.select(345, 0).is_none());
assert!(schedule.select(345, 1).unwrap().page);
let cwd = std::env::temp_dir().join(format!("texrra-edit-line-{}", std::process::id()));
fs::create_dir(&cwd).unwrap();
let cwd = cwd.canonicalize().unwrap();
let entry = cwd.join("main.tex");
let child = cwd.join("child.tex");
let source_prefix = format!(
"\\catcode123=1 \\catcode125=2\n{}\\input child.tex\n{}",
"\\advance\\count0 by 1\\relax\n".repeat(40),
"\\advance\\count2 by 1\\relax\n".repeat(18),
);
let edited_line_start = source_prefix.len();
let original = format!(
"{source_prefix}\\shipout\\hbox{{\\vrule width1pt height\\heightfromchild pt}}\n{}\\end\n",
"\\advance\\count1 by 1\\relax\n".repeat(5),
);
let mut world = WorldConfig::new(&cwd);
world.input_policy = InputPolicy::Tex;
let project = ProjectSnapshot::new(ProjectDefinition {
configuration: world.clone(),
revision: 1,
roots: BTreeSet::from([cwd.clone()]),
files: BTreeMap::from([
(entry.clone(), Arc::from(original.as_bytes())),
(
child.clone(),
Arc::from(b"\\def\\heightfromchild{1}\n".as_slice()),
),
]),
directories: BTreeSet::new(),
aliases: BTreeMap::new(),
generated_roots: BTreeSet::from([cwd.clone()]),
generated: BTreeSet::new(),
})
.unwrap();
let mut request = CompileRequest::new(
world,
"main.tex",
"main.pdf",
JobTime::new(2026, 11, 20, 540)
.unwrap()
.with_pdf_clock(0, 0)
.unwrap(),
)
.with_project(project.clone())
.observe_generated_initial();
request.entry = Entry::Initex;
NativeCompiler::default().compile(request.clone()).unwrap();
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
session.compile(request.clone()).unwrap();
let entry_edit = project
.with_file_edits(
2,
BTreeMap::from([(
entry.clone(),
Arc::from(original.replace("width1pt", "width2pt").into_bytes()),
)]),
)
.unwrap();
session
.compile(request.clone().with_project(entry_edit.clone()))
.unwrap();
let child_edit = entry_edit
.with_file_edits(
3,
BTreeMap::from([(child, Arc::from(b"\\def\\heightfromchild{3}\n".as_slice()))]),
)
.unwrap();
let child_result = session
.compile(request.clone().with_project(child_edit.clone()))
.unwrap();
let child_work = &child_result.entry_checkpoint_work;
assert!(
child_work.reused_frontier.unwrap() < edited_line_start,
"{child_work:?}"
);
let revision = child_edit
.with_file_edits(
4,
BTreeMap::from([(
entry,
Arc::from(original.replace("width1pt", "width4pt").into_bytes()),
)]),
)
.unwrap();
let request = request.with_project(revision);
let updated = session.compile(request.clone()).unwrap();
let full = NativeCompiler::default().compile(request).unwrap();
let work = &updated.entry_checkpoint_work;
assert_eq!(work.reused_frontier, Some(edited_line_start), "{work:?}");
assert!(work.reused_steps > child_work.reused_steps, "{work:?}");
assert!(
work.retained_checkpoints <= 2 * SOURCE_INTERVALS,
"{work:?}"
);
assert!(updated.pages[0].items.iter().any(|item| matches!(
item,
texrra_tex_core::render::DisplayItem::Rule { width, height, .. }
if (*width, *height) == (4 * 65_536, 3 * 65_536)
)));
assert_eq!(updated.pdf, full.pdf);
assert_eq!(updated.source_map.sources, full.source_map.sources);
assert_eq!(updated.source_map.pages, full.source_map.pages);
assert!(updated.execution.execution == full.execution.execution);
}
#[test]
fn generated_input_change_uses_a_checkpoint_before_the_read() {
let cwd = std::env::temp_dir().join(format!("texrra-generated-prefix-{}", std::process::id()));
fs::create_dir(&cwd).unwrap();
let cwd = cwd.canonicalize().unwrap();
let entry = cwd.join("main.tex");
let aux = cwd.join("observed.aux");
fs::write(&aux, b"\\def\\widthfromaux{11}\n").unwrap();
let source = format!(
"\\catcode123=1 \\catcode125=2\n{}\\input observed.aux\n{}\\shipout\\hbox{{\\vrule width\\widthfromaux pt height1pt}}\n\\end",
"\\advance\\count0 by 1\\relax\n".repeat(20),
"\\advance\\count0 by 1\\relax\n".repeat(12),
);
let input_offset = source.find("\\input observed.aux").unwrap();
let mut world = WorldConfig::new(&cwd);
world.input_policy = texrra_tex_core::resources::InputPolicy::Tex;
let project = ProjectSnapshot::new(ProjectDefinition {
configuration: world.clone(),
revision: 1,
roots: BTreeSet::from([cwd.clone()]),
files: BTreeMap::from([(entry, Arc::from(source.into_bytes()))]),
directories: BTreeSet::new(),
aliases: BTreeMap::new(),
generated_roots: BTreeSet::from([cwd.clone()]),
generated: BTreeSet::from([aux.clone()]),
})
.unwrap();
let mut request = CompileRequest::new(
world,
"main.tex",
"main.pdf",
JobTime::new(2026, 11, 20, 540)
.unwrap()
.with_pdf_clock(0, 0)
.unwrap(),
)
.with_project(project)
.observe_generated_initial();
request.entry = Entry::Initex;
let session = NativeCompiler::default().with_automatic_entry_checkpoints();
let original = session.compile(request.clone()).unwrap();
let last = original.entry_checkpoint_work.captured_frontier.unwrap();
assert!(last > input_offset);
fs::write(&aux, b"\\def\\widthfromaux{22}\n").unwrap();
let updated = session.compile(request.clone()).unwrap();
let full = NativeCompiler::default().compile(request).unwrap();
let work = &updated.entry_checkpoint_work;
assert!(work.reused_steps > 0, "{work:?}");
assert!(work.reused_frontier.unwrap() < last, "{work:?}");
for (document, width) in [(&original, 11_i64), (&updated, 22)] {
let rules: Vec<_> = document
.pages
.iter()
.flat_map(|page| &page.items)
.filter_map(|item| match item {
texrra_tex_core::render::DisplayItem::Rule { width, height, .. } => {
Some((*width, *height))
}
_ => None,
})
.collect();
assert_eq!(rules, [(width * 65_536, 65_536)]);
}
assert_ne!(updated.pdf, original.pdf);
assert_eq!(updated.pdf, full.pdf);
assert_eq!(updated.source_map.sources, full.source_map.sources);
assert_eq!(updated.source_map.pages, full.source_map.pages);
assert!(updated.execution.execution == full.execution.execution);
assert_eq!(fs::read(&aux).unwrap(), b"\\def\\widthfromaux{22}\n");
}
#[test]
fn automatic_checkpoints_follow_successive_edits_at_different_frontiers() {
let cwd = std::env::temp_dir().join(format!("texrra-rolling-{}", std::process::id()));
+16 -1
View File
@@ -1,6 +1,6 @@
//! Capture and verify the native host calls made by an entry prefix.
use super::*;
use std::fmt::Debug;
use std::{collections::BTreeSet, fmt::Debug};
#[cfg(test)]
use std::{fs, path::Path};
#[cfg(test)]
@@ -42,6 +42,10 @@ impl<'a> RecordingHost<'a> {
(count < MAX_REPLAY_CALLS).then(|| (self.files.resource_trace(), count))
}
pub(super) fn generated_outputs(&self) -> &BTreeSet<PathBuf> {
self.files.generated_outputs()
}
pub(super) fn into_calls(self) -> Option<Vec<Call>> {
self.calls
}
@@ -83,6 +87,17 @@ macro_rules! call {
}
impl SourceProvider for RecordingHost<'_> {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn match_pdf_regex(
&mut self,
request: &texrra_tex_core::execution::RegexRequest,
cancellation: Option<&Cancellation>,
) -> Result<texrra_tex_core::execution::RegexOutcome, String> {
// GNU matching consumes only kernel-supplied bytes and is pinned to
// this executable on registered frontends. Its result is kernel state.
self.files.match_pdf_regex(request, cancellation)
}
fn execution_resource_trace(&self) -> Option<&ResourceTrace> {
self.files.execution_resource_trace()
}
+28
View File
@@ -151,6 +151,8 @@ struct DraftLedger {
pub struct Files {
world: FileWorld,
#[cfg(all(target_os = "linux", target_env = "gnu"))]
regex_worker: Option<crate::native_regex::Worker>,
cwd: PathBuf,
inputs: BTreeMap<u8, Input>,
outputs: BTreeMap<u8, Output>,
@@ -547,6 +549,8 @@ impl Files {
preparation.phase = HostPreparationPhase::Ready;
Ok(Self {
world: stored_world.take().unwrap(),
#[cfg(all(target_os = "linux", target_env = "gnu"))]
regex_worker: None,
cwd,
inputs: BTreeMap::new(),
outputs: BTreeMap::new(),
@@ -638,6 +642,11 @@ impl Files {
.borrow_mut()
.operation(name, path, result);
}
pub(super) fn generated_outputs(&self) -> &BTreeSet<PathBuf> {
&self.generated_written
}
pub fn resource_trace(&self) -> &texrra_tex_core::resources::ResourceTrace {
self.world.trace()
}
@@ -1399,6 +1408,25 @@ pub(crate) fn absolute_output(cwd: &Path, path: &Path) -> Result<PathBuf, String
}
impl SourceProvider for Files {
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn match_pdf_regex(
&mut self,
request: &texrra_tex_core::execution::RegexRequest,
cancellation: Option<&Cancellation>,
) -> Result<texrra_tex_core::execution::RegexOutcome, String> {
use crate::native_regex::{self, Worker};
if !native_regex::enabled() {
return texrra_tex_core::execution::match_pdf_regex(request);
}
if self.regex_worker.is_none() {
self.regex_worker = Some(Worker::start()?);
}
self.regex_worker
.as_mut()
.expect("native matcher was started")
.request(request, cancellation)
}
fn execution_resource_trace(&self) -> Option<&texrra_tex_core::resources::ResourceTrace> {
Some(self.world.trace())
}
+143
View File
@@ -0,0 +1,143 @@
use std::{
ffi::OsStr,
io::{self, BufRead, BufReader, Write},
process::{Child, Command, Stdio},
sync::{
atomic::{AtomicBool, Ordering},
mpsc::{self, Receiver, Sender},
},
thread::{self, JoinHandle},
time::Duration,
};
use texrra_tex_core::execution::{Cancellation, RegexOutcome, RegexRequest, match_pdf_regex};
const WORKER_ARGUMENT: &str = "--internal-pdf-regex-worker";
static WORKER_ENABLED: AtomicBool = AtomicBool::new(false);
pub(crate) fn dispatch() -> Option<i32> {
let mut args = std::env::args_os().skip(1);
if args.next().as_deref() != Some(OsStr::new(WORKER_ARGUMENT)) {
WORKER_ENABLED.store(true, Ordering::Relaxed);
return None;
}
Some(match serve() {
Ok(()) => 0,
Err(error) => {
eprintln!("pdfTeX regex worker: {error}");
1
}
})
}
pub(crate) fn enabled() -> bool {
WORKER_ENABLED.load(Ordering::Relaxed)
}
fn serve() -> Result<(), Box<dyn std::error::Error>> {
let mut input = io::stdin().lock();
let mut output = io::stdout().lock();
let mut request = Vec::new();
loop {
request.clear();
if input.read_until(b'\n', &mut request)? == 0 {
return Ok(());
}
let request: RegexRequest = serde_json::from_slice(&request)?;
serde_json::to_writer(&mut output, &match_pdf_regex(&request))?;
output.write_all(b"\n")?;
output.flush()?;
}
}
pub(crate) struct Worker {
child: Child,
requests: Option<Sender<Vec<u8>>>,
answers: Receiver<Result<RegexOutcome, String>>,
pipe: Option<JoinHandle<()>>,
}
impl Worker {
pub(crate) fn start() -> Result<Self, String> {
// Re-execute the current image, even if an installer has replaced its
// original path since the process opened the project.
let mut child = Command::new("/proc/self/exe")
.arg(WORKER_ARGUMENT)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.map_err(|e| format!("pdfTeX regex worker launch: {e}"))?;
let mut input = child.stdin.take().expect("worker stdin is piped");
let mut output = BufReader::new(child.stdout.take().expect("worker stdout is piped"));
let (requests, waiting) = mpsc::channel::<Vec<u8>>();
let (answer, answers) = mpsc::sync_channel(1);
let pipe = thread::spawn(move || {
let mut response = Vec::new();
for request in waiting {
let result = (|| {
input.write_all(&request).map_err(|e| e.to_string())?;
input.write_all(b"\n").map_err(|e| e.to_string())?;
response.clear();
if output
.read_until(b'\n', &mut response)
.map_err(|e| e.to_string())?
== 0
{
return Err("pdfTeX regex worker closed its response pipe".into());
}
serde_json::from_slice::<Result<RegexOutcome, String>>(&response)
.map_err(|e| format!("pdfTeX regex response: {e}"))?
})();
if answer.send(result).is_err() {
break;
}
}
});
Ok(Self {
child,
requests: Some(requests),
answers,
pipe: Some(pipe),
})
}
pub(crate) fn request(
&mut self,
request: &RegexRequest,
cancellation: Option<&Cancellation>,
) -> Result<RegexOutcome, String> {
let payload = serde_json::to_vec(request).map_err(|e| e.to_string())?;
self.requests
.as_ref()
.ok_or("pdfTeX regex worker has stopped")?
.send(payload)
.map_err(|_| "pdfTeX regex worker has stopped")?;
loop {
if cancellation.is_some_and(Cancellation::is_cancelled) {
self.stop();
return Err("native compilation cancelled".into());
}
match self.answers.recv_timeout(Duration::from_millis(2)) {
Ok(result) => return result,
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => {
return Err("pdfTeX regex worker lost its response pipe".into());
}
}
}
}
fn stop(&mut self) {
self.requests.take();
if let Some(pipe) = self.pipe.take() {
let _ = self.child.kill();
let _ = self.child.wait();
let _ = pipe.join();
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
self.stop();
}
}
+41
View File
@@ -158,6 +158,47 @@ fn preview_reuses_unchanged_page_svg_with_current_sources_after_edits() {
fs::remove_dir_all(p).unwrap();
}
#[test]
fn replacing_a_type1_program_at_the_same_path_updates_native_pdf_and_preview() {
let p = directory("type1-cache");
let compiler = NativeCompiler::default();
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("assets/fonts");
let font = p.join("example.pfb");
fs::write(p.join("pdftex.map"), "cmr10 <example.pfb\n").unwrap();
write(&p, r"\shipout\hbox{A stable word}\end");
let request_for_font = || {
let mut r = request(&p);
for kind in [ResourceKind::Map, ResourceKind::Type1] {
r.world
.paths
.insert(kind, vec![SearchPath::directory(p.clone(), false)]);
}
r
};
fs::copy(root.join("cmr10.pfb"), &font).unwrap();
let actual_first = file_version(&font).unwrap().unwrap();
let before = compiler.compile(request_for_font()).unwrap();
assert!(before.resources.trace.reads.contains(&actual_first));
let old_svg = before.preview_since(None).unwrap().pages[0].svg.clone();
fs::copy(root.join("cmss10.pfb"), &font).unwrap();
let actual_second = file_version(&font).unwrap().unwrap();
assert_ne!(actual_first.sha256, actual_second.sha256);
let after = compiler.compile(request_for_font()).unwrap();
assert!(after.resources.trace.reads.contains(&actual_second));
let delta = after.preview_since(Some(before.revision())).unwrap();
assert_eq!(delta.pages.len(), 1);
assert_ne!(old_svg, delta.pages[0].svg);
assert!(before.pdf != after.pdf);
let cold = NativeCompiler::default().compile(request_for_font()).unwrap();
assert_eq!(delta.pages, cold.preview_since(None).unwrap().pages);
assert!(after.pdf == cold.pdf);
assert_eq!(after.source_map.pages, cold.source_map.pages);
assert_eq!(before.preview_since(None).unwrap().pages[0].svg, old_svg);
fs::remove_dir_all(p).unwrap();
}
#[test]
fn graphics_transform_updates_preview_and_source_bounds_without_remeasuring_the_box() {
use texrra_tex_core::{pdf_device::PdfGraphics, render::DisplayItem, source_map::Bounds};