Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
31bf50806e |
No files matched your search
@@ -1,22 +1,18 @@
|
||||
# texrra engine
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## Native execution bootstrap
|
||||
|
||||
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).
|
||||
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.
|
||||
|
||||
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:
|
||||
@@ -44,8 +40,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 loads its initial cmr10 through World. The current native job reports
|
||||
missing resources directly.
|
||||
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.
|
||||
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
|
||||
@@ -58,12 +54,13 @@ 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).
|
||||
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).
|
||||
HTTP/project routes still use the older implementation and have not migrated
|
||||
to this kernel.
|
||||
|
||||
[Streaming TFM keep/pass/boundary execution](docs/NATIVE_FONT_PROGRAMS.md) is
|
||||
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
|
||||
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
|
||||
|
||||
@@ -332,8 +332,6 @@ 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()
|
||||
@@ -614,8 +612,6 @@ 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,15 +25,9 @@ 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 {
|
||||
@@ -43,10 +37,6 @@ 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,8 +7,6 @@ pub enum DiagnosticNode {
|
||||
Character {
|
||||
font: FontId,
|
||||
slot: u8,
|
||||
#[serde(default, skip_serializing_if = "crate::native_font::unexpanded")]
|
||||
expansion: i32,
|
||||
ligature: Option<String>,
|
||||
},
|
||||
Box(DiagnosticBox),
|
||||
@@ -52,8 +50,6 @@ 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)]
|
||||
@@ -153,7 +149,6 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
|
||||
TextNode::Language(l) => DiagnosticNode::Language(*l),
|
||||
TextNode::Glyph {
|
||||
font,
|
||||
glyph,
|
||||
slot,
|
||||
original,
|
||||
ligature,
|
||||
@@ -163,13 +158,6 @@ 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}{}",
|
||||
@@ -192,7 +180,6 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
|
||||
DiagnosticNode::Character {
|
||||
font: font.id,
|
||||
slot: *slot,
|
||||
expansion: font.expansion,
|
||||
ligature: None,
|
||||
}
|
||||
} else {
|
||||
@@ -222,11 +209,6 @@ 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,
|
||||
@@ -349,12 +331,9 @@ impl Printer<'_> {
|
||||
self.flex(g.shrink.amount, g.shrink.order);
|
||||
}
|
||||
}
|
||||
fn character(&mut self, font: FontId, slot: u8, expansion: i32) -> Result<(), String> {
|
||||
fn character(&mut self, font: FontId, slot: u8) -> 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(())
|
||||
@@ -457,10 +436,9 @@ impl Printer<'_> {
|
||||
DiagnosticNode::Character {
|
||||
font,
|
||||
slot,
|
||||
expansion,
|
||||
ligature,
|
||||
} => {
|
||||
self.character(*font, *slot, *expansion)?;
|
||||
self.character(*font, *slot)?;
|
||||
if let Some(s) = ligature {
|
||||
self.literal(" (ligature ");
|
||||
for c in s.chars() {
|
||||
@@ -493,17 +471,6 @@ 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 {
|
||||
@@ -596,10 +563,6 @@ 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));
|
||||
|
||||
@@ -25,7 +25,6 @@ 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;
|
||||
@@ -695,54 +694,36 @@ impl Executor {
|
||||
return self.fail("native expansion nesting limit exceeded");
|
||||
}
|
||||
self.expansion_depth += 1;
|
||||
let result = self.expand_with_pending_tokens(input, files, definition_context);
|
||||
let result = if input.frozen {
|
||||
Ok(Some(input))
|
||||
} else {
|
||||
match self.meaning(&input.token) {
|
||||
Meaning::Primitive(Primitive::Expandafter) => {
|
||||
self.expand_after(&input.token, files)
|
||||
}
|
||||
meaning => self.expand_one_inner(input, meaning, files, definition_context),
|
||||
}
|
||||
};
|
||||
self.expansion_depth -= 1;
|
||||
result
|
||||
}
|
||||
|
||||
fn expand_with_pending_tokens(
|
||||
// Keep the recursive path outside the expansion dispatch frame.
|
||||
fn expand_after(
|
||||
&mut self,
|
||||
mut input: InputToken,
|
||||
token: &Token,
|
||||
files: &mut impl SourceProvider,
|
||||
mut definition_context: bool,
|
||||
) -> Result<Option<InputToken>, Error> {
|
||||
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)?;
|
||||
self.trace_command(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 {
|
||||
let first = self.required_raw(files)?;
|
||||
let second = self.required_raw(files)?;
|
||||
if let Some(second) = self.expand_one(second, files, false)? {
|
||||
self.unread(second)?;
|
||||
}
|
||||
self.unread(first)?;
|
||||
for token in pending.into_iter().rev() {
|
||||
self.unread(token)?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn expand_one_inner(
|
||||
&mut self,
|
||||
input: InputToken,
|
||||
@@ -876,26 +857,6 @@ impl Executor {
|
||||
return self
|
||||
.fail("pdfTeX regular expressions are unavailable on this host");
|
||||
}
|
||||
Pdfuniformdeviate => {
|
||||
let bound = self.integer(files)?;
|
||||
self.reads.insert(Dependency::PdfRandomState);
|
||||
let value = self.state.random().uniform(bound);
|
||||
self.print_tokens(&value.to_string(), token)?;
|
||||
}
|
||||
Pdfnormaldeviate => {
|
||||
self.reads.insert(Dependency::PdfRandomState);
|
||||
let value = loop {
|
||||
self.tick()?;
|
||||
if let Some(value) = self.state.random().normal_trial() {
|
||||
break value;
|
||||
}
|
||||
};
|
||||
self.print_tokens(&value.to_string(), token)?;
|
||||
}
|
||||
Pdfpageref => {
|
||||
let number = self.pdf_page_reference(files)?;
|
||||
self.print_tokens(&number.to_string(), token)?;
|
||||
}
|
||||
Pdfcolorstackinit => {
|
||||
let stack = self.init_pdf_color_stack(files)?;
|
||||
self.print_tokens(&stack.to_string(), token)?;
|
||||
@@ -1666,7 +1627,7 @@ impl Executor {
|
||||
Ok(replacement)
|
||||
}
|
||||
fn paragraph_argument(&self, token: &Token, long: bool) -> Result<(), Error> {
|
||||
if !long && self.state.is_paragraph_token(&token.kind) {
|
||||
if !long && token.kind == TokenKind::Command(CommandName::Control("par".into())) {
|
||||
return Err(self.error(
|
||||
"paragraph ended before non-long macro argument was complete",
|
||||
token.span,
|
||||
@@ -1735,10 +1696,6 @@ impl Executor {
|
||||
if self.required_raw(files)?.token.kind != *expected {
|
||||
return self.fail("macro prefix does not match");
|
||||
}
|
||||
self.consume_macro_delimiter(expected);
|
||||
}
|
||||
if !definition.long && !definition.parameters.is_empty() {
|
||||
self.reads.insert(Dependency::ParagraphToken);
|
||||
}
|
||||
let mut arguments = Vec::new();
|
||||
for (index, delimiter) in definition.parameters.iter().enumerate() {
|
||||
@@ -1777,7 +1734,6 @@ impl Executor {
|
||||
// became argument text when the match shifted.
|
||||
matched += 1;
|
||||
if matched == delimiter.len() {
|
||||
self.consume_macro_delimiter(&next.kind);
|
||||
argument.truncate(argument.len() + 1 - matched);
|
||||
break;
|
||||
}
|
||||
@@ -2032,16 +1988,6 @@ 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,
|
||||
@@ -2066,15 +2012,6 @@ 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);
|
||||
@@ -2123,14 +2060,6 @@ 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::Pdfrandomseed) => {
|
||||
self.reads.insert(Dependency::PdfRandomState);
|
||||
Ok(self.state.random_seed())
|
||||
}
|
||||
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
|
||||
@@ -2698,7 +2627,6 @@ 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
|
||||
@@ -2776,9 +2704,6 @@ impl Executor {
|
||||
self.current = node.span;
|
||||
self.tick()?;
|
||||
match &node.operation {
|
||||
OutputOperation::PdfObject(_) => {
|
||||
return self.fail("PDF object reference requires a native PDF shipout");
|
||||
}
|
||||
OutputOperation::PdfImage { image, .. } => {
|
||||
return self.declare_pdf_image(image.id);
|
||||
}
|
||||
@@ -3400,24 +3325,6 @@ impl Executor {
|
||||
}
|
||||
Ok(initial_depth)
|
||||
}
|
||||
fn insert_paragraph_token(&mut self, span: Span) -> Result<(), Error> {
|
||||
self.reads.insert(Dependency::ParagraphToken);
|
||||
self.push(vec![Token::new(self.state.paragraph_token(), span).into()])
|
||||
}
|
||||
|
||||
fn in_unrestricted_horizontal_mode(&self) -> bool {
|
||||
self.paragraph.is_some() && self.math.is_empty() && !self.restricted()
|
||||
}
|
||||
|
||||
fn group_end_needs_paragraph_token(&mut self) -> bool {
|
||||
let minimum = match self.state.group_kind() {
|
||||
Some(GroupKind::Vbox | GroupKind::Vtop | GroupKind::Vcenter) => 1,
|
||||
Some(GroupKind::Insertion | GroupKind::Output | GroupKind::NoAlign) => 2,
|
||||
_ => return false,
|
||||
};
|
||||
self.read_parameter(Parameter::Partokencontext).width() >= minimum
|
||||
}
|
||||
|
||||
fn run_active_input<F: SourceProvider>(
|
||||
&mut self,
|
||||
initial_depth: usize,
|
||||
@@ -3446,8 +3353,11 @@ impl Executor {
|
||||
self.trace_command(&token, files)?;
|
||||
}
|
||||
}
|
||||
if self.in_unrestricted_horizontal_mode()
|
||||
&& (matches!(
|
||||
if self.native_page.is_some()
|
||||
&& self.paragraph.is_some()
|
||||
&& self.math.is_empty()
|
||||
&& !self.restricted()
|
||||
&& matches!(
|
||||
&meaning,
|
||||
Meaning::Primitive(
|
||||
Primitive::End
|
||||
@@ -3464,19 +3374,21 @@ impl Executor {
|
||||
| Primitive::Splitdiscards
|
||||
| Primitive::Halign
|
||||
)
|
||||
) || (matches!(
|
||||
&meaning,
|
||||
Meaning::Character(TokenKind::Character(_, CatCode::EndGroup))
|
||||
) && self.group_end_needs_paragraph_token()))
|
||||
)
|
||||
{
|
||||
let span = token.span;
|
||||
self.unread(InputToken {
|
||||
token,
|
||||
token: token.clone(),
|
||||
frozen: input.frozen,
|
||||
end_write: input.end_write,
|
||||
alignment: None,
|
||||
})?;
|
||||
self.insert_paragraph_token(span)?;
|
||||
self.push(vec![
|
||||
Token::new(
|
||||
TokenKind::Command(CommandName::Control("par".into())),
|
||||
token.span,
|
||||
)
|
||||
.into(),
|
||||
])?;
|
||||
continue;
|
||||
}
|
||||
if frozen_expandable {
|
||||
@@ -3494,7 +3406,6 @@ impl Executor {
|
||||
)) | Meaning::CharGiven(_)
|
||||
| Meaning::Primitive(
|
||||
Primitive::Char
|
||||
| Primitive::Accent
|
||||
| Primitive::Hskip
|
||||
| Primitive::Hfil
|
||||
| Primitive::Hfill
|
||||
@@ -3602,11 +3513,6 @@ impl Executor {
|
||||
token.invocation.unwrap_or(token.span),
|
||||
files,
|
||||
)?,
|
||||
Partokenname => {
|
||||
if let TokenKind::Command(name) = self.required_raw(files)?.token.kind {
|
||||
self.state.set_paragraph_token(name);
|
||||
}
|
||||
}
|
||||
Par => {
|
||||
if self.paragraph.is_none() {
|
||||
self.normal_paragraph(files)?;
|
||||
@@ -3672,7 +3578,6 @@ 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 => {
|
||||
@@ -3764,13 +3669,6 @@ impl Executor {
|
||||
Pdfstartlink | Pdfendlink | Pdfdest => {
|
||||
self.scan_pdf_link(primitive, token.span, files)?;
|
||||
}
|
||||
Pdfsetrandomseed => {
|
||||
let seed = self.integer(files)?;
|
||||
self.reads.insert(Dependency::PdfRandomState);
|
||||
self.state.reseed_random(seed);
|
||||
}
|
||||
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)?,
|
||||
@@ -3856,23 +3754,13 @@ impl Executor {
|
||||
key: Option<Key>,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), Error> {
|
||||
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.assignment_inner(primitive, key, 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::*;
|
||||
@@ -3947,33 +3835,6 @@ 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)?;
|
||||
@@ -4070,9 +3931,6 @@ 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
|
||||
|
||||
@@ -94,13 +94,6 @@ impl Executor {
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
pub(super) fn consume_macro_delimiter(&mut self, kind: &TokenKind) {
|
||||
// The final literal brace of a hash-brace delimiter is appended to the
|
||||
// replacement. Count it when that replacement reaches the alignment.
|
||||
if kind.begin_group() && !self.alignments.is_empty() {
|
||||
self.alignment_balance -= 1;
|
||||
}
|
||||
}
|
||||
pub(super) fn alignment_brace(&mut self, token: &Token) -> i64 {
|
||||
match self.meaning(token) {
|
||||
Meaning::Character(TokenKind::Character(_, CatCode::BeginGroup)) => 1,
|
||||
@@ -169,16 +162,7 @@ impl Executor {
|
||||
) -> Result<(), Error> {
|
||||
match boundary {
|
||||
Boundary::Prefix => unreachable!("prefix boundary is handled by raw"),
|
||||
Boundary::Entry => {
|
||||
if self.alignments.last().is_some_and(|frame| !frame.horizontal)
|
||||
&& self.in_unrestricted_horizontal_mode()
|
||||
&& self.read_parameter(Parameter::Partokencontext).width() > 1
|
||||
{
|
||||
self.alignment_marker(Boundary::Entry)?;
|
||||
return self.insert_paragraph_token(self.current);
|
||||
}
|
||||
self.finish_alignment_column(files)
|
||||
}
|
||||
Boundary::Entry => self.finish_alignment_column(files),
|
||||
Boundary::Peek => self.peek_alignment(files),
|
||||
}
|
||||
}
|
||||
@@ -292,7 +276,7 @@ impl Executor {
|
||||
};
|
||||
}
|
||||
if self.meaning(&t.token) == Meaning::Parameter(Parameter::Tabskip) {
|
||||
self.assignment_inner(None, Some(Key::Parameter(Parameter::Tabskip)), true, files)?;
|
||||
self.assignment_inner(None, Some(Key::Parameter(Parameter::Tabskip)), files)?;
|
||||
} else {
|
||||
return Ok(t);
|
||||
}
|
||||
|
||||
@@ -165,9 +165,7 @@ impl Executor {
|
||||
.as_mut()
|
||||
.expect("unhbox starts an actual paragraph")
|
||||
.nodes
|
||||
.extend(
|
||||
nodes.into_iter().filter(|node| !matches!(node, TextNode::MarginKern { .. })),
|
||||
),
|
||||
.extend(nodes),
|
||||
BoxContent::Vertical(nodes) => self.append_unboxed_vertical(nodes),
|
||||
}
|
||||
Ok(())
|
||||
@@ -251,7 +249,6 @@ 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.assignments_before_content(true, files)?;
|
||||
let close = self.display_assignments(files)?;
|
||||
if !matches!(
|
||||
self.meaning(&close.token),
|
||||
Meaning::Character(TokenKind::Character(_, CatCode::MathShift))
|
||||
@@ -353,19 +353,14 @@ impl Executor {
|
||||
self.display.take().unwrap();
|
||||
self.resume_after_display(span, files)
|
||||
}
|
||||
pub(super) fn assignments_before_content(
|
||||
fn display_assignments(
|
||||
&mut self,
|
||||
allow_setbox: bool,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<InputToken, Error> {
|
||||
use Primitive::*;
|
||||
loop {
|
||||
let t = self.expanded_non_space(files)?;
|
||||
let meaning = self.meaning(&t.token);
|
||||
if !allow_setbox && Self::suppresses_meaning(&t, &meaning) {
|
||||
continue;
|
||||
}
|
||||
match meaning {
|
||||
match self.meaning(&t.token) {
|
||||
Meaning::Primitive(Relax) => continue,
|
||||
Meaning::Primitive(p)
|
||||
if p.page_dimension().is_some()
|
||||
@@ -407,10 +402,6 @@ impl Executor {
|
||||
| Font
|
||||
| Fontdimen
|
||||
| Hyphenchar
|
||||
| Lpcode
|
||||
| Rpcode
|
||||
| Efcode
|
||||
| Pdffontexpand
|
||||
| Skewchar
|
||||
| Textfont
|
||||
| Scriptfont
|
||||
@@ -440,7 +431,7 @@ impl Executor {
|
||||
| Insertpenalties
|
||||
) =>
|
||||
{
|
||||
self.assignment_with_box_policy(Some(p), None, allow_setbox, files)?
|
||||
self.assignment(Some(p), None, files)?
|
||||
}
|
||||
Meaning::Count(n) => self.assignment(None, Some(Key::Count(n)), files)?,
|
||||
Meaning::Toks(n) => self.assignment(None, Some(Key::Toks(n)), files)?,
|
||||
|
||||
@@ -20,9 +20,8 @@ impl Tail {
|
||||
TextNode::Glue(g)
|
||||
| TextNode::NamedGlue(g, _)
|
||||
| TextNode::Leaders(LeaderGlue { glue: g, .. }) => Self::Glue(*g, false),
|
||||
TextNode::Kern { width, .. } | TextNode::AccentKern(width) => Self::Kern(*width),
|
||||
TextNode::Kern { 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,12 +783,11 @@ 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 | Lpcode | Rpcode | Efcode | Pdffontexpand
|
||||
| Textfont | Scriptfont
|
||||
| Font | Fontdimen | Hyphenchar | Skewchar | Textfont | Scriptfont
|
||||
| Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time
|
||||
| Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage
|
||||
| Endinput | Showbox | Show | Showthe | Discretionary | DiscretionaryHyphen
|
||||
| Parshape | Partokenname => {
|
||||
| Parshape => {
|
||||
return Ok(false);
|
||||
}
|
||||
_ => return self.fail(format!("unsupported native math primitive: {p:?}")),
|
||||
|
||||
@@ -264,17 +264,6 @@ 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 {
|
||||
@@ -310,16 +299,8 @@ impl Executor {
|
||||
} else {
|
||||
Vec::new().into_iter()
|
||||
};
|
||||
let mut pdf_objects = Vec::new();
|
||||
for output in outputs {
|
||||
if let OutputOperation::PdfObject(number) = output.operation {
|
||||
self.current = output.span;
|
||||
self.tick()?;
|
||||
if device.pdf.is_none() {
|
||||
return self.fail("cannot ship a PDF object reference to DVI");
|
||||
}
|
||||
pdf_objects.push((number, output.span));
|
||||
} else if let OutputOperation::PdfColor { stack, action } = &output.operation {
|
||||
if let OutputOperation::PdfColor { stack, action } = &output.operation {
|
||||
if device.pdf.is_none() {
|
||||
return self.fail("cannot ship a PDF color operation to DVI");
|
||||
}
|
||||
@@ -371,10 +352,6 @@ impl Executor {
|
||||
*span,
|
||||
));
|
||||
}
|
||||
for (number, span) in pdf_objects {
|
||||
self.current = span;
|
||||
self.write_pdf_object(number, files)?;
|
||||
}
|
||||
let pdf_links = if has_link_material {
|
||||
self.ship_pdf_link_material(&b, &device, &pdf_graphics_steps, files)?
|
||||
} else {
|
||||
@@ -390,7 +367,6 @@ impl Executor {
|
||||
pdf_color_start,
|
||||
pdf_color_steps,
|
||||
pdf_graphics_steps,
|
||||
pdf_resource_entries,
|
||||
pdf_links,
|
||||
})));
|
||||
self.statistics_after_shipout(before, files)?;
|
||||
|
||||
@@ -1,128 +1,5 @@
|
||||
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)
|
||||
}
|
||||
|
||||
pub(super) fn pdf_token_bytes(&mut self, tokens: &[Token]) -> Result<Vec<u8>, Error> {
|
||||
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");
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
use super::*;
|
||||
use crate::{pdf_device::page_resources::ObjectBody, resources::ResourceKind};
|
||||
|
||||
impl Executor {
|
||||
pub(super) fn pdf_page_reference(
|
||||
&mut self,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<u32, Error> {
|
||||
let page = self.positive_pdf_number("page reference", files)? as u32;
|
||||
self.reads.insert(Dependency::PdfObjects);
|
||||
self.state
|
||||
.pdf_objects
|
||||
.get_or_insert_with(Default::default)
|
||||
.page_reference(page, self.limits.tokens)
|
||||
.map_err(|error| self.error(error, self.current))
|
||||
}
|
||||
|
||||
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 declaration = self.current;
|
||||
let attributes = if self.keyword("stream", files)? {
|
||||
Some(if self.keyword("attr", files)? {
|
||||
self.scan_pdf_bytes(files)?
|
||||
} else {
|
||||
Vec::new()
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let value = if self.keyword("file", files)? {
|
||||
let tokens = self.scan_pdf_tokens(files)?;
|
||||
let name = self.token_list_text(&tokens);
|
||||
ObjectBody::File {
|
||||
attributes,
|
||||
name: self.decode_filename(name)?,
|
||||
from: self.source_name(declaration),
|
||||
}
|
||||
} else {
|
||||
let bytes = self.scan_pdf_bytes(files)?;
|
||||
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, files)?;
|
||||
}
|
||||
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,
|
||||
files: &mut impl SourceProvider,
|
||||
) -> Result<(), Error> {
|
||||
self.reads.insert(Dependency::PdfObjects);
|
||||
let object = self
|
||||
.state
|
||||
.pdf_objects
|
||||
.as_deref()
|
||||
.ok_or_else(|| String::from("unknown native PDF object"))
|
||||
.and_then(|objects| objects.unwritten(number))
|
||||
.map_err(|error| self.error(error, self.current))?;
|
||||
let Some(object) = object else { return Ok(()) };
|
||||
let materialized = if let ObjectBody::File {
|
||||
attributes,
|
||||
name,
|
||||
from,
|
||||
} = object
|
||||
{
|
||||
self.reads.insert(Dependency::FileLookup {
|
||||
name: name.clone(),
|
||||
from: from.clone(),
|
||||
});
|
||||
let resource = files
|
||||
.resource(ResourceKind::Tex, name, from)
|
||||
.map_err(|error| {
|
||||
self.error(
|
||||
format!("cannot open PDF object file {name}: {error}"),
|
||||
self.current,
|
||||
)
|
||||
})?;
|
||||
self.check_cancellation()?;
|
||||
Some(match attributes {
|
||||
Some(attributes) => ObjectBody::Stream {
|
||||
attributes: attributes.clone(),
|
||||
bytes: resource.data,
|
||||
},
|
||||
None => ObjectBody::Direct(resource.data),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.state
|
||||
.pdf_objects
|
||||
.as_deref_mut()
|
||||
.expect("existing object table")
|
||||
.write(number, materialized, self.limits.tokens)
|
||||
.map_err(|error| self.error(error, self.current))
|
||||
}
|
||||
}
|
||||
@@ -207,8 +207,6 @@ impl Executor {
|
||||
| Primitive::Month
|
||||
| Primitive::Year
|
||||
| Primitive::Inputlineno
|
||||
| Primitive::Pdfrandomseed
|
||||
| Primitive::Pdflastobj
|
||||
| Primitive::Pdflastximage
|
||||
| Primitive::Pdflastximagepages
|
||||
| Primitive::Pdflastximagecolordepth
|
||||
@@ -225,9 +223,6 @@ impl Executor {
|
||||
| Primitive::Prevgraf
|
||||
| Primitive::Spacefactor
|
||||
| Primitive::Hyphenchar
|
||||
| Primitive::Lpcode
|
||||
| Primitive::Rpcode
|
||||
| Primitive::Efcode
|
||||
| Primitive::Skewchar
|
||||
)
|
||||
)
|
||||
@@ -279,7 +274,7 @@ impl Executor {
|
||||
}
|
||||
Ok(n as i32)
|
||||
}
|
||||
pub(super) fn optional_space(&mut self, files: &mut impl SourceProvider) -> Result<(), Error> {
|
||||
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::{collections::BTreeMap, sync::Arc};
|
||||
use std::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,25 +138,12 @@ 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 {
|
||||
@@ -186,9 +173,6 @@ impl FontCatalog {
|
||||
resources: Vec::new(),
|
||||
parameter_words: 7,
|
||||
limits,
|
||||
protrusion: BTreeMap::new(),
|
||||
expansion: BTreeMap::new(),
|
||||
expansion_codes: BTreeMap::new(),
|
||||
})
|
||||
}
|
||||
pub fn fonts(&self) -> &[FontInstance] {
|
||||
@@ -284,9 +268,8 @@ impl FontCatalog {
|
||||
let glyph_font = Arc::new(crate::native_font::NativeFont {
|
||||
id,
|
||||
name: name.into(),
|
||||
metrics: Arc::new(metrics),
|
||||
metrics,
|
||||
resource: self.resources[resource].clone(),
|
||||
expansion: 0,
|
||||
});
|
||||
self.fonts.push(FontInstance {
|
||||
name: name.into(),
|
||||
@@ -333,74 +316,6 @@ 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) = (face.advance(slot), f.height(c), f.depth(c), f.italic(c));
|
||||
let (width, height, depth, italic) = (f.width(c), f.height(c), f.depth(c), f.italic(c));
|
||||
HorizontalBox {
|
||||
width,
|
||||
height,
|
||||
|
||||
@@ -8,8 +8,7 @@ use std::{
|
||||
sync::{Arc, Mutex, OnceLock, Weak},
|
||||
};
|
||||
|
||||
const SCHEMA: u32 = 37;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 9] = [27, 28, 31, 32, 33, 34, 35, 36, SCHEMA];
|
||||
const SCHEMA: u32 = 30;
|
||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
@@ -106,16 +105,16 @@ impl FormatImage {
|
||||
schema: u32,
|
||||
engine: String,
|
||||
}
|
||||
// The new schemas add primitive or node variants. Previously
|
||||
// published state fields and variants retain their meanings.
|
||||
// Check identity before decoding state: old schemas can lack fields
|
||||
// which the current kernel must own, even with a valid checksum.
|
||||
let identity: Identity =
|
||||
serde_json::from_str(&envelope.payload).map_err(|error| error.to_string())?;
|
||||
if !COMPATIBLE_SCHEMAS.contains(&identity.schema) || identity.engine != ENGINE {
|
||||
if identity.schema != 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 != identity.schema
|
||||
if image.schema != SCHEMA
|
||||
|| image.engine != ENGINE
|
||||
|| image.state.is_initex()
|
||||
|| image.state.group_depth() != 0
|
||||
|
||||
@@ -15,7 +15,6 @@ pub enum TokenParameter {
|
||||
Output,
|
||||
Errhelp,
|
||||
Everycr,
|
||||
Pdfpageresources,
|
||||
}
|
||||
impl TokenParameter {
|
||||
pub const ALL: &'static [Self] = &[
|
||||
@@ -29,7 +28,6 @@ impl TokenParameter {
|
||||
Self::Output,
|
||||
Self::Errhelp,
|
||||
Self::Everycr,
|
||||
Self::Pdfpageresources,
|
||||
];
|
||||
pub fn name(self) -> String {
|
||||
format!("{self:?}").to_ascii_lowercase()
|
||||
|
||||
@@ -26,8 +26,6 @@ pub struct JobTime {
|
||||
pdf_clock: Option<(u8, i16)>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pdf_calendar: Option<(i32, i32, i32, i32)>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) random_seed: Option<i32>,
|
||||
}
|
||||
impl JobTime {
|
||||
pub fn new(year: i32, month: i32, day: i32, minutes: i32) -> Result<Self, &'static str> {
|
||||
@@ -49,15 +47,8 @@ impl JobTime {
|
||||
minutes,
|
||||
pdf_clock: None,
|
||||
pdf_calendar: None,
|
||||
random_seed: None,
|
||||
})
|
||||
}
|
||||
/// Fix the job's initial pdfTeX random sequence across equivalent runs.
|
||||
pub fn with_random_seed(mut self, seed: i32) -> Self {
|
||||
self.random_seed = Some(seed.saturating_abs());
|
||||
self
|
||||
}
|
||||
|
||||
/// Add the seconds and UTC offset supplied by the job host.
|
||||
pub fn with_pdf_clock(
|
||||
mut self,
|
||||
@@ -237,7 +228,6 @@ pub enum OutputOperation {
|
||||
stack: usize,
|
||||
action: crate::pdf_device::PdfColorStackAction,
|
||||
},
|
||||
PdfObject(u32),
|
||||
PdfSave,
|
||||
PdfSetMatrix(Vec<Token>),
|
||||
PdfRestore,
|
||||
|
||||
@@ -33,7 +33,6 @@ mod page_builder;
|
||||
mod paragraph;
|
||||
mod paragraph_trace;
|
||||
mod parameters;
|
||||
mod random;
|
||||
mod reconstitute;
|
||||
mod registers;
|
||||
mod rule;
|
||||
@@ -368,7 +367,6 @@ pub enum Dependency {
|
||||
MagnificationState,
|
||||
PdfFileState,
|
||||
PdfCatalogState,
|
||||
PdfObjects,
|
||||
PdfImages,
|
||||
GlyphUnicode,
|
||||
ResourceStatistics,
|
||||
@@ -410,7 +408,6 @@ pub enum Dependency {
|
||||
JobParameter(JobParameter),
|
||||
JobName,
|
||||
PdfCreationDate,
|
||||
PdfRandomState,
|
||||
FileLookup {
|
||||
name: String,
|
||||
from: String,
|
||||
@@ -423,7 +420,6 @@ pub enum Dependency {
|
||||
InputStream(u8),
|
||||
InputPosition(usize),
|
||||
OutputStream(u8),
|
||||
ParagraphToken,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
@@ -678,7 +674,6 @@ impl Execution {
|
||||
})?);
|
||||
}
|
||||
}
|
||||
self.resolve_page_graphics_resources(&mut pages)?;
|
||||
if let Some(first) = pages.first_mut() {
|
||||
first.items.extend(
|
||||
image_objects
|
||||
@@ -688,28 +683,6 @@ 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> {
|
||||
@@ -787,14 +760,13 @@ impl Execution {
|
||||
}
|
||||
NativeVerticalNode::Glue(g)
|
||||
| NativeVerticalNode::NamedGlue(g, _)
|
||||
| NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) => {
|
||||
items.push(VerticalItem::StretchGlue(VerticalGlue::with_order(
|
||||
| NativeVerticalNode::Leaders(LeaderGlue { glue: g, .. }) => items
|
||||
.push(VerticalItem::StretchGlue(VerticalGlue::with_order(
|
||||
bp(g.width as i64),
|
||||
bp(g.stretch.amount as i64),
|
||||
bp(g.shrink.amount as i64),
|
||||
g.stretch.order,
|
||||
)))
|
||||
}
|
||||
))),
|
||||
NativeVerticalNode::Kern(n) | NativeVerticalNode::ImplicitKern(n) => {
|
||||
items.push(VerticalItem::Glue(bp(*n as i64)))
|
||||
}
|
||||
|
||||
@@ -499,10 +499,7 @@ impl Mouth {
|
||||
CatCode::EndLine => {
|
||||
self.cursor = self.line.len();
|
||||
let kind = match self.state {
|
||||
LineState::New => {
|
||||
reads.insert(Dependency::ParagraphToken);
|
||||
state.paragraph_token()
|
||||
}
|
||||
LineState::New => TokenKind::Command(CommandName::Control("par".into())),
|
||||
LineState::Middle => TokenKind::Character(' ', CatCode::Space),
|
||||
LineState::Skip => continue,
|
||||
};
|
||||
|
||||
@@ -4,8 +4,6 @@ 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};
|
||||
|
||||
@@ -72,9 +70,6 @@ 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 {
|
||||
@@ -388,8 +383,6 @@ 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,
|
||||
@@ -557,8 +550,6 @@ 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,
|
||||
@@ -593,7 +584,6 @@ fn break_lines(
|
||||
&& matches!(
|
||||
projected[i - 1],
|
||||
BreakNode::Content(_)
|
||||
| BreakNode::AccentKern(_)
|
||||
| BreakNode::Discretionary { .. }
|
||||
| BreakNode::Kern {
|
||||
explicit: false,
|
||||
@@ -738,17 +728,7 @@ fn break_lines(
|
||||
if target < 0 && shape.is_empty() {
|
||||
return Err("negative native paragraph measure".into());
|
||||
}
|
||||
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 delta = target - natural;
|
||||
let infinite = stretch[1..].iter().any(|n| *n != 0);
|
||||
let bad = if delta >= 0 {
|
||||
if infinite {
|
||||
@@ -934,32 +914,17 @@ 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, bool), String> {
|
||||
) -> Result<(Paragraph, NativeBox, super::marks::MigratingMaterial), String> {
|
||||
let left = p[&Parameter::Leftskip].glue();
|
||||
let mut material = Vec::new();
|
||||
if left != Glue::default() {
|
||||
material.push(TextNode::NamedGlue(left, Parameter::Leftskip));
|
||||
}
|
||||
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]);
|
||||
material.extend_from_slice(nodes);
|
||||
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,
|
||||
@@ -969,11 +934,7 @@ fn pack(
|
||||
p[&Parameter::Rightskip].glue(),
|
||||
Parameter::Rightskip,
|
||||
));
|
||||
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 (material, adjustments) = super::marks::extract(material);
|
||||
let mut b = super::boxes::hpack(
|
||||
material,
|
||||
super::boxes::PackSpec::To(
|
||||
@@ -997,7 +958,7 @@ fn pack(
|
||||
centered: false,
|
||||
right_aligned: false,
|
||||
};
|
||||
Ok((paragraph, b, adjustments, shrinking))
|
||||
Ok((paragraph, b, adjustments))
|
||||
}
|
||||
// TeX init_math scans natural widths and visible nodes, independently of
|
||||
// rounded glue-setting coordinates. Stretch/shrink before the last visible
|
||||
@@ -1120,7 +1081,6 @@ pub(super) fn finish(
|
||||
if let Some(path) = break_cache::solve(
|
||||
&b.nodes,
|
||||
¶meters,
|
||||
state,
|
||||
shape,
|
||||
pass,
|
||||
&mut work,
|
||||
@@ -1150,6 +1110,13 @@ 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,
|
||||
@@ -1159,26 +1126,23 @@ pub(super) fn finish(
|
||||
true,
|
||||
point.zero_tail,
|
||||
);
|
||||
let (natural, stretch, shrink) = metrics(&material, left, right);
|
||||
let dimensions = geometry(¶meters, shape, i + b.previous_lines);
|
||||
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(
|
||||
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(
|
||||
&material,
|
||||
¶meters,
|
||||
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!()
|
||||
@@ -1352,7 +1316,6 @@ fn add_hyphens(
|
||||
| TextNode::NamedGlue(_, _)
|
||||
| TextNode::Leaders(_)
|
||||
| TextNode::Penalty(_)
|
||||
| TextNode::AccentKern(_)
|
||||
| TextNode::Kern { explicit: true, .. }
|
||||
)
|
||||
})
|
||||
|
||||
@@ -47,8 +47,6 @@ 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,
|
||||
@@ -59,10 +57,7 @@ struct Entry {
|
||||
|
||||
impl Entry {
|
||||
fn retained_nodes(&self) -> usize {
|
||||
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)
|
||||
self.nodes.len() + self.shape.len()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,7 +128,6 @@ pub(super) enum BreakNode {
|
||||
post_break: Option<Widths>,
|
||||
replacement_count: u8,
|
||||
},
|
||||
AccentKern(i32),
|
||||
}
|
||||
|
||||
impl BreakNode {
|
||||
@@ -152,8 +146,6 @@ 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,
|
||||
@@ -186,9 +178,7 @@ impl BreakNode {
|
||||
natural,
|
||||
..Default::default()
|
||||
},
|
||||
Self::Kern { width, .. }
|
||||
| Self::AccentKern(width)
|
||||
| Self::MathBoundary { width, .. } => Widths {
|
||||
Self::Kern { width, .. } | Self::MathBoundary { width, .. } => Widths {
|
||||
natural: i64::from(width),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -265,7 +255,6 @@ pub(super) fn candidate_widths(
|
||||
pub(super) fn solve(
|
||||
source: &[TextNode],
|
||||
parameters: &BTreeMap<Parameter, ParameterValue>,
|
||||
state: &State,
|
||||
shape: &[ParagraphShapeLine],
|
||||
pass: u8,
|
||||
work: &mut usize,
|
||||
@@ -274,23 +263,14 @@ pub(super) fn solve(
|
||||
cache: Option<&LineBreakCache>,
|
||||
) -> Result<Path, String> {
|
||||
let nodes: Vec<_> = source.iter().map(BreakNode::project).collect();
|
||||
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 retained = nodes.len() + shape.len();
|
||||
let mut hash = None;
|
||||
if let Some(cache) = cache
|
||||
&& retained <= RETAINED_NODES
|
||||
&& parameters[&Parameter::Tracingparagraphs].width() <= 0
|
||||
{
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(&nodes, &margins, &expansion, parameters, shape, pass, previous_lines).hash(&mut hasher);
|
||||
(&nodes, parameters, shape, pass, previous_lines).hash(&mut hasher);
|
||||
let key = hasher.finish();
|
||||
hash = Some(key);
|
||||
let mut cache = cache
|
||||
@@ -304,8 +284,6 @@ 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;
|
||||
@@ -324,8 +302,6 @@ pub(super) fn solve(
|
||||
let result = break_lines(
|
||||
source,
|
||||
&nodes,
|
||||
margins.as_ref(),
|
||||
expansion.as_ref(),
|
||||
parameters,
|
||||
shape,
|
||||
pass,
|
||||
@@ -355,8 +331,6 @@ pub(super) fn solve(
|
||||
cache.entries.push_back(Entry {
|
||||
hash,
|
||||
nodes,
|
||||
margins,
|
||||
expansion,
|
||||
parameters: parameters.clone(),
|
||||
shape: shape.to_vec(),
|
||||
previous_lines,
|
||||
|
||||
@@ -1,301 +0,0 @@
|
||||
//! 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(())
|
||||
}
|
||||
@@ -1,205 +0,0 @@
|
||||
//! 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,8 +230,7 @@ impl<'a> Tracer<'a> {
|
||||
self.short(post_break, out)?;
|
||||
i += usize::from(*replacement_count);
|
||||
}
|
||||
TextNode::Kern { .. } | TextNode::AccentKern(_) | TextNode::Penalty(_)
|
||||
| TextNode::MarginKern { .. } => {}
|
||||
TextNode::Kern { .. } | TextNode::Penalty(_) => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
@@ -111,9 +111,6 @@ pub enum Parameter {
|
||||
Baselineskip,
|
||||
Lineskip,
|
||||
Tabskip,
|
||||
Pdfprotrudechars,
|
||||
Pdfadjustspacing,
|
||||
Partokencontext,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ParameterValue {
|
||||
@@ -228,9 +225,6 @@ impl Parameter {
|
||||
Self::Baselineskip,
|
||||
Self::Lineskip,
|
||||
Self::Tabskip,
|
||||
Self::Pdfprotrudechars,
|
||||
Self::Pdfadjustspacing,
|
||||
Self::Partokencontext,
|
||||
];
|
||||
pub fn name(self) -> String {
|
||||
format!("{self:?}").to_ascii_lowercase()
|
||||
|
||||
@@ -1,113 +0,0 @@
|
||||
//! The pdfTeX random primitives share a job-owned fixed-point sequence.
|
||||
//! Both draws and explicit reseeding become part of a saved continuation.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const FRACTION: i64 = 1 << 28;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub(super) struct Random {
|
||||
seed: i32,
|
||||
values: Vec<i64>,
|
||||
position: usize,
|
||||
}
|
||||
|
||||
impl Random {
|
||||
pub(super) fn new(seed: i32) -> Self {
|
||||
let seed = seed.saturating_abs();
|
||||
let mut previous = i64::from(seed);
|
||||
while previous >= FRACTION {
|
||||
previous /= 2;
|
||||
}
|
||||
let mut delta = 1;
|
||||
let mut state = Self {
|
||||
seed,
|
||||
values: vec![0; 55],
|
||||
position: 0,
|
||||
};
|
||||
for index in 0..55 {
|
||||
(previous, delta) = (delta, (previous - delta).rem_euclid(FRACTION));
|
||||
state.values[(index * 21) % 55] = previous;
|
||||
}
|
||||
for _ in 0..3 {
|
||||
state.advance();
|
||||
}
|
||||
state
|
||||
}
|
||||
|
||||
pub(super) fn seed(&self) -> i32 {
|
||||
self.seed
|
||||
}
|
||||
|
||||
fn advance(&mut self) {
|
||||
for i in 0..55 {
|
||||
let offset = if i < 24 { i + 31 } else { i - 24 };
|
||||
self.values[i] = (self.values[i] - self.values[offset]).rem_euclid(FRACTION);
|
||||
}
|
||||
self.position = 54;
|
||||
}
|
||||
|
||||
fn next(&mut self) -> i64 {
|
||||
if self.position == 0 {
|
||||
self.advance();
|
||||
} else {
|
||||
self.position -= 1;
|
||||
}
|
||||
self.values[self.position]
|
||||
}
|
||||
|
||||
pub(super) fn uniform(&mut self, bound: i32) -> i32 {
|
||||
let value = rounded_quotient(i64::from(bound) * self.next(), FRACTION) as i32;
|
||||
if value == bound { 0 } else { value }
|
||||
}
|
||||
|
||||
/// One trial of the ratio method. The executor can cancel or charge work
|
||||
/// between trials, including trials rejected before the logarithm.
|
||||
pub(super) fn normal_trial(&mut self) -> Option<i32> {
|
||||
let offset = self.next() - FRACTION / 2;
|
||||
let x = rounded_quotient(112_429 * offset, FRACTION);
|
||||
let uniform = self.next();
|
||||
if x.abs() >= uniform {
|
||||
return None;
|
||||
}
|
||||
let sample = rounded_quotient(x * FRACTION, uniform);
|
||||
let log = 139_548_960 - fixed_log(uniform);
|
||||
(sample * sample <= 1024 * log).then_some(sample as i32)
|
||||
}
|
||||
}
|
||||
|
||||
fn rounded_quotient(numerator: i64, denominator: i64) -> i64 {
|
||||
numerator.signum() * ((numerator.abs() + denominator / 2) / denominator)
|
||||
}
|
||||
|
||||
/// Fixed-point logarithm used by the ratio acceptance test. Computing a
|
||||
/// floating-point log here can select a different trial and change later draws.
|
||||
fn fixed_log(mut sample: i64) -> i64 {
|
||||
const LOGARITHMS: [i64; 13] = [
|
||||
93_032_640, 38_612_034, 17_922_280, 8_662_214, 4_261_238, 2_113_709, 1_052_693, 525_315,
|
||||
262_400, 131_136, 65_552, 32_772, 16_385,
|
||||
];
|
||||
const FLOOR: i64 = 4 * FRACTION;
|
||||
let mut result = 1_302_456_860 - 100;
|
||||
let mut remainder = 27_595 + 6_553_600;
|
||||
while sample < FLOOR {
|
||||
sample *= 2;
|
||||
result -= 93_032_639;
|
||||
remainder -= 48_782;
|
||||
}
|
||||
result += remainder / 65_536;
|
||||
let mut bit = 2;
|
||||
while sample > FLOOR + 4 {
|
||||
let mut amount = ((sample - 1) >> bit) + 1;
|
||||
while sample < FLOOR + amount {
|
||||
amount = (amount + 1) / 2;
|
||||
bit += 1;
|
||||
}
|
||||
result += match bit {
|
||||
1..=13 => LOGARITHMS[bit - 1],
|
||||
14..=27 => 1 << (27 - bit),
|
||||
_ => 1,
|
||||
};
|
||||
sample -= amount;
|
||||
}
|
||||
result / 8
|
||||
}
|
||||
@@ -41,38 +41,13 @@ 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()
|
||||
.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 {
|
||||
.map(|source| SourceVersion {
|
||||
sha256: format!("{:x}", Sha256::digest(&source.data)),
|
||||
bytes: source.data.len() as u64,
|
||||
},
|
||||
|(_, version)| version.clone(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
@@ -152,19 +127,6 @@ 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
|
||||
@@ -204,7 +166,7 @@ impl RevisionJob {
|
||||
let executed = executor
|
||||
.with_cancellation(self.cancellation.clone())
|
||||
.run_detailed(source, files);
|
||||
self.finish_execution(executed, files, None)
|
||||
self.finish_execution(executed, files)
|
||||
}
|
||||
|
||||
/// Capture selected entry continuations while running the full revision.
|
||||
@@ -219,7 +181,7 @@ impl RevisionJob {
|
||||
let executed = executor
|
||||
.with_cancellation(self.cancellation.clone())
|
||||
.run_capturing_entries(source, files, select, capture);
|
||||
self.finish_execution(executed, files, None)
|
||||
self.finish_execution(executed, files)
|
||||
}
|
||||
|
||||
/// Resume after the host has validated prefix dependencies and replayed
|
||||
@@ -230,10 +192,9 @@ 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, previous.as_deref()))
|
||||
Some(self.finish_execution(executed, files))
|
||||
}
|
||||
|
||||
/// Resume a verified prefix and observe new boundaries in the executed suffix.
|
||||
@@ -256,24 +217,22 @@ impl RevisionJob {
|
||||
select,
|
||||
capture,
|
||||
)?;
|
||||
Some(self.finish_execution(executed, files, previous.as_deref()))
|
||||
Some(self.finish_execution(executed, files))
|
||||
}
|
||||
|
||||
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::with_previous_sources(
|
||||
Arc::new(RevisionExecution::from_execution(
|
||||
self.revision,
|
||||
execution,
|
||||
resources.clone(),
|
||||
previous,
|
||||
))
|
||||
});
|
||||
let mut state = self
|
||||
|
||||
@@ -102,6 +102,8 @@ pub enum Primitive {
|
||||
Ifpdfabsnum,
|
||||
Ifpdfabsdim,
|
||||
Pdfstrcmp,
|
||||
Pdfmatch,
|
||||
Pdflastmatch,
|
||||
Pdfcolorstackinit,
|
||||
Pdfcolorstack,
|
||||
Pdfsave,
|
||||
@@ -312,22 +314,6 @@ pub enum Primitive {
|
||||
Overwithdelims,
|
||||
Atopwithdelims,
|
||||
Abovewithdelims,
|
||||
Accent,
|
||||
Pdfmatch,
|
||||
Pdflastmatch,
|
||||
Lpcode,
|
||||
Rpcode,
|
||||
Efcode,
|
||||
Pdffontexpand,
|
||||
Pdfobj,
|
||||
Pdfrefobj,
|
||||
Pdflastobj,
|
||||
Pdfrandomseed,
|
||||
Pdfsetrandomseed,
|
||||
Pdfuniformdeviate,
|
||||
Pdfnormaldeviate,
|
||||
Pdfpageref,
|
||||
Partokenname,
|
||||
}
|
||||
|
||||
impl Primitive {
|
||||
@@ -380,9 +366,6 @@ impl Primitive {
|
||||
| Pdfstrcmp
|
||||
| Pdfmatch
|
||||
| Pdflastmatch
|
||||
| Pdfuniformdeviate
|
||||
| Pdfnormaldeviate
|
||||
| Pdfpageref
|
||||
| Pdfcolorstackinit
|
||||
| Csname
|
||||
| Unless
|
||||
@@ -595,16 +578,10 @@ pub struct State {
|
||||
pub newlinechar: i32,
|
||||
pub escapechar: i32,
|
||||
pub globaldefs: i32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
paragraph_token: Option<CommandName>,
|
||||
groups: Vec<Group>,
|
||||
job_parameters: BTreeMap<JobParameter, i32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) pdf_creation_date: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
initial_random_seed: Option<i32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
random: Option<Box<super::random::Random>>,
|
||||
#[serde(with = "ordered_map")]
|
||||
registers: BTreeMap<Register, RegisterValue>,
|
||||
parameters: BTreeMap<Parameter, ParameterValue>,
|
||||
@@ -629,8 +606,6 @@ 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,
|
||||
@@ -712,7 +687,6 @@ impl Default for State {
|
||||
escapechar: 92,
|
||||
globaldefs: 0,
|
||||
groups: Vec::new(),
|
||||
paragraph_token: None,
|
||||
job_parameters: BTreeMap::new(),
|
||||
pdf_creation_date: None,
|
||||
registers: BTreeMap::new(),
|
||||
@@ -733,9 +707,6 @@ impl Default for State {
|
||||
output_mode_set: None,
|
||||
pdf_file_options: None,
|
||||
pdf_catalog: None,
|
||||
pdf_objects: None,
|
||||
initial_random_seed: None,
|
||||
random: None,
|
||||
pdf_info: Vec::new(),
|
||||
glyph_unicode: crate::pdf_unicode::GlyphUnicodeMap::default(),
|
||||
hyphenation: super::hyphenation::HyphenationData::default(),
|
||||
@@ -755,7 +726,6 @@ impl Default for State {
|
||||
("radical", Radical),
|
||||
("left", Left),
|
||||
("right", Right),
|
||||
("accent", Accent),
|
||||
("mathaccent", Mathaccent),
|
||||
("mathchoice", Mathchoice),
|
||||
("overline", Overline),
|
||||
@@ -763,10 +733,6 @@ impl Default for State {
|
||||
("eqno", Eqno),
|
||||
("leqno", Leqno),
|
||||
("hyphenchar", Hyphenchar),
|
||||
("lpcode", Lpcode),
|
||||
("rpcode", Rpcode),
|
||||
("efcode", Efcode),
|
||||
("pdffontexpand", Pdffontexpand),
|
||||
("fontname", Fontname),
|
||||
("fontdimen", Fontdimen),
|
||||
("skewchar", Skewchar),
|
||||
@@ -961,15 +927,6 @@ impl Default for State {
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
("pdflastmatch", Pdflastmatch),
|
||||
("pdfcolorstackinit", Pdfcolorstackinit),
|
||||
("pdfobj", Pdfobj),
|
||||
("pdfrefobj", Pdfrefobj),
|
||||
("pdflastobj", Pdflastobj),
|
||||
("pdfrandomseed", Pdfrandomseed),
|
||||
("pdfsetrandomseed", Pdfsetrandomseed),
|
||||
("pdfuniformdeviate", Pdfuniformdeviate),
|
||||
("pdfnormaldeviate", Pdfnormaldeviate),
|
||||
("pdfpageref", Pdfpageref),
|
||||
("partokenname", Partokenname),
|
||||
("pdfcolorstack", Pdfcolorstack),
|
||||
("pdfsave", Pdfsave),
|
||||
("pdfstartlink", Pdfstartlink),
|
||||
@@ -1236,24 +1193,8 @@ impl State {
|
||||
pub fn with_job_time(mut self, time: JobTime) -> Self {
|
||||
self.job_parameters.extend(time.parameters());
|
||||
self.pdf_creation_date = time.pdf_creation_date();
|
||||
self.initial_random_seed = time.random_seed;
|
||||
self.random = None;
|
||||
self
|
||||
}
|
||||
pub(super) fn random_seed(&self) -> i32 {
|
||||
self.random.as_deref().map_or_else(
|
||||
|| self.initial_random_seed.unwrap_or_default(),
|
||||
super::random::Random::seed,
|
||||
)
|
||||
}
|
||||
pub(super) fn reseed_random(&mut self, seed: i32) {
|
||||
self.random = Some(Box::new(super::random::Random::new(seed)));
|
||||
}
|
||||
pub(super) fn random(&mut self) -> &mut super::random::Random {
|
||||
self.random.get_or_insert_with(|| {
|
||||
Box::new(super::random::Random::new(self.initial_random_seed.unwrap_or_default()))
|
||||
})
|
||||
}
|
||||
pub fn job_parameter(&self, parameter: JobParameter) -> Option<i32> {
|
||||
self.job_parameters.get(¶meter).copied()
|
||||
}
|
||||
@@ -1339,11 +1280,8 @@ impl State {
|
||||
pub fn tokens(&self, index: u16) -> Vec<Token> {
|
||||
self.toks.get(&index).cloned().unwrap_or_default()
|
||||
}
|
||||
pub(super) fn group_kind(&self) -> Option<GroupKind> {
|
||||
self.groups.last().map(|group| group.kind)
|
||||
}
|
||||
pub(super) fn group_type(&self) -> i32 {
|
||||
match self.group_kind() {
|
||||
match self.groups.last().map(|g| g.kind) {
|
||||
None => 0,
|
||||
Some(GroupKind::Simple) => 1,
|
||||
Some(GroupKind::SemiSimple) => 14,
|
||||
@@ -1379,8 +1317,6 @@ impl State {
|
||||
self.initex = false;
|
||||
self.job_parameters.clear();
|
||||
self.pdf_creation_date = None;
|
||||
self.initial_random_seed = None;
|
||||
self.random = None;
|
||||
self.split_marks.clear();
|
||||
self.page_marks.clear();
|
||||
self.last_badness = 0;
|
||||
@@ -1388,7 +1324,6 @@ 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
|
||||
}
|
||||
@@ -1403,7 +1338,6 @@ 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)
|
||||
@@ -1579,26 +1513,6 @@ impl State {
|
||||
pub fn count(&self, index: u16) -> i32 {
|
||||
self.counts.get(&index).copied().unwrap_or(0)
|
||||
}
|
||||
pub(super) fn set_paragraph_token(&mut self, name: CommandName) {
|
||||
self.paragraph_token = match &name {
|
||||
CommandName::Control(value) if value == "par" => None,
|
||||
_ => Some(name),
|
||||
};
|
||||
}
|
||||
pub(super) fn paragraph_token(&self) -> TokenKind {
|
||||
let name = self
|
||||
.paragraph_token
|
||||
.clone()
|
||||
.unwrap_or_else(|| CommandName::Control("par".into()));
|
||||
TokenKind::Command(name)
|
||||
}
|
||||
pub(super) fn is_paragraph_token(&self, token: &TokenKind) -> bool {
|
||||
match (token, &self.paragraph_token) {
|
||||
(TokenKind::Command(name), Some(paragraph)) => name == paragraph,
|
||||
(TokenKind::Command(CommandName::Control(name)), None) => name == "par",
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
pub fn group_depth(&self) -> usize {
|
||||
self.groups.len()
|
||||
}
|
||||
|
||||
@@ -3,15 +3,9 @@
|
||||
//! 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)]
|
||||
@@ -54,17 +48,9 @@ impl NativeFontProgram {
|
||||
pub struct NativeFont {
|
||||
pub id: FontId,
|
||||
pub name: String,
|
||||
pub metrics: Arc<TfmMetrics>,
|
||||
pub metrics: 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
|
||||
@@ -72,22 +58,6 @@ 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)
|
||||
}
|
||||
@@ -216,85 +186,6 @@ 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.
|
||||
@@ -302,15 +193,22 @@ pub fn resolve_native_fonts(
|
||||
pages: &mut [crate::render::DisplayList],
|
||||
files: &mut impl crate::execution::SourceProvider,
|
||||
) -> Result<(), String> {
|
||||
NativeFontCache::default().resolve(pages, files)
|
||||
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)
|
||||
}
|
||||
}
|
||||
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};
|
||||
use std::collections::BTreeSet;
|
||||
use crate::{render::DisplayItem, resources::ResourceKind, type1::Type1Font};
|
||||
use std::{collections::BTreeSet, sync::Arc};
|
||||
let mut used: BTreeMap<FontId, (Arc<NativeFont>, BTreeSet<u8>)> = BTreeMap::new();
|
||||
for page in pages.iter() {
|
||||
for item in &page.items {
|
||||
@@ -318,7 +216,7 @@ fn resolve_physical_fonts(
|
||||
let entry = used
|
||||
.entry(font.id)
|
||||
.or_insert_with(|| (font.clone(), BTreeSet::new()));
|
||||
if !Arc::ptr_eq(&entry.0, font) && !entry.0.same_base(font) {
|
||||
if entry.0.as_ref() != font.as_ref() {
|
||||
return Err("native font ids from different jobs cannot share output".into());
|
||||
}
|
||||
entry.1.insert(*slot);
|
||||
@@ -340,7 +238,10 @@ fn resolve_physical_fonts(
|
||||
.iter()
|
||||
.find_map(|p| p.pdf.as_ref())
|
||||
.map(|p| p.file.clone());
|
||||
let mut cache: BTreeMap<_, (NativeFontPaint, Arc<DecodedType1>)> = BTreeMap::new();
|
||||
let mut cache: BTreeMap<
|
||||
(String, Option<String>),
|
||||
(NativeFontPaint, crate::type1_outline::Type1Outlines),
|
||||
> = BTreeMap::new();
|
||||
for (id, (font, slots)) in used {
|
||||
let entry = map_entry(&map.data, &font.name)?;
|
||||
let Some(entry) = entry else {
|
||||
@@ -416,8 +317,12 @@ fn resolve_physical_fonts(
|
||||
&file,
|
||||
&map.version.path.to_string_lossy(),
|
||||
)?;
|
||||
let decoded = font_cache.type1(&resource)?;
|
||||
let program = &decoded.program;
|
||||
let program = Type1Font::from_pfb(&resource.data).ok_or_else(|| {
|
||||
format!(
|
||||
"invalid Type1 PFB program: {}",
|
||||
resource.version.path.display()
|
||||
)
|
||||
})?;
|
||||
let mut resources = vec![map.version.clone(), resource.version];
|
||||
let encoding = if let Some(name) = entry.encoding {
|
||||
let enc = actual_resource(
|
||||
@@ -434,23 +339,25 @@ 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.clone()),
|
||||
program: NativeFontProgram::Type1(program),
|
||||
encoding,
|
||||
glyph_paths: BTreeMap::new(),
|
||||
bbox: decoded.bbox,
|
||||
stem_v: decoded.stem_v,
|
||||
bbox,
|
||||
stem_v,
|
||||
resources,
|
||||
},
|
||||
decoded,
|
||||
outlines,
|
||||
),
|
||||
);
|
||||
}
|
||||
let (paint, decoded) = cache.get_mut(&key).unwrap();
|
||||
let outlines = &decoded.outlines;
|
||||
let (paint, outlines) = cache.get_mut(&key).unwrap();
|
||||
for slot in slots {
|
||||
if paint.glyph_paths.contains_key(&slot) {
|
||||
continue;
|
||||
|
||||
@@ -18,7 +18,6 @@ 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,
|
||||
}
|
||||
@@ -47,7 +46,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.same_base(font) {
|
||||
if !Arc::ptr_eq(old, font) && old != font {
|
||||
return Err("native font ids from different jobs cannot share output".into());
|
||||
}
|
||||
return Ok(vf.clone());
|
||||
@@ -105,8 +104,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
|
||||
let font = Arc::new(NativeFont {
|
||||
id: FontId::for_device(self.last_id),
|
||||
name: local.name.clone(),
|
||||
metrics: Arc::new(metrics),
|
||||
expansion: 0,
|
||||
metrics,
|
||||
resource: FontResource {
|
||||
version: file.version,
|
||||
data: Arc::new(file.data),
|
||||
@@ -166,18 +164,7 @@ impl<'a, F: SourceProvider> Expansion<'a, F> {
|
||||
font.name
|
||||
));
|
||||
}
|
||||
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 width = font.metrics.width(char::from(slot));
|
||||
let size = font.size_sp();
|
||||
self.expand(
|
||||
Glyph {
|
||||
@@ -268,7 +255,6 @@ pub(super) fn expand_pages(
|
||||
files,
|
||||
virtuals: BTreeMap::new(),
|
||||
local_fonts: BTreeMap::new(),
|
||||
expanded_fonts: BTreeMap::new(),
|
||||
last_id: 0x7fff_ffff,
|
||||
commands: 0,
|
||||
};
|
||||
@@ -292,7 +278,6 @@ 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()
|
||||
};
|
||||
|
||||
@@ -441,7 +441,6 @@ fn native_pdf_font_size(size: i64) -> i64 {
|
||||
|
||||
struct NativeTextRun {
|
||||
font: crate::execution::FontId,
|
||||
expansion: i32,
|
||||
size: i64,
|
||||
y: i64,
|
||||
cursor: f64,
|
||||
@@ -452,11 +451,7 @@ impl NativeTextRun {
|
||||
fn flush(run: &mut Option<Self>, content: &mut String) {
|
||||
if let Some(run) = run.take() {
|
||||
content.push_str(&run.text);
|
||||
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) {
|
||||
@@ -687,7 +682,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 && font.expansion==run.expansion && *size==run.size && *y==run.y)
|
||||
|| !matches!(item,DisplayItem::NativeGlyph{font,size,y,..}if font.id==run.font && *size==run.size && *y==run.y)
|
||||
{
|
||||
NativeTextRun::flush(&mut native_text, &mut content);
|
||||
}
|
||||
@@ -709,22 +704,14 @@ 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 * f64::from(1000 + font.expansion) / 1000.0,
|
||||
point_size,
|
||||
text: format!(
|
||||
"BT /N{} {point_size:.4} Tf {spacing}1 0 0 1 {} {} Tm [",
|
||||
"BT /N{} {point_size:.4} Tf 1 0 0 1 {} {} Tm [",
|
||||
font.id.index(),
|
||||
pt(*x),
|
||||
pt(height - *y)
|
||||
@@ -1098,7 +1085,6 @@ pub fn display_lists_to_pdf_with_paper(
|
||||
&PdfMetadata::default(),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&mut Vec::new(),
|
||||
)
|
||||
}
|
||||
@@ -1131,7 +1117,6 @@ pub fn display_lists_to_pdf_with_cm_type1(
|
||||
&PdfMetadata::default(),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&mut Vec::new(),
|
||||
)
|
||||
}
|
||||
@@ -1233,7 +1218,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.same_base(font) || old_paint != paint {
|
||||
if old_font != font || old_paint != paint {
|
||||
return Err("inconsistent native font snapshots or programs in PDF output".into());
|
||||
}
|
||||
}
|
||||
@@ -1251,24 +1236,6 @@ 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,
|
||||
@@ -1279,7 +1246,6 @@ fn native_pdf(
|
||||
&PdfMetadata::default(),
|
||||
final_compression,
|
||||
unicode,
|
||||
resources,
|
||||
&mut diagnostics,
|
||||
);
|
||||
Ok(NativePdfDocument { bytes, diagnostics })
|
||||
@@ -1302,7 +1268,6 @@ pub fn display_lists_to_pdf_with_truetype_and_metadata(
|
||||
metadata,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&mut Vec::new(),
|
||||
)
|
||||
}
|
||||
@@ -1324,7 +1289,6 @@ pub fn display_lists_to_pdf_with_cm_type1_and_metadata(
|
||||
metadata,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
&mut Vec::new(),
|
||||
)
|
||||
}
|
||||
@@ -1768,7 +1732,6 @@ 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;
|
||||
@@ -1831,8 +1794,9 @@ fn write_pdf(
|
||||
}
|
||||
(font.clone(), paint.clone(), BTreeMap::new())
|
||||
});
|
||||
assert!(
|
||||
entry.0.same_base(font),
|
||||
assert_eq!(
|
||||
entry.0.as_ref(),
|
||||
font.as_ref(),
|
||||
"native font ids from different jobs cannot share a PDF"
|
||||
);
|
||||
entry.2.insert(*slot, *character);
|
||||
@@ -2015,7 +1979,6 @@ 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, diagnostics));
|
||||
let mut kids = Vec::new();
|
||||
let mut page_ids: Vec<usize> = Vec::new();
|
||||
let mut destinations = BTreeMap::new();
|
||||
@@ -2042,7 +2005,7 @@ fn write_pdf(
|
||||
}
|
||||
}
|
||||
}
|
||||
for (page_index, list) in pages.iter().enumerate() {
|
||||
for list in pages {
|
||||
let width = if final_compression.is_some() {
|
||||
list.width
|
||||
} else {
|
||||
@@ -2072,11 +2035,8 @@ fn write_pdf(
|
||||
}
|
||||
}
|
||||
|
||||
let reserved_page = remapped.as_ref()
|
||||
.and_then(|resources| resources.page_objects.get(&page_index))
|
||||
.copied();
|
||||
let page_id = reserved_page.unwrap_or(objects.len() + 1);
|
||||
let content_id = objects.len() + 1 + usize::from(reserved_page.is_none());
|
||||
let page_id = objects.len() + 1;
|
||||
let content_id = page_id + 1;
|
||||
let image_base = content_id + 1;
|
||||
let mut xobjects = used
|
||||
.iter()
|
||||
@@ -2146,25 +2106,14 @@ fn write_pdf(
|
||||
};
|
||||
page_ids.push(page_id);
|
||||
kids.push(format!("{page_id} 0 R"));
|
||||
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());
|
||||
if let Some(id) = reserved_page {
|
||||
objects[id - 1] = page;
|
||||
} else {
|
||||
objects.push(page);
|
||||
}
|
||||
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 names = BTreeMap::new();
|
||||
for (index, slot) in &used {
|
||||
@@ -2391,11 +2340,9 @@ fn write_pdf(
|
||||
}
|
||||
let mut catalog = catalog.into_bytes();
|
||||
if let Some(extra) = extra {
|
||||
let entries = remapped.as_ref().and_then(|resources| resources.catalog.as_deref())
|
||||
.unwrap_or(&extra.entries);
|
||||
if !entries.is_empty() {
|
||||
if !extra.entries.is_empty() {
|
||||
catalog.push(b'\n');
|
||||
catalog.extend_from_slice(entries);
|
||||
catalog.extend_from_slice(&extra.entries);
|
||||
catalog.push(b'\n');
|
||||
}
|
||||
if let Some(id) = action {
|
||||
@@ -2407,11 +2354,7 @@ fn write_pdf(
|
||||
|
||||
if let Some(level) = final_compression {
|
||||
let info = match unicode {
|
||||
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,
|
||||
}),
|
||||
Some(options) => native_information_dictionary(options.info),
|
||||
None => metadata_object(metadata)
|
||||
.map(String::into_bytes)
|
||||
.unwrap_or_else(|| b"<< /Producer (texrra Route-D native) >>".to_vec()),
|
||||
|
||||
@@ -82,6 +82,3 @@ pub(crate) use graphics::Affine;
|
||||
pub use graphics::{PdfGraphics, PdfMatrix};
|
||||
pub mod catalog;
|
||||
pub mod links;
|
||||
|
||||
#[doc(hidden)]
|
||||
pub mod page_resources;
|
||||
@@ -9,7 +9,6 @@ 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 {
|
||||
@@ -17,16 +16,8 @@ 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 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") {
|
||||
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],
|
||||
@@ -62,14 +53,13 @@ impl PdfColorProgram {
|
||||
operands.push(number.clamp(0.0, 1.0));
|
||||
}
|
||||
}
|
||||
if !operands.is_empty() || name.is_some() {
|
||||
if !operands.is_empty() {
|
||||
return Err("PDF color program ends with unconsumed operands".into());
|
||||
}
|
||||
Ok(Self {
|
||||
literal,
|
||||
fill,
|
||||
stroke,
|
||||
graphics_states,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -118,7 +108,6 @@ 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(),
|
||||
}])
|
||||
|
||||
@@ -1,506 +0,0 @@
|
||||
//! 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 {
|
||||
Page,
|
||||
Direct(Vec<u8>),
|
||||
Stream {
|
||||
attributes: Vec<u8>,
|
||||
bytes: Vec<u8>,
|
||||
},
|
||||
File {
|
||||
attributes: Option<Vec<u8>>,
|
||||
name: String,
|
||||
from: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl ObjectBody {
|
||||
fn len(&self) -> usize {
|
||||
match self {
|
||||
Self::Page => 0,
|
||||
Self::Direct(bytes) => bytes.len(),
|
||||
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
|
||||
Self::File {
|
||||
attributes,
|
||||
name,
|
||||
from,
|
||||
} => attributes
|
||||
.as_ref()
|
||||
.map_or(0, Vec::len)
|
||||
.saturating_add(name.len())
|
||||
.saturating_add(from.len()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(&self) -> Result<Object, String> {
|
||||
match self {
|
||||
Self::Page => Err("expected a generic native PDF object".into()),
|
||||
Self::Direct(bytes) => parse_value(bytes),
|
||||
Self::File { .. } => Err("PDF object file payload was not read before export".into()),
|
||||
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,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
page_references: BTreeMap<u32, u32>,
|
||||
}
|
||||
|
||||
impl PdfObjects {
|
||||
pub(crate) fn last(&self) -> i32 {
|
||||
self.last
|
||||
}
|
||||
|
||||
fn entry(&self, number: u32) -> Option<&Option<Arc<ObjectBody>>> {
|
||||
self.values.get(number.checked_sub(1)? as usize)
|
||||
}
|
||||
|
||||
pub(crate) fn contains(&self, number: u32) -> bool {
|
||||
self.entry(number)
|
||||
.is_some_and(|entry| !matches!(entry.as_deref(), Some(ObjectBody::Page)))
|
||||
}
|
||||
|
||||
pub(crate) fn is_reserved(&self, number: u32) -> bool {
|
||||
self.entry(number).is_some_and(Option::is_none)
|
||||
}
|
||||
|
||||
fn allocate(&mut self, body: Option<Arc<ObjectBody>>, 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(body);
|
||||
Ok(self.values.len() as u32)
|
||||
}
|
||||
|
||||
pub(crate) fn reserve(&mut self, limit: usize) -> Result<u32, String> {
|
||||
let number = self.allocate(None, limit)?;
|
||||
self.last = number as i32;
|
||||
Ok(number)
|
||||
}
|
||||
|
||||
pub(crate) fn page_reference(&mut self, page: u32, limit: usize) -> Result<u32, String> {
|
||||
if let Some(number) = self.page_references.get(&page) {
|
||||
return Ok(*number);
|
||||
}
|
||||
let number = self.allocate(Some(Arc::new(ObjectBody::Page)), limit)?;
|
||||
self.page_references.insert(page, number);
|
||||
Ok(number)
|
||||
}
|
||||
|
||||
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 unwritten(&self, number: u32) -> Result<Option<&ObjectBody>, String> {
|
||||
if self.written.contains(&number) {
|
||||
Ok(None)
|
||||
} else {
|
||||
self.body(number).map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write(
|
||||
&mut self,
|
||||
number: u32,
|
||||
materialized: Option<ObjectBody>,
|
||||
limit: usize,
|
||||
) -> Result<(), String> {
|
||||
let old = self.body(number)?;
|
||||
if let Some(value) = materialized {
|
||||
let bytes = (self.bytes - old.len()).saturating_add(value.len());
|
||||
if bytes > limit {
|
||||
return Err("native PDF object payload capacity exceeded".into());
|
||||
}
|
||||
self.values[number as usize - 1] = Some(Arc::new(value));
|
||||
self.bytes = bytes;
|
||||
}
|
||||
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> {
|
||||
self.entry(number)
|
||||
.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_references: BTreeMap<u32, u32>,
|
||||
page_entries: Vec<Dictionary>,
|
||||
catalog: Option<Dictionary>,
|
||||
info: Option<Dictionary>,
|
||||
}
|
||||
|
||||
pub(crate) struct RemappedResources {
|
||||
pub pages: Vec<Vec<u8>>,
|
||||
pub page_objects: BTreeMap<usize, usize>,
|
||||
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 page_objects: BTreeSet<_> = objects.page_references.values().copied().collect();
|
||||
let mut values = BTreeMap::new();
|
||||
while let Some(number) = pending.pop_first() {
|
||||
if values.contains_key(&number) || page_objects.contains(&number) {
|
||||
continue;
|
||||
}
|
||||
let value = objects.written_body(number)?.parse()?;
|
||||
references(&value, &mut pending)?;
|
||||
values.insert(number, value);
|
||||
}
|
||||
Ok(Self {
|
||||
values,
|
||||
page_references: objects.page_references.clone(),
|
||||
page_entries,
|
||||
catalog,
|
||||
info,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn append(
|
||||
self,
|
||||
output: &mut Vec<Vec<u8>>,
|
||||
diagnostics: &mut Vec<String>,
|
||||
) -> RemappedResources {
|
||||
let mut ids = BTreeMap::new();
|
||||
let mut page_objects = BTreeMap::new();
|
||||
for (page, number) in self.page_references {
|
||||
// The real Page dictionary fills this slot at export. A missing
|
||||
// page leaves a free entry in the cross-reference table.
|
||||
output.push(Vec::new());
|
||||
let id = output.len();
|
||||
if page as usize <= self.page_entries.len() {
|
||||
page_objects.insert(page as usize - 1, id);
|
||||
} else {
|
||||
diagnostics.push(format!("PDF page {page} has been referenced but does not exist"));
|
||||
}
|
||||
ids.insert(number, id as u32);
|
||||
}
|
||||
ids.extend(
|
||||
self.values
|
||||
.keys()
|
||||
.copied()
|
||||
.enumerate()
|
||||
.map(|(i, number)| (number, (output.len() + i + 1) as u32)),
|
||||
);
|
||||
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(),
|
||||
page_objects,
|
||||
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)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ use crate::{
|
||||
pub(super) struct NativeText {
|
||||
font: Option<FontId>,
|
||||
effective_size: i64,
|
||||
expansion: i32,
|
||||
v: i64,
|
||||
start_h: i64,
|
||||
delta_h: i64,
|
||||
@@ -31,7 +30,6 @@ impl NativeText {
|
||||
Self {
|
||||
font: None,
|
||||
effective_size: 0,
|
||||
expansion: 0,
|
||||
v: height,
|
||||
start_h: 0,
|
||||
delta_h: 0,
|
||||
@@ -49,21 +47,8 @@ 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, horizontal_size, 3);
|
||||
divide_scaled(x - state.start_h - state.delta_h, state.effective_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)
|
||||
@@ -92,7 +77,7 @@ impl NativeText {
|
||||
state.delta_h += shift_out;
|
||||
}
|
||||
out.push_str(&format!("<{slot:02X}>"));
|
||||
let advance = match &paint.program {
|
||||
state.delta_h += match &paint.program {
|
||||
crate::native_font::NativeFontProgram::Pk(pk) => pk.advances[&slot],
|
||||
crate::native_font::NativeFontProgram::Type1(_) => {
|
||||
divide_scaled(
|
||||
@@ -103,11 +88,6 @@ 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 {
|
||||
@@ -118,9 +98,6 @@ 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,7 +129,6 @@ 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>,
|
||||
}
|
||||
|
||||
|
||||
@@ -135,7 +135,6 @@ pub enum DisplayItem {
|
||||
struct NativeSvgGlyph<'a> {
|
||||
position: [i64; 2],
|
||||
size: i64,
|
||||
expansion: i32,
|
||||
slot: u8,
|
||||
font: &'a str,
|
||||
glyph: &'a str,
|
||||
@@ -174,7 +173,6 @@ impl DisplayItem {
|
||||
Ok(NativeSvgGlyph {
|
||||
position: [*x, *y],
|
||||
size: *size,
|
||||
expansion: font.expansion,
|
||||
slot: *slot,
|
||||
font: paint.program.name(),
|
||||
glyph: &paint.encoding[usize::from(*slot)],
|
||||
@@ -247,7 +245,6 @@ 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 {
|
||||
@@ -261,35 +258,6 @@ 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -297,9 +265,7 @@ impl SvgTransparency {
|
||||
impl DisplayList {
|
||||
/// Whether this page needs the complete PDF device output for SVG preview.
|
||||
pub fn has_embedded_pdf(&self) -> bool {
|
||||
self.pdf_resources.needs_pdf_for_preview
|
||||
|| self
|
||||
.items
|
||||
self.items
|
||||
.iter()
|
||||
.any(|item| matches!(item, DisplayItem::PdfImage { .. }))
|
||||
}
|
||||
@@ -312,8 +278,6 @@ 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()) {
|
||||
@@ -391,17 +355,9 @@ 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 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 matches!(item, DisplayItem::PdfImage { .. }) {
|
||||
return Err("embedded PDF page requires a PDF renderer".into());
|
||||
}
|
||||
if let Some(glyph) = item.native_svg_glyph() {
|
||||
glyph?;
|
||||
@@ -447,18 +403,14 @@ 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,
|
||||
@@ -471,17 +423,12 @@ 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({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]));
|
||||
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]));
|
||||
}
|
||||
DisplayItem::MathGlyph {
|
||||
x,
|
||||
@@ -495,7 +442,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}\"{fill_opacity}/><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}\"/><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())
|
||||
));
|
||||
@@ -560,7 +507,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}{fill_opacity}>{}</text>\n",
|
||||
"<text x=\"{x:.3}\" y=\"{y:.3}\" font-size=\"{size:.3}\" font-family=\"{family}\"{weight}{style}{fill_attr}>{}</text>\n",
|
||||
escape(text)
|
||||
));
|
||||
}
|
||||
@@ -572,7 +519,7 @@ impl DisplayList {
|
||||
color,
|
||||
} => {
|
||||
out.push_str(&format!(
|
||||
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}/>\n",
|
||||
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"#{:02x}{:02x}{:02x}\"/>\n",
|
||||
*x as f64 / 65_536.0,
|
||||
*y as f64 / 65_536.0,
|
||||
*width as f64 / 65_536.0,
|
||||
@@ -592,21 +539,14 @@ 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 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] {
|
||||
let color = if rule_fill == [0; 3] {
|
||||
"black".to_owned()
|
||||
} else {
|
||||
let [r, g, b] = rgb;
|
||||
let [r, g, b] = rule_fill;
|
||||
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}\"{rule_alpha}/>\n"
|
||||
"<rect x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" fill=\"{color}\"/>\n"
|
||||
));
|
||||
}
|
||||
// Link annotations are PDF metadata; the SVG preview omits them.
|
||||
@@ -619,7 +559,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}\"{stroke_opacity}/>\n",
|
||||
"<rect x=\"{:.3}\" y=\"{:.3}\" width=\"{:.3}\" height=\"{:.3}\" fill=\"none\" stroke=\"#{:02x}{:02x}{:02x}\" stroke-width=\"{:.3}\"/>\n",
|
||||
*x as f64 / 65_536.0,
|
||||
(*y - *height) as f64 / 65_536.0,
|
||||
*width as f64 / 65_536.0,
|
||||
@@ -646,21 +586,12 @@ 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,
|
||||
transparency.clone(),
|
||||
));
|
||||
graphics.push((open_transforms, fill, rule_fill, stroke));
|
||||
}
|
||||
PdfGraphics::Matrix(matrix) => {
|
||||
let [a, b, c, d, e, f] = matrix
|
||||
@@ -672,15 +603,12 @@ impl DisplayList {
|
||||
open_transforms += 1;
|
||||
}
|
||||
PdfGraphics::Restore { shift: [dx, dy] } => {
|
||||
if let Some((depth, old_fill, old_rule, old_stroke, old_alpha)) =
|
||||
graphics.pop()
|
||||
{
|
||||
if let Some((depth, old_fill, old_rule, old_stroke)) = 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;
|
||||
@@ -705,7 +633,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}\"{stroke_opacity}/>\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}\"/>\n"
|
||||
));
|
||||
}
|
||||
DisplayItem::PdfImage { .. } => unreachable!("checked before SVG export"),
|
||||
@@ -725,9 +653,8 @@ 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}\"{image_opacity}/>\n"
|
||||
"<image x=\"{x:.3}\" y=\"{y:.3}\" width=\"{width:.3}\" height=\"{height:.3}\" href=\"{uri}\"/>\n"
|
||||
));
|
||||
} else {
|
||||
out.push_str(&format!(
|
||||
|
||||
@@ -109,7 +109,10 @@ impl ProjectSnapshot {
|
||||
revision: u64,
|
||||
edits: BTreeMap<PathBuf, Arc<[u8]>>,
|
||||
) -> Result<Arc<Self>, String> {
|
||||
let mut next = self.next_revision(revision)?;
|
||||
self.validate()?;
|
||||
let mut next = self.clone();
|
||||
next.version.revision = revision;
|
||||
next.validated = OnceLock::new();
|
||||
for (path, data) in edits {
|
||||
let previous = next.files.get_mut(&path).ok_or_else(|| {
|
||||
format!("atomic edit requires an immutable file: {}", path.display())
|
||||
@@ -121,44 +124,6 @@ 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 {
|
||||
@@ -196,12 +161,6 @@ 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
|
||||
@@ -209,7 +168,8 @@ impl ProjectSnapshot {
|
||||
&& self.directories == next.directories
|
||||
&& self.aliases == next.aliases
|
||||
&& self.generated_roots == next.generated_roots
|
||||
&& self.generated == next.generated)
|
||||
&& self.generated == next.generated
|
||||
&& self.files.keys().eq(next.files.keys()))
|
||||
}
|
||||
pub fn generated(&self) -> impl Iterator<Item = &Path> {
|
||||
self.generated.iter().map(PathBuf::as_path)
|
||||
|
||||
@@ -94,12 +94,7 @@ impl Bounds {
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum PaintKind {
|
||||
Glyph {
|
||||
font: u32,
|
||||
slot: u8,
|
||||
#[serde(default, skip_serializing_if = "crate::native_font::unexpanded")]
|
||||
expansion: i32,
|
||||
},
|
||||
Glyph { font: u32, slot: u8 },
|
||||
Rule,
|
||||
PdfImage { page: usize },
|
||||
}
|
||||
@@ -201,13 +196,6 @@ 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() {
|
||||
@@ -220,8 +208,7 @@ impl SourceMap {
|
||||
.enumerate()
|
||||
.map(|(id, (file, version))| {
|
||||
if version.bytes != file.data.len() as u64
|
||||
|| (verify_source_hashes
|
||||
&& version.sha256 != format!("{:x}", Sha256::digest(&file.data)))
|
||||
|| version.sha256 != format!("{:x}", Sha256::digest(&file.data))
|
||||
{
|
||||
return Err(format!("source map version mismatch for source {id}"));
|
||||
}
|
||||
@@ -346,13 +333,12 @@ 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(font.advance(*slot))?,
|
||||
width: scale(metrics.width(c))?,
|
||||
height: h
|
||||
.checked_add(d)
|
||||
.ok_or("source map glyph height overflow")?,
|
||||
|
||||
@@ -135,17 +135,6 @@ fn templates_execute_macros_groups_assignments_hooks_and_nested_lists() {
|
||||
compare(body);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn hash_brace_macro_delimiters_preserve_alignment_cell_boundaries() {
|
||||
compare(
|
||||
r"\def\prefix#{\relax}\def\argument#1:#2#{#2#1}
|
||||
\setbox0=\vbox{\halign{#&#\cr
|
||||
A\prefix{B}&C\cr
|
||||
D\argument A:B{C}&DEF\cr
|
||||
}}",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vertical_alignment_uses_vertical_cells_and_horizontal_rows() {
|
||||
for spec in ["", "to40pt", "spread5pt"] {
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
//! 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};
|
||||
@@ -303,160 +301,3 @@ 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"], 37);
|
||||
assert_eq!(payload["schema"], 27);
|
||||
let state = State::initex().with_etex();
|
||||
let loaded = FormatImage::decode(&bytes)
|
||||
.unwrap()
|
||||
|
||||
@@ -146,53 +146,6 @@ fn catalog_appends_expanded_lists_and_prints_with_final_token_settings() {
|
||||
assert!(native.catalog().unwrap().get(b"OpenAction").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expanded_page_references_target_shipped_pages_and_preserve_free_objects() {
|
||||
let (reference, native, messages) = pair(&format!(
|
||||
r"\def\space{{ }}
|
||||
\pdfobj reserveobjnum \edef\data{{\the\pdflastobj}}
|
||||
\edef\missing{{\pdfpageref 9}}
|
||||
\edef\first{{\pdfpageref 1}}
|
||||
\ifnum\pdflastobj=\data\relax\else\errmessage{{page changed last object}}\fi
|
||||
{PAGE}
|
||||
\ifnum\pdfpageref 1=\first\relax\else\errmessage{{page identity changed}}\fi
|
||||
\edef\third{{\pdfpageref 3}}
|
||||
\immediate\pdfobj useobjnum\data {{<< /Third \third\space 0 R /Missing \missing\space 0 R >>}}
|
||||
\edef\resources{{\pdfpageresources{{/Witness \first\space 0 R}}}}\resources
|
||||
\pdfcatalog{{/Witness << /First \first\space 0 R /Data \data\space 0 R >>}}
|
||||
{PAGE}{PAGE}"
|
||||
));
|
||||
for pdf in [&reference, &native] {
|
||||
let pages = pdf.get_pages();
|
||||
assert_eq!(pages.len(), 3);
|
||||
let witness = get(pdf, pdf.catalog().unwrap(), b"Witness").as_dict().unwrap();
|
||||
assert_eq!(
|
||||
witness.get(b"First").unwrap().as_reference().unwrap(),
|
||||
pages[&1],
|
||||
);
|
||||
let data = get(pdf, witness, b"Data").as_dict().unwrap();
|
||||
assert_eq!(
|
||||
data.get(b"Third").unwrap().as_reference().unwrap(),
|
||||
pages[&3],
|
||||
);
|
||||
let missing = data.get(b"Missing").unwrap().as_reference().unwrap();
|
||||
assert!(pdf.get_object(missing).is_err());
|
||||
let second = pdf.get_dictionary(pages[&2]).unwrap();
|
||||
let resources = get(pdf, second, b"Resources").as_dict().unwrap();
|
||||
assert_eq!(
|
||||
resources.get(b"Witness").unwrap().as_reference().unwrap(),
|
||||
pages[&1],
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
messages
|
||||
.iter()
|
||||
.filter(|message| message.contains("page 9"))
|
||||
.count(),
|
||||
1,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_actions_use_the_actual_objects_and_page_references() {
|
||||
for command in [
|
||||
|
||||
@@ -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"], 37);
|
||||
assert_eq!(original["schema"], 27);
|
||||
for (schema, expected) in [
|
||||
(1, "incompatible native format"),
|
||||
(2, "incompatible native format"),
|
||||
@@ -363,11 +363,6 @@ 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,22 +150,13 @@ 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,43 +283,6 @@ 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"], 37);
|
||||
assert_eq!(payload["schema"], 27);
|
||||
let executor = FormatImage::decode(&bytes)
|
||||
.unwrap()
|
||||
.new_job(
|
||||
|
||||
@@ -2,28 +2,7 @@
|
||||
|
||||
本文件记录用户重申的最终目标,是短期 goal、实现优先级和验收标准的上位约束。
|
||||
|
||||
## 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 产品优先级(历史记录)
|
||||
## 2026-11-19 产品优先级
|
||||
|
||||
产品主体是**面向编辑会话的实时 TeX 编译和渲染内核**。一次实际编辑触发
|
||||
可追踪的失效和局部更新,返回可见页面、诊断及来源。稳定后的页面、字形、
|
||||
@@ -46,15 +25,14 @@ Tectonic 的 XeTeX 入口在进程级锁内运行,桥接层能提供输入输
|
||||
[Tectonic 桥接层](https://github.com/tectonic-typesetting/tectonic/blob/master/crates/bridge_core/src/lib.rs#L271-L288)
|
||||
|
||||
原样 A4 在连续子文件编辑中,取消旧作业的浏览器观测 p95 已低于100 ms。
|
||||
当前两轮原样 A4 主文件编辑的可见 p95 为224.0和208.6 ms,仍需达到100 ms
|
||||
门禁。评估上游执行入口时,分别测量编辑到可见页面、可恢复的状态范围与
|
||||
全量一致性,并记录完整重新执行的成本作为基线。
|
||||
新编辑到可见页面的 p95 仍高于250 ms。接下来分解编译准备、执行复用和页面
|
||||
交付,继续按固定预算及逐版本全量一致性验收。
|
||||
[阶段测量与回执](P2_M1_PROGRESS.md)
|
||||
|
||||
## 2026-11-11 总目标重新确认
|
||||
|
||||
用户明确要求设置并持续执行完整目标:**完整 LaTeX 引擎,加上类 Typst 的实时
|
||||
编译与渲染能力**。总目标覆盖下文 P0–P5;P2-M1、单个原语或
|
||||
编译与渲染能力**。总目标现为 active,持续覆盖下文 P0–P5;P2-M1、单个原语或
|
||||
某个项目通过都不构成总目标完成。
|
||||
|
||||
兼容性与实时性同时验收:真实格式/类/包和原样项目迁移;有状态的安全增量执行、
|
||||
|
||||
@@ -66,23 +66,6 @@ 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身份、
|
||||
|
||||
+4
-764
@@ -2,8 +2,8 @@
|
||||
|
||||
2026-11-02:用户已授权完整执行 [阶段目标](NATIVE_FORMAT_ARTICLE_STAGE.md),
|
||||
并要求 **G1 的全部退出条件为 W1 必选门禁**。整体状态:**执行中,未完成**。
|
||||
最近一次完整工作区回归为 **1628 项通过、零失败**,覆盖来源映射指纹复用。
|
||||
之后的检查点和文本重音变更使用定向回归及原样项目对照。P2-M1 总验收仍按原 W0–W7 门槛执行。
|
||||
最近可复现的完整工作区回归为 **1564 tests / 0 failed**,覆盖已推广的公式编号
|
||||
和 `\mathchoice`。前序显示数学对齐正式验收为 1553/0。P2-M1 总验收仍按原 W0–W7 门槛执行。
|
||||
|
||||
## 工作包状态
|
||||
|
||||
@@ -655,12 +655,7 @@ 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次
|
||||
@@ -668,762 +663,7 @@ 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)
|
||||
|
||||
### 原生段落结束 token 和分组上下文
|
||||
|
||||
`\partokenname` 全局选择引擎插入的段落 token,并用实际 token 身份检查
|
||||
非 long 宏的参数。空行和经典隐式段落边界使用该命令。`\partokencontext`
|
||||
是普通局部整数参数;模式1扩展至垂直盒、垂直顶盒和 `\vcenter`,模式2也
|
||||
覆盖插入、调整、输出例程、`\noalign` 及垂直对齐的单元格。实现先把遇到
|
||||
的闭合 token 放回输入,再执行当前段落命令,因此分组还在,命令效果遵循
|
||||
正常执行及恢复。schema37 格式保存改名和参数。
|
||||
[TeX Live 的段落 token 更改文件](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/partoken.ch)
|
||||
|
||||
同一输入下实际段落输出的10条上下文记录逐字节一致,两页144 DPI灰度图
|
||||
逐像素一致。TeX Live 原样成功用例的90个字形和 DVI 坐标逐个匹配,
|
||||
最大位置偏差0 sp,原样失败用例在重命名后的段落 token 处拒绝非 long
|
||||
参数。两个相关测试文件合计18项通过。首次对照缺少字体查找根,恢复
|
||||
真实 TeX Live 的两处搜索根后通过,早期日志保留。
|
||||
[TeX Live 原样成功用例](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/tests/partoken-ok.tex)
|
||||
[TeX Live 原样预期失败用例](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/tests/partoken-xfail.tex)
|
||||
|
||||
实际 INITEX 还转储了名为 `\renamedpar` 的段落 token 和模式1。加载后
|
||||
两个盒子中的隐式命令各修改一次作业计数。编辑第二页时复用1015步只
|
||||
替换第二页,PDF、SVG 和来源映射与独立零复用一致。来源映射只归一化
|
||||
测试目录和会话修订号。首次验证计数赋值未设为全局,修正用例后通过。
|
||||
|
||||
`target/p3-paragraph-token-native` 的回执:
|
||||
|
||||
- `receipt.json` 为 `03eface7fac03417da5437c240176281bfb410e070f7568f6e40a63e19a0d8de`。
|
||||
- `minimal-format/seed.tfx` 为 `e6ee320d0b87cf3f25e8a52b858f1eb491e77356b2f4b60781233b1d4bb11347`。
|
||||
- `checkpoint/receipt.json` 为 `07e1e1d38425b91587029fc838b7dde351bd394ae473ebf3552f7e567b6637af`。
|
||||
- `targeted-regression.log` 为 `295b489dfef681c254f4a2afcba01511f08e0c69b99aaf9be33153ac0ad8397d`。
|
||||
|
||||
### 宏的左花括号分隔符与表格行边界
|
||||
|
||||
带 `#{` 的 TeX 宏把字面左花括号匹配为分隔符,再将同一括号放回替换
|
||||
文本。对齐深度现在只在读到替换文本中的括号时计入一次。无参数的宏
|
||||
前缀和有参数的最后一个分隔符都按这条规则处理。
|
||||
[pdfTeX 的宏分隔符对齐状态](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L9429-L9441)
|
||||
|
||||
原样 arXiv 作者表格的换行差异用普通 `article`、原版 `hyperref` 和
|
||||
单列表格复现。移除图片或脚注仍复现,保留图片、移除实际链接后可编译。
|
||||
新增核心对照验证两种宏分隔形式生成的完整盒列表与 pdfTeX 相同。
|
||||
对齐测试文件11项通过,最后另外核对了在单元格已有文本后读取分隔符
|
||||
的情况。编辑第二页的表格时复用945步,只替换第二页,PDF、SVG 和
|
||||
来源映射与独立零复用一致。来源映射只归一化会话修订号和测试项目根。
|
||||
|
||||
`target/p3-arxiv-title-alignment` 的回执:
|
||||
|
||||
- `bisect/result.json` 为 `af39b0de752d7a66b28e4ea8833238633ef2eeafb66b1e6fd38508c5e0413b9c`。
|
||||
- `alignment-test.log` 为 `4aa21ddf1c71e7d028bf13d0fba93a2937842c0fafcf4e137b8dd69f167f97c2`。
|
||||
- `hash-brace-test.log` 为 `a388b5874e0eacb92ffbb9f3beda6d7ce97c2a88bbcf395e8524c8c72222cbe3`。
|
||||
- `checkpoint/receipt.json` 为 `1cf6357762f1641b1849523abe29c3b8b56410d0c376fefe1c53a42b3d516761`。
|
||||
|
||||
### 原生 PDF 页对象引用
|
||||
|
||||
`\pdfpageref` 展开出同一作业内稳定的页对象编号,可以在对应物理页出页前
|
||||
取得,也可在出页后重复取得。它和普通 PDF 对象共用编号空间,保留
|
||||
`\pdflastobj` 语义。导出时在真实 PDF 对象图中解析目录、附加页资源和普通
|
||||
对象字典中的引用。实际出页填充对应的 `/Page` 字典。未出页的引用使用空闲
|
||||
交叉引用条目,并产生诊断。逻辑编号和 PDF 文件中的物理编号由原生写出器
|
||||
分配,对照核验引用指向及对象状态。
|
||||
[pdfTeX 的引用登记与输出](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L34732-L34759)
|
||||
|
||||
三页定向对照覆盖预先引用、出页后重复取得编号、普通对象中的跨页与
|
||||
缺页引用。三页144 DPI灰度图与 pdfTeX 逐像素一致。目录相关检查共15项通过,
|
||||
包含新增的对象图对照。真实 INITEX 最小格式为 schema36。
|
||||
在第一页后恢复、编辑第二页时,复用921个执行步骤并只替换第二页。
|
||||
目录仍指向实际第二页,PDF 和 SVG 与独立零复用一致。来源映射仅归一化
|
||||
测试项目根及会话修订号。
|
||||
|
||||
`target/p3-pdf-page-reference-native` 回执:
|
||||
|
||||
- `receipt.json` 为 `f1e727af03c1df86222ebe944bb9d9abb219db05bb1855a0a5687e304df611d5`。
|
||||
- `checkpoint/receipt.json` 为 `447e27d7e3e8e892b9c812ff3bb78d15f691b922bac65a3879ae9bf7f2df3f1a`。
|
||||
- `catalog.log` 为 `149dd3ce9f8598febbe19a3acb057894ee3ceff57893131db17aa786a7498dd1`。
|
||||
|
||||
### pdfTeX 随机序列与检查点
|
||||
|
||||
`\pdfsetrandomseed`、`\pdfrandomseed`、`\pdfuniformdeviate` 与
|
||||
`\pdfnormaldeviate` 使用原生整数序列。显式种子作用于整项作业,正常分组
|
||||
结束后继续沿用。执行检查点保存当前种子与序列位置;schema35 原生格式
|
||||
登记新原语,每项作业独立初始化序列。宿主支持显式指定初始种子,并从
|
||||
冻结的 `SOURCE_DATE_EPOCH` 得到可重放的默认种子。参考 pdfTeX
|
||||
在同样设置下仍使用运行时种子,因此参考序列对照固定了显式种子。
|
||||
[pdfTeX 的随机种子与整数抽样](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L2814-L2880)
|
||||
|
||||
六个种子下的415次均匀抽取和205次正态抽取与 pdfTeX 逐项一致,
|
||||
覆盖零、负数和极值上界,以及分组播种、原语别名和定义内展开。
|
||||
一页144 DPI灰度图逐像素一致。真实 INITEX 转储未保留运行中的序列。
|
||||
两页会话中,第二页编辑从首个随机抽取后的检查点恢复,前沿字节5746,
|
||||
复用878步且只替换第二页。PDF 和 SVG 与独立零复用一致,来源映射
|
||||
仅归一化测试项目根及会话修订号。
|
||||
|
||||
`target/p3-pdf-random-native` 的回执:
|
||||
|
||||
- `receipt.json` 为 `421b80ec3a486a207c8ce2e0d6953a3faa6a446996709313d600b884e3512bfe`。
|
||||
- `checkpoint/receipt.json` 为 `2c9f36da8b0bfd1e9c08fed2abddb24d06d80ebee2f7e83d24bf1748dbcd1f5a`。
|
||||
|
||||
### 文件型 PDF 对象和真实资源依赖
|
||||
|
||||
`\pdfobj file` 与 `\pdfobj stream ... file` 在对象实际写入时
|
||||
通过宿主读取文件。普通出页先执行原有写入队列,再物化引用的 PDF 对象。
|
||||
同一对象一旦写入,跨页引用使用该版本的字节。宿主记录请求路径、资源
|
||||
身份和所读字节版本;检查点保留实际对象状态及真实依赖。
|
||||
[pdfTeX 的对象写入位置](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web)
|
||||
|
||||
定向对照覆盖含 NUL 和非 UTF-8 字节的真实流、磁盘直接对象和同一次
|
||||
出页稍后生成的内容。按实际读取版本物化的三个对象各只读取一次。
|
||||
两页144 DPI灰度图逐像素一致。保持主文件不变,只编辑图形状态资源,
|
||||
会话恢复37步,只替换第一页;第二页的 SVG 保持一致。最终原生
|
||||
PDF 和 SVG 与独立零复用一致。移除会话修订号和测试项目根之后来源
|
||||
映射一致。该对照验证版本失效和结果,未采样正式性能。
|
||||
|
||||
回执位于 `target/p3-pdf-file-object-native`:
|
||||
|
||||
- `receipt.json` 为 `e2dc5bc98943f565ebfac15a5cdcf4e9b7538d62cd399e267fcadeea11d7ab76`。
|
||||
- `asset-edit/receipt.json` 为 `8c581797ef1b4aaba72b38b873e34874c2636ab1f76466fb0d593c3ee78cc81d`。
|
||||
|
||||
### 原生 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 输入的默认扩展名候选
|
||||
|
||||
|
||||
@@ -384,122 +384,6 @@ 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#原生段落边缘悬挂)
|
||||
|
||||
### 优化版的原样 arXiv 对齐诊断
|
||||
|
||||
主线 schema35 用原样 `pdflatex.ini` 生成格式后,沿用原样 arXiv 的六个
|
||||
输入和冻结字体映射。原生越过 microtype 的字宽伸缩设置,在
|
||||
`template.tex:94` 的 `\maketitle` 展开链中遇到 misplaced native
|
||||
alignment command。回溯显示 `\reserved@c` 展开为 `\ifnum 0=` 加
|
||||
左花括号字符常量、`\fi`、右花括号与 `\cr`。该轮未生成 PDF。
|
||||
`target/p3-pdf-random-native/arxiv-first-blocker/receipt.json` 的 SHA-256
|
||||
为 `05432989407b5d9ea8a592de5998a6ea81788fedc359fe1f24444d19836214ef`。
|
||||
|
||||
修正宏分隔符的对齐深度后,新代码使用同一只读原样格式、同一组六份
|
||||
输入和同一字体映射执行。原样标题通过,`template.tex:119` 的
|
||||
`\end{equation}` 展开至 microtype 的 `\MT@suspend@tagging` 后,
|
||||
实际首个缺失原语是 `\partokencontext`。该轮未生成 PDF。
|
||||
`target/p3-arxiv-title-alignment/original-arxiv/receipt.json` 的 SHA-256
|
||||
为 `75a1803375d875d710427f6cf8e36a972657728d0890f5ab96026c9c0ac41762`。
|
||||
|
||||
### 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` 和会议
|
||||
@@ -530,32 +414,6 @@ SHA-256 为 `0f9082ccfabbd34895b95abe9a20011c68cd9669a5cc69c2068e97b7aa3ae631`
|
||||
[pdfTeX 对象写出](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L31785-L31839)
|
||||
[pdfTeX 页面资源写出](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L17886-L17903)
|
||||
|
||||
主线 schema34 优化版用冻结依赖从原样 `pdflatex.ini` 生成格式,用时
|
||||
209.7秒。用同一版编译原样 `acmtog` 双栏期刊,44个出版资源及字体映射
|
||||
保持原有身份。透明度初始化完成,下一处诊断为 `tagpdf.sty:1458` 使用
|
||||
`\tex_uniformdeviate:D`;该轮未生成 PDF。格式和探测回执均在
|
||||
`target/p3-pdf-page-graphics-state-native`。
|
||||
|
||||
- `acm-format/receipt.json` 为 `aaaa0ca82e2481371e794c39d60c065eadd35a6f1f407c32e1feb05afdc9d7ec`。
|
||||
- `acm-acmtog/receipt.json` 为 `4ea3f87e2674b711b1217e4d4e1e17d2a823080614586471061462569c283dcb`。
|
||||
|
||||
随后 schema35 用冻结输入从原样 `pdflatex.ini` 生成格式,用时189.9秒。
|
||||
原样 `acmtog` 使用同一批44个出版资源与相同字体映射,越过随机原语,
|
||||
在 `hgeneric-testphase.def:1579` 使用 `\tex_pdfpageref:D` 时停止,
|
||||
未生成 PDF。回执位于 `target/p3-pdf-random-native`。
|
||||
|
||||
- `acm-format/receipt.json` 为 `b19359f4af8aacce9087c3713def1878b4915ed8226cf34e4f2ebd87322a728e`。
|
||||
- `acm-acmtog/receipt.json` 为 `e9a87f4eac0299c01fa85f0ebe1b478f630cb074b705dd526848e267627e3f5d`。
|
||||
|
||||
schema36 优化版在冻结输入上生成的原样格式耗时211.1秒。原样双栏
|
||||
越过 PDF 页对象引用,完成文档类及导言区执行。首次出页期间,LaTeX
|
||||
后端展开 `\tex_pdfliteral:D shipout page{...}` 时停止,该轮未生成
|
||||
PDF。同一作业中,`cmap` 的 `\pdffontattr` 能力检查发出退出告警。
|
||||
`target/p3-pdf-page-reference-native` 保留两份回执。
|
||||
|
||||
- `acm-format/receipt.json` 为 `e9580f5a2aa3fa0665d29fbd42650230b7dcf4203daed946a6170767d0b506df`。
|
||||
- `acm-acmtog/receipt.json` 为 `56956692e4524398200b6fbbbd7a0d96d030d5dc3c27975b8dde743473e4ab09`。
|
||||
|
||||
最终矩阵 `target/publisher-template-matrix/acm-official/matrix-schema29-utf8/report.json`
|
||||
SHA-256 为 `d914d7c7dfa1ee28dff20e77231fef35e390041cde6180bcc361de83288ec9e1`。其 `preparation/acmart` 保存
|
||||
DocStrip 记录。同目录的前序依赖失败、补充包指纹和原样源均保留。用现有
|
||||
|
||||
@@ -30,7 +30,7 @@ struct Edit {
|
||||
visible_revision: Option<u64>,
|
||||
source: Option<String>,
|
||||
#[serde(default)]
|
||||
files: BTreeMap<String, Option<String>>,
|
||||
files: BTreeMap<String, String>,
|
||||
#[serde(default)]
|
||||
preview_draft: bool,
|
||||
}
|
||||
@@ -169,9 +169,6 @@ 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()?;
|
||||
@@ -217,8 +214,12 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let file = project.file(&entry).expect("the editor owns its entry");
|
||||
let files = editable
|
||||
.iter()
|
||||
.filter_map(|(name, path)| project.file(path).map(|file| (name, file)))
|
||||
.map(|(name, file)| Ok((name, std::str::from_utf8(&file.data)?)))
|
||||
.map(|(name, path)| {
|
||||
let file = project
|
||||
.file(path)
|
||||
.expect("editable project files are immutable");
|
||||
Ok((name, std::str::from_utf8(&file.data)?))
|
||||
})
|
||||
.collect::<Result<BTreeMap<_, _>, std::str::Utf8Error>>()?;
|
||||
reply(
|
||||
request,
|
||||
@@ -256,21 +257,18 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let path = editable
|
||||
.get(&name)
|
||||
.ok_or_else(|| format!("File is not editable: {name}"))?;
|
||||
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()))))
|
||||
Ok((path.clone(), Arc::from(value.into_bytes())))
|
||||
})
|
||||
.collect::<Result<BTreeMap<_, _>, String>>();
|
||||
let next = updates.and_then(|mut updates| {
|
||||
if let Some(source) = edit.source
|
||||
&& updates
|
||||
.insert(entry.clone(), Some(Arc::from(source.into_bytes())))
|
||||
.insert(entry.clone(), Arc::from(source.into_bytes()))
|
||||
.is_some()
|
||||
{
|
||||
return Err("The entry file was edited twice".into());
|
||||
}
|
||||
project.with_file_changes(edit.sequence, updates)
|
||||
project.with_file_edits(edit.sequence, updates)
|
||||
});
|
||||
project = match next {
|
||||
Ok(project) => project,
|
||||
@@ -401,8 +399,6 @@ 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
|
||||
@@ -416,51 +412,24 @@ fn prepare(
|
||||
.into());
|
||||
}
|
||||
let logical = run.join(relative);
|
||||
if !declared.insert(logical.clone()) {
|
||||
return Err(format!("Project file is listed twice: {}", relative.display()).into());
|
||||
}
|
||||
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(_) => {
|
||||
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: {}",
|
||||
"Project file is outside the entry directory or is listed twice: {}",
|
||||
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),
|
||||
);
|
||||
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)?;
|
||||
if let Some(name) = relative.to_str()
|
||||
&& data
|
||||
.as_deref()
|
||||
.is_none_or(|bytes| std::str::from_utf8(bytes).is_ok())
|
||||
&& std::str::from_utf8(&data).is_ok()
|
||||
{
|
||||
editable.insert(name.into(), logical.clone());
|
||||
}
|
||||
if let Some(data) = data {
|
||||
fs::write(&logical, &data)?;
|
||||
files.insert(logical, data);
|
||||
}
|
||||
}
|
||||
let mut request = CompileRequest::new(
|
||||
world.clone(),
|
||||
&entry,
|
||||
@@ -506,7 +475,7 @@ fn prepare(
|
||||
revision: 1,
|
||||
roots: coverage,
|
||||
files,
|
||||
directories,
|
||||
directories: BTreeSet::new(),
|
||||
aliases: BTreeMap::new(),
|
||||
generated_roots: BTreeSet::from([run.to_owned()]),
|
||||
generated,
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
use std::io::{self, BufRead, Write};
|
||||
use texrra_tex_core::execution::{RegexRequest, match_pdf_regex};
|
||||
|
||||
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()?;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(all(target_os = "linux", target_env = "gnu")))]
|
||||
fn main() -> std::process::ExitCode {
|
||||
eprintln!("pdfTeX regular expressions require the GNU backend");
|
||||
std::process::ExitCode::FAILURE
|
||||
}
|
||||
@@ -17,9 +17,6 @@ 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);
|
||||
|
||||
+23
-21
@@ -73,16 +73,6 @@ 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,
|
||||
@@ -569,7 +559,6 @@ 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>>,
|
||||
}
|
||||
@@ -945,19 +934,30 @@ impl CompileJob {
|
||||
.filter(|_| checkpoint_guard::can_stage(&request));
|
||||
let format_cache = &self.compiler.format_cache;
|
||||
let mut entry_checkpoint_work = EntryCheckpointWork::default();
|
||||
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)),
|
||||
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),
|
||||
Err(error) => {
|
||||
check(&cancellation)?;
|
||||
*evidence = AttemptEvidence::new(revision);
|
||||
entry_checkpoint_work.rejection = Some(error.to_string());
|
||||
(None, None)
|
||||
active_checkpoint = None;
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
(None, None)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let PreparedJob {
|
||||
executor,
|
||||
@@ -1080,11 +1080,12 @@ impl CompileJob {
|
||||
)
|
||||
};
|
||||
if let Some(path) = &request.layout_manifest {
|
||||
let source_map = self.compiler.session.source_map(&execution, &pages)?;
|
||||
let source_map =
|
||||
texrra_tex_core::source_map::SourceMap::from_revision(&execution, &pages)?;
|
||||
files.write_layout_manifest(path, e, &pages, &source_map)?;
|
||||
}
|
||||
evidence.phase = AttemptPhase::Fonts;
|
||||
let fonts = self.compiler.font_cache.resolve(&mut pages, files);
|
||||
let fonts = texrra_tex_core::native_font::resolve_native_fonts(&mut pages, files);
|
||||
let reported = report(files, &request);
|
||||
if let Err(error) = fonts {
|
||||
if let Err(report) = reported {
|
||||
@@ -1093,7 +1094,8 @@ impl CompileJob {
|
||||
return Err(CompileError::Host(error));
|
||||
}
|
||||
reported?;
|
||||
let source_map = self.compiler.session.source_map(&execution, &pages)?;
|
||||
let source_map =
|
||||
texrra_tex_core::source_map::SourceMap::from_revision(&execution, &pages)?;
|
||||
notify(
|
||||
&request,
|
||||
revision,
|
||||
|
||||
+90
-641
@@ -4,10 +4,7 @@ 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, ResourceLookup},
|
||||
};
|
||||
use texrra_tex_core::{execution::EntryCheckpoint, resources::ResourceKind};
|
||||
#[cfg(test)]
|
||||
use texrra_tex_core::{execution::HostResourceUsage, resources::InputPolicy};
|
||||
|
||||
@@ -44,7 +41,6 @@ pub(super) struct CheckpointSet {
|
||||
entries: Vec<Arc<CachedCheckpoint>>,
|
||||
calls: Vec<Call>,
|
||||
refresh_on_resume: bool,
|
||||
edit_frontier: Option<usize>,
|
||||
}
|
||||
|
||||
pub(super) struct SelectedCheckpoint {
|
||||
@@ -62,7 +58,6 @@ struct CaptureSchedule {
|
||||
seen: [bool; SOURCE_INTERVALS],
|
||||
next_page: usize,
|
||||
fixed_frontier: Option<usize>,
|
||||
pending_edit_frontier: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -70,38 +65,20 @@ struct CaptureSlots {
|
||||
interval: usize,
|
||||
early: bool,
|
||||
page: bool,
|
||||
edit: bool,
|
||||
next_page: usize,
|
||||
}
|
||||
|
||||
impl CaptureSchedule {
|
||||
fn new(bytes: usize, fixed_frontier: Option<usize>, edit_frontier: Option<usize>) -> Self {
|
||||
fn new(bytes: usize, fixed_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 {
|
||||
@@ -112,7 +89,6 @@ impl CaptureSchedule {
|
||||
interval: 0,
|
||||
early: true,
|
||||
page: false,
|
||||
edit: false,
|
||||
next_page: self.next_page,
|
||||
});
|
||||
}
|
||||
@@ -125,12 +101,10 @@ impl CaptureSchedule {
|
||||
if page {
|
||||
self.next_page = pages.saturating_add((pages / 8).max(1).next_power_of_two());
|
||||
}
|
||||
let edit = self.take_edit_frontier(frontier, early || page);
|
||||
(early || page || edit).then_some(CaptureSlots {
|
||||
(early || page).then_some(CaptureSlots {
|
||||
interval,
|
||||
early,
|
||||
page,
|
||||
edit,
|
||||
next_page: self.next_page,
|
||||
})
|
||||
}
|
||||
@@ -146,7 +120,6 @@ impl CaptureSchedule {
|
||||
Some(CaptureSlots {
|
||||
interval,
|
||||
early,
|
||||
edit: self.take_edit_frontier(frontier, early || checkpoint.slots.page),
|
||||
..checkpoint.slots
|
||||
})
|
||||
}
|
||||
@@ -158,7 +131,6 @@ struct CapturedEntries<'a> {
|
||||
initial: Option<GeneratedInitialState>,
|
||||
early: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
|
||||
shipped: [Option<Arc<CachedCheckpoint>>; SOURCE_INTERVALS],
|
||||
edit: Option<Arc<CachedCheckpoint>>,
|
||||
changed: bool,
|
||||
}
|
||||
|
||||
@@ -174,7 +146,6 @@ impl<'a> CapturedEntries<'a> {
|
||||
initial: files.preparation().generated_initial.clone(),
|
||||
early: Default::default(),
|
||||
shipped: Default::default(),
|
||||
edit: None,
|
||||
changed: false,
|
||||
}
|
||||
}
|
||||
@@ -183,9 +154,6 @@ 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);
|
||||
}
|
||||
@@ -199,13 +167,8 @@ impl<'a> CapturedEntries<'a> {
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let Ok(guard) = PrefixInputGuard::capture(
|
||||
self.request,
|
||||
path,
|
||||
trace,
|
||||
host.generated_outputs(),
|
||||
initial.clone(),
|
||||
) else {
|
||||
let Ok(guard) = PrefixInputGuard::capture(self.request, path, trace, initial.clone())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.retain(
|
||||
@@ -228,34 +191,14 @@ 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);
|
||||
@@ -263,7 +206,6 @@ impl<'a> CapturedEntries<'a> {
|
||||
entries,
|
||||
calls,
|
||||
refresh_on_resume,
|
||||
edit_frontier,
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -341,7 +283,7 @@ impl CheckpointCache {
|
||||
Result<Arc<RevisionExecution>, RevisionFailure>,
|
||||
Option<Arc<CheckpointSet>>,
|
||||
) {
|
||||
let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier, None);
|
||||
let mut schedule = CaptureSchedule::new(source.data.len(), self.minimum_frontier);
|
||||
let mut captures = CapturedEntries::new(request, files);
|
||||
let mut recording = RecordingHost::new(files);
|
||||
let result = job.run_capturing_entries(
|
||||
@@ -361,92 +303,24 @@ impl CheckpointCache {
|
||||
}
|
||||
|
||||
impl PublishedCheckpoints {
|
||||
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))
|
||||
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
|
||||
{
|
||||
Ok(_) => true,
|
||||
Err(error) => {
|
||||
rejection.get_or_insert(error);
|
||||
false
|
||||
return Ok(previous);
|
||||
}
|
||||
}
|
||||
})
|
||||
.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)?;
|
||||
}
|
||||
if !checkpoint
|
||||
.guard
|
||||
.project
|
||||
.immutable_paths()
|
||||
.eq(project.immutable_paths())
|
||||
{
|
||||
checkpoint.guard.verify_replayed_lookups(&prepared.files)?;
|
||||
}
|
||||
Ok((selected, prepared))
|
||||
current
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,7 +342,6 @@ impl CheckpointSet {
|
||||
entries,
|
||||
calls: self.calls[..replay_count].to_vec(),
|
||||
refresh_on_resume: self.refresh_on_resume,
|
||||
edit_frontier: self.edit_frontier,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -477,13 +350,27 @@ impl CheckpointSet {
|
||||
work.captured_frontier = self.entries.last().map(|entry| entry.entry.frontier());
|
||||
}
|
||||
|
||||
fn candidates(self: &Arc<Self>) -> impl Iterator<Item = SelectedCheckpoint> + '_ {
|
||||
(0..self.entries.len())
|
||||
.rev()
|
||||
.map(|index| SelectedCheckpoint {
|
||||
set: Arc::clone(self),
|
||||
index,
|
||||
})
|
||||
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()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -507,6 +394,38 @@ 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,
|
||||
@@ -536,13 +455,7 @@ impl SelectedCheckpoint {
|
||||
return Ok((result, self.set));
|
||||
}
|
||||
|
||||
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 schedule = CaptureSchedule::new(source.data.len(), None);
|
||||
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] {
|
||||
@@ -585,36 +498,12 @@ 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 = ¤t[..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]>,
|
||||
}
|
||||
|
||||
@@ -627,7 +516,6 @@ impl PrefixInputGuard {
|
||||
request: &CompileRequest,
|
||||
entry: &Path,
|
||||
trace: &ResourceTrace,
|
||||
written: &BTreeSet<PathBuf>,
|
||||
initial: GeneratedInitialState,
|
||||
) -> Result<Self, String> {
|
||||
let project = request
|
||||
@@ -662,26 +550,16 @@ 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) {
|
||||
generated.insert(path.to_path_buf());
|
||||
} else {
|
||||
} else if !initial.files().contains_key(path) {
|
||||
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());
|
||||
@@ -694,8 +572,6 @@ impl PrefixInputGuard {
|
||||
initial,
|
||||
entry: entry.to_path_buf(),
|
||||
immutable,
|
||||
generated,
|
||||
lookups: trace.lookups.clone(),
|
||||
clock_environment: (!trace.file_modifications.is_empty()).then(date_environment),
|
||||
})
|
||||
}
|
||||
@@ -721,8 +597,8 @@ impl PrefixInputGuard {
|
||||
.project
|
||||
.as_deref()
|
||||
.ok_or("checkpoint requires an atomic project")?;
|
||||
if !self.project.same_lookup_configuration(current)? {
|
||||
return Err("checkpoint lookup configuration changed".into());
|
||||
if !self.project.same_lookup_namespace(current)? {
|
||||
return Err("checkpoint lookup namespace changed".into());
|
||||
}
|
||||
for path in &self.immutable {
|
||||
let old = self.project.file(path).map(|file| &file.version);
|
||||
@@ -745,19 +621,6 @@ 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,
|
||||
@@ -772,21 +635,7 @@ impl PrefixInputGuard {
|
||||
.generated_initial
|
||||
.as_ref()
|
||||
.ok_or("checkpoint requires generated versions observed under the job lock")?;
|
||||
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(())
|
||||
self.initial.check(current)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -879,14 +728,10 @@ 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.generated_outputs().clone(),
|
||||
)
|
||||
(host.capture(), host.resource_usage().unwrap().unwrap())
|
||||
});
|
||||
assert!(executed.is_ok());
|
||||
let (checkpoint, (recorded, usage, written)) = checkpoint.unwrap();
|
||||
let (checkpoint, (recorded, usage)) = checkpoint.unwrap();
|
||||
let (calls, trace) = recorded.unwrap();
|
||||
assert_eq!(usage.open_outputs, Some(1));
|
||||
assert!(
|
||||
@@ -895,9 +740,7 @@ 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, &written, initial).unwrap();
|
||||
assert!(guard.generated.contains(&aux));
|
||||
assert!(!guard.generated.contains(&seed));
|
||||
let guard = PrefixInputGuard::capture(&request, &entry, &trace, initial).unwrap();
|
||||
assert!(guard.immutable.contains(&library));
|
||||
assert!(!guard.immutable.contains(&unrelated));
|
||||
assert!(!guard.immutable.contains(&entry));
|
||||
@@ -962,16 +805,16 @@ fn prefix_guard_checks_actual_dependencies_and_preserves_live_artifacts_on_rejec
|
||||
&request.clone().with_project(changed_prefix),
|
||||
"entry prefix changed",
|
||||
);
|
||||
let mut changed_namespace = definition;
|
||||
changed_namespace.revision = 3;
|
||||
changed_namespace
|
||||
.directories
|
||||
.insert(cwd.join("new-directory"));
|
||||
let mut appeared = definition;
|
||||
appeared.revision = 3;
|
||||
appeared
|
||||
.files
|
||||
.insert(cwd.join("optional.tex"), Arc::from(b"present".as_slice()));
|
||||
rejected(
|
||||
&request
|
||||
.clone()
|
||||
.with_project(ProjectSnapshot::new(changed_namespace).unwrap()),
|
||||
"lookup configuration changed",
|
||||
.with_project(ProjectSnapshot::new(appeared).unwrap()),
|
||||
"lookup namespace changed",
|
||||
);
|
||||
let mut changed_clock = request.clone();
|
||||
changed_clock.time = JobTime::new(2026, 11, 18, 1001).unwrap();
|
||||
@@ -1334,400 +1177,6 @@ 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()));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Capture and verify the native host calls made by an entry prefix.
|
||||
use super::*;
|
||||
use std::{collections::BTreeSet, fmt::Debug};
|
||||
use std::fmt::Debug;
|
||||
#[cfg(test)]
|
||||
use std::{fs, path::Path};
|
||||
#[cfg(test)]
|
||||
@@ -42,10 +42,6 @@ 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
|
||||
}
|
||||
@@ -93,8 +89,6 @@ impl SourceProvider for RecordingHost<'_> {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -274,12 +268,12 @@ fn original_a3_resume_uses_real_host_and_matches_independent_full_jobs() {
|
||||
files: &mut files,
|
||||
calls: Some(Vec::new()),
|
||||
};
|
||||
let (original_execution, captured) = executor.unwrap().run_capturing_entry(
|
||||
source,
|
||||
&mut record,
|
||||
marker_start,
|
||||
|host| host.calls.take().unwrap(),
|
||||
);
|
||||
let (original_execution, captured) =
|
||||
executor
|
||||
.unwrap()
|
||||
.run_capturing_entry(source, &mut record, marker_start, |host| {
|
||||
host.calls.take().unwrap()
|
||||
});
|
||||
let original_execution = original_execution.expect("the original A3 job reaches its end");
|
||||
let (checkpoint, calls) = captured.expect("a physical command boundary before the edited line");
|
||||
assert!(checkpoint.frontier() <= marker_start);
|
||||
|
||||
+14
-24
@@ -31,8 +31,8 @@ pub fn job_time() -> Result<JobTime, String> {
|
||||
let local = chrono::Local::now().fixed_offset();
|
||||
let source_date = std::env::var_os("SOURCE_DATE_EPOCH");
|
||||
let force_utc = std::env::var_os("FORCE_SOURCE_DATE").is_some_and(|value| value == "1");
|
||||
let pdf_date = match source_date.as_deref() {
|
||||
Some(value) => source_date_epoch(value)?,
|
||||
let pdf_date = match source_date {
|
||||
Some(value) => source_date_epoch(&value)?,
|
||||
None => local,
|
||||
};
|
||||
let registers = if force_utc {
|
||||
@@ -40,14 +40,7 @@ pub fn job_time() -> Result<JobTime, String> {
|
||||
} else {
|
||||
local
|
||||
};
|
||||
// A declared build clock also fixes the random stream, so an independent
|
||||
// full build can replay an editor revision under the same inputs.
|
||||
let seed_clock = if source_date.is_some() { pdf_date } else { local };
|
||||
let seed = i64::from(seed_clock.timestamp_subsec_micros()) * 1000
|
||||
+ seed_clock.timestamp().rem_euclid(1_000_000);
|
||||
Ok(pdf_clock(registers)?
|
||||
.with_pdf_date(pdf_clock(pdf_date)?)
|
||||
.with_random_seed(seed as i32))
|
||||
Ok(pdf_clock(registers)?.with_pdf_date(pdf_clock(pdf_date)?))
|
||||
}
|
||||
|
||||
fn source_date_epoch(value: &OsStr) -> Result<DateTime<FixedOffset>, String> {
|
||||
@@ -649,11 +642,6 @@ 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()
|
||||
}
|
||||
@@ -1421,17 +1409,19 @@ impl SourceProvider for Files {
|
||||
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()?);
|
||||
let path = self
|
||||
.runtime_observations
|
||||
.borrow_mut()
|
||||
.environment("TEXRRA_PDF_REGEX_WORKER");
|
||||
if let Some(path) = path {
|
||||
self.regex_worker = Some(crate::native_regex::Worker::start(Path::new(&path))?);
|
||||
}
|
||||
}
|
||||
match &mut self.regex_worker {
|
||||
Some(worker) => worker.request(request, cancellation),
|
||||
None => texrra_tex_core::execution::match_pdf_regex(request),
|
||||
}
|
||||
self.regex_worker
|
||||
.as_mut()
|
||||
.expect("native matcher was started")
|
||||
.request(request, cancellation)
|
||||
}
|
||||
|
||||
fn execution_resource_trace(&self) -> Option<&texrra_tex_core::resources::ResourceTrace> {
|
||||
|
||||
+6
-50
@@ -1,53 +1,12 @@
|
||||
use std::{
|
||||
ffi::OsStr,
|
||||
io::{self, BufRead, BufReader, Write},
|
||||
io::{BufRead, BufReader, Write},
|
||||
path::Path,
|
||||
process::{Child, Command, Stdio},
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
mpsc::{self, Receiver, Sender},
|
||||
},
|
||||
sync::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()?;
|
||||
}
|
||||
}
|
||||
use texrra_tex_core::execution::{Cancellation, RegexOutcome, RegexRequest};
|
||||
|
||||
pub(crate) struct Worker {
|
||||
child: Child,
|
||||
@@ -57,11 +16,8 @@ pub(crate) struct Worker {
|
||||
}
|
||||
|
||||
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)
|
||||
pub(crate) fn start(path: &Path) -> Result<Self, String> {
|
||||
let mut child = Command::new(path)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
|
||||
@@ -158,47 +158,6 @@ 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};
|
||||
|
||||
Reference in new issue
Block a user