Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
60d7411dfe | ||
|
|
7f74251c8a |
No files matched your search
@@ -2146,6 +2146,14 @@ impl Executor {
|
||||
self.reads.insert(Dependency::PdfRandomState);
|
||||
Ok(self.state.random_seed())
|
||||
}
|
||||
Meaning::Primitive(Primitive::Pdflastlink) => {
|
||||
self.reads.insert(Dependency::PdfObjects);
|
||||
Ok(self
|
||||
.state
|
||||
.pdf_objects
|
||||
.as_deref()
|
||||
.map_or(0, |objects| objects.last_link()))
|
||||
}
|
||||
Meaning::Primitive(Primitive::Pdflastobj) => {
|
||||
self.reads.insert(Dependency::PdfObjects);
|
||||
Ok(self.state.pdf_objects.as_deref().map_or(0, |objects| objects.last()))
|
||||
|
||||
@@ -76,6 +76,7 @@ impl ActiveLink {
|
||||
transformed: transform.1,
|
||||
});
|
||||
output.annotations.push(LinkAnnotation {
|
||||
object_number: None,
|
||||
rect: link_rect(rect, transform.0, margin),
|
||||
attributes: self.attributes.clone(),
|
||||
action: self.action.clone(),
|
||||
@@ -119,6 +120,13 @@ impl Executor {
|
||||
}
|
||||
let operation = match command {
|
||||
Primitive::Pdfstartlink => {
|
||||
self.reads.insert(Dependency::PdfObjects);
|
||||
let object_number = self
|
||||
.state
|
||||
.pdf_objects
|
||||
.get_or_insert_with(Default::default)
|
||||
.reserve_link(self.limits.tokens)
|
||||
.map_err(|error| self.error(error, self.current))?;
|
||||
let (mut width, mut height, mut depth) = (None, None, None);
|
||||
loop {
|
||||
let target = if self.keyword("width", files)? {
|
||||
@@ -144,7 +152,13 @@ impl Executor {
|
||||
} else {
|
||||
return self.fail("expected a user or named goto PDF link action");
|
||||
};
|
||||
self.state
|
||||
.pdf_objects
|
||||
.as_mut()
|
||||
.expect("allocated PDF link object")
|
||||
.record_last_link(object_number);
|
||||
LinkNode::Start(LinkStart {
|
||||
object_number: Some(object_number),
|
||||
width,
|
||||
height,
|
||||
depth,
|
||||
@@ -258,6 +272,9 @@ impl Executor {
|
||||
let mut start = ActiveLink { layout: layout.clone(), attributes,
|
||||
action, level: row.level, segment: None };
|
||||
start.start_segment(&mut output, row, [x, y], transform, margin);
|
||||
// The scan-time object number belongs only to the
|
||||
// initial annotation, never to a continuation row.
|
||||
output.annotations.last_mut().unwrap().object_number = layout.object_number;
|
||||
active.push(start);
|
||||
}
|
||||
LinkNode::End => {
|
||||
|
||||
@@ -209,6 +209,7 @@ impl Executor {
|
||||
| Primitive::Inputlineno
|
||||
| Primitive::Pdfrandomseed
|
||||
| Primitive::Pdflastobj
|
||||
| Primitive::Pdflastlink
|
||||
| Primitive::Pdflastximage
|
||||
| Primitive::Pdflastximagepages
|
||||
| Primitive::Pdflastximagecolordepth
|
||||
|
||||
@@ -8,8 +8,8 @@ use std::{
|
||||
sync::{Arc, Mutex, OnceLock, Weak},
|
||||
};
|
||||
|
||||
const SCHEMA: u32 = 39;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 11] = [27, 28, 31, 32, 33, 34, 35, 36, 37, 38, SCHEMA];
|
||||
const SCHEMA: u32 = 40;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 12] = [27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, SCHEMA];
|
||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
|
||||
@@ -331,6 +331,7 @@ pub enum Primitive {
|
||||
Pdfliteral,
|
||||
Leftmarginkern,
|
||||
Rightmarginkern,
|
||||
Pdflastlink,
|
||||
}
|
||||
|
||||
impl Primitive {
|
||||
@@ -969,6 +970,7 @@ impl Default for State {
|
||||
("pdfobj", Pdfobj),
|
||||
("pdfrefobj", Pdfrefobj),
|
||||
("pdflastobj", Pdflastobj),
|
||||
("pdflastlink", Pdflastlink),
|
||||
("pdfrandomseed", Pdfrandomseed),
|
||||
("pdfsetrandomseed", Pdfsetrandomseed),
|
||||
("pdfuniformdeviate", Pdfuniformdeviate),
|
||||
@@ -1396,7 +1398,13 @@ impl State {
|
||||
self.output_mode_set = None;
|
||||
self.pdf_file_options = None;
|
||||
self.pdf_catalog = None;
|
||||
self.pdf_objects = None;
|
||||
if !self
|
||||
.pdf_objects
|
||||
.as_deref_mut()
|
||||
.is_some_and(crate::pdf_device::page_resources::PdfObjects::retain_format_links)
|
||||
{
|
||||
self.pdf_objects = None;
|
||||
}
|
||||
self.pdf_info.clear();
|
||||
self
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
@@ -2220,15 +2207,28 @@ fn write_pdf(
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let annotation_base = image_base + used.len();
|
||||
let annotation_count = links.len() + list.pdf_links.annotations.len();
|
||||
let annots = if annotation_count == 0 {
|
||||
let native_annotation_base = annotation_base + links.len();
|
||||
let mut next_annotation = native_annotation_base;
|
||||
let native_annotation_ids: Vec<_> = list.pdf_links.annotations.iter().enumerate()
|
||||
.map(|(index, _)| {
|
||||
remapped.as_ref()
|
||||
.and_then(|resources| resources.link_objects.get(&(page_index, index)).copied())
|
||||
.unwrap_or_else(|| {
|
||||
let id = next_annotation;
|
||||
next_annotation += 1;
|
||||
id
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let annotation_refs = (annotation_base..native_annotation_base)
|
||||
.chain(native_annotation_ids.iter().copied())
|
||||
.map(|id| format!("{id} 0 R"))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let annots = if annotation_refs.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
let refs = (0..annotation_count)
|
||||
.map(|index| format!("{} 0 R", annotation_base + index))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
format!(" /Annots [{refs}]")
|
||||
format!(" /Annots [{annotation_refs}]")
|
||||
};
|
||||
page_ids.push(page_id);
|
||||
kids.push(format!("{page_id} 0 R"));
|
||||
@@ -2308,7 +2308,7 @@ fn write_pdf(
|
||||
.into_bytes(),
|
||||
);
|
||||
}
|
||||
for annotation in &list.pdf_links.annotations {
|
||||
for (index, (annotation, id)) in list.pdf_links.annotations.iter().zip(native_annotation_ids).enumerate() {
|
||||
use crate::pdf_device::links::AnnotationAction;
|
||||
let [left, top, right, bottom] = annotation.rect;
|
||||
let coordinates = [left, height - bottom, right, height - top].map(physical);
|
||||
@@ -2317,8 +2317,25 @@ fn write_pdf(
|
||||
AnnotationAction::GotoName(name) =>
|
||||
format!("/Subtype /Link /A << /S /GoTo /D {} >>", pdf_text(name)),
|
||||
};
|
||||
objects.push(format!("<< /Type /Annot {} /Rect [{}] {} >>",
|
||||
annotation.attributes, coordinates.join(" "), action).into_bytes());
|
||||
let entries = remapped.as_ref().and_then(|resources|
|
||||
resources.annotations[page_index][index].as_deref());
|
||||
let body = if let Some(entries) = entries {
|
||||
let mut body = format!("<< /Type /Annot /Rect [{}] ", coordinates.join(" ")).into_bytes();
|
||||
body.extend_from_slice(entries);
|
||||
if matches!(annotation.action, AnnotationAction::GotoName(_)) {
|
||||
body.extend_from_slice(action.as_bytes());
|
||||
}
|
||||
body.extend_from_slice(b" >>");
|
||||
body
|
||||
} else {
|
||||
format!("<< /Type /Annot {} /Rect [{}] {} >>",
|
||||
annotation.attributes, coordinates.join(" "), action).into_bytes()
|
||||
};
|
||||
if id == objects.len() + 1 {
|
||||
objects.push(body);
|
||||
} else {
|
||||
objects[id - 1] = body;
|
||||
}
|
||||
}
|
||||
for destination in &list.pdf_links.destinations {
|
||||
use crate::pdf_device::links::DestinationView;
|
||||
|
||||
@@ -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]);
|
||||
|
||||
|
||||
@@ -9,6 +9,8 @@ pub enum LinkAction {
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct LinkStart {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub object_number: Option<u32>,
|
||||
pub width: Option<i32>,
|
||||
pub height: Option<i32>,
|
||||
pub depth: Option<i32>,
|
||||
@@ -53,6 +55,8 @@ pub enum AnnotationAction {
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct LinkAnnotation {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub object_number: Option<u32>,
|
||||
/// Left, top, right and bottom in TeX sp, with y measured down the page.
|
||||
pub rect: [i64; 4],
|
||||
pub attributes: String,
|
||||
|
||||
@@ -12,6 +12,8 @@ use std::{
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub(crate) enum ObjectBody {
|
||||
Page,
|
||||
Link,
|
||||
FormatLink,
|
||||
Direct(Vec<u8>),
|
||||
Stream {
|
||||
attributes: Vec<u8>,
|
||||
@@ -27,7 +29,7 @@ pub(crate) enum ObjectBody {
|
||||
impl ObjectBody {
|
||||
fn len(&self) -> usize {
|
||||
match self {
|
||||
Self::Page => 0,
|
||||
Self::Page | Self::Link | Self::FormatLink => 0,
|
||||
Self::Direct(bytes) => bytes.len(),
|
||||
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
|
||||
Self::File {
|
||||
@@ -44,7 +46,7 @@ impl ObjectBody {
|
||||
|
||||
fn parse(&self) -> Result<Object, String> {
|
||||
match self {
|
||||
Self::Page => Err("expected a generic native PDF object".into()),
|
||||
Self::Page | Self::Link | Self::FormatLink => 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 } => {
|
||||
@@ -64,6 +66,8 @@ pub struct PdfObjects {
|
||||
values: Vec<Option<Arc<ObjectBody>>>,
|
||||
written: BTreeSet<u32>,
|
||||
last: i32,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
last_link: Option<u32>,
|
||||
bytes: usize,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
page_references: BTreeMap<u32, u32>,
|
||||
@@ -80,7 +84,9 @@ impl PdfObjects {
|
||||
|
||||
pub(crate) fn contains(&self, number: u32) -> bool {
|
||||
self.entry(number)
|
||||
.is_some_and(|entry| !matches!(entry.as_deref(), Some(ObjectBody::Page)))
|
||||
.is_some_and(|entry| {
|
||||
!matches!(entry.as_deref(), Some(ObjectBody::Page | ObjectBody::Link | ObjectBody::FormatLink))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn is_reserved(&self, number: u32) -> bool {
|
||||
@@ -101,6 +107,47 @@ impl PdfObjects {
|
||||
Ok(number)
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_link(&mut self, limit: usize) -> Result<u32, String> {
|
||||
self.allocate(Some(Arc::new(ObjectBody::Link)), limit)
|
||||
}
|
||||
|
||||
pub(crate) fn record_last_link(&mut self, number: u32) {
|
||||
self.last_link = Some(number);
|
||||
}
|
||||
|
||||
pub(crate) fn last_link(&self) -> i32 {
|
||||
self.last_link.unwrap_or_default() as i32
|
||||
}
|
||||
|
||||
pub(crate) fn retain_format_links(&mut self) -> bool {
|
||||
let Some(last_link) = self
|
||||
.values
|
||||
.iter()
|
||||
.rposition(|entry| matches!(entry.as_deref(), Some(ObjectBody::Link)))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
// The reservation survives the format, but pdfTeX assigns a new
|
||||
// object to the annotation when it ships the restored whatsit.
|
||||
self.values.truncate(last_link + 1);
|
||||
for entry in &mut self.values {
|
||||
*entry = matches!(entry.as_deref(), Some(ObjectBody::Link))
|
||||
.then(|| Arc::new(ObjectBody::FormatLink));
|
||||
}
|
||||
self.written.clear();
|
||||
self.last = 0;
|
||||
self.last_link = None;
|
||||
self.bytes = 0;
|
||||
self.page_references.clear();
|
||||
true
|
||||
}
|
||||
|
||||
fn is_link(&self, number: u32) -> bool {
|
||||
self.entry(number).is_some_and(|entry| {
|
||||
matches!(entry.as_deref(), Some(ObjectBody::Link | ObjectBody::FormatLink))
|
||||
})
|
||||
}
|
||||
|
||||
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);
|
||||
@@ -174,7 +221,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;
|
||||
@@ -356,7 +403,9 @@ impl PageResources {
|
||||
pub(crate) struct ResourceOutput {
|
||||
values: BTreeMap<u32, Object>,
|
||||
page_references: BTreeMap<u32, u32>,
|
||||
link_references: BTreeMap<u32, Option<(usize, usize)>>,
|
||||
page_entries: Vec<Dictionary>,
|
||||
annotation_entries: Vec<Vec<Option<Dictionary>>>,
|
||||
catalog: Option<Dictionary>,
|
||||
info: Option<Dictionary>,
|
||||
}
|
||||
@@ -364,6 +413,8 @@ pub(crate) struct ResourceOutput {
|
||||
pub(crate) struct RemappedResources {
|
||||
pub pages: Vec<Vec<u8>>,
|
||||
pub page_objects: BTreeMap<usize, usize>,
|
||||
pub link_objects: BTreeMap<(usize, usize), usize>,
|
||||
pub annotations: Vec<Vec<Option<Vec<u8>>>>,
|
||||
pub catalog: Option<Vec<u8>>,
|
||||
pub info: Option<Vec<u8>>,
|
||||
}
|
||||
@@ -398,8 +449,54 @@ impl ResourceOutput {
|
||||
}
|
||||
}
|
||||
let page_objects: BTreeSet<_> = objects.page_references.values().copied().collect();
|
||||
let annotation_entries = pages
|
||||
.iter()
|
||||
.map(|page| {
|
||||
page.pdf_links
|
||||
.annotations
|
||||
.iter()
|
||||
.map(|annotation| {
|
||||
use crate::pdf_device::links::AnnotationAction;
|
||||
let mut entries = parse_entries(annotation.attributes.as_bytes())?;
|
||||
if let AnnotationAction::User(action) = &annotation.action {
|
||||
for (key, value) in parse_entries(action.as_bytes())?.iter() {
|
||||
entries.set(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
let mut related = BTreeSet::new();
|
||||
for (_, value) in entries.iter() {
|
||||
references(value, &mut related)?;
|
||||
}
|
||||
if related.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
pending.extend(related);
|
||||
Ok(Some(entries))
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
let mut link_references = BTreeMap::new();
|
||||
for (page_index, page) in pages.iter().enumerate() {
|
||||
for (annotation_index, annotation) in page.pdf_links.annotations.iter().enumerate() {
|
||||
if let Some(number) = annotation.object_number
|
||||
&& matches!(
|
||||
objects.entry(number).and_then(Option::as_deref),
|
||||
Some(ObjectBody::Link)
|
||||
)
|
||||
{
|
||||
link_references
|
||||
.entry(number)
|
||||
.or_insert(Some((page_index, annotation_index)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut values = BTreeMap::new();
|
||||
while let Some(number) = pending.pop_first() {
|
||||
if objects.is_link(number) {
|
||||
link_references.entry(number).or_insert(None);
|
||||
continue;
|
||||
}
|
||||
if values.contains_key(&number) || page_objects.contains(&number) {
|
||||
continue;
|
||||
}
|
||||
@@ -410,7 +507,9 @@ impl ResourceOutput {
|
||||
Ok(Self {
|
||||
values,
|
||||
page_references: objects.page_references.clone(),
|
||||
link_references,
|
||||
page_entries,
|
||||
annotation_entries,
|
||||
catalog,
|
||||
info,
|
||||
})
|
||||
@@ -435,6 +534,17 @@ impl ResourceOutput {
|
||||
}
|
||||
ids.insert(number, id as u32);
|
||||
}
|
||||
let mut link_objects = BTreeMap::new();
|
||||
for (number, annotation) in self.link_references {
|
||||
// Repeated copies get independent annotations. Only the first
|
||||
// shipped occurrence fills the object reserved for the TeX link.
|
||||
output.push(Vec::new());
|
||||
let id = output.len();
|
||||
if let Some(annotation) = annotation {
|
||||
link_objects.insert(annotation, id);
|
||||
}
|
||||
ids.insert(number, id as u32);
|
||||
}
|
||||
ids.extend(
|
||||
self.values
|
||||
.keys()
|
||||
@@ -458,6 +568,10 @@ impl ResourceOutput {
|
||||
RemappedResources {
|
||||
pages: self.page_entries.into_iter().map(&encode).collect(),
|
||||
page_objects,
|
||||
link_objects,
|
||||
annotations: self.annotation_entries.into_iter()
|
||||
.map(|row| row.into_iter().map(|dict| dict.map(&encode)).collect())
|
||||
.collect(),
|
||||
catalog: self.catalog.map(&encode),
|
||||
info: self.info.map(encode),
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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"], 39);
|
||||
assert_eq!(payload["schema"], 40);
|
||||
let state = State::initex().with_etex();
|
||||
let loaded = FormatImage::decode(&bytes)
|
||||
.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 original: serde_json::Value =
|
||||
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(original["schema"], 39);
|
||||
assert_eq!(original["schema"], 40);
|
||||
for (schema, expected) in [
|
||||
(1, "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 payload: serde_json::Value =
|
||||
serde_json::from_str(envelope["payload"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(payload["schema"], 39);
|
||||
assert_eq!(payload["schema"], 40);
|
||||
let executor = FormatImage::decode(&bytes)
|
||||
.unwrap()
|
||||
.new_job(
|
||||
|
||||
@@ -1126,6 +1126,54 @@ 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 引用
|
||||
|
||||
`\pdflastlink` 从作业共有的 PDF 对象表读取最近一次成功扫描的链接编号。
|
||||
链接扫描保留真实编号,实际发页建立注释。目录、用户对象或注释字段中的
|
||||
间接引用都重映射到实际对象。复制同一个盒时,首个注释取得该次扫描的
|
||||
引用身份,后续副本和跨行注释拥有独立的 PDF 对象。未发页但被引用的
|
||||
链接留下空闲交叉引用项。
|
||||
[pdfTeX 对链接对象的扫描](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L34919-L34936)
|
||||
[pdfTeX 对复制和跨行注释的处理](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/pdftexdir/pdftex.web#L36522-L36534)
|
||||
|
||||
schema40 保存格式中的链接保留项,并将最近链接恢复为0。实际重载后,
|
||||
来自格式的旧编号保持空闲,原盒出页得到新注释编号,与 pdfTeX 的观察
|
||||
一致。新链接也得到独立注释。普通文件与格式重载文件共四页144 DPI
|
||||
灰度图逐像素一致。检查验证目录、普通对象、注释和两页 `/Annots` 的
|
||||
实际对象图,保留初次验证对 PDF 合法紧凑词法的误判。原有真实跨行链接
|
||||
及命名目标对照通过。
|
||||
|
||||
编辑第二页的链接盒宽度时,复用1051步,只更新第二页,第二页注释仍引用
|
||||
第一张页面中的真实注释。PDF、SVG 与来源映射和独立零复用一致,来源
|
||||
映射只归一化会话修订号及测试目录。
|
||||
|
||||
`target/p3-pdf-lastlink-native` 的回执:
|
||||
|
||||
- `receipt.json` 为 `c1fa0672ac47cf23093a4cb9d4d2e3c384c9a6ee6c9755a6bab3dd8ee60f6f20`。
|
||||
- `checkpoint/receipt.json` 为 `7d3af1417582a36aa782ce0f91354624d77e8492100286a1e941e8b072d17f36`。
|
||||
|
||||
### 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