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),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1126,6 +1126,28 @@ schema28 更新。schema 1至26和29仍拒绝,27与28缺少必需 Unicode
|
||||
[原样模板记录](PUBLISHER_TEMPLATE_MATRIX.md#aps-revtex-原样双栏样稿)
|
||||
[pdfTeX 的重音布局](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L28084-L28143)
|
||||
|
||||
### PDF 字面中的矩阵与来源映射
|
||||
|
||||
来源映射与 PDF 写入共用设备原点的取整。实际字面中的 `q`、`Q` 和
|
||||
`cm` 和显式矩阵共用 PDF 图形状态,并投影后续有来源的 TeX 绘制范围。
|
||||
原始文字指令改变文本游标时,受影响的字形明确列为未映射,新的原生
|
||||
文本对象重新取得可验证的位置。来源映射当前仍以 TeX 绘制节点为单位,
|
||||
原始字面独立绘制的路径及不透明 PDF 操作未提供绘制来源。
|
||||
[PDF 图形状态说明](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/pdfreference1.7old.pdf)
|
||||
|
||||
实际编辑将第二页矩阵横向比例从2改为4。续编复用890步,只替换第二页;
|
||||
PDF、SVG 和来源映射与独立零复用一致,来源映射仅归一化会话修订号
|
||||
和测试项目根。两页144 DPI灰度图与 pdfTeX 逐像素一致。从 pdfTeX
|
||||
实际内容流独立读取设备变换和矩形,来源边界最大差0.001414 bp。
|
||||
初次夹入段内空白影响锚点,原失败已保存。随后对照固定空白,并使用
|
||||
参考文件中的真实坐标和明示的设备精度核验。独立测试也验证了原始
|
||||
`Td` 修改文本游标后,后续原生文本对象恢复映射。
|
||||
|
||||
`target/p4-pdf-literal-source-projection` 的回执:
|
||||
|
||||
- `checkpoint/receipt.json` 为 `9e78b3088757473b0163a532df405c353185e4c854ef898abf0d3a4a6e3bcbfe`。
|
||||
- `text-regression.log` 为 `26d641aea1b0f23cd33376cec1e33b9b220d84806dc85e2e51c1913ca3b389ee`。
|
||||
|
||||
### 实际横盒的左右边缘 kern
|
||||
|
||||
`\leftmarginkern` 和 `\rightmarginkern` 从指定横盒自己的列表读出带符号
|
||||
|
||||
@@ -468,6 +468,14 @@ schema37 优化版使用冻结输入耗时197.5秒生成原样格式,LaTeX 自
|
||||
- `format/receipt.json` 为 `cbccbcfa02f2eaeba27662357b093087441fbee999a4c6cebbfbaf31f521691d`。
|
||||
- `original-arxiv/receipt.json` 为 `441d98f0c53f7a46a2696e3e93d7a7efb7620d1e01dfb8ee28d05aa82c50bd79`。
|
||||
|
||||
接入实际盒左右边缘后,schema39 优化版在同一组冻结输入上耗时208.9秒
|
||||
生成原样格式。原样 arXiv 六份输入和原字体映射核对通过,首轮生成
|
||||
3页 PDF 1.7。首轮仍有未解析的引用和文献,需要多轮收敛及版面对照。
|
||||
本轮使用与原样 ACM 双栏共用的引擎和格式。
|
||||
|
||||
- `target/p3-margin-kern-query-native/format/receipt.json` 为 `a9484ec1c83d7f1f420028003f5f422a0e45b5bd7c06f62eb4c98252dc3cdf6d`。
|
||||
- `target/p3-margin-kern-query-native/arxiv/receipt.json` 为 `85b2ee927455fae5f72d4aeb8373ffd27d6452d21c8c8fceadbd4a3be3a0f9a2`。
|
||||
|
||||
### Elsevier CAS 双栏首轮输出
|
||||
|
||||
通用展开调度改动通过了实际图像高度与 LaTeX 浮点公式的差分。
|
||||
@@ -565,6 +573,12 @@ PDF。同一作业中,`cmap` 的 `\pdffontattr` 能力检查发出退出告警
|
||||
- `acm-format/receipt.json` 为 `e9580f5a2aa3fa0665d29fbd42650230b7dcf4203daed946a6170767d0b506df`。
|
||||
- `acm-acmtog/receipt.json` 为 `56956692e4524398200b6fbbbd7a0d96d030d5dc3c27975b8dde743473e4ab09`。
|
||||
|
||||
同一 schema39 优化版的原样 ACM 双栏继续通过 `\pdfliteral` 的首次
|
||||
发页入口,在 `acmtog.tex:265` 的标题处理中读取
|
||||
`\tex_pdflastlink:D` 时停止。该轮未生成 PDF,44个原样输入和字体
|
||||
映射已核对。`target/p3-margin-kern-query-native/acm-acmtog/receipt.json`
|
||||
为 `32080c820174aa79f545b79c747324d755cfbe170d54b3823492e7c51ba5b517`。
|
||||
|
||||
最终矩阵 `target/publisher-template-matrix/acm-official/matrix-schema29-utf8/report.json`
|
||||
SHA-256 为 `d914d7c7dfa1ee28dff20e77231fef35e390041cde6180bcc361de83288ec9e1`。其 `preparation/acmart` 保存
|
||||
DocStrip 记录。同目录的前序依赖失败、补充包指纹和原样源均保留。用现有
|
||||
|
||||
@@ -199,6 +199,32 @@ fn replacing_a_type1_program_at_the_same_path_updates_native_pdf_and_preview() {
|
||||
fs::remove_dir_all(p).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_text_position_is_unmapped_until_the_next_native_text_object() {
|
||||
use texrra_tex_core::source_map::{PaintKind, UnmappedReason};
|
||||
|
||||
let path = directory("literal-text-source-map");
|
||||
write(
|
||||
&path,
|
||||
r"\pdfoutput=1 \pdfpagewidth=90pt \pdfpageheight=70pt
|
||||
\shipout\hbox{A\pdfliteral direct{4 0 Td}B\pdfliteral page{}C}\end",
|
||||
);
|
||||
let compiled = NativeCompiler::default().compile(request(&path)).unwrap();
|
||||
let page = &compiled.source_map.pages[0];
|
||||
let glyphs: Vec<_> = page
|
||||
.entries
|
||||
.iter()
|
||||
.filter_map(|entry| match entry.kind {
|
||||
PaintKind::Glyph { slot, .. } => Some(slot),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(glyphs, b"AC");
|
||||
assert_eq!(page.unmapped.len(), 1);
|
||||
assert_eq!(page.unmapped[0].reason, UnmappedReason::UnsupportedPrimitive);
|
||||
fs::remove_dir_all(path).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