Share pdfTeX image and page object numbers
This commit is contained in:
1 parent
57a7097857
commit
d12c4b034b
11 files changed
+321
-62
No files matched your search
@@ -28,6 +28,8 @@ pub struct ShipoutSpecial {
|
||||
pub struct NativeShipout {
|
||||
pub box_node: NativeBox,
|
||||
pub device: ShipoutDevice,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(super) pdf_objects: Option<crate::pdf_device::page_resources::PageObjects>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub(super) font_overrides: BTreeMap<FontId, Arc<crate::native_font::NativeFont>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -84,6 +86,7 @@ impl NativeShipout {
|
||||
pdf_background: self.pdf_background.clone(),
|
||||
pdf_text_spaces: self.pdf_text_spaces.clone(),
|
||||
pdf_resources: crate::pdf_device::page_resources::PageResources {
|
||||
objects: self.pdf_objects,
|
||||
entries: self.pdf_resource_entries.clone(),
|
||||
attributes: self.pdf_page_attributes.clone(),
|
||||
..Default::default()
|
||||
|
||||
@@ -380,9 +380,19 @@ impl Executor {
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
let pdf_objects = if !for_form && !unicode_pages && device.pdf.is_some() {
|
||||
self.reads.insert(Dependency::PdfObjects);
|
||||
let page_number = self.shipped_pages as u32 + 1;
|
||||
let limit = self.limits.tokens;
|
||||
Some(self.state.pdf_objects.get_or_insert_with(Default::default)
|
||||
.begin_page(page_number, limit).map_err(|message| self.error(message, current))?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut shipout = NativeShipout {
|
||||
box_node: b,
|
||||
device,
|
||||
pdf_objects,
|
||||
font_overrides,
|
||||
virtual_glyphs: None,
|
||||
pdf_font_bindings: self.pdf_virtual_fonts.captured_font_bindings(),
|
||||
@@ -689,6 +699,12 @@ impl Executor {
|
||||
links.xdv_destinations = std::mem::take(&mut shipout.pdf_links.xdv_destinations);
|
||||
shipout.pdf_links = links;
|
||||
}
|
||||
if let Some(objects) = &mut shipout.pdf_objects {
|
||||
let limit = self.limits.tokens;
|
||||
objects.parent = self.state.pdf_objects.as_deref_mut().expect("allocated PDF page")
|
||||
.finish_page(self.shipped_pages as u32 + 1, limit)
|
||||
.map_err(|message| self.error(message, current))?;
|
||||
}
|
||||
if reopened_images {
|
||||
self.rebind_shipped_format_images(&mut shipout.box_node)?;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,10 @@ impl Executor {
|
||||
images: Vec<Arc<PdfImageUse>>,
|
||||
warnings: Vec<String>,
|
||||
) -> Self {
|
||||
if let Some(last) = images.iter().rfind(|image| image.xdv.is_none() && image.pdf_object_number.is_none()) {
|
||||
self.state.pdf_objects.get_or_insert_with(Default::default)
|
||||
.retain_legacy_image_numbers(last.id);
|
||||
}
|
||||
self.restored_pdf_image_count = images.len();
|
||||
self.pdf_images = definitions.iter().zip(images).map(|(saved, image)| {
|
||||
RegisteredImage {
|
||||
@@ -39,9 +43,6 @@ impl Executor {
|
||||
if image.saved.is_none() {
|
||||
return self.fail("cannot dump a format with an unrecorded image object");
|
||||
}
|
||||
if image.image.image.color_space.is_some() {
|
||||
return self.fail("cannot dump a format with image color-space object references");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -71,7 +72,8 @@ impl Executor {
|
||||
return 0;
|
||||
}
|
||||
match (command, self.pdf_images.last()) {
|
||||
(Primitive::Pdflastximage, Some(image)) => image.image.id as i32,
|
||||
(Primitive::Pdflastximage, Some(image)) => image.image.pdf_object_number
|
||||
.map_or(image.image.id as i32, |number| number as i32),
|
||||
(Primitive::Pdflastximagepages, Some(image)) => image.image.image.page_count as i32,
|
||||
(Primitive::Pdflastximagecolordepth, Some(image)) => image
|
||||
.image
|
||||
@@ -224,9 +226,14 @@ impl Executor {
|
||||
PdfImage::read(source, doc, page, page_box, remap_type1)
|
||||
.map_err(|error| self.error(error, token.span))?
|
||||
};
|
||||
let image = PdfImageUse::new(self.pdf_images.len() + 1, image, dimensions)
|
||||
let mut image = PdfImageUse::new(self.pdf_images.len() + 1, image, dimensions)
|
||||
.map_err(|error| self.error(error, token.span))?;
|
||||
let id = image.id;
|
||||
if pdftex {
|
||||
self.reads.insert(Dependency::PdfObjects);
|
||||
image.pdf_object_number = Some(self.state.pdf_objects.get_or_insert_with(Default::default)
|
||||
.reserve_image(id, self.limits.tokens).map_err(|error| self.error(error, token.span))?);
|
||||
}
|
||||
let saved = (pdftex && self.state.is_initex())
|
||||
.then(|| FormatPdfImage::capture(&image, &attributes, format_kind));
|
||||
self.pdf_images.push(RegisteredImage {
|
||||
@@ -591,10 +598,21 @@ impl Executor {
|
||||
self.check_pdf_image()?;
|
||||
let id = self.integer(files)?;
|
||||
self.reads.insert(Dependency::PdfImages);
|
||||
let image = usize::try_from(id)
|
||||
.ok()
|
||||
.and_then(|id| id.checked_sub(1))
|
||||
.and_then(|index| self.pdf_images.get(index))
|
||||
let slot = if self.state.input_profile() == InputProfile::TeX8Bit {
|
||||
self.reads.insert(Dependency::PdfObjects);
|
||||
u32::try_from(id).ok()
|
||||
.and_then(|number| self.state.pdf_objects.as_deref()?.image_slot(number))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let image = slot.or_else(|| {
|
||||
// Existing format images keep the positional numbers embedded in their macros.
|
||||
let id = usize::try_from(id).ok()?;
|
||||
self.pdf_images.get(id.checked_sub(1)?)
|
||||
.filter(|registered| registered.image.pdf_object_number.is_none())
|
||||
.map(|_| id)
|
||||
})
|
||||
.and_then(|id| self.pdf_images.get(id - 1))
|
||||
.map(|registered| registered.image.clone())
|
||||
.ok_or_else(|| self.error(format!("cannot find referenced object {id}"), token.span))?;
|
||||
self.defer_image(image, token)
|
||||
|
||||
@@ -14,9 +14,9 @@ use std::{
|
||||
sync::{Arc, Mutex, OnceLock, Weak},
|
||||
};
|
||||
|
||||
const SCHEMA: u32 = 86;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 53] = [
|
||||
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, SCHEMA,
|
||||
const SCHEMA: u32 = 87;
|
||||
const COMPATIBLE_SCHEMAS: [u32; 54] = [
|
||||
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, SCHEMA,
|
||||
];
|
||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||
|
||||
@@ -191,6 +191,8 @@ impl FormatImage {
|
||||
Parameter::Pdfoptionalwaysusepdfpagebox,
|
||||
]);
|
||||
}
|
||||
let pdf_objects = image.state.pdf_objects.as_deref();
|
||||
let mut numbered_images = 0;
|
||||
for (index, saved) in image.pdf_images.iter().enumerate() {
|
||||
let valid_profile = if saved.kind.reads_at_load() {
|
||||
image.schema >= 83 && image.state.input_profile() == InputProfile::TeX8Bit
|
||||
@@ -199,14 +201,24 @@ impl FormatImage {
|
||||
image.schema >= 84 && image.state.input_profile() == InputProfile::XeTeX
|
||||
&& saved.image.xdv.is_some()
|
||||
};
|
||||
let valid_number = if let Some(number) = saved.image.pdf_object_number {
|
||||
numbered_images += 1;
|
||||
image.schema >= 87 && saved.kind.reads_at_load()
|
||||
&& pdf_objects.and_then(|objects| objects.image_slot(number)) == Some(index + 1)
|
||||
} else {
|
||||
saved.image.image.color_space.is_none()
|
||||
};
|
||||
if !valid_profile
|
||||
|| !valid_number
|
||||
|| saved.image.id != index + 1
|
||||
|| saved.image.image.color_space.is_some()
|
||||
|| saved.path().as_os_str().is_empty()
|
||||
{
|
||||
return Err("invalid native format image registry".into());
|
||||
}
|
||||
}
|
||||
if numbered_images != pdf_objects.map_or(0, |objects| objects.image_count()) {
|
||||
return Err("invalid native format PDF image numbers".into());
|
||||
}
|
||||
if (!image.state.pdf_forms.is_empty()
|
||||
&& (image.schema < 86 || image.state.input_profile() != InputProfile::TeX8Bit))
|
||||
|| !image.state.validate_format_pdf_forms()
|
||||
|
||||
@@ -794,6 +794,7 @@ impl Execution {
|
||||
page.pdf_resources = PageResources::from_page(
|
||||
page.pdf_resources.entries.clone(),
|
||||
page.pdf_resources.attributes.clone(),
|
||||
page.pdf_resources.objects,
|
||||
&states,
|
||||
objects,
|
||||
).map_err(|message| Error::at(
|
||||
|
||||
@@ -2080,6 +2080,54 @@ fn write_pdf_outlines(
|
||||
root_id
|
||||
}
|
||||
|
||||
fn pdf_pages_dictionary(kids: &[usize], pages: usize, parent: Option<usize>) -> Vec<u8> {
|
||||
let refs = kids.iter().map(|kid| format!("{kid} 0 R")).collect::<Vec<_>>().join(" ");
|
||||
let mut node = format!("<< /Type /Pages /Kids [{refs}] /Count {pages}").into_bytes();
|
||||
if let Some(parent) = parent {
|
||||
write!(&mut node, " /Parent {parent} 0 R >>").unwrap();
|
||||
}
|
||||
node
|
||||
}
|
||||
|
||||
fn write_pdf_page_tree(
|
||||
objects: &mut Vec<Vec<u8>>,
|
||||
pages: &[usize],
|
||||
groups: BTreeMap<usize, Vec<usize>>,
|
||||
) -> Vec<usize> {
|
||||
struct Node {
|
||||
id: usize,
|
||||
pages: usize,
|
||||
kids: Vec<usize>,
|
||||
}
|
||||
let fanout = crate::pdf_device::page_resources::PAGE_TREE_FANOUT as usize;
|
||||
let grouped: BTreeSet<_> = groups.values().flatten().copied().collect();
|
||||
let mut level: Vec<_> = groups.into_iter().map(|(id, kids)| Node {
|
||||
id, pages: kids.len(), kids,
|
||||
}).collect();
|
||||
while level.len() > fanout {
|
||||
let mut upper = Vec::with_capacity(level.len().div_ceil(fanout));
|
||||
for children in level.chunks(fanout) {
|
||||
objects.push(Vec::new());
|
||||
let parent = objects.len();
|
||||
for node in children {
|
||||
objects[node.id - 1] = pdf_pages_dictionary(&node.kids, node.pages, Some(parent));
|
||||
}
|
||||
upper.push(Node {
|
||||
id: parent,
|
||||
pages: children.iter().map(|node| node.pages).sum(),
|
||||
kids: children.iter().map(|node| node.id).collect(),
|
||||
});
|
||||
}
|
||||
level = upper;
|
||||
}
|
||||
for node in &level {
|
||||
objects[node.id - 1] = pdf_pages_dictionary(&node.kids, node.pages, Some(2));
|
||||
}
|
||||
level.into_iter().map(|node| node.id)
|
||||
.chain(pages.iter().copied().filter(|id| !grouped.contains(id)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn write_pdf(
|
||||
pages: &[DisplayList],
|
||||
page_width: i64,
|
||||
@@ -2182,7 +2230,7 @@ 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.id, object.image.image.as_ref(), object.attributes.as_slice(), object.compression))
|
||||
Some((object.image.as_ref(), object.attributes.as_slice(), object.compression))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -2191,7 +2239,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.id, image.image.as_ref(), &[][..], compression))
|
||||
Some((image.as_ref(), &[][..], compression))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
@@ -2199,15 +2247,15 @@ fn write_pdf(
|
||||
});
|
||||
let mut image_ids = HashSet::new();
|
||||
let images: Vec<_> = declarations.chain(placements)
|
||||
.filter(|(id, ..)| image_ids.insert(*id))
|
||||
.filter(|(image, ..)| image_ids.insert(image.id))
|
||||
.collect();
|
||||
|
||||
let compression = final_compression.unwrap_or(0).clamp(0, 9) as u8;
|
||||
let mut type1_plans = type1_fonts::FontPlans::default();
|
||||
// pdfTeX collects included font descriptors as it writes forms. The
|
||||
// TeX font dictionaries and their glyph marks are finalized afterward.
|
||||
for (_, image, _, _) in &images {
|
||||
for font in image.mapped_type1_fonts() {
|
||||
for (image, _, _) in &images {
|
||||
for font in image.image.mapped_type1_fonts() {
|
||||
type1_plans.include(font);
|
||||
}
|
||||
}
|
||||
@@ -2422,6 +2470,29 @@ fn write_pdf(
|
||||
device_objects.insert(number, objects.len() as u32);
|
||||
}
|
||||
}
|
||||
for number in images.iter().filter_map(|(image, ..)| image.pdf_object_number) {
|
||||
objects.push(Vec::new());
|
||||
device_objects.insert(number, objects.len() as u32);
|
||||
}
|
||||
let parents: BTreeSet<_> = pages.iter().filter_map(|page| {
|
||||
page.pdf_resources.objects.map(|allocation| allocation.parent)
|
||||
}).collect();
|
||||
let grouped_pages = parents.len() > 1;
|
||||
for number in parents {
|
||||
let id = if grouped_pages {
|
||||
objects.push(Vec::new());
|
||||
objects.len() as u32
|
||||
} else {
|
||||
2
|
||||
};
|
||||
device_objects.insert(number, id);
|
||||
}
|
||||
for allocation in pages.iter().filter_map(|page| page.pdf_resources.objects) {
|
||||
for number in [allocation.resources, allocation.contents] {
|
||||
objects.push(Vec::new());
|
||||
device_objects.insert(number, objects.len() as u32);
|
||||
}
|
||||
}
|
||||
let remapped = resources
|
||||
.map(|resources| resources.append(&mut objects, diagnostics, device_objects.clone()))
|
||||
.transpose()?;
|
||||
@@ -2437,6 +2508,7 @@ fn write_pdf(
|
||||
}
|
||||
}
|
||||
let mut kids = Vec::new();
|
||||
let mut page_groups = BTreeMap::<usize, Vec<usize>>::new();
|
||||
let mut navigation = PdfNavigation::default();
|
||||
let mut annotation_actions = Vec::new();
|
||||
let mut xdv_annotations = Vec::new();
|
||||
@@ -2445,8 +2517,9 @@ 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(|(id, image, attributes, compression)| {
|
||||
let color_space = image.color_space.map(|number| {
|
||||
let form_ids: BTreeMap<_, _> = images.into_iter().map(|(image, attributes, compression)| {
|
||||
let target = image.pdf_object_number.map(|number| device_objects[&number] as usize);
|
||||
let color_space = image.image.color_space.map(|number| {
|
||||
let Ok(reference) = u32::try_from(number) else {
|
||||
return i64::from(number);
|
||||
};
|
||||
@@ -2460,10 +2533,10 @@ fn write_pdf(
|
||||
objects.len() as i64
|
||||
})
|
||||
});
|
||||
let object = image.append_to(
|
||||
&mut objects, attributes, compression, pdf_version, &type1_references, color_space,
|
||||
let object = image.image.append_to(
|
||||
&mut objects, attributes, compression, pdf_version, &type1_references, color_space, target,
|
||||
);
|
||||
(id, object)
|
||||
(image.id, object)
|
||||
}).collect();
|
||||
let append_xobjects = |list: &DisplayList, xobjects: &mut String| -> Result<(), String> {
|
||||
let images = list
|
||||
@@ -2607,9 +2680,13 @@ fn write_pdf(
|
||||
let reserved_page = remapped.as_ref()
|
||||
.and_then(|resources| resources.page_objects.get(&page_index))
|
||||
.copied();
|
||||
let allocation = list.pdf_resources.objects;
|
||||
let content_slot = allocation.map(|page| device_objects[&page.contents] as usize);
|
||||
let parent = allocation.map_or(2, |page| device_objects[&page.parent] as usize);
|
||||
let page_id = reserved_page.unwrap_or(objects.len() + 1);
|
||||
let content_id = objects.len() + 1 + usize::from(reserved_page.is_none());
|
||||
let image_base = content_id + 1;
|
||||
let next_object = objects.len() + 1 + usize::from(reserved_page.is_none());
|
||||
let content_id = content_slot.unwrap_or(next_object);
|
||||
let image_base = next_object + usize::from(content_slot.is_none());
|
||||
let mut xobjects = used
|
||||
.iter()
|
||||
.map(|(_, slot)| format!("/Im{slot} {} 0 R", image_base + *slot))
|
||||
@@ -2663,33 +2740,42 @@ fn write_pdf(
|
||||
format!(" /Annots [{annotation_refs}]")
|
||||
};
|
||||
navigation.pages.push(page_id);
|
||||
kids.push(format!("{page_id} 0 R"));
|
||||
kids.push(page_id);
|
||||
if parent != 2 {
|
||||
page_groups.entry(parent).or_default().push(page_id);
|
||||
}
|
||||
let decorated = !list.pdf_resources.attributes.is_empty();
|
||||
let mut page = b"<< /Type /Page".to_vec();
|
||||
if !decorated {
|
||||
page.extend_from_slice(b" /Parent 2 0 R");
|
||||
write!(&mut page, " /Parent {parent} 0 R").unwrap();
|
||||
}
|
||||
if !crate::pdf_device::page_attributes::supplies_media_box(&list.pdf_resources.attributes) {
|
||||
page.extend_from_slice(format!(" /MediaBox [0 0 {} {}]", physical(width), physical(height)).as_bytes());
|
||||
}
|
||||
page.extend_from_slice(b" /Resources ");
|
||||
let mut resources = resources.into_bytes();
|
||||
let additional = remapped.as_ref().map(|resources| resources.pages[page_index].as_slice())
|
||||
.unwrap_or_default();
|
||||
let writes_procset = list.pdf.as_ref().is_some_and(|pdf| pdf.writes_procset());
|
||||
if !additional.is_empty() || writes_procset {
|
||||
page.extend_from_slice(&resources.as_bytes()[..resources.len() - 2]);
|
||||
page.extend_from_slice(additional);
|
||||
resources.truncate(resources.len() - 2);
|
||||
resources.extend_from_slice(additional);
|
||||
if writes_procset {
|
||||
append_page_procset(&mut page, list, !used.is_empty());
|
||||
append_page_procset(&mut resources, list, !used.is_empty());
|
||||
}
|
||||
page.extend_from_slice(b" >>");
|
||||
resources.extend_from_slice(b" >>");
|
||||
}
|
||||
page.extend_from_slice(b" /Resources ");
|
||||
if let Some(allocation) = allocation {
|
||||
let id = device_objects[&allocation.resources];
|
||||
objects[id as usize - 1] = resources;
|
||||
write!(&mut page, "{id} 0 R").unwrap();
|
||||
} else {
|
||||
page.extend_from_slice(resources.as_bytes());
|
||||
page.extend_from_slice(&resources);
|
||||
}
|
||||
if decorated {
|
||||
page.extend_from_slice(format!(" /Contents {content_id} 0 R ").as_bytes());
|
||||
page.extend_from_slice(&remapped.as_ref().expect("validated page dictionary").page_attributes[page_index]);
|
||||
page.extend_from_slice(format!(" /Parent 2 0 R{annots}{png_group_ref} >>").as_bytes());
|
||||
page.extend_from_slice(format!(" /Parent {parent} 0 R{annots}{png_group_ref} >>").as_bytes());
|
||||
} else {
|
||||
page.extend_from_slice(format!("{annots} /Contents {content_id} 0 R{png_group_ref} >>").as_bytes());
|
||||
}
|
||||
@@ -2718,11 +2804,12 @@ fn write_pdf(
|
||||
&opentype,
|
||||
font_opacities,
|
||||
);
|
||||
objects.push(objects::stream(
|
||||
"",
|
||||
&content,
|
||||
list.pdf.as_ref().map_or(0, |p| p.stream_compression),
|
||||
));
|
||||
let stream = objects::stream("", &content, list.pdf.as_ref().map_or(0, |p| p.stream_compression));
|
||||
if let Some(id) = content_slot {
|
||||
objects[id - 1] = stream;
|
||||
} else {
|
||||
objects.push(stream);
|
||||
}
|
||||
|
||||
for (index, _) in &used {
|
||||
let image = &list.images[*index];
|
||||
@@ -2854,12 +2941,12 @@ fn write_pdf(
|
||||
}
|
||||
}
|
||||
}
|
||||
objects[1] = format!(
|
||||
"<< /Type /Pages /Kids [{}] /Count {}",
|
||||
kids.join(" "),
|
||||
pages.len()
|
||||
)
|
||||
.into_bytes();
|
||||
let root_children = if page_groups.is_empty() {
|
||||
kids
|
||||
} else {
|
||||
write_pdf_page_tree(&mut objects, &kids, page_groups)
|
||||
};
|
||||
objects[1] = pdf_pages_dictionary(&root_children, pages.len(), None);
|
||||
if let Some(resources) = &remapped && !resources.page_tree_attributes.is_empty() {
|
||||
objects[1].push(b' ');
|
||||
objects[1].extend_from_slice(&resources.page_tree_attributes);
|
||||
|
||||
@@ -17,6 +17,10 @@ pub(crate) enum ObjectBody {
|
||||
FormatLink,
|
||||
Form,
|
||||
FormResources,
|
||||
Image(usize),
|
||||
PageResources,
|
||||
PageContents,
|
||||
Pages,
|
||||
DiscardedAtDump,
|
||||
Direct(Vec<u8>),
|
||||
Stream {
|
||||
@@ -34,7 +38,8 @@ impl ObjectBody {
|
||||
fn len(&self) -> usize {
|
||||
match self {
|
||||
Self::Page | Self::Link | Self::FormatLink | Self::Form
|
||||
| Self::FormResources | Self::DiscardedAtDump => 0,
|
||||
| Self::FormResources | Self::Image(_) | Self::PageResources | Self::PageContents
|
||||
| Self::Pages | Self::DiscardedAtDump => 0,
|
||||
Self::Direct(bytes) => bytes.len(),
|
||||
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
|
||||
Self::File {
|
||||
@@ -51,7 +56,8 @@ impl ObjectBody {
|
||||
|
||||
fn parse(&self) -> Result<Object, String> {
|
||||
match self {
|
||||
Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources => {
|
||||
Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources
|
||||
| Self::Image(_) | Self::PageResources | Self::PageContents | Self::Pages => {
|
||||
Err("expected a generic native PDF object".into())
|
||||
}
|
||||
Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".into()),
|
||||
@@ -69,6 +75,15 @@ impl ObjectBody {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct PageObjects {
|
||||
pub resources: u32,
|
||||
pub contents: u32,
|
||||
pub parent: u32,
|
||||
}
|
||||
|
||||
pub(crate) const PAGE_TREE_FANOUT: u32 = 6;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct PdfObjects {
|
||||
values: Vec<Option<Arc<ObjectBody>>>,
|
||||
@@ -79,6 +94,8 @@ pub struct PdfObjects {
|
||||
bytes: usize,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
page_references: BTreeMap<u32, u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
page_parent: Option<u32>,
|
||||
}
|
||||
|
||||
impl PdfObjects {
|
||||
@@ -125,6 +142,42 @@ impl PdfObjects {
|
||||
self.allocate(Some(Arc::new(ObjectBody::FormResources)), limit)
|
||||
}
|
||||
|
||||
pub(crate) fn reserve_image(&mut self, image: usize, limit: usize) -> Result<u32, String> {
|
||||
self.allocate(Some(Arc::new(ObjectBody::Image(image))), limit)
|
||||
}
|
||||
|
||||
pub(crate) fn image_slot(&self, number: u32) -> Option<usize> {
|
||||
match self.entry(number)?.as_deref()? {
|
||||
ObjectBody::Image(slot) => Some(*slot),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn image_count(&self) -> usize {
|
||||
self.values.iter().filter(|entry| matches!(entry.as_deref(), Some(ObjectBody::Image(_)))).count()
|
||||
}
|
||||
|
||||
pub(crate) fn retain_legacy_image_numbers(&mut self, slots: usize) {
|
||||
if slots > self.values.len() {
|
||||
let reserved = Arc::new(ObjectBody::DiscardedAtDump);
|
||||
self.values.resize(slots, Some(reserved));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn begin_page(&mut self, page: u32, limit: usize) -> Result<PageObjects, String> {
|
||||
let resources = self.allocate(Some(Arc::new(ObjectBody::PageResources)), limit)?;
|
||||
self.page_reference(page, limit)?;
|
||||
let contents = self.allocate(Some(Arc::new(ObjectBody::PageContents)), limit)?;
|
||||
Ok(PageObjects { resources, contents, parent: 0 })
|
||||
}
|
||||
|
||||
pub(crate) fn finish_page(&mut self, page: u32, limit: usize) -> Result<u32, String> {
|
||||
if (page - 1) % PAGE_TREE_FANOUT == 0 {
|
||||
self.page_parent = Some(self.allocate(Some(Arc::new(ObjectBody::Pages)), limit)?);
|
||||
}
|
||||
self.page_parent.ok_or_else(|| "missing native PDF page parent".into())
|
||||
}
|
||||
|
||||
pub(crate) fn form_numbers(&self) -> impl Iterator<Item = u32> + '_ {
|
||||
self.values.iter().enumerate().filter_map(|(index, entry)| {
|
||||
matches!(entry.as_deref(), Some(ObjectBody::Form)).then_some(index as u32 + 1)
|
||||
@@ -149,7 +202,8 @@ impl PdfObjects {
|
||||
let replacement = match entry.as_deref() {
|
||||
// A restored link whatsit gets its own annotation object when shipped.
|
||||
Some(ObjectBody::Link) => ObjectBody::FormatLink,
|
||||
Some(ObjectBody::Page | ObjectBody::FormResources) => ObjectBody::DiscardedAtDump,
|
||||
Some(ObjectBody::Page | ObjectBody::FormResources | ObjectBody::PageResources
|
||||
| ObjectBody::PageContents | ObjectBody::Pages) => ObjectBody::DiscardedAtDump,
|
||||
_ if self.written.contains(&number) => ObjectBody::DiscardedAtDump,
|
||||
_ => continue,
|
||||
};
|
||||
@@ -159,6 +213,7 @@ impl PdfObjects {
|
||||
self.last_link = None;
|
||||
self.bytes = self.values.iter().flatten().map(|body| body.len()).sum();
|
||||
self.page_references.clear();
|
||||
self.page_parent = None;
|
||||
!self.values.is_empty()
|
||||
}
|
||||
|
||||
@@ -342,6 +397,7 @@ pub(super) fn encode_value(object: Object) -> Result<Vec<u8>, String> {
|
||||
/// Referenced names affect SVG painting only when they are used by the page.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PageResources {
|
||||
pub(crate) objects: Option<PageObjects>,
|
||||
pub(crate) entries: Arc<[u8]>,
|
||||
pub(crate) attributes: Arc<[u8]>,
|
||||
pub(crate) viewport: Option<super::page_attributes::Viewport>,
|
||||
@@ -397,11 +453,13 @@ impl PageResources {
|
||||
pub(crate) fn from_page(
|
||||
bytes: Arc<[u8]>,
|
||||
attributes: Arc<[u8]>,
|
||||
allocation: Option<PageObjects>,
|
||||
names: &BTreeSet<Vec<u8>>,
|
||||
objects: &PdfObjects,
|
||||
) -> Result<Self, String> {
|
||||
if names.is_empty() {
|
||||
return Ok(Self {
|
||||
objects: allocation,
|
||||
entries: bytes,
|
||||
attributes,
|
||||
..Self::default()
|
||||
@@ -413,6 +471,7 @@ impl PageResources {
|
||||
.map_err(|_| "PDF graphics state used without an ExtGState resource")?;
|
||||
let definitions = resolve_dictionary(definitions.clone(), objects)?;
|
||||
let mut resources = Self {
|
||||
objects: allocation,
|
||||
entries: bytes,
|
||||
attributes,
|
||||
..Self::default()
|
||||
@@ -544,8 +603,17 @@ impl ResourceOutput {
|
||||
}
|
||||
}
|
||||
let page_objects: BTreeSet<_> = objects.page_references.values().copied().collect();
|
||||
let form_objects: BTreeSet<_> = pages.iter().flat_map(|page| {
|
||||
let device_objects: BTreeSet<_> = pages.iter().flat_map(|page| {
|
||||
use crate::render::DisplayItem;
|
||||
page.forms.iter().flat_map(|form| [form.form.number, form.resource_number])
|
||||
.chain(page.pdf_resources.objects.into_iter().flat_map(|objects| {
|
||||
[objects.resources, objects.contents, objects.parent]
|
||||
}))
|
||||
.chain(page.items.iter().filter_map(|item| match item {
|
||||
DisplayItem::PdfImage { image, .. } => image.pdf_object_number,
|
||||
DisplayItem::PdfImageObject(object) => object.image.pdf_object_number,
|
||||
_ => None,
|
||||
}))
|
||||
}).collect();
|
||||
let annotation_entries = pages
|
||||
.iter()
|
||||
@@ -600,7 +668,7 @@ impl ResourceOutput {
|
||||
link_references.entry(number).or_insert(None);
|
||||
continue;
|
||||
}
|
||||
if values.contains_key(&number) || page_objects.contains(&number) || form_objects.contains(&number) {
|
||||
if values.contains_key(&number) || page_objects.contains(&number) || device_objects.contains(&number) {
|
||||
continue;
|
||||
}
|
||||
if objects.is_discarded_at_dump(number) {
|
||||
|
||||
@@ -59,6 +59,8 @@ pub struct PdfImage {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PdfImageUse {
|
||||
pub id: usize,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub(crate) pdf_object_number: Option<u32>,
|
||||
pub image: Arc<PdfImage>,
|
||||
pub width: i64,
|
||||
pub height: i64,
|
||||
@@ -136,6 +138,7 @@ impl PdfImageUse {
|
||||
}
|
||||
Ok(Self {
|
||||
id,
|
||||
pdf_object_number: None,
|
||||
image: Arc::new(image),
|
||||
width,
|
||||
height,
|
||||
@@ -182,6 +185,7 @@ impl PdfImageUse {
|
||||
});
|
||||
Ok(Self {
|
||||
id,
|
||||
pdf_object_number: None,
|
||||
image,
|
||||
width,
|
||||
height,
|
||||
@@ -228,6 +232,7 @@ impl PdfImageUse {
|
||||
let matrix = matrix.0.map(|value| (value * 100_000.0).round() / 100_000.0);
|
||||
Ok(Self {
|
||||
id,
|
||||
pdf_object_number: None,
|
||||
image,
|
||||
width: (right - left) as i64,
|
||||
height: (top - bottom) as i64,
|
||||
@@ -849,12 +854,16 @@ impl PdfImage {
|
||||
pdf_version: (i32, i32),
|
||||
fonts: &crate::pdf::type1_fonts::References<'_>,
|
||||
color_space: Option<i64>,
|
||||
target: Option<usize>,
|
||||
) -> usize {
|
||||
if let Some(samples) = self.sampled_image() {
|
||||
return samples.append(pdf, attributes, compression, pdf_version, color_space);
|
||||
return samples.append(pdf, attributes, compression, pdf_version, color_space, target);
|
||||
}
|
||||
let base = pdf.len() + 1;
|
||||
pdf.extend(self.objects.iter().enumerate().map(|(index, parts)| {
|
||||
// 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);
|
||||
for (index, parts) in self.objects.iter().enumerate() {
|
||||
let mut body = Vec::new();
|
||||
if index == 0 {
|
||||
body.extend_from_slice(b"<< ");
|
||||
@@ -866,7 +875,10 @@ impl PdfImage {
|
||||
for part in parts {
|
||||
match part {
|
||||
Part::Bytes(bytes) | Part::Jpeg { bytes, .. } => body.extend_from_slice(bytes),
|
||||
Part::Ref(id) => write!(body, "{} 0 R", base + id).unwrap(),
|
||||
Part::Ref(id) => {
|
||||
let object = if *id == 0 { root } else { base + id };
|
||||
write!(body, "{object} 0 R").unwrap();
|
||||
}
|
||||
Part::ImageColorSpace => {
|
||||
let id = color_space.expect("mapped image color space");
|
||||
write!(body, "{id} 0 R").unwrap();
|
||||
@@ -888,9 +900,13 @@ impl PdfImage {
|
||||
}
|
||||
}
|
||||
}
|
||||
body
|
||||
}));
|
||||
base
|
||||
if index == 0 && target.is_some() {
|
||||
pdf[root - 1] = body;
|
||||
} else {
|
||||
pdf.push(body);
|
||||
}
|
||||
}
|
||||
root
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -184,8 +184,9 @@ impl SampledImage {
|
||||
compression: u8,
|
||||
pdf_version: (i32, i32),
|
||||
color_space: Option<i64>,
|
||||
target: Option<usize>,
|
||||
) -> usize {
|
||||
let id = pdf.len() + 1;
|
||||
let id = target.unwrap_or(pdf.len() + 1);
|
||||
let [width, height] = self.size;
|
||||
let mut color = match (color_space, &self.color) {
|
||||
(Some(id), _) => format!("{id} 0 R"),
|
||||
@@ -202,7 +203,8 @@ impl SampledImage {
|
||||
};
|
||||
let has_alpha = self.has_alpha(pdf_version);
|
||||
if has_alpha {
|
||||
write!(color, " /SMask {} 0 R", id + 1).expect("writing to a string");
|
||||
let mask = pdf.len() + 1 + usize::from(target.is_none());
|
||||
write!(color, " /SMask {mask} 0 R").expect("writing to a string");
|
||||
}
|
||||
let strip_16 = pdf_version < (1, 5) && self.depth == 16;
|
||||
let reduced;
|
||||
@@ -221,7 +223,11 @@ impl SampledImage {
|
||||
// Image attributes are TeX printer bytes and may be non-UTF-8.
|
||||
stream.splice(3..3, attributes.iter().copied().chain([b'\n']));
|
||||
}
|
||||
pdf.push(stream);
|
||||
if target.is_some() {
|
||||
pdf[id - 1] = stream;
|
||||
} else {
|
||||
pdf.push(stream);
|
||||
}
|
||||
if has_alpha {
|
||||
pdf.push(objects::stream(
|
||||
&format!(
|
||||
|
||||
+22
-1
@@ -801,12 +801,33 @@ PDF 对象的引用进入同一重编号过程。边界框、矩阵和资源引
|
||||
后,安全复用该文件首次读取前的检查点,只更新第二页。PDF、SVG
|
||||
和来源映射与独立全量一致,实际辅助文件内容一致。
|
||||
|
||||
下一入口为图片与其它 PDF 对象共用编号。冻结用例的原版打印
|
||||
当时冻结了图片与其他 PDF 对象的编号差异。原版用例打印
|
||||
1/2/3/4,当前原生打印 1/1/2/3。首次发页后新原始对象的编号
|
||||
分别为 9 和 5。保留两端实际 PDF 与日志,并用真实页面资源和
|
||||
内容流补齐剩余的分配时机。回执 target/p3-pdf-form-format/receipt.json
|
||||
的 SHA-256 为 9f58bf51a894b698a90640c65c8fd7a3a6877b244aaebe1c676f169b0d1fb423。
|
||||
|
||||
### pdfTeX 图像与实际页面对象共享编号
|
||||
|
||||
TeX 可见的图像号由通用 PDF 对象表分配。真实页开始时分配
|
||||
资源、页面和内容流,在写页字典时分配每组六页的 Pages 叶节点。
|
||||
输出 PDF 使用实际资源字典、内容流和页树。通用对象中的引用映射
|
||||
到这批输出对象,重复引用使用同一个物理对象。旧格式的图像号仍可
|
||||
使用,schema87 保存新的对象身份和图像颜色空间引用。
|
||||
[TeX Live 的页面输出和编号分配](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L19165-L19187)
|
||||
|
||||
原差异用例的四个对象和首次发页后的新编号现与 pdfTeX 一致。
|
||||
38 页对照覆盖未来页号、每组六页的叶节点和多层页树。五组参考
|
||||
作业共 43 页 144 DPI 灰度逐像素一致,错误类型引用有明确诊断。
|
||||
真实 schema86 旧格式两页光栅保持一致。十六项图像、链接和 PDF
|
||||
配置回归通过。图像编辑会话复用读取图像前的检查点,只更新实际
|
||||
引用的第二页。PDF、SVG 和来源映射与独立全量一致。
|
||||
|
||||
下一入口是字体、透明 PNG 和压缩对象流在发页时的实际分配。
|
||||
现有三个用例首次发页后读取的新对象编号与原版仍分别差 1、2 和 1。
|
||||
源码、原版和原生出页见 target/p3-pdf-shared-numbers/next-device-objects。
|
||||
回执 target/p3-pdf-shared-numbers/receipt.json 的 SHA-256 为 e77e730569d6643bf5155c93cf1bb1e64070823d05094e962623fb736d88894e。
|
||||
|
||||
### PDF 预览按实际页面资源复用
|
||||
|
||||
编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。
|
||||
|
||||
@@ -375,9 +375,13 @@ fn png_project_edit_updates_only_the_page_using_the_image() {
|
||||
\pdfoutput=1 \pdfminorversion=7 \pdfcompresslevel=0 \pdfobjcompresslevel=0
|
||||
\pdfpagewidth=120bp \pdfpageheight=120bp \pdfhorigin=4bp \pdfvorigin=4bp
|
||||
\shipout\vbox{\hrule width12pt height20pt depth0pt}
|
||||
\def\space{ }
|
||||
";
|
||||
let continuation = r"\pdfximage width36bp {figure.data}
|
||||
\shipout\hbox{\pdfrefximage\pdflastximage}\end
|
||||
\edef\imageobject{\the\pdflastximage}
|
||||
\ifnum\imageobject=5\else\errorstopmode\errmessage{wrong image object number}\fi
|
||||
\pdfobj{<< /OriginalImage \imageobject\space 0 R >>}
|
||||
\shipout\hbox{\pdfrefobj\pdflastobj\pdfrefximage\imageobject}\end
|
||||
";
|
||||
let complete_line = format!("{}\n", "\\relax ".repeat(26));
|
||||
let source = format!("{prefix}{}{continuation}", complete_line.repeat(40));
|
||||
@@ -447,6 +451,13 @@ fn png_project_edit_updates_only_the_page_using_the_image() {
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(images.len(), 1);
|
||||
let image_id = document.objects.values().find_map(|object| {
|
||||
object.as_dict().ok()?.get(b"OriginalImage").ok()?.as_reference().ok()
|
||||
}).unwrap();
|
||||
assert!(std::ptr::eq(
|
||||
document.get_object(image_id).unwrap().as_stream().unwrap(),
|
||||
images[0].0,
|
||||
));
|
||||
assert_eq!(images[0].0.content, [0, 0, 255, 0, 255, 0]);
|
||||
assert_eq!(images[0].1.content, [255, 128]);
|
||||
fs::remove_dir_all(root).unwrap();
|
||||
|
||||
Reference in new issue
Block a user