Track PDF literal transforms in native source maps
This commit is contained in:
1 parent
d46d6d79a8
commit
7f74251c8a
9 files changed
+303
-22
No files matched your search
@@ -612,7 +612,7 @@ fn write_type0_font(
|
||||
#[derive(Default)]
|
||||
struct PageContent {
|
||||
bytes: Vec<u8>,
|
||||
origin: [i64; 2],
|
||||
origin: crate::pdf_device::DeviceOrigin,
|
||||
}
|
||||
|
||||
impl PageContent {
|
||||
@@ -625,22 +625,9 @@ impl PageContent {
|
||||
}
|
||||
|
||||
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] {
|
||||
let Some([h, v]) = self.origin.move_to(point, units, digits) else {
|
||||
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),
|
||||
@@ -752,7 +739,7 @@ fn page_content(
|
||||
height: rule_height,
|
||||
} = item
|
||||
{
|
||||
let [h, v] = content.origin;
|
||||
let [h, v] = content.origin.position();
|
||||
native_text::rule(
|
||||
&mut content, *x - h, *y + v, *width, *rule_height, height, digits,
|
||||
);
|
||||
@@ -766,7 +753,7 @@ fn page_content(
|
||||
NativeTextRun::flush(&mut native_text, &mut content);
|
||||
}
|
||||
}
|
||||
let [h, v] = content.origin;
|
||||
let [h, v] = content.origin.position();
|
||||
let px = |x| pt(x - h);
|
||||
let py = |y| pt(height - y - v);
|
||||
match item {
|
||||
|
||||
@@ -78,7 +78,7 @@ mod color;
|
||||
mod graphics;
|
||||
pub(crate) use color::{ColorResult, PdfColorStacks};
|
||||
pub use color::{PdfColorProgram, PdfColorStackAction};
|
||||
pub(crate) use graphics::Affine;
|
||||
pub(crate) use graphics::{Affine, DeviceOrigin};
|
||||
pub use graphics::{PdfGraphics, PdfLiteralMode, PdfMatrix};
|
||||
pub mod catalog;
|
||||
pub mod links;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Graphics state produced by the pdfTeX extension whatsits.
|
||||
|
||||
use crate::render::DisplayUnits;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
@@ -48,6 +49,41 @@ impl PdfMatrix {
|
||||
}
|
||||
}
|
||||
|
||||
/// Native device origin in logical scaled units, with the same rounding as
|
||||
/// the emitted PDF translation. The returned operands have \`digits\` decimals.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct DeviceOrigin([i64; 2]);
|
||||
|
||||
impl DeviceOrigin {
|
||||
pub(crate) fn position(&self) -> [i64; 2] {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub(crate) fn move_to(
|
||||
&mut self,
|
||||
point: [i64; 2],
|
||||
units: DisplayUnits,
|
||||
digits: u8,
|
||||
) -> Option<[i64; 2]> {
|
||||
let delta = [point[0] - self.0[0], point[1] - self.0[1]];
|
||||
if delta == [0, 0] {
|
||||
return None;
|
||||
}
|
||||
let (scale, precision) = match units {
|
||||
DisplayUnits::TeX => (6_578_176, digits + 2),
|
||||
DisplayUnits::PostScript => (65_536, digits),
|
||||
};
|
||||
let [(h, h_sp), (v, v_sp)] =
|
||||
delta.map(|value| super::divide_scaled(value, scale, precision));
|
||||
if h == 0 && v == 0 {
|
||||
return None;
|
||||
}
|
||||
self.0[0] += h_sp;
|
||||
self.0[1] += v_sp;
|
||||
Some([h, v])
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct Affine(pub [f64; 6]);
|
||||
|
||||
|
||||
@@ -174,7 +174,7 @@ impl PdfObjects {
|
||||
}
|
||||
}
|
||||
|
||||
fn check_pdf_nesting(bytes: &[u8]) -> Result<(), String> {
|
||||
pub(crate) fn check_pdf_nesting(bytes: &[u8]) -> Result<(), String> {
|
||||
let mut input = bytes.iter().copied().peekable();
|
||||
let mut depth = 0usize;
|
||||
let mut literal = 0usize;
|
||||
|
||||
@@ -11,6 +11,8 @@ use crate::{
|
||||
render::{DisplayItem, DisplayList, DisplayUnits},
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
mod pdf_projection;
|
||||
use pdf_projection::PdfProjection;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SourceKind {
|
||||
@@ -296,8 +298,15 @@ impl SourceMap {
|
||||
};
|
||||
let mut transform = Affine::IDENTITY;
|
||||
let mut graphics_stack = Vec::new();
|
||||
let mut pdf_projection = PdfProjection::for_page(page);
|
||||
for (item_index, item) in page.items.iter().enumerate() {
|
||||
let placement = pdf_projection
|
||||
.as_mut()
|
||||
.map_or(Some(transform), |projection| projection.observe(item));
|
||||
if let DisplayItem::PdfGraphics { x, y, operation } = item {
|
||||
if pdf_projection.is_some() {
|
||||
continue;
|
||||
}
|
||||
match operation {
|
||||
PdfGraphics::Literal { .. } => {}
|
||||
PdfGraphics::Save => graphics_stack.push(transform),
|
||||
@@ -403,16 +412,17 @@ impl SourceMap {
|
||||
page.sources
|
||||
.get(&item_index)
|
||||
.filter(|s| !s.tokens.is_empty()),
|
||||
placement,
|
||||
) {
|
||||
(Some((kind, bounds)), Some(source)) => map.entries.push(MappedPaint {
|
||||
(Some((kind, bounds)), Some(source), Some(transform)) => map.entries.push(MappedPaint {
|
||||
item_index,
|
||||
kind,
|
||||
bounds: bounds.transformed(transform)?,
|
||||
source: source.clone(),
|
||||
}),
|
||||
(geometry, _) => map.unmapped.push(UnmappedPaint {
|
||||
(geometry, _, placement) => map.unmapped.push(UnmappedPaint {
|
||||
item_index,
|
||||
reason: if geometry.is_some() {
|
||||
reason: if geometry.is_some() && placement.is_some() {
|
||||
UnmappedReason::MissingProvenance
|
||||
} else {
|
||||
UnmappedReason::UnsupportedPrimitive
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user