Allocate indirect PDF import objects during native writes

This commit is contained in:
gloamxun committed 2026-11-28 00:06:51 +08:00
1 parent 5a2df6781a
commit 861c9dbfc9
14 files changed
+588 -32

No files matched your search

@@ -1,7 +1,7 @@
use super::*;
use crate::{
execution::format_image::{FormatImageKind, FormatPdfImage},
pdf_image::{PageBox, PageSelection, PdfImage, PdfImageObject, PdfImageUse, XdvImagePlacement},
pdf_image::{ImportWrite, PageBox, PageSelection, PdfImage, PdfImageObject, PdfImageUse, XdvImagePlacement},
resources::ResourceKind,
};
@@ -238,6 +238,15 @@ impl Executor {
let mut image = PdfImageUse::new(id, image, dimensions)
.map_err(|error| self.error(error, token.span))?;
image.pdf_object_number = object_number;
if pdftex && image.image.has_source_graph() {
image.pdftex_file_name = Some(if std::path::Path::new(&filename).is_absolute()
|| filename.starts_with("./") || filename.starts_with("../")
{
filename
} else {
format!("./{filename}")
});
}
if let Some(header) = header {
if image.image.reserves_png_group((header.major, i32::from(header.minor))) {
image.png_group = Some(self.state.pdf_objects.as_deref_mut().expect("registered image")
@@ -496,7 +505,7 @@ impl Executor {
pending_xdv: None,
});
let hidden = special.hidden;
self.emit_pdf_image_object(image.clone(), special.attributes, None);
self.emit_pdf_image_object(image.clone(), special.attributes, None, None);
Ok((!hidden).then_some(image))
}
@@ -562,7 +571,24 @@ impl Executor {
} else {
None
};
self.emit_pdf_image_object(image, attributes, png_auxiliary);
let imports = if self.state.input_profile() == InputProfile::TeX8Bit
&& let Some(header) = self.state.pdf_header_options
&& image.image.has_source_graph()
{
let suppress = self.read_parameter(Parameter::Pdfsuppressptexinfo).width();
let underscore = self.read_parameter(Parameter::Pdfptexuseunderscore).width() != 0;
let file_name = image.pdftex_file_name.as_deref().map(std::borrow::Cow::Borrowed)
.unwrap_or_else(|| image.image.version.path.to_string_lossy());
self.reads.insert(Dependency::PdfObjects);
Some(image.image.write_import(
&file_name, suppress, underscore,
self.state.pdf_objects.get_or_insert_with(Default::default),
header.object_compression, self.limits.tokens,
).map_err(|error| self.error(error, self.current))?)
} else {
None
};
self.emit_pdf_image_object(image, attributes, png_auxiliary, imports);
Ok(())
}
@@ -604,6 +630,7 @@ impl Executor {
fn emit_pdf_image_object(
&mut self, image: Arc<PdfImageUse>, attributes: Vec<u8>, png_auxiliary: Option<u32>,
imports: Option<ImportWrite>,
) {
let compression = self
.read_parameter(Parameter::Pdfcompresslevel)
@@ -614,6 +641,7 @@ impl Executor {
attributes,
compression,
png_auxiliary,
imports,
}));
}
@@ -14,7 +14,7 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 90;
const SCHEMA: u32 = 91;
const COMPATIBLE_SCHEMAS: [u32; 57] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, SCHEMA,
];
@@ -194,6 +194,12 @@ impl FormatImage {
if image.schema < 90 {
image.state.restore_legacy_pdf_parameters(&[Parameter::Pdfdraftmode]);
}
if image.schema < 91 {
image.state.restore_legacy_pdf_parameters(&[
Parameter::Pdfsuppressptexinfo,
Parameter::Pdfptexuseunderscore,
]);
}
let pdf_objects = image.state.pdf_objects.as_deref();
let mut numbered_images = 0;
for (index, saved) in image.pdf_images.iter().enumerate() {
@@ -141,6 +141,8 @@ pub enum Parameter {
XeTeXlinebreakpenalty,
XeTeXinputnormalization,
Pdfdraftmode,
Pdfsuppressptexinfo,
Pdfptexuseunderscore,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue {
@@ -157,6 +159,8 @@ impl Parameter {
| Self::Pdfobjcompresslevel
| Self::Pdfcompresslevel
| Self::Pdfdraftmode
| Self::Pdfsuppressptexinfo
| Self::Pdfptexuseunderscore
| Self::Pdfdecimaldigits
| Self::Pdfpkresolution
| Self::Pdfimageresolution
@@ -204,6 +208,8 @@ impl Parameter {
Self::Pdfobjcompresslevel,
Self::Pdfcompresslevel,
Self::Pdfdraftmode,
Self::Pdfsuppressptexinfo,
Self::Pdfptexuseunderscore,
Self::Pdfdecimaldigits,
Self::Pdfpkresolution,
Self::Pdfimageresolution,
@@ -1765,6 +1765,9 @@ impl State {
generate_unicode: self.parameter(Parameter::Pdfgentounicode).width(),
omit_charset: self.parameter(Parameter::Pdfomitcharset).width() != 0,
omit_info: self.parameter(Parameter::Pdfomitinfodict).width() != 0,
ptex_banner_separator: (self.input_profile == super::InputProfile::TeX8Bit
&& self.parameter(Parameter::Pdfsuppressptexinfo).width() & 1 == 0)
.then(|| if self.parameter(Parameter::Pdfptexuseunderscore).width() == 0 { '.' } else { '_' }),
glyph_unicode: &self.glyph_unicode,
fonts: &self.fonts,
page_tree_attributes: &self.pdf_pages_attributes,
+15 -6
View File
@@ -1309,7 +1309,9 @@ fn metadata_object(metadata: &PdfMetadata) -> Option<String> {
Some(format!("<< {} >>", fields.join(" ")))
}
fn native_information_dictionary(info: crate::pdf_device::PdfInfo<'_>) -> Vec<u8> {
fn native_information_dictionary(
info: crate::pdf_device::PdfInfo<'_>, banner_separator: Option<char>,
) -> Vec<u8> {
// pdfTeX suppresses defaults based on the raw byte spelling anywhere in
// the expanded list. Preserve the supplied PDF syntax verbatim.
let supplied = |key: &[u8]| info.entries.windows(key.len()).any(|value| value == key);
@@ -1335,6 +1337,9 @@ fn native_information_dictionary(info: crate::pdf_device::PdfInfo<'_>) -> Vec<u8
if !supplied(b"/Trapped") {
object.extend_from_slice(b"/Trapped /False\n");
}
if let Some(separator) = banner_separator {
writeln!(&mut object, "/PTEX{separator}Fullbanner (texrra Route-D native)").unwrap();
}
object.extend_from_slice(b">>");
object
}
@@ -2314,7 +2319,10 @@ fn write_pdf(
// retains its measured source image and can precede that registration.
let declarations = paint_lists.iter().flat_map(|list| &list.items).filter_map(|item| {
if let DisplayItem::PdfImageObject(object) = item {
Some((object.image.as_ref(), object.attributes.as_slice(), object.compression, object.png_auxiliary))
Some((
object.image.as_ref(), object.attributes.as_slice(), object.compression,
object.png_auxiliary, object.imports.as_ref(),
))
} else {
None
}
@@ -2323,7 +2331,7 @@ fn write_pdf(
let compression = list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression);
list.items.iter().filter_map(move |item| {
if let DisplayItem::PdfImage { image, .. } = item {
Some((image.as_ref(), &[][..], compression, None))
Some((image.as_ref(), &[][..], compression, None, None))
} else {
None
}
@@ -2566,7 +2574,7 @@ fn write_pdf(
}
const PNG_GROUP: &[u8] = b"<< /Type /Group /S /Transparency /CS /DeviceRGB /I true >>";
if let Some(registry) = registry {
for number in registry.png_object_numbers() {
for number in registry.png_object_numbers().chain(registry.imported_image_numbers()) {
objects.push(Vec::new());
device_objects.insert(number, objects.len() as u32);
}
@@ -2633,11 +2641,12 @@ fn write_pdf(
.and_then(|page| page.pdf.as_ref())
.map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor)));
let mut unwritten_color_spaces = BTreeMap::new();
let form_ids: BTreeMap<_, _> = images.into_iter().map(|(image, attributes, compression, auxiliary)| {
let form_ids: BTreeMap<_, _> = images.into_iter().map(|(image, attributes, compression, auxiliary, imports)| {
let physical = |number: u32| device_objects[&number] as usize;
let targets = crate::pdf_image::PdfImageTargets {
image: image.pdf_object_number.map(physical),
png_auxiliary: auxiliary.map(physical),
imports: imports.map(|imports| (imports, &device_objects)),
};
let color_space = image.image.color_space.map(|number| {
let Ok(reference) = u32::try_from(number) else {
@@ -3313,7 +3322,7 @@ fn write_pdf(
if device.driver == crate::pdf_device::PdfDriver::Xdv {
crate::pdf_device::xdv_document::information_dictionary(info, diagnostics)?
} else {
native_information_dictionary(info)
native_information_dictionary(info, options.ptex_banner_separator)
}
}
None => metadata_object(metadata)
@@ -1,13 +1,14 @@
//! Native PDF objects and extra resources captured at page shipout.
use crate::execution::FontId;
use crate::{execution::FontId, resources::ResourceVersion};
use super::links::DestinationId;
use lopdf::{
Dictionary, Object, Stream,
Dictionary, Object, ObjectId, Stream,
content::{Content, Operation},
};
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, BTreeSet},
path::PathBuf,
sync::Arc,
};
@@ -38,6 +39,7 @@ pub(crate) enum ObjectBody {
},
ObjectStream,
Destination,
ImportedImage,
}
impl ObjectBody {
@@ -46,7 +48,7 @@ impl ObjectBody {
Self::Page | Self::Link | Self::FormatLink | Self::Form
| Self::FormResources | Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream
| Self::Destination | Self::DiscardedAtDump => 0,
| Self::Destination | Self::ImportedImage | Self::DiscardedAtDump => 0,
Self::Direct(bytes) => bytes.len(),
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
Self::File {
@@ -66,7 +68,7 @@ impl ObjectBody {
Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources
| Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream
| Self::Destination => {
| Self::Destination | Self::ImportedImage => {
Err("expected a generic native PDF object".into())
}
Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".into()),
@@ -130,6 +132,9 @@ pub struct PdfObjects {
destination_numbers: BTreeMap<(DestinationId<String>, bool), (u32, bool)>,
#[serde(skip)]
shipped_links: BTreeSet<u32>,
// Source object numbers belong to one particular version of one file.
#[serde(skip)]
imported_images: BTreeMap<PathBuf, BTreeMap<String, BTreeMap<ObjectId, u32>>>,
}
impl PdfObjects {
@@ -263,6 +268,27 @@ impl PdfObjects {
self.written_png_group
}
pub(crate) fn import_image_object(
&mut self, version: &ResourceVersion, source: ObjectId, limit: usize,
) -> Result<(u32, bool), String> {
if let Some(&number) = self.imported_images.get(&version.path)
.and_then(|versions| versions.get(&version.sha256))
.and_then(|objects| objects.get(&source))
{
return Ok((number, false));
}
let number = self.allocate(Some(Arc::new(ObjectBody::ImportedImage)), limit)?;
self.imported_images.entry(version.path.clone()).or_default()
.entry(version.sha256.clone()).or_default().insert(source, number);
Ok((number, true))
}
pub(crate) fn imported_image_numbers(&self) -> impl Iterator<Item = u32> + '_ {
self.values.iter().enumerate().filter_map(|(index, entry)| {
matches!(entry.as_deref(), Some(ObjectBody::ImportedImage)).then_some(index as u32 + 1)
})
}
pub(crate) fn reserve_image(&mut self, image: usize, limit: usize) -> Result<u32, String> {
self.allocate(Some(Arc::new(ObjectBody::Image(image))), limit)
}
@@ -361,7 +387,8 @@ impl PdfObjects {
Some(ObjectBody::Link) => ObjectBody::FormatLink,
Some(ObjectBody::Page | ObjectBody::FormResources | ObjectBody::PageResources
| ObjectBody::PageContents | ObjectBody::Pages | ObjectBody::Font(_)
| ObjectBody::PngAuxiliary | ObjectBody::ObjectStream | ObjectBody::Destination) => {
| ObjectBody::PngAuxiliary | ObjectBody::ObjectStream | ObjectBody::Destination
| ObjectBody::ImportedImage) => {
ObjectBody::DiscardedAtDump
}
_ if self.written.contains(&number) => ObjectBody::DiscardedAtDump,
@@ -381,6 +408,7 @@ impl PdfObjects {
self.object_streams.clear();
self.destination_numbers.clear();
self.shipped_links.clear();
self.imported_images.clear();
!self.values.is_empty()
}
@@ -841,7 +869,7 @@ impl ResourceOutput {
|| device_objects.contains(&number) || objects.font_owner(number).is_some()
|| matches!(objects.entry(number).and_then(Option::as_deref),
Some(ObjectBody::PngGroup | ObjectBody::PngAuxiliary | ObjectBody::ObjectStream
| ObjectBody::Destination))
| ObjectBody::Destination | ObjectBody::ImportedImage))
{
continue;
}
+65 -15
View File
@@ -4,6 +4,8 @@ mod destinations;
mod jpeg;
mod icc;
mod imported_fonts;
mod imports;
pub(crate) use imports::ImportWrite;
mod page_boxes;
pub(crate) use imported_fonts::ImportedType1Use;
mod png;
@@ -54,6 +56,8 @@ pub struct PdfImage {
pub(crate) color_space: Option<i32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
imported_fonts: Vec<imported_fonts::ImportedType1>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pdftex_source: Option<imports::SourceGraph>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -63,6 +67,8 @@ pub struct PdfImageUse {
pub(crate) pdf_object_number: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) png_group: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) pdftex_file_name: Option<String>,
pub image: Arc<PdfImage>,
pub width: i64,
pub height: i64,
@@ -108,12 +114,15 @@ pub struct PdfImageObject {
pub compression: u8,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) png_auxiliary: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) imports: Option<ImportWrite>,
}
#[derive(Clone, Copy)]
pub(crate) struct PdfImageTargets {
pub(crate) struct PdfImageTargets<'a> {
pub image: Option<usize>,
pub png_auxiliary: Option<usize>,
pub imports: Option<(&'a ImportWrite, &'a BTreeMap<u32, u32>)>,
}
impl PdfImageUse {
@@ -150,6 +159,7 @@ impl PdfImageUse {
id,
pdf_object_number: None,
png_group: None,
pdftex_file_name: None,
image: Arc::new(image),
width,
height,
@@ -198,6 +208,7 @@ impl PdfImageUse {
id,
pdf_object_number: None,
png_group: None,
pdftex_file_name: None,
image,
width,
height,
@@ -246,6 +257,7 @@ impl PdfImageUse {
id,
pdf_object_number: None,
png_group: None,
pdftex_file_name: None,
image,
width: (right - left) as i64,
height: (top - bottom) as i64,
@@ -407,6 +419,7 @@ impl PdfImage {
objects: Vec::new(),
color_space: self.color_space,
imported_fonts: Vec::new(),
pdftex_source: None,
}
}
@@ -545,6 +558,7 @@ impl PdfImage {
objects,
color_space,
imported_fonts: Vec::new(),
pdftex_source: None,
}
}
@@ -593,6 +607,7 @@ impl PdfImage {
objects: vec![vec![part]],
color_space: None,
imported_fonts: Vec::new(),
pdftex_source: None,
})
}
@@ -743,6 +758,7 @@ impl PdfImage {
let chain = page_chain(&doc, page_id)?;
let inherited = |name: &[u8]| chain.iter().find_map(|dict| dict.get(name).ok());
let restored = matches!(box_selection, PageBoxSelection::RestoredPdfTeX(_));
let pdftex = !matches!(box_selection, PageBoxSelection::Xdv(_));
let ([left, bottom, right, top], rotation, keep_page_origin) = match box_selection {
PageBoxSelection::PdfTeX(spec) | PageBoxSelection::RestoredPdfTeX(spec) => (
page_boxes::pdftex(&doc, &chain, spec)?,
@@ -829,18 +845,34 @@ impl PdfImage {
};
let mut form = Vec::new();
let header = format!(
"/Type /XObject /Subtype /Form /FormType 1 /BBox [{}] /Matrix [{}] /Resources ",
"/Type /XObject /Subtype /Form /FormType 1 /BBox [{}] /Matrix [{}] ",
array(&[left, bottom, right, top]),
array(&matrix)
);
form.push(Part::Bytes(header.into_bytes()));
match inherited(b"Resources") {
Some(resources) => graph.render(resources, &mut form, 0)?,
None => form.push(Part::Bytes(b"<<>>".to_vec())),
if pdftex {
for key in [b"LastModified".as_slice(), b"Metadata", b"PieceInfo", b"SeparationInfo", b"Group"] {
if let Ok(value) = chain[0].get(key) && !matches!(value, Object::Null) {
let mut name = b" ".to_vec();
name.extend(pdf_name(key));
name.push(b' ');
form.push(Part::Bytes(name));
graph.render(value, &mut form, 0)?;
}
}
}
if let Ok(group) = chain[0].get(b"Group") {
form.push(Part::Bytes(b" /Group ".to_vec()));
graph.render(group, &mut form, 0)?;
form.push(Part::Bytes(b" /Resources ".to_vec()));
if pdftex {
graph.pdftex_resources(inherited(b"Resources"), &mut form)?;
} else {
match inherited(b"Resources") {
Some(resources) => graph.render(resources, &mut form, 0)?,
None => form.push(Part::Bytes(b"<<>>".to_vec())),
}
if let Ok(group) = chain[0].get(b"Group") {
form.push(Part::Bytes(b" /Group ".to_vec()));
graph.render(group, &mut form, 0)?;
}
}
let mut stream = format!(" /Length {} >>\nstream\n", contents.len()).into_bytes();
stream.extend(contents);
@@ -852,6 +884,7 @@ impl PdfImage {
} else {
Vec::new()
};
let pdftex_source = pdftex.then(|| imports::SourceGraph::capture(&mut graph)).transpose()?;
Ok((
Self {
version: resource.version,
@@ -863,6 +896,7 @@ impl PdfImage {
objects: graph.bodies,
color_space: None,
imported_fonts,
pdftex_source,
},
[left, bottom],
))
@@ -880,17 +914,30 @@ impl PdfImage {
pdf_version: (i32, i32),
fonts: &crate::pdf::type1_fonts::References<'_>,
color_space: Option<i64>,
targets: PdfImageTargets,
targets: PdfImageTargets<'_>,
) -> usize {
if let Some(samples) = self.sampled_image() {
return samples.append(pdf, attributes, compression, pdf_version, color_space, targets);
}
let target = targets.image;
// A preallocated image slot owns the first object. Other imported objects
// still occupy a contiguous range, including references back to the image.
let base = pdf.len() + usize::from(target.is_none());
let root = target.unwrap_or(base);
let physical = |index: usize| {
if index == 0 {
root
} else if let Some((allocation, numbers)) = targets.imports {
numbers[&allocation.objects[index].expect("referenced import").number] as usize
} else {
base + index
}
};
for (index, parts) in self.objects.iter().enumerate() {
if index != 0
&& let Some((allocation, _)) = targets.imports
&& !allocation.objects[index].is_some_and(|object| object.write)
{
continue;
}
let mut body = Vec::new();
if index == 0 {
body.extend_from_slice(b"<< ");
@@ -899,11 +946,14 @@ impl PdfImage {
body.push(b'\n');
}
}
for part in parts {
let form_entries = targets.imports
.filter(|_| index == 0)
.map_or(&[][..], |(imports, _)| imports.form_entries.as_slice());
for part in form_entries.iter().chain(parts) {
match part {
Part::Bytes(bytes) | Part::Jpeg { bytes, .. } => body.extend_from_slice(bytes),
Part::Ref(id) => {
let object = if *id == 0 { root } else { base + id };
let object = physical(*id);
write!(body, "{object} 0 R").unwrap();
}
Part::ImageColorSpace => {
@@ -927,8 +977,8 @@ impl PdfImage {
}
}
}
if index == 0 && target.is_some() {
pdf[root - 1] = body;
if (index == 0 && target.is_some()) || (index != 0 && targets.imports.is_some()) {
pdf[physical(index) - 1] = body;
} else {
pdf.push(body);
}
@@ -312,6 +312,7 @@ impl PdfImage {
fn retain_reachable_objects(&mut self) {
let mut used = vec![false; self.objects.len()];
let mut visit = vec![0];
visit.extend(self.pdftex_source.iter().filter_map(|source| source.info()));
while let Some(index) = visit.pop() {
if std::mem::replace(&mut used[index], true) {
continue;
@@ -339,6 +340,9 @@ impl PdfImage {
}
}
}
if let Some(source) = &mut self.pdftex_source {
source.retain(&used, &reindex);
}
self.objects = keep;
}
}
@@ -0,0 +1,195 @@
//! Indirect source objects are allocated in the order pdfTeX writes them.
use super::{Graph, Part, PdfImage, resolved};
use crate::{pdf_device::page_resources::PdfObjects, resources::ResourceVersion};
use lopdf::{Dictionary, Object, ObjectId};
use serde::{Deserialize, Serialize};
use std::{collections::VecDeque, io::Write};
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(super) struct SourceGraph {
// Slot zero belongs to the output Form, which has no source object number.
nodes: Vec<Option<SourceObject>>,
info: Option<usize>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
struct SourceObject {
id: ObjectId,
stream: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) struct ImportWrite {
pub(crate) objects: Vec<Option<ImportedObject>>,
pub(super) form_entries: Vec<Part>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub(crate) struct ImportedObject {
pub(crate) number: u32,
pub(super) write: bool,
}
impl SourceGraph {
pub(super) fn capture(graph: &mut Graph<'_>) -> Result<Self, String> {
let mut info_ref = Vec::new();
if let Ok(info @ Object::Reference(_)) = graph.doc.trailer.get(b"Info") {
graph.render(info, &mut info_ref, 0)?;
}
let info = match info_ref.as_slice() {
[Part::Ref(index)] => Some(*index),
_ => None,
};
let mut nodes = vec![None; graph.bodies.len()];
for (&id, &index) in &graph.ids {
nodes[index] = Some(SourceObject {
id,
stream: matches!(graph.doc.objects.get(&id), Some(Object::Stream(_))),
});
}
Ok(Self { nodes, info })
}
pub(super) fn info(&self) -> Option<usize> {
self.info
}
pub(super) fn retain(&mut self, used: &[bool], reindex: &[usize]) {
self.nodes = std::mem::take(&mut self.nodes)
.into_iter()
.zip(used)
.filter_map(|(node, &keep)| keep.then_some(node))
.collect();
self.info = self.info.map(|index| reindex[index]);
}
}
impl Graph<'_> {
// pdfTeX inlines the selected page's resource dictionary and its top-level
// groups. References *inside* those groups are preserved and queued.
pub(super) fn pdftex_resources(
&mut self,
source: Option<&Object>,
form: &mut Vec<Part>,
) -> Result<(), String> {
let mut entries = Dictionary::new();
if let Some(source) = source {
let resources = resolved(self.doc, source)?
.as_dict()
.map_err(|error| error.to_string())?;
for (key, value) in resources.iter() {
let value = resolved(self.doc, value)?;
let valid = match key.as_slice() {
b"ProcSet" => matches!(value, Object::Array(_)),
b"Subtype" => matches!(value, Object::Name(_)),
_ => matches!(value, Object::Dictionary(_)),
};
if valid {
entries.set(key.clone(), value.clone());
}
}
}
self.render(&Object::Dictionary(entries), form, 0)
}
}
impl PdfImage {
pub(crate) fn has_source_graph(&self) -> bool {
self.pdftex_source.is_some()
}
pub(crate) fn write_import(
&self,
file_name: &str,
suppress: i32,
underscore: bool,
registry: &mut PdfObjects,
compression: u8,
limit: usize,
) -> Result<ImportWrite, String> {
let source = self.pdftex_source.as_ref().expect("pdfTeX source graph");
let separator = if underscore { '_' } else { '.' };
let mut form_entries = Vec::new();
let mut header = Vec::new();
if suppress & 2 == 0 {
write!(header, "/PTEX{separator}FileName <").unwrap();
for byte in file_name.bytes() {
write!(header, "{byte:02X}").unwrap();
}
header.extend_from_slice(b">\n");
}
if suppress & 4 == 0 {
writeln!(header, "/PTEX{separator}PageNumber {}", self.page).unwrap();
}
if suppress & 8 == 0
&& let Some(info) = source.info
{
write!(header, "/PTEX{separator}InfoDict ").unwrap();
form_entries.push(Part::Bytes(std::mem::take(&mut header)));
form_entries.push(Part::Ref(info));
header.push(b'\n');
}
if !header.is_empty() {
form_entries.push(Part::Bytes(header));
}
let mut queue = VecDeque::new();
let mut objects = vec![None; source.nodes.len()];
let mut numbering = ImportNumbering {
source,
version: &self.version,
registry,
limit,
};
numbering.references(
form_entries.iter().chain(&self.objects[0]),
&mut objects,
&mut queue,
)?;
while let Some(index) = queue.pop_front() {
let object = source.nodes[index].expect("indirect source object");
if compression >= 2 && !object.stream {
numbering
.registry
.pack_object(objects[index].unwrap().number, limit)?;
}
numbering.references(self.objects[index].iter(), &mut objects, &mut queue)?;
}
Ok(ImportWrite {
objects,
form_entries,
})
}
}
struct ImportNumbering<'a> {
source: &'a SourceGraph,
version: &'a ResourceVersion,
registry: &'a mut PdfObjects,
limit: usize,
}
impl ImportNumbering<'_> {
fn references<'a>(
&mut self,
parts: impl Iterator<Item = &'a Part>,
objects: &mut [Option<ImportedObject>],
queue: &mut VecDeque<usize>,
) -> Result<(), String> {
for part in parts {
let Part::Ref(index) = *part else { continue };
if objects[index].is_some() {
continue;
}
let source = self.source.nodes[index].expect("indirect source object");
let (number, write) =
self.registry
.import_image_object(self.version, source.id, self.limit)?;
objects[index] = Some(ImportedObject { number, write });
if write {
queue.push_back(index);
}
}
Ok(())
}
}
+2 -1
View File
@@ -147,6 +147,7 @@ pub(super) fn read(
objects: vec![vec![Part::Png(image)]],
color_space,
imported_fonts: Vec::new(),
pdftex_source: None,
restored_pdf_origin: None,
},
warning,
@@ -193,7 +194,7 @@ impl SampledImage {
compression: u8,
pdf_version: (i32, i32),
color_space: Option<i64>,
targets: PdfImageTargets,
targets: PdfImageTargets<'_>,
) -> usize {
let target = targets.image;
let id = target.unwrap_or(pdf.len() + 1);
@@ -131,6 +131,7 @@ pub struct PdfFinalOptions<'a> {
pub generate_unicode: i32,
pub(crate) omit_charset: bool,
pub(crate) omit_info: bool,
pub(crate) ptex_banner_separator: Option<char>,
pub glyph_unicode: &'a GlyphUnicodeMap,
pub fonts: &'a crate::execution::FontCatalog,
pub page_tree_attributes: &'a [u8],
+33
View File
@@ -979,6 +979,39 @@ DVI 模式的原生出页几何、两种格式镜像和二十五项定向回归
schema90 支持草稿参数持久化,schema89 镜像加载时恢复此原语。
回执 SHA-256 为 0084b0d17763f7a9b6f5d6d6816334a40e9e1ff069428e3f8880866fb77a3396。
### pdfTeX 导入页的实际间接对象
导入 Form 内联源页面的 Resources 和顶层资源组,保留其实际间接引用。
写出时按原文件路径、字节指纹和源对象编号及 generation 分配并复用。
执行器先登记根引用,再按队列逐个写出并发现后续引用,非流对象在
符合压缩等级时加入实际对象流。导出器消费对应的编号和对象体。
首次使用和立即写出分别在各自的时点执行,草稿模式沿用现有写出行为。
[参考导入对象与写出队列](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftoepdf.cc#L628-L655)
写出时读取 pdfsuppressptexinfo 和 pdfptexuseunderscore。被抑制的
源 Info 字典不进入导入图,目标文档仍标记实际生产者。格式 schema91
保存新参数和声明时的文件名,重载从实际图片重建图,旧格式恢复参数定义。
发布版十项图像回归通过,含 PNG、JPEG、格式图像重载、
XeTeX 及 Form。原样 teaser 和无图控制共六组的编号与 pdfTeX 相同。
同文件重复声明共享依赖,另一文件即使字节相同也有独立对象。
三页会话中,图片改色并增加一个实际资源后复原。两次各复用 1,007 步,
只更新第 2 页。PDF 字节、测量页面、SVG、来源映射及记录对象号的辅助
文件均与独立零复用全量编译一致。会话先用真实作业生成辅助文件,
保留辅助文件初次出现时未复用的试验记录。
证据在 target/p3-imported-pdf-objects。witness/variants.json 的
SHA-256 为 3e03acf5b4f933056a5e93efa35d9b5be13d7c09edccf937b487be44551c2b1f,
revision-settled.log 为 89e96d66430120a969f2896ffac35aa68953d19d138e8d2c043548b4a8b6f8bc。
图像中的现有 Type 1 字体默认映射和原样复制各复验一页,
两种模式的词框及灰度像素与参考相同,字体描述符与前一主线一致。
只在出页后读取下一个对象号时,原样复制与参考均为 11。
默认映射从 6 推进到 9,参考为 12。接下来需要验证并接通替换字体
的实际编码、描述符等分配。两种见证在
target/p3-imported-pdf-objects/font-ids-default 和 font-ids-copy。
[原样 sigconf 的稳定辅助文件](PUBLISHER_TEMPLATE_MATRIX.md#2026-11-28-sigconf-导入图编号复验)
### 行内数学字符参与 pdfTeX 字宽伸缩
行内数学结束后,实际未装盒的传统字体字符进入段落水平列表。
+17
View File
@@ -1199,6 +1199,23 @@ variants.json 的 SHA-256 为
[pdfTeX 的导入图和写出顺序](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftoepdf.cc#L244-L275)
[pdfTeX 的导入溯源和页面资源](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftoepdf.cc#L804-L975)
### 2026-11-28 sigconf 导入图编号复验
同一作业、44 项原始交付文件、冻结 schema51 和字体映射,以
新发布候选继续读第五轮的实际辅助文件和原生 BibTeX 产物。
第六轮 40 个结构引用的对象号与冻结参考一致,整个 aux 逐字节相同。
第七轮 aux 保持稳定,bbl 与参考相同。七页 30,130 个字形、
4,651 个提取词和词框、144 DPI 灰度像素、命名目的地及
76 个结构链接动作与参考一致。Poppler 的标记警告和完整可访问性
验收仍保留。
原样 teaser 的六组编号对照全部一致。默认写出从旧原生的
1、3、9、13 修正为与 pdfTeX 一致的 1、3、15、19。
见 [间接图实现和编辑对照](P2_M1_PROGRESS.md#pdftex-导入页的实际间接对象)。
回执在 target/p3-imported-pdf-objects/acm-sigconf。
receipt.json 的 SHA-256 为 230c29ff12658a9aaa768f00cd95acffcf7d73a43967d8052eb4267177ca26c0,
pass-7/comparison.json 为 7ff193a7ba1b183c9813667d97e2947188998ff26e8102c66c9eb7f3056c74ca。
单纯生成 PDF 或 DVI 只说明编译路径可达。完整验收要在参考环境闭合后比较页数、
双栏位置及跨栏材料、实际字体/字形、图表浮动、引用收敛、词框及墨迹;测试源
与容差都不得为通过而替换。类 Typst 的编辑延迟另用同批原样项目分规模测量,
+175
View File
@@ -962,3 +962,178 @@ fn restored_form_reads_the_current_pdf_object_and_updates_only_its_page() {
);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn imported_pdf_indirect_objects_share_the_device_registry_at_write_time() {
let root = std::env::temp_dir().join(format!("texrra-pdf-import-{}", std::process::id()));
fs::create_dir(&root).unwrap();
let source = root.join("figure.pdf");
rotated_document(&source);
let mut fixture = Document::load(&source).unwrap();
let page_id = fixture.get_pages()[&1];
let resources = fixture
.get_dictionary(page_id)
.unwrap()
.get(b"Parent")
.and_then(Object::as_reference)
.and_then(|parent| fixture.get_dictionary(parent))
.and_then(|parent| parent.get(b"Resources"))
.and_then(Object::as_reference)
.unwrap();
let state = fixture.add_object(dictionary! {"Type" => "ExtGState", "CA" => 1});
let info =
fixture.add_object(dictionary! {"Title" => Object::string_literal("actual imported PDF")});
fixture
.objects
.get_mut(&resources)
.unwrap()
.as_dict_mut()
.unwrap()
.set("ExtGState", dictionary! {"GS" => state});
fixture.trailer.set("Info", info);
fixture.save(&source).unwrap();
fs::copy(&source, root.join("identical.pdf")).unwrap();
fs::write(
root.join("probe.tex"),
r"\catcode123=1 \catcode125=2
\pdfoutput=1 \pdfminorversion=7 \pdfobjcompresslevel=3 \pdfcompresslevel=9
\def\trace{\pdfobj reserveobjnum\message{[object=\the\pdflastobj]}}
\pdfximage{figure.pdf}\trace
\pdfsuppressptexinfo=8 \pdfptexuseunderscore=1
\shipout\hbox{\pdfrefximage\pdflastximage}\trace
\pdfsuppressptexinfo=0 \pdfptexuseunderscore=0
\immediate\pdfximage{figure.pdf}\trace
\shipout\hbox{\pdfrefximage\pdflastximage}\trace
\immediate\pdfximage{identical.pdf}\trace
\shipout\hbox{\pdfrefximage\pdflastximage}\trace
\pdfsuppressptexinfo=1
\end",
)
.unwrap();
let reference = Command::new("pdftex")
.args([
"-ini",
"-etex",
"-interaction=nonstopmode",
"-halt-on-error",
"probe.tex",
])
.current_dir(&root)
.output()
.unwrap();
assert!(
reference.status.success(),
"{}",
String::from_utf8_lossy(&reference.stdout)
);
let native = Command::new(env!("CARGO_BIN_EXE_texrra"))
.args([
"native",
"--job",
"--initex",
"--etex",
"probe.tex",
"native.pdf",
])
.current_dir(&root)
.output()
.unwrap();
assert!(
native.status.success(),
"{}",
String::from_utf8_lossy(&native.stderr)
);
let observations = |name| {
fs::read_to_string(root.join(name))
.unwrap()
.replace('\n', "")
.split("[object=")
.skip(1)
.map(|value| value.split_once(']').unwrap().0.parse::<u32>().unwrap())
.collect::<Vec<_>>()
};
let expected = observations("probe.log");
assert_eq!(expected.len(), 6);
assert_eq!(observations("native.log"), expected);
for file in ["probe.pdf", "native.pdf"] {
let pdf = Document::load(root.join(file)).unwrap();
let mut copies = Vec::new();
for page in pdf.get_pages().values() {
let resources = pdf
.get_dictionary(*page)
.unwrap()
.get(b"Resources")
.unwrap();
let resources = pdf.dereference(resources).unwrap().1.as_dict().unwrap();
let xobjects = pdf
.dereference(resources.get(b"XObject").unwrap())
.unwrap()
.1
.as_dict()
.unwrap();
let only_form = xobjects.iter().next().unwrap().1;
let form = &pdf
.dereference(only_form)
.unwrap()
.1
.as_stream()
.unwrap()
.dict;
let resources = form.get(b"Resources").unwrap().as_dict().unwrap();
let state = resources
.get(b"ExtGState")
.unwrap()
.as_dict()
.unwrap()
.get(b"GS")
.unwrap()
.as_reference()
.unwrap();
let info = form
.get(b"PTEX.InfoDict")
.and_then(Object::as_reference)
.ok();
if let Some(info) = info {
assert_eq!(
pdf.get_dictionary(info)
.unwrap()
.get(b"Title")
.unwrap()
.as_str()
.unwrap(),
b"actual imported PDF",
);
}
let file_name = form
.get(b"PTEX.FileName")
.or_else(|_| form.get(b"PTEX_FileName"))
.unwrap()
.as_str()
.unwrap();
assert_eq!(
file_name,
if copies.len() < 2 {
b"./figure.pdf".as_slice()
} else {
b"./identical.pdf"
}
);
assert_eq!(form.has(b"PTEX_PageNumber"), copies.is_empty());
copies.push((state, info));
}
assert_eq!(copies.len(), 3);
assert_eq!(copies[0].0, copies[1].0);
assert_ne!(copies[1].0, copies[2].0);
assert_eq!(copies[0].1, None);
assert_ne!(copies[1].1, None);
assert_ne!(copies[1].1, copies[2].1);
let output_info = pdf.trailer.get(b"Info").unwrap().as_reference().unwrap();
assert!(
!pdf.get_dictionary(output_info)
.unwrap()
.has(b"PTEX.Fullbanner")
);
}
fs::remove_dir_all(root).unwrap();
}