Track PDF literal transforms in native source maps

This commit is contained in:
gloamxun committed 2026-11-21 02:23:12 +08:00
1 parent d46d6d79a8
commit 7f74251c8a
9 files changed
+303 -22

No files matched your search

@@ -0,0 +1,186 @@
//! Project TeX paint through the PDF device and any literal graphics state.
use crate::{
pdf_device::{
Affine, DeviceOrigin, PdfGraphics, PdfLiteralMode, page_resources::check_pdf_nesting,
},
render::{DisplayItem, DisplayList, DisplayUnits},
};
use lopdf::{Object, content::Content};
#[derive(Clone, Copy)]
struct GraphicsState {
matrix: Affine,
modified_text_parameters: bool,
}
pub(super) struct PdfProjection {
origin: DeviceOrigin,
graphics: Option<GraphicsState>,
stack: Vec<GraphicsState>,
units: DisplayUnits,
height: i64,
digits: u8,
units_per_bp: f64,
text_active: bool,
modified_text_position: bool,
}
impl PdfProjection {
pub(super) fn for_page(page: &DisplayList) -> Option<Self> {
if !page.items.iter().any(|item| {
matches!(
item,
DisplayItem::PdfGraphics {
operation: PdfGraphics::Literal { .. },
..
}
)
}) {
return None;
}
let graphics = GraphicsState {
matrix: Affine::IDENTITY,
modified_text_parameters: false,
};
Some(Self {
origin: DeviceOrigin::default(),
graphics: Some(graphics),
stack: vec![graphics], // The page writer begins with q.
units: page.units,
height: page.height,
digits: page.pdf.as_ref().map_or(3, |page| page.file.decimal_digits),
units_per_bp: 1.0 / page.units.bp(1),
text_active: false,
modified_text_position: false,
})
}
fn concatenate(&mut self, matrix: Affine) {
if let Some(graphics) = &mut self.graphics {
graphics.matrix = graphics.matrix.concatenate(matrix);
}
}
fn move_origin(&mut self, point: [i64; 2]) {
if let Some(translation) = self.origin.move_to(point, self.units, self.digits) {
let scale = self.units_per_bp / 10f64.powi(i32::from(self.digits));
let [x, y] = translation.map(|value| value as f64 * scale);
self.concatenate(Affine::translation(x, y));
}
}
fn save(&mut self) {
if let Some(graphics) = self.graphics {
self.stack.push(graphics);
}
}
fn restore(&mut self) {
self.graphics = self.stack.pop();
}
fn apply_literal(&mut self, bytes: &[u8]) -> Option<()> {
check_pdf_nesting(bytes).ok()?;
// The content parser accepts a valid prefix. Require the final marker
// so an unfinished or opaque byte sequence cannot silently change CTM.
let mut input = bytes.to_vec();
input.extend_from_slice(b"\nSourceMapEnd\n");
let mut program = Content::decode(&input).ok()?;
let marker = program.operations.pop()?;
if marker.operator != "SourceMapEnd" || !marker.operands.is_empty() {
return None;
}
for operation in program.operations {
match operation.operator.as_str() {
"q" => self.save(),
"Q" => self.restore(),
"cm" => {
let coefficients: &[Object; 6] =
operation.operands.as_slice().try_into().ok()?;
let mut matrix = [0.0; 6];
for (value, coefficient) in matrix.iter_mut().zip(coefficients) {
*value = match coefficient {
Object::Integer(n) => *n as f64,
Object::Real(n) if n.is_finite() => *n,
_ => return None,
};
}
matrix[4] *= self.units_per_bp;
matrix[5] *= self.units_per_bp;
self.concatenate(Affine(matrix));
}
"BT" | "ET" | "Tm" | "Td" | "TD" | "T*" | "Tj" | "TJ" | "'" | "\"" => {
self.modified_text_position |= self.text_active;
}
"Tw" | "Tc" | "Tz" | "Ts" | "Tf" | "TL" => {
if let Some(graphics) = &mut self.graphics {
graphics.modified_text_parameters = true;
}
}
"BI" | "ID" | "EI" => return None,
_ => {}
}
}
Some(())
}
pub(super) fn observe(&mut self, item: &DisplayItem) -> Option<Affine> {
match item {
DisplayItem::PdfGraphics { x, y, operation } => {
let [x, y] = [*x, self.height - *y];
if let PdfGraphics::Literal { mode, bytes } = operation {
if *mode != PdfLiteralMode::Direct {
self.text_active = false;
}
if *mode == PdfLiteralMode::Origin {
self.move_origin([x, y]);
}
if self.apply_literal(bytes).is_none() {
self.graphics = None;
self.stack.clear();
}
return None;
}
self.text_active = false;
let native = self.units == DisplayUnits::TeX;
if native {
self.move_origin([x, y]);
}
match operation {
PdfGraphics::Save => self.save(),
PdfGraphics::Restore { shift: [dx, dy] } => {
self.restore();
if !native {
self.concatenate(Affine::translation(*dx as f64, -*dy as f64));
}
}
PdfGraphics::Matrix(matrix) => {
let [x, y] = if native { [0, 0] } else { [x, y] };
self.concatenate(matrix.about(x as f64, y as f64, false));
}
PdfGraphics::Literal { .. } => unreachable!("handled before typed graphics"),
}
return None;
}
DisplayItem::NativeGlyph { .. } if self.units == DisplayUnits::TeX => {
if !self.text_active {
self.move_origin([0, 0]);
self.text_active = true;
self.modified_text_position = false;
}
if self.modified_text_position || self.graphics?.modified_text_parameters {
return None;
}
}
_ => self.text_active = false,
}
let [x, y] = self.origin.position().map(|n| n as f64);
let flip = Affine([1.0, 0.0, 0.0, -1.0, 0.0, self.height as f64]);
Some(
flip.concatenate(self.graphics?.matrix)
.concatenate(Affine::translation(-x, -y))
.concatenate(flip),
)
}
}