Allocate indirect PDF import objects during native writes
This commit is contained in:
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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -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],
|
||||
|
||||
Reference in new issue
Block a user