Emit native PDF literals at scan and shipout boundaries

This commit is contained in:
gloamxun committed 2026-11-21 02:03:25 +08:00
1 parent 13ab32247d
commit 432c1d2ba7
21 files changed
+264 -61

No files matched your search

@@ -75,11 +75,11 @@ impl NativeShipout {
return; return;
} }
boxes::GeometryItem::PdfGraphics { x, y } => { boxes::GeometryItem::PdfGraphics { x, y } => {
if let Some(&operation) = graphics_steps.next() { if let Some(operation) = graphics_steps.next() {
page.items.push(DisplayItem::PdfGraphics { page.items.push(DisplayItem::PdfGraphics {
x: self.device.horizontal_origin + x, x: self.device.horizontal_origin + x,
y: self.device.vertical_origin + self.box_node.height + y, y: self.device.vertical_origin + self.box_node.height + y,
operation, operation: operation.clone(),
}); });
} else { } else {
missing_graphics_step = true; missing_graphics_step = true;
@@ -614,6 +614,19 @@ impl Printer<'_> {
LinkNode::Destination { .. } => "pdfdest", LinkNode::Destination { .. } => "pdfdest",
}); });
} }
OutputOperation::PdfLiteral { mode, shipout, tokens } => {
use crate::pdf_device::PdfLiteralMode;
self.command("pdfliteral");
if *shipout {
self.literal(" shipout");
}
match mode {
PdfLiteralMode::Origin => {}
PdfLiteralMode::Page => self.literal(" page"),
PdfLiteralMode::Direct => self.literal(" direct"),
}
self.tokens(tokens)?;
}
OutputOperation::PdfSetMatrix(tokens) => { OutputOperation::PdfSetMatrix(tokens) => {
self.command("pdfsetmatrix"); self.command("pdfsetmatrix");
self.tokens(tokens)?; self.tokens(tokens)?;
@@ -1510,7 +1510,10 @@ impl Executor {
self.push(vec![ self.push(vec![
Token::new(TokenKind::Character('{', CatCode::BeginGroup), span).into(), Token::new(TokenKind::Character('{', CatCode::BeginGroup), span).into(),
])?; ])?;
let expanded = self.scan_expanded_group(files)?; let previous_writing = std::mem::replace(&mut self.writing, true);
let expanded = self.scan_expanded_group(files);
self.writing = previous_writing;
let expanded = expanded?;
if !self.required_raw(files)?.end_write { if !self.required_raw(files)?.end_write {
return self.fail("unbalanced expanded native write"); return self.fail("unbalanced expanded native write");
} }
@@ -2790,7 +2793,8 @@ impl Executor {
} }
OutputOperation::PdfSave OutputOperation::PdfSave
| OutputOperation::PdfSetMatrix(_) | OutputOperation::PdfSetMatrix(_)
| OutputOperation::PdfRestore => { | OutputOperation::PdfRestore
| OutputOperation::PdfLiteral { .. } => {
return self.fail("PDF graphics operation requires a positioned shipout"); return self.fail("PDF graphics operation requires a positioned shipout");
} }
OutputOperation::Open { stream, name, from } => { OutputOperation::Open { stream, name, from } => {
@@ -2812,10 +2816,7 @@ impl Executor {
} }
} }
OutputOperation::Write { stream, tokens } => { OutputOperation::Write { stream, tokens } => {
let previous_writing = std::mem::replace(&mut self.writing, true); let expanded = self.fully_expand(tokens.clone(), files)?;
let expanded = self.fully_expand(tokens.clone(), files);
self.writing = previous_writing;
let expanded = expanded?;
let text = self.token_list_text(&expanded); let text = self.token_list_text(&expanded);
let mut text = self.external_print(&text); let mut text = self.external_print(&text);
if *stream == 18 { if *stream == 18 {
@@ -3758,7 +3759,7 @@ impl Executor {
self.output_command(primitive, token.span, files)? self.output_command(primitive, token.span, files)?
} }
Pdfcolorstack => self.scan_pdf_color_action(token.span, files)?, Pdfcolorstack => self.scan_pdf_color_action(token.span, files)?,
Pdfsave | Pdfsetmatrix | Pdfrestore => { Pdfsave | Pdfsetmatrix | Pdfrestore | Pdfliteral => {
self.scan_pdf_graphics(primitive, token.span, files)? self.scan_pdf_graphics(primitive, token.span, files)?
} }
Pdfstartlink | Pdfendlink | Pdfdest => { Pdfstartlink | Pdfendlink | Pdfdest => {
@@ -788,7 +788,7 @@ impl Executor {
| Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time | Scriptscriptfont | Endlinechar | Newlinechar | Escapechar | Globaldefs | Time
| Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage | Day | Month | Year | BeginGroup | EndGroup | Relax | Message | Errmessage
| Endinput | Showbox | Show | Showthe | Discretionary | DiscretionaryHyphen | Endinput | Showbox | Show | Showthe | Discretionary | DiscretionaryHyphen
| Parshape | Partokenname => { | Parshape | Partokenname | Pdfliteral => {
return Ok(false); return Ok(false);
} }
_ => return self.fail(format!("unsupported native math primitive: {p:?}")), _ => return self.fail(format!("unsupported native math primitive: {p:?}")),
@@ -1,5 +1,5 @@
use super::*; use super::*;
use crate::pdf_device::{PdfGraphics, PdfMatrix}; use crate::pdf_device::{PdfGraphics, PdfLiteralMode, PdfMatrix};
impl Executor { impl Executor {
pub(super) fn scan_pdf_graphics( pub(super) fn scan_pdf_graphics(
@@ -14,6 +14,26 @@ impl Executor {
let operation = match command { let operation = match command {
Primitive::Pdfsave => OutputOperation::PdfSave, Primitive::Pdfsave => OutputOperation::PdfSave,
Primitive::Pdfrestore => OutputOperation::PdfRestore, Primitive::Pdfrestore => OutputOperation::PdfRestore,
Primitive::Pdfliteral => {
let shipout = self.keyword("shipout", files)?;
let mode = if self.keyword("direct", files)? {
PdfLiteralMode::Direct
} else if self.keyword("page", files)? {
PdfLiteralMode::Page
} else {
PdfLiteralMode::Origin
};
let tokens = if shipout {
self.scan_group(files)?
} else {
self.scan_expanded_group(files)?
};
OutputOperation::PdfLiteral {
mode,
shipout,
tokens,
}
}
Primitive::Pdfsetmatrix => { Primitive::Pdfsetmatrix => {
let tokens = self.with_scanner(ScannerStatus::Absorbing, |scanner| { let tokens = self.with_scanner(ScannerStatus::Absorbing, |scanner| {
scanner.scan_expanded_group_mode(files, false) scanner.scan_expanded_group_mode(files, false)
@@ -45,6 +65,19 @@ impl Executor {
.map_err(|error| self.error(format!("\\pdfsetmatrix: {error}"), node.span))?; .map_err(|error| self.error(format!("\\pdfsetmatrix: {error}"), node.span))?;
Ok(PdfGraphics::Matrix(matrix)) Ok(PdfGraphics::Matrix(matrix))
} }
OutputOperation::PdfLiteral { mode, shipout, tokens } => {
let expanded;
let tokens = if *shipout {
expanded = self.fully_expand(tokens.clone(), files)?;
&expanded
} else {
tokens
};
Ok(PdfGraphics::Literal {
mode: *mode,
bytes: self.pdf_token_bytes(tokens)?.into(),
})
}
OutputOperation::PdfRestore => { OutputOperation::PdfRestore => {
let (shift, warning) = match saved.pop() { let (shift, warning) = match saved.pop() {
Some((previous, _)) if previous == point => ([0, 0], None), Some((previous, _)) if previous == point => ([0, 0], None),
@@ -231,6 +231,7 @@ impl Executor {
previous.1 || *dx != 0 || *dy != 0); previous.1 || *dx != 0 || *dy != 0);
} }
} }
Some(PdfGraphics::Literal { .. }) => {}
None => failure = Some(self.error("missing PDF transform at link shipout", self.current)), None => failure = Some(self.error("missing PDF transform at link shipout", self.current)),
}, },
BoxPaint::RowStart(row) => { BoxPaint::RowStart(row) => {
@@ -8,8 +8,8 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak}, sync::{Arc, Mutex, OnceLock, Weak},
}; };
const SCHEMA: u32 = 37; const SCHEMA: u32 = 38;
const COMPATIBLE_SCHEMAS: [u32; 9] = [27, 28, 31, 32, 33, 34, 35, 36, SCHEMA]; const COMPATIBLE_SCHEMAS: [u32; 10] = [27, 28, 31, 32, 33, 34, 35, 36, 37, SCHEMA];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION")); const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
#[derive(serde::Serialize, serde::Deserialize)] #[derive(serde::Serialize, serde::Deserialize)]
@@ -246,6 +246,11 @@ pub enum OutputOperation {
image: std::sync::Arc<crate::pdf_image::PdfImageUse>, image: std::sync::Arc<crate::pdf_image::PdfImageUse>,
origin: super::TokenOrigin, origin: super::TokenOrigin,
}, },
PdfLiteral {
mode: crate::pdf_device::PdfLiteralMode,
shipout: bool,
tokens: Vec<Token>,
},
} }
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -265,6 +270,7 @@ impl OutputNode {
OutputOperation::PdfSave OutputOperation::PdfSave
| OutputOperation::PdfSetMatrix(_) | OutputOperation::PdfSetMatrix(_)
| OutputOperation::PdfRestore | OutputOperation::PdfRestore
| OutputOperation::PdfLiteral { .. }
) )
} }
@@ -328,6 +328,7 @@ pub enum Primitive {
Pdfnormaldeviate, Pdfnormaldeviate,
Pdfpageref, Pdfpageref,
Partokenname, Partokenname,
Pdfliteral,
} }
impl Primitive { impl Primitive {
@@ -970,6 +971,7 @@ impl Default for State {
("pdfnormaldeviate", Pdfnormaldeviate), ("pdfnormaldeviate", Pdfnormaldeviate),
("pdfpageref", Pdfpageref), ("pdfpageref", Pdfpageref),
("partokenname", Partokenname), ("partokenname", Partokenname),
("pdfliteral", Pdfliteral),
("pdfcolorstack", Pdfcolorstack), ("pdfcolorstack", Pdfcolorstack),
("pdfsave", Pdfsave), ("pdfsave", Pdfsave),
("pdfstartlink", Pdfstartlink), ("pdfstartlink", Pdfstartlink),
@@ -174,7 +174,9 @@ impl Collector {
} }
} }
pub fn output(&mut self, n: &OutputNode) { pub fn output(&mut self, n: &OutputNode) {
if let OutputOperation::Write { tokens, .. } = &n.operation { if let OutputOperation::Write { tokens, .. }
| OutputOperation::PdfLiteral { tokens, .. } = &n.operation
{
self.usage.token_list_cells += tokens.len(); self.usage.token_list_cells += tokens.len();
} }
} }
+123 -37
View File
@@ -449,7 +449,7 @@ struct NativeTextRun {
text: String, text: String,
} }
impl NativeTextRun { impl NativeTextRun {
fn flush(run: &mut Option<Self>, content: &mut String) { fn flush(run: &mut Option<Self>, content: &mut PageContent) {
if let Some(run) = run.take() { if let Some(run) = run.take() {
content.push_str(&run.text); content.push_str(&run.text);
if run.expansion == 0 { if run.expansion == 0 {
@@ -607,6 +607,48 @@ fn write_type0_font(
type0_id type0_id
} }
/// The PDF stream can contain an 8-bit TeX literal. Keep its bytes alongside
/// the device origin used by subsequent positioned text, rules, and images.
#[derive(Default)]
struct PageContent {
bytes: Vec<u8>,
origin: [i64; 2],
}
impl PageContent {
fn push_str(&mut self, text: &str) {
self.bytes.extend_from_slice(text.as_bytes());
}
fn push(&mut self, byte: u8) {
self.bytes.push(byte);
}
fn move_origin(&mut self, point: [i64; 2], units: crate::render::DisplayUnits, digits: u8) {
let delta = [point[0] - self.origin[0], point[1] - self.origin[1]];
if delta == [0, 0] {
return;
}
let (scale, precision) = match units {
crate::render::DisplayUnits::TeX => (6_578_176, digits + 2),
crate::render::DisplayUnits::PostScript => (65_536, digits),
};
let [(h, h_sp), (v, v_sp)] = delta.map(|value| {
crate::pdf_device::divide_scaled(value, scale, precision)
});
if h == 0 && v == 0 {
return;
}
self.origin[0] += h_sp;
self.origin[1] += v_sp;
self.push_str(&format!(
"1 0 0 1 {} {} cm\n",
crate::pdf_device::print_decimal(h, digits),
crate::pdf_device::print_decimal(v, digits),
));
}
}
fn page_content( fn page_content(
list: &DisplayList, list: &DisplayList,
height: i64, height: i64,
@@ -615,7 +657,7 @@ fn page_content(
cm_codes: &[Option<&BTreeMap<char, u8>>], cm_codes: &[Option<&BTreeMap<char, u8>>],
fallback_ids: &[usize; FACE_COUNT], fallback_ids: &[usize; FACE_COUNT],
origin: PageOrigin, origin: PageOrigin,
) -> String { ) -> Vec<u8> {
let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits); let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits);
let pt = |n: i64| { let pt = |n: i64| {
if list.units == crate::render::DisplayUnits::TeX { if list.units == crate::render::DisplayUnits::TeX {
@@ -624,7 +666,11 @@ fn page_content(
pt(n) pt(n)
} }
}; };
let mut content = String::from("q\n0 0 0 rg\n"); use crate::pdf_device::{PdfGraphics, PdfLiteralMode};
use crate::render::DisplayUnits;
let mut content = PageContent::default();
content.push_str("q\n0 0 0 rg\n");
if list.magnification != 1000 { if list.magnification != 1000 {
let ratio = f64::from(list.magnification) / 1000.0; let ratio = f64::from(list.magnification) / 1000.0;
content.push_str(&format!("{ratio:.3} 0 0 {ratio:.3} 0 0 cm\n")); content.push_str(&format!("{ratio:.3} 0 0 {ratio:.3} 0 0 cm\n"));
@@ -649,7 +695,29 @@ fn page_content(
let mut native_text: Option<NativeTextRun> = None; let mut native_text: Option<NativeTextRun> = None;
let mut tex_text: Option<native_text::NativeText> = None; let mut tex_text: Option<native_text::NativeText> = None;
for item in &list.items { for item in &list.items {
if list.units == crate::render::DisplayUnits::TeX { if let DisplayItem::PdfGraphics {
x,
y,
operation: PdfGraphics::Literal { mode, bytes },
} = item
{
NativeTextRun::flush(&mut native_text, &mut content);
match mode {
PdfLiteralMode::Direct => {
native_text::NativeText::break_string(&mut tex_text, &mut content);
}
PdfLiteralMode::Page | PdfLiteralMode::Origin => {
native_text::NativeText::finish(&mut tex_text, &mut content);
if *mode == PdfLiteralMode::Origin {
content.move_origin([*x, height - *y], list.units, digits);
}
}
}
content.bytes.extend_from_slice(bytes);
content.push(b'\n');
continue;
}
if list.units == DisplayUnits::TeX {
if let DisplayItem::NativeGlyph { if let DisplayItem::NativeGlyph {
x, x,
y, y,
@@ -660,6 +728,9 @@ fn page_content(
} = item } = item
{ {
assert!(paint.is_some(), "native glyph program must be resolved"); assert!(paint.is_some(), "native glyph program must be resolved");
if tex_text.is_none() {
content.move_origin([0, 0], list.units, digits);
}
native_text::NativeText::glyph( native_text::NativeText::glyph(
&mut tex_text, &mut tex_text,
&mut content, &mut content,
@@ -681,7 +752,10 @@ fn page_content(
height: rule_height, height: rule_height,
} = item } = item
{ {
native_text::rule(&mut content, *x, *y, *width, *rule_height, height, digits); let [h, v] = content.origin;
native_text::rule(
&mut content, *x - h, *y + v, *width, *rule_height, height, digits,
);
continue; continue;
} }
} }
@@ -692,6 +766,9 @@ fn page_content(
NativeTextRun::flush(&mut native_text, &mut content); NativeTextRun::flush(&mut native_text, &mut content);
} }
} }
let [h, v] = content.origin;
let px = |x| pt(x - h);
let py = |y| pt(height - y - v);
match item { match item {
DisplayItem::NativeGlyph { DisplayItem::NativeGlyph {
x, x,
@@ -721,13 +798,13 @@ fn page_content(
expansion: font.expansion, expansion: font.expansion,
size: *size, size: *size,
y: *y, y: *y,
cursor: pt(*x).parse().unwrap(), cursor: px(*x).parse().unwrap(),
point_size: point_size * f64::from(1000 + font.expansion) / 1000.0, point_size: point_size * f64::from(1000 + font.expansion) / 1000.0,
text: format!( text: format!(
"BT /N{} {point_size:.4} Tf {spacing}1 0 0 1 {} {} Tm [", "BT /N{} {point_size:.4} Tf {spacing}1 0 0 1 {} {} Tm [",
font.id.index(), font.id.index(),
pt(*x), px(*x),
pt(height - *y) py(*y)
), ),
} }
}); });
@@ -745,8 +822,8 @@ fn page_content(
"BT /M{} {} Tf 1 0 0 1 {} {} Tm <{slot:02X}> Tj ET\n", "BT /M{} {} Tf 1 0 0 1 {} {} Tm <{slot:02X}> Tj ET\n",
face.0, face.0,
pt(*size), pt(*size),
pt(*x), px(*x),
pt(height - *y) py(*y)
)); ));
} }
DisplayItem::Text { DisplayItem::Text {
@@ -785,8 +862,8 @@ fn page_content(
"BT /{} {} Tf 1 0 0 1 {} {} Tm {} Tj ET\n", "BT /{} {} Tf 1 0 0 1 {} {} Tm {} Tj ET\n",
resource, resource,
pt(*size), pt(*size),
pt(*x), px(*x),
pt(height - *y), py(*y),
operand operand
)); ));
} }
@@ -803,8 +880,8 @@ fn page_content(
color[0] as f64 / 255.0, color[0] as f64 / 255.0,
color[1] as f64 / 255.0, color[1] as f64 / 255.0,
color[2] as f64 / 255.0, color[2] as f64 / 255.0,
pt(*x), px(*x),
pt(height - *y - *height), py(*y + *height),
pt(*width), pt(*width),
pt(*height) pt(*height)
)); ));
@@ -817,8 +894,8 @@ fn page_content(
} => { } => {
content.push_str(&format!( content.push_str(&format!(
"{} {} {} {} re f\n", "{} {} {} {} re f\n",
pt(*x), px(*x),
pt(height - *y - *rule_height), py(*y + *rule_height),
pt(*width), pt(*width),
pt(*rule_height) pt(*rule_height)
)); ));
@@ -833,10 +910,10 @@ fn page_content(
content.push_str(&format!( content.push_str(&format!(
"{} w {} {} m {} {} l S\n", "{} w {} {} m {} {} l S\n",
pt(*line_width), pt(*line_width),
pt(*x1), px(*x1),
pt(height - *y1), py(*y1),
pt(*x2), px(*x2),
pt(height - *y2) py(*y2)
)); ));
} }
DisplayItem::Image { DisplayItem::Image {
@@ -851,8 +928,8 @@ fn page_content(
"q {} 0 0 {} {} {} cm /{name} Do Q\n", "q {} 0 0 {} {} {} cm /{name} Do Q\n",
pt(*width), pt(*width),
pt(*image_height), pt(*image_height),
pt(*x), px(*x),
pt(height - *y - *image_height) py(*y + *image_height)
)); ));
} }
} }
@@ -892,8 +969,8 @@ fn page_content(
let name = image.id; let name = image.id;
content.push_str(&format!( content.push_str(&format!(
"q {sx} 0 0 {sy} {} {} cm /PI{name} Do Q\n", "q {sx} 0 0 {sy} {} {} cm /PI{name} Do Q\n",
pt(*x), px(*x),
pt(height - *y - *image_height) py(*y + *image_height)
)); ));
} }
DisplayItem::Frame { DisplayItem::Frame {
@@ -910,8 +987,8 @@ fn page_content(
color[1] as f64 / 255.0, color[1] as f64 / 255.0,
color[2] as f64 / 255.0, color[2] as f64 / 255.0,
*thickness as f64 / 65_536.0, *thickness as f64 / 65_536.0,
pt(*x), px(*x),
pt(list.height - *y - *height), pt(list.height - *y - *height - v),
pt(*width), pt(*width),
pt(*height) pt(*height)
)); ));
@@ -928,33 +1005,42 @@ fn page_content(
} }
DisplayItem::Special(special) => { DisplayItem::Special(special) => {
content.push_str(special); content.push_str(special);
content.push('\n'); content.push(b'\n');
} }
DisplayItem::PdfColor(program) => { DisplayItem::PdfColor(program) => {
content.push_str(program.literal()); content.push_str(program.literal());
content.push('\n'); content.push(b'\n');
} }
DisplayItem::PdfGraphics { x, y, operation } => { DisplayItem::PdfGraphics { x, y, operation } => {
use crate::pdf_device::PdfGraphics; let device_origin = list.units == DisplayUnits::TeX;
if device_origin {
content.move_origin([*x, height - *y], list.units, digits);
}
match operation { match operation {
PdfGraphics::Save => content.push_str("q\n"), PdfGraphics::Save => content.push_str("q\n"),
PdfGraphics::Restore { shift: [dx, dy] } => { PdfGraphics::Restore { shift: [dx, dy] } => {
content.push_str("Q\n"); content.push_str("Q\n");
if *dx != 0 || *dy != 0 { if !device_origin && (*dx != 0 || *dy != 0) {
content.push_str(&format!("1 0 0 1 {} {} cm\n", pt(*dx), pt(-*dy))); content.push_str(&format!(
"1 0 0 1 {} {} cm\n", pt(*dx), pt(-*dy),
));
} }
} }
PdfGraphics::Matrix(matrix) => { PdfGraphics::Matrix(matrix) => {
let point = |coordinate| { let coordinates = if device_origin {
let displayed = pt(coordinate); [0.0, 0.0]
displayed.parse::<f64>().expect("formatted PDF dimension") } else {
[*x, height - *y].map(|coordinate| {
pt(coordinate).parse::<f64>().expect("formatted PDF dimension")
})
}; };
let [a, b, c, d, e, f] = matrix let [a, b, c, d, e, f] = matrix
.about(point(*x), point(height - *y), false) .about(coordinates[0], coordinates[1], false)
.0 .0
.map(crate::pdf_image::real); .map(crate::pdf_image::real);
content.push_str(&format!("{a} {b} {c} {d} {e} {f} cm\n")); content.push_str(&format!("{a} {b} {c} {d} {e} {f} cm\n"));
} }
PdfGraphics::Literal { .. } => unreachable!("literal handled before text"),
} }
} }
} }
@@ -962,7 +1048,7 @@ fn page_content(
NativeTextRun::flush(&mut native_text, &mut content); NativeTextRun::flush(&mut native_text, &mut content);
native_text::NativeText::finish(&mut tex_text, &mut content); native_text::NativeText::finish(&mut tex_text, &mut content);
content.push_str("Q\n"); content.push_str("Q\n");
content content.bytes
} }
/// Document information written into the PDF Info dictionary. /// Document information written into the PDF Info dictionary.
@@ -2181,7 +2267,7 @@ fn write_pdf(
); );
objects.push(objects::stream( objects.push(objects::stream(
"", "",
content.as_bytes(), &content,
list.pdf.as_ref().map_or(0, |p| p.stream_compression), list.pdf.as_ref().map_or(0, |p| p.stream_compression),
)); ));
+1 -1
View File
@@ -79,7 +79,7 @@ mod graphics;
pub(crate) use color::{ColorResult, PdfColorStacks}; pub(crate) use color::{ColorResult, PdfColorStacks};
pub use color::{PdfColorProgram, PdfColorStackAction}; pub use color::{PdfColorProgram, PdfColorStackAction};
pub(crate) use graphics::Affine; pub(crate) use graphics::Affine;
pub use graphics::{PdfGraphics, PdfMatrix}; pub use graphics::{PdfGraphics, PdfLiteralMode, PdfMatrix};
pub mod catalog; pub mod catalog;
pub mod links; pub mod links;
@@ -1,10 +1,20 @@
//! Graphics state produced by the pdfTeX extension whatsits. //! Graphics state produced by the pdfTeX extension whatsits.
use std::sync::Arc;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum PdfLiteralMode {
Origin,
Page,
Direct,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum PdfGraphics { pub enum PdfGraphics {
Save, Save,
Matrix(PdfMatrix), Matrix(PdfMatrix),
Restore { shift: [i64; 2] }, Restore { shift: [i64; 2] },
Literal { mode: PdfLiteralMode, bytes: Arc<[u8]> },
} }
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
+12 -5
View File
@@ -1,4 +1,5 @@
//! Native pdfTeX text cursor, in original TeX sp, before the page matrix. //! Native pdfTeX text cursor, in original TeX sp, before the page matrix.
use super::PageContent;
use crate::{ use crate::{
execution::FontId, execution::FontId,
native_font::NativeFont, native_font::NativeFont,
@@ -16,7 +17,7 @@ pub(super) struct NativeText {
impl NativeText { impl NativeText {
pub(super) fn glyph( pub(super) fn glyph(
text: &mut Option<Self>, text: &mut Option<Self>,
out: &mut String, out: &mut PageContent,
x: i64, x: i64,
y: i64, y: i64,
font: &NativeFont, font: &NativeFont,
@@ -84,7 +85,7 @@ impl NativeText {
shift = 0; shift = 0;
} }
if !state.opened { if !state.opened {
out.push('['); out.push(b'[');
state.opened = true; state.opened = true;
} }
if shift != 0 { if shift != 0 {
@@ -109,13 +110,19 @@ impl NativeText {
crate::pdf_device::magnify(advance, 1000 + font.expansion) crate::pdf_device::magnify(advance, 1000 + font.expansion)
}; };
} }
fn close_string(&mut self, out: &mut String) { fn close_string(&mut self, out: &mut PageContent) {
if self.opened { if self.opened {
out.push_str("] TJ\n"); out.push_str("] TJ\n");
self.opened = false; self.opened = false;
} }
} }
pub(super) fn finish(text: &mut Option<Self>, out: &mut String) { pub(super) fn break_string(text: &mut Option<Self>, out: &mut PageContent) {
if let Some(text) = text {
text.close_string(out);
}
}
pub(super) fn finish(text: &mut Option<Self>, out: &mut PageContent) {
if let Some(mut text) = text.take() { if let Some(mut text) = text.take() {
text.close_string(out); text.close_string(out);
if text.expansion != 0 { if text.expansion != 0 {
@@ -127,7 +134,7 @@ impl NativeText {
} }
pub(super) fn rule( pub(super) fn rule(
out: &mut String, out: &mut PageContent,
x: i64, x: i64,
top: i64, top: i64,
w: i64, w: i64,
+6 -1
View File
@@ -301,7 +301,11 @@ impl DisplayList {
|| self || self
.items .items
.iter() .iter()
.any(|item| matches!(item, DisplayItem::PdfImage { .. })) .any(|item| matches!(item, DisplayItem::PdfImage { .. }
| DisplayItem::PdfGraphics {
operation: crate::pdf_device::PdfGraphics::Literal { .. },
..
}))
} }
/// Compare the inputs consumed by SVG rendering. Font data for glyphs not /// Compare the inputs consumed by SVG rendering. Font data for glyphs not
@@ -653,6 +657,7 @@ impl DisplayList {
DisplayItem::PdfGraphics { x, y, operation } => { DisplayItem::PdfGraphics { x, y, operation } => {
use crate::pdf_device::PdfGraphics; use crate::pdf_device::PdfGraphics;
match operation { match operation {
PdfGraphics::Literal { .. } => unreachable!("PDF literal requires PDF rendering"),
PdfGraphics::Save => { PdfGraphics::Save => {
graphics.push(( graphics.push((
open_transforms, open_transforms,
+1
View File
@@ -299,6 +299,7 @@ impl SourceMap {
for (item_index, item) in page.items.iter().enumerate() { for (item_index, item) in page.items.iter().enumerate() {
if let DisplayItem::PdfGraphics { x, y, operation } = item { if let DisplayItem::PdfGraphics { x, y, operation } = item {
match operation { match operation {
PdfGraphics::Literal { .. } => {}
PdfGraphics::Save => graphics_stack.push(transform), PdfGraphics::Save => graphics_stack.push(transform),
PdfGraphics::Matrix(matrix) => { PdfGraphics::Matrix(matrix) => {
transform = transform =
@@ -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 envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value = let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(payload["schema"], 37); assert_eq!(payload["schema"], 38);
let state = State::initex().with_etex(); let state = State::initex().with_etex();
let loaded = FormatImage::decode(&bytes) let loaded = FormatImage::decode(&bytes)
.unwrap() .unwrap()
@@ -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 envelope: serde_json::Value = serde_json::from_slice(&encoded).unwrap();
let original: serde_json::Value = let original: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(original["schema"], 37); assert_eq!(original["schema"], 38);
for (schema, expected) in [ for (schema, expected) in [
(1, "incompatible native format"), (1, "incompatible native format"),
(2, "incompatible native format"), (2, "incompatible native format"),
@@ -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 envelope: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
let payload: serde_json::Value = let payload: serde_json::Value =
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap(); serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
assert_eq!(payload["schema"], 37); assert_eq!(payload["schema"], 38);
let executor = FormatImage::decode(&bytes) let executor = FormatImage::decode(&bytes)
.unwrap() .unwrap()
.new_job( .new_job(
+27
View File
@@ -1126,6 +1126,33 @@ schema28 更新。schema 1至26和29仍拒绝,27与28缺少必需 Unicode
[原样模板记录](PUBLISHER_TEMPLATE_MATRIX.md#aps-revtex-原样双栏样稿) [原样模板记录](PUBLISHER_TEMPLATE_MATRIX.md#aps-revtex-原样双栏样稿)
[pdfTeX 的重音布局](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L28084-L28143) [pdfTeX 的重音布局](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L28084-L28143)
### 原生 PDF 字面与实际设备原点
`\pdfliteral` 保留实际列表节点和八位 PDF 字节。普通节点在扫描时展开,
`shipout` 节点按实际发页顺序读取当时的宏和状态。默认模式移动 PDF
设备原点,`page` 结束文本对象并保留已有原点,`direct` 只关闭当前
字形串。显式的矩阵和图形状态栈、文字、规则及图片使用同一设备原点。
schema38 保存新增原语和列表节点。包含原始指令的预览页由已发布的原生
PDF 生成 SVG。来源映射使用 TeX 的布局坐标与受跟踪的显式矩阵,任意
原始 PDF 字面引入的坐标变换还需接入来源映射。
[pdfTeX 的字面扫描与出页](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L18575-L18597)
两页冻结用例对照实际内容流、两次出页读取的值、同一 PDF 文本对象内
的 `direct` 指令及144 DPI灰度图,两页图像逐像素相同。独立字节用例
保留了实际 `0xe9`,且丢弃盒中的未定义延迟命令未执行。字面与显式
保存、恢复和矩阵混合的第三页对照也逐像素一致,灰度图 SHA-256
为 `3a81caa031e393fced824bc4aa29a18927cc206c47c956bafe6b15e42a652923`。
编辑第二页的延迟展开值时,检查点复用927步,第一次发页前已构建的
盒保持有效,只更新第二页。PDF、SVG 和来源映射与独立零复用一致。
来源映射仅归一化测试项目根及会话修订号。
`target/p3-pdf-literal-native` 的回执:
- `receipt.json` 为 `786c7e5ee75063120fa887daf8af621c0f1185d2836d9b96f018df002ba43fca`。
- `checkpoint/receipt.json` 为 `4e53adbb0497ab957c4baab4b8fdf1afaec216af12cd033c2f4a89c2583683e2`。
- `graphics-regression.log` 为 `edcd9a0528a7bef897569a6381241c61849067cd58853c29143a9d412db16782`。
### 原生段落结束 token 和分组上下文 ### 原生段落结束 token 和分组上下文
`\partokenname` 全局选择引擎插入的段落 token,并用实际 token 身份检查 `\partokenname` 全局选择引擎插入的段落 token,并用实际 token 身份检查
+9
View File
@@ -459,6 +459,15 @@ alignment command。回溯显示 `\reserved@c` 展开为 `\ifnum 0=` 加
`target/p3-arxiv-title-alignment/original-arxiv/receipt.json` 的 SHA-256 `target/p3-arxiv-title-alignment/original-arxiv/receipt.json` 的 SHA-256
为 `75a1803375d875d710427f6cf8e36a972657728d0890f5ab96026c9c0ac41762`。 为 `75a1803375d875d710427f6cf8e36a972657728d0890f5ab96026c9c0ac41762`。
schema37 优化版使用冻结输入耗时197.5秒生成原样格式,LaTeX 自己把
`\partokencontext` 设为2。原样 arXiv 的六个源输入及原字体映射经再次
核对。作业越过段落原语,在同一公式结束路径读取 `\leftmarginkern`
时停止,该轮未生成 PDF。`target/p3-paragraph-token-native`
保留两份实际回执。
- `format/receipt.json` 为 `cbccbcfa02f2eaeba27662357b093087441fbee999a4c6cebbfbaf31f521691d`。
- `original-arxiv/receipt.json` 为 `441d98f0c53f7a46a2696e3e93d7a7efb7620d1e01dfb8ee28d05aa82c50bd79`。
### Elsevier CAS 双栏首轮输出 ### Elsevier CAS 双栏首轮输出
通用展开调度改动通过了实际图像高度与 LaTeX 浮点公式的差分。 通用展开调度改动通过了实际图像高度与 LaTeX 浮点公式的差分。