use super::acroform_field_prune::DEFAULT_MAX_ACROFORM_DEPTH;
use super::resource_pruning::{should_remove_unreferenced_resources, RemoveUnreferencedResources};
use crate::object_copy::{
copy_foreign_object_for_preserve, copy_foreign_object_with_stale_generation_policy,
copy_foreign_value_with_stale_generation_policy,
};
use crate::page_extract::{append_selection_kids, null_copied_removed_pages, target_pages_root};
use crate::page_label_document_helper::{
copy_raw_page_label_entries, merge_adjacent_raw_page_labels, record_primary_label_provenance,
RawPageLabelEntry,
};
use crate::pages::page_refs;
use crate::pdf::WriterObjectOrderKey;
use crate::pdf_string::{new_unicode_string, utf8_value};
use crate::qpdf_obj_gen::QpdfObjGen;
use crate::{
AcroFormDocumentHelper, Error, ObjectHandle, ObjectRef, ObjectStreamMode, PageDocumentHelper,
PageObjectHelper, Pdf, Result, XrefEntry,
};
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Cursor, Read, Seek};
pub struct MergeInput<'a, R: Read + Seek + 'static> {
pub source: &'a mut Pdf<R>,
pub pages: Vec<usize>,
}
fn project_foreign_object_map(
raw_map: &BTreeMap<QpdfObjGen, ObjectRef>,
) -> BTreeMap<ObjectRef, ObjectRef> {
raw_map
.iter()
.filter_map(|(object_gen, target_ref)| {
object_gen
.to_object_ref()
.map(|source_ref| (source_ref, *target_ref))
})
.collect()
}
fn wire_primary_catalog<RS: Read + Seek, RT: Read + Seek>(
source: &mut Pdf<RS>,
target: &mut Pdf<RT>,
source_id: u64,
remove_stale_generations: bool,
) -> Result<()> {
let source_catalog = source.root_handle()?;
let target_catalog = target.root_handle()?;
for key in source_catalog.try_get_keys()? {
if key == b"/Pages" {
continue;
}
let value = source_catalog.try_get_key(&key)?;
let copied = copy_foreign_value_with_stale_generation_policy(
target,
source_id,
&value,
remove_stale_generations,
)?; target_catalog.replace_key(&key, copied)?;
}
Ok(())
}
fn wire_primary_pages_root<RS: Read + Seek, RT: Read + Seek>(
source: &mut Pdf<RS>,
target: &mut Pdf<RT>,
source_id: u64,
target_pages_ref: ObjectRef,
remove_stale_generations: bool,
) -> Result<()> {
let source_catalog = source.root_handle()?;
let source_pages = source_catalog.try_get_key(b"/Pages")?;
source_pages.try_dereference()?;
let target_pages = target.get_object_handle(target_pages_ref);
target_pages.try_dereference()?;
for key in source_pages.try_get_keys()? {
if matches!(
key.as_slice(),
b"/Type"
| b"/Parent"
| b"/Kids"
| b"/Count"
| b"/MediaBox"
| b"/CropBox"
| b"/Resources"
| b"/Rotate"
) {
continue;
}
let value = source_pages.try_get_key(&key)?;
let copied = copy_foreign_value_with_stale_generation_policy(
target,
source_id,
&value,
remove_stale_generations,
)?; target_pages.replace_key(&key, copied)?;
}
Ok(())
}
fn preserve_primary_root_shape<RS: Read + Seek, RT: Read + Seek>(
source: &mut Pdf<RS>,
target: &mut Pdf<RT>,
) -> Result<()> {
if source.root_ref().is_some() {
return Ok(());
}
let temporary_root_ref = target.root_ref();
let target_root = target.root_handle()?;
target_root.try_dereference()?;
let direct_root = target_root.shallow_copy()?;
target.trailer().replace_key(b"/Root", direct_root)?;
if let Some(temporary_root_ref) = temporary_root_ref {
target.remove_object_handle(temporary_root_ref)?; } Ok(())
}
fn wire_primary_trailer<RS: Read + Seek, RT: Read + Seek>(
source: &mut Pdf<RS>,
target: &mut Pdf<RT>,
source_id: u64,
remove_stale_generations: bool,
) -> Result<()> {
let source_trailer = source.trailer();
let target_trailer = target.trailer();
let Some(root_ref) = target.root_ref() else {
return Ok(());
};
for key in source_trailer.try_get_keys()? {
if matches!(
key.as_slice(),
b"/Root"
| b"/Size"
| b"/Prev"
| b"/Encrypt"
| b"/Type"
| b"/W"
| b"/Index"
| b"/XRefStm"
| b"/Length"
| b"/Filter"
| b"/DecodeParms"
) {
continue;
}
let value = source_trailer.try_get_key(&key)?;
let copied = copy_foreign_value_with_stale_generation_policy(
target,
source_id,
&value,
remove_stale_generations,
)?; target_trailer.replace_key(&key, copied)?;
}
target_trailer.replace_key(b"/Root", target.get_object_handle(root_ref))?;
Ok(())
}
fn install_primary_object_stream_membership<RS: Read + Seek, RT: Read + Seek>(
source: &mut Pdf<RS>,
target: &mut Pdf<RT>,
source_xref_entries: &BTreeMap<ObjectRef, XrefEntry>,
copied: &BTreeMap<ObjectRef, ObjectRef>,
) -> Result<()> {
let mut target_containers = BTreeMap::new();
for (&source_member, entry) in source_xref_entries {
let XrefEntry::Compressed { stream, index } = *entry else {
continue;
};
let Some(&target_member) = copied.get(&source_member) else {
continue;
};
let target_container = ensure_object_stream_container(
source,
target,
ObjectRef::new(stream, 0),
&mut target_containers,
copied,
)?; target.install_object_stream_member(target_member, target_container, index);
}
Ok(())
}
fn ensure_object_stream_container<RS: Read + Seek, RT: Read + Seek>(
source: &mut Pdf<RS>,
target: &mut Pdf<RT>,
source_container: ObjectRef,
target_containers: &mut BTreeMap<ObjectRef, ObjectRef>,
copied: &BTreeMap<ObjectRef, ObjectRef>,
) -> Result<ObjectRef> {
let mut chain = Vec::new();
let mut current = Some(source_container);
while let Some(container) = current {
if target_containers.contains_key(&container) || chain.contains(&container) {
break;
}
if let Some(&already_copied) = copied.get(&container) {
target_containers.insert(container, already_copied);
break;
}
chain.push(container);
current = {
let source_stream = source.get_object_handle(container);
source_stream.try_dereference()?;
source_stream
.as_stream_dict()
.map(|dictionary| dictionary.try_get_key(b"/Extends"))
.transpose()?
.and_then(|extends| extends.object_ref())
};
}
for &container in chain.iter().rev() {
let source_stream = source.get_object_handle(container);
source_stream.try_dereference()?;
let target_stream = copy_foreign_object_for_preserve(target, &source_stream)?;
let target_container = target_stream.object_ref().ok_or(Error::Internal(
"copied ObjStm container lost its object identity".to_owned(),
))?;
target_containers.insert(container, target_container);
}
target_containers
.get(&source_container)
.copied()
.ok_or(Error::Internal(
"ObjStm container copy did not register its source identity".to_owned(),
))
}
pub(crate) fn unique_field_name(base: &[u8], used: &BTreeSet<Vec<u8>>) -> Vec<u8> {
if !used.contains(base) {
return base.to_vec();
}
for n in 1u32.. {
let mut candidate = base.to_vec();
candidate.extend_from_slice(format!("+{n}").as_bytes());
if !used.contains(&candidate) {
return candidate;
}
}
unreachable!("u32 candidate space exhausted") }
struct KeptField {
target_ref: ObjectRef,
partial_name: Option<Vec<u8>>,
is_primary: bool,
}
#[derive(Default)]
struct PrimaryAcroForm {
has_dr: bool,
has_da: bool,
had_fields_array: bool,
fields_are_indirect: bool,
original_field_names: BTreeSet<Vec<u8>>,
}
fn discover_primary_acroform<R: Read + Seek>(source: &mut Pdf<R>) -> Result<PrimaryAcroForm> {
let had_fields_array = {
let mut acroform = AcroFormDocumentHelper::new_for_field_tree(source)?;
acroform.has_fields_array()?
};
let mut out = PrimaryAcroForm {
had_fields_array,
..Default::default()
};
let root = source.root_handle()?;
let acroform = root.try_get_key(b"/AcroForm")?;
acroform.try_dereference()?;
if acroform.try_is_dictionary()? {
let dr = acroform.try_get_key(b"/DR")?;
let da = acroform.try_get_key(b"/DA")?;
out.has_dr = !dr.try_is_null()?;
out.has_da = !da.try_is_null()?;
let fields = acroform.try_get_key(b"/Fields")?;
out.fields_are_indirect = fields.is_indirect() && fields.try_is_array()?;
}
Ok(out)
}
pub(crate) fn source_top_level_field_names<R: Read + Seek>(
source: &mut Pdf<R>,
) -> Result<Vec<(ObjectRef, Option<Vec<u8>>)>> {
let top_fields = source.acroform()?.top_level_fields()?;
source_top_level_field_names_from_refs(source, top_fields)
}
fn source_top_level_field_names_without_page_scan<R: Read + Seek>(
source: &mut Pdf<R>,
) -> Result<Vec<(ObjectRef, Option<Vec<u8>>)>> {
let top_fields = {
let mut acroform = AcroFormDocumentHelper::new_for_field_tree(source)?;
acroform.top_level_fields()?
};
source_top_level_field_names_from_refs(source, top_fields)
}
fn source_top_level_field_names_from_refs<R: Read + Seek>(
source: &mut Pdf<R>,
top_fields: Vec<ObjectRef>,
) -> Result<Vec<(ObjectRef, Option<Vec<u8>>)>> {
let mut out = Vec::with_capacity(top_fields.len());
for field_ref in top_fields {
let field_handle = source.get_object_handle(field_ref);
let terminal = field_handle.object_ref().unwrap_or(field_ref);
field_handle.try_dereference()?;
let name = resolve_field_partial_name(source, terminal)?;
out.push((terminal, name));
}
Ok(out)
}
fn resolve_field_partial_name<R: Read + Seek>(
source: &mut Pdf<R>,
field_ref: ObjectRef,
) -> Result<Option<Vec<u8>>> {
let field_handle = source.get_object_handle(field_ref);
field_handle.try_dereference()?;
let field = field_handle;
if !field.try_is_dictionary()? {
return Ok(None);
}
let t_value = field.try_get_key(b"/T")?;
if t_value.try_is_null()? {
return Ok(None);
}
let resolved = t_value.clone();
resolved.try_dereference()?;
Ok(resolved.as_string().map(|raw| utf8_value(&raw)))
}
fn remove_target_acroform<R: Read + Seek>(target: &mut Pdf<R>) -> Result<()> {
let Some(catalog_ref) = target.root_ref() else {
return Ok(()); };
let catalog_handle = target.get_object_handle(catalog_ref);
catalog_handle.try_dereference()?;
let catalog = catalog_handle;
if !catalog.try_is_dictionary()? {
return Ok(()); }
catalog.remove_key(b"/AcroForm");
Ok(())
}
fn build_merged_acroform<R: Read + Seek>(
target: &mut Pdf<R>,
primary: &PrimaryAcroForm,
kept: &[KeptField],
) -> Result<()> {
if kept.is_empty() && !primary.had_fields_array {
return Ok(());
}
if kept.is_empty() && !primary.has_dr && !primary.has_da {
if primary.had_fields_array {
remove_target_acroform(target)?;
}
return Ok(());
}
let acroform =
AcroFormDocumentHelper::new_for_field_tree(target)?.canonical_get_or_create_acroform()?;
if !acroform.try_is_dictionary()? {
return Ok(()); }
let mut used = primary.original_field_names.clone();
for field in kept {
if field.is_primary {
if let Some(name) = &field.partial_name {
used.insert(name.clone());
}
}
}
let mut fields = Vec::with_capacity(kept.len());
for field in kept {
if !field.is_primary {
if let Some(name) = &field.partial_name {
let unique = unique_field_name(name, &used);
used.insert(unique.clone());
if unique != *name {
rename_field(target, field.target_ref, unique)?;
}
}
}
fields.push(target.get_object_handle(field.target_ref));
}
let replacement = ObjectHandle::array(fields);
let replacement = if primary.fields_are_indirect {
target.make_indirect_object_handle(replacement)?
} else {
replacement
};
acroform.replace_key(b"/Fields", replacement)?;
Ok(())
}
fn rename_field<R: Read + Seek>(
target: &mut Pdf<R>,
field_ref: ObjectRef,
name: Vec<u8>,
) -> Result<()> {
let field_handle = target.get_object_handle(field_ref);
field_handle.try_dereference()?;
let field = field_handle;
if !field.try_is_dictionary()? {
return Ok(()); }
field.replace_key(b"/T", ObjectHandle::string(new_unicode_string(&name)))?;
Ok(())
}
fn field_kid_refs<R: Read + Seek>(
source: &mut Pdf<R>,
field_ref: ObjectRef,
) -> Result<Option<Vec<ObjectRef>>> {
let field_handle = source.get_object_handle(field_ref);
field_handle.try_dereference()?;
let field = field_handle;
if !field.try_is_dictionary()? {
return Ok(None);
}
let kids_value = field.try_get_key(b"/Kids")?;
if kids_value.try_is_null()? {
return Ok(None);
}
let resolved = kids_value.clone();
resolved.try_dereference()?;
let Some(items) = resolved.try_as_array()? else {
return Ok(Some(Vec::new())); };
let mut refs = Vec::with_capacity(items.len());
for item in items {
let terminal_ref = item.object_ref();
item.try_dereference()?;
if let Some(r) = terminal_ref {
refs.push(r);
} }
Ok(Some(refs))
}
fn collect_retained_widget_refs<R: Read + Seek>(
source: &mut Pdf<R>,
selected_pages: &BTreeSet<ObjectRef>,
retained: &mut BTreeSet<ObjectRef>,
) -> Result<()> {
for &page_ref in selected_pages {
let page_handle = source.get_object_handle(page_ref);
page_handle.try_dereference()?;
let page = page_handle;
if !page.try_is_dictionary()? {
continue; }
let annots_val = page.try_get_key(b"/Annots")?;
if annots_val.try_is_null()? {
continue;
}
let concrete = annots_val.clone();
concrete.try_dereference()?;
let Some(elems) = concrete.try_as_array()? else {
continue; };
for elem in elems {
let terminal_ref = elem.object_ref();
elem.try_dereference()?;
if let Some(r) = terminal_ref {
retained.insert(r);
}
}
}
Ok(())
}
fn widget_page_ref<R: Read + Seek>(
source: &mut Pdf<R>,
widget_ref: ObjectRef,
) -> Result<Option<ObjectRef>> {
let widget_handle = source.get_object_handle(widget_ref);
widget_handle.try_dereference()?;
let widget = widget_handle;
if !widget.try_is_dictionary()? {
return Ok(None);
}
let p_value = widget.try_get_key(b"/P")?;
if p_value.try_is_null()? {
return Ok(None);
}
let last_ref = p_value.object_ref();
p_value.try_dereference()?;
Ok(last_ref)
}
#[allow(clippy::too_many_arguments)]
fn trim_field_kids<R: Read + Seek, T: Read + Seek>(
source: &mut Pdf<R>,
target: &mut Pdf<T>,
field_ref: ObjectRef,
surviving_pages: &BTreeSet<ObjectRef>,
retained_widgets: &BTreeSet<ObjectRef>,
map: &BTreeMap<ObjectRef, ObjectRef>,
orphan_pages: &mut BTreeSet<ObjectRef>,
depth: usize,
visited: &mut BTreeSet<ObjectRef>,
) -> Result<Option<Vec<ObjectRef>>> {
if depth > DEFAULT_MAX_ACROFORM_DEPTH {
return Err(Error::Unsupported(format!(
"AcroForm field tree depth exceeds maximum of {DEFAULT_MAX_ACROFORM_DEPTH}"
)));
}
if !visited.insert(field_ref) {
return Ok(Some(Vec::new()));
}
let Some(kids) = field_kid_refs(source, field_ref)? else {
return Ok(None); };
let mut survivors: Vec<ObjectRef> = Vec::with_capacity(kids.len());
for kid_ref in kids {
let kid_kind = trim_field_kids(
source,
target,
kid_ref,
surviving_pages,
retained_widgets,
map,
orphan_pages,
depth + 1,
visited,
)?;
match kid_kind {
Some(sub_survivors) => {
if sub_survivors.is_empty() {
continue;
}
rewrite_field_kids(target, kid_ref, &sub_survivors, map)?;
survivors.push(kid_ref);
}
None => {
if retained_widgets.contains(&kid_ref) {
survivors.push(kid_ref);
} else {
match widget_page_ref(source, kid_ref)? {
Some(page_ref) if surviving_pages.contains(&page_ref) => {
survivors.push(kid_ref)
}
Some(page_ref) => {
orphan_pages.insert(page_ref);
}
None => {}
}
}
}
}
}
Ok(Some(survivors))
}
fn rewrite_field_kids<R: Read + Seek>(
target: &mut Pdf<R>,
src_field_ref: ObjectRef,
survivors: &[ObjectRef],
map: &BTreeMap<ObjectRef, ObjectRef>,
) -> Result<()> {
let Some(target_field_ref) = map.get(&src_field_ref).copied() else {
return Ok(()); };
let field_handle = target.get_object_handle(target_field_ref);
field_handle.try_dereference()?;
let field = field_handle;
if !field.try_is_dictionary()? {
return Ok(()); }
let mut kids = Vec::with_capacity(survivors.len());
for src in survivors {
if let Some(&target_ref) = map.get(src) {
kids.push(target.get_object_handle(target_ref));
}
}
field.replace_key(b"/Kids", ObjectHandle::array(kids))?;
Ok(())
}
pub fn merge_documents<R: Read + Seek>(
inputs: &mut [MergeInput<'_, R>],
) -> Result<Pdf<Cursor<Vec<u8>>>> {
merge_documents_with_resource_mode(inputs, RemoveUnreferencedResources::No)
}
pub(crate) fn merge_documents_with_resource_mode<R: Read + Seek>(
inputs: &mut [MergeInput<'_, R>],
resource_mode: RemoveUnreferencedResources,
) -> Result<Pdf<Cursor<Vec<u8>>>> {
merge_documents_with_resource_mode_and_preserve_primary(inputs, resource_mode, false)
}
pub(crate) fn merge_documents_with_resource_mode_and_preserve_primary<R: Read + Seek>(
inputs: &mut [MergeInput<'_, R>],
resource_mode: RemoveUnreferencedResources,
preserve_primary_unreferenced: bool,
) -> Result<Pdf<Cursor<Vec<u8>>>> {
let remove_resources: Vec<bool> = inputs
.iter_mut()
.map(|input| match resource_mode {
RemoveUnreferencedResources::No => Ok(false),
RemoveUnreferencedResources::Yes => Ok(true),
RemoveUnreferencedResources::Auto => should_remove_unreferenced_resources(input.source),
})
.collect::<Result<_>>()?;
merge_documents_with_resource_decisions_and_preserve_primary(
inputs,
&remove_resources,
preserve_primary_unreferenced,
)
}
pub(crate) fn merge_documents_with_resource_decisions_and_preserve_primary<R: Read + Seek>(
inputs: &mut [MergeInput<'_, R>],
remove_resources: &[bool],
preserve_primary_unreferenced: bool,
) -> Result<Pdf<Cursor<Vec<u8>>>> {
let target = Pdf::empty()?;
merge_documents_with_resource_decisions_and_preserve_primary_into(
inputs,
remove_resources,
preserve_primary_unreferenced,
target,
)
}
pub(crate) fn merge_documents_with_resource_decisions_and_preserve_primary_into<
R: Read + Seek,
T: Read + Seek,
>(
inputs: &mut [MergeInput<'_, R>],
remove_resources: &[bool],
preserve_primary_unreferenced: bool,
target: Pdf<T>,
) -> Result<Pdf<T>> {
merge_documents_with_resource_decisions_and_preserve_primary_into_impl(
inputs,
remove_resources,
preserve_primary_unreferenced,
target,
false,
ObjectStreamMode::Preserve,
)
}
pub(crate) fn merge_documents_for_page_specs_into<R: Read + Seek, T: Read + Seek>(
inputs: &mut [MergeInput<'_, R>],
remove_resources: &[bool],
preserve_primary_unreferenced: bool,
target: Pdf<T>,
object_stream_mode: ObjectStreamMode,
) -> Result<Pdf<T>> {
merge_documents_with_resource_decisions_and_preserve_primary_into_impl(
inputs,
remove_resources,
preserve_primary_unreferenced,
target,
true,
object_stream_mode,
)
}
fn merge_documents_with_resource_decisions_and_preserve_primary_into_impl<
R: Read + Seek,
T: Read + Seek,
>(
inputs: &mut [MergeInput<'_, R>],
remove_resources: &[bool],
preserve_primary_unreferenced: bool,
mut target: Pdf<T>,
defer_foreign_acroform_fields: bool,
object_stream_mode: ObjectStreamMode,
) -> Result<Pdf<T>> {
if inputs.is_empty() {
return Err(Error::Unsupported(
"merge requires at least one input".to_string(),
));
}
if inputs.len() != remove_resources.len() {
return Err(Error::Internal(
"page merge resource decisions do not match source count".to_owned(),
));
}
let original_page_refs: Vec<Vec<ObjectRef>> = inputs
.iter_mut()
.enumerate()
.map(|(input_index, input)| {
if input_index != 0 && input.pages.is_empty() {
Ok(Vec::new())
} else {
page_refs(input.source)
}
})
.collect::<Result<_>>()?;
let pages_root_ref = target_pages_root(&mut target)?;
let mut writer_object_order: BTreeMap<ObjectRef, WriterObjectOrderKey> = BTreeMap::new();
let mut primary_max_object = 0;
let mut next_foreign_original = 1;
let mut kids: Vec<ObjectRef> = Vec::new();
let mut used: BTreeSet<ObjectRef> = BTreeSet::new();
let mut kept_fields: Vec<KeptField> = Vec::new();
let mut primary_acroform = PrimaryAcroForm::default();
let total_selected: usize = inputs.iter().map(|i| i.pages.len()).sum();
let mut label_entries: Vec<RawPageLabelEntry> = Vec::with_capacity(total_selected);
let mut any_page_labels = false;
let mut out_pageno: i64 = 0;
for (input_index, input) in inputs.iter_mut().enumerate() {
let is_primary = input_index == 0;
if !is_primary && input.pages.is_empty() {
continue;
}
let primary_source_xref_entries = if is_primary {
input.source.source_xref_entries()
} else {
BTreeMap::new()
};
let source_has_object_streams = primary_source_xref_entries
.values()
.any(|entry| matches!(entry, XrefEntry::Compressed { .. }));
let remove_stale_generations = is_primary
&& (!preserve_primary_unreferenced || object_stream_mode == ObjectStreamMode::Generate)
&& match object_stream_mode {
ObjectStreamMode::Disable => false,
ObjectStreamMode::Preserve => source_has_object_streams,
ObjectStreamMode::Generate => true,
};
let all = original_page_refs[input_index].clone();
PageDocumentHelper::new(input.source).push_inherited_attributes_to_pages()?;
if !input.pages.is_empty() {
let source_id = input.source.unique_id();
let mut src_labels = input.source.page_labels();
if src_labels.has_page_labels()? {
any_page_labels = true;
}
let src_indices: Vec<i64> = input.pages.iter().map(|&i| i as i64).collect();
label_entries.extend(
src_labels
.labels_for_selection_raw(&src_indices, out_pageno)?
.into_iter()
.map(|(index, label)| RawPageLabelEntry {
index,
source_id,
source_is_primary: is_primary,
label,
}),
);
out_pageno = out_pageno.saturating_add(input.pages.len() as i64);
}
if is_primary {
primary_acroform = discover_primary_acroform(input.source)?;
}
let source_fields = if is_primary {
source_top_level_field_names_without_page_scan(input.source)?
} else {
source_top_level_field_names(input.source)?
};
if is_primary {
primary_acroform.original_field_names.extend(
source_fields
.iter()
.filter_map(|(_, name)| name.as_ref().cloned()),
);
}
let mut selected: Vec<ObjectRef> = Vec::with_capacity(input.pages.len());
for &idx in &input.pages {
let page_ref = *all.get(idx).ok_or_else(|| {
Error::Unsupported(format!(
"page index {idx} out of range (input document has {} pages)",
all.len()
))
})?;
selected.push(page_ref);
}
let mut seen: BTreeSet<ObjectRef> = BTreeSet::new();
let mut unique: Vec<ObjectRef> = Vec::with_capacity(selected.len());
for &page_ref in &selected {
if seen.insert(page_ref) {
unique.push(page_ref);
}
}
if remove_resources[input_index] {
for &page_ref in &unique {
PageObjectHelper::new(page_ref, input.source).remove_unreferenced_resources()?;
}
}
if is_primary {
for &page_ref in &all {
PageDocumentHelper::new(input.source).remove_page(page_ref)?;
}
primary_max_object = input.source.get_object_count()?;
next_foreign_original = primary_max_object.checked_add(1).ok_or_else(|| {
Error::Unsupported("foreign QDF object identity overflows u32".to_owned())
})?;
}
let source_id = input.source.unique_id();
let mut copy_seed = target.take_foreign_object_map(source_id);
if is_primary {
let target_catalog_ref = target
.root_ref()
.expect("Pdf::empty always populates a root catalog");
let primary_catalog = input.source.root_handle()?;
let primary_pages_ref = primary_catalog
.try_get_key(b"/Pages")?
.object_ref()
.expect("page_refs above already required an indirect primary /Pages");
if let Some(primary_catalog_ref) = input.source.root_ref() {
copy_seed.insert(
QpdfObjGen::try_from_object_ref(primary_catalog_ref)?,
target_catalog_ref,
);
}
copy_seed.insert(
QpdfObjGen::try_from_object_ref(primary_pages_ref)?,
pages_root_ref,
);
}
target.set_foreign_object_map(source_id, copy_seed);
for &page_ref in &unique {
let allocation_checkpoint = target.allocation_checkpoint();
let source_page = input.source.get_object_handle(page_ref);
let copied_page = if is_primary {
copy_foreign_object_with_stale_generation_policy(
&mut target,
&source_page,
remove_stale_generations,
)? } else {
target.copy_foreign_object(&source_page)?
};
if copied_page.object_ref().is_none() {
return Err(Error::Missing("merged page missing from foreign copy map"));
}
if !is_primary {
let new_objects = target.allocated_object_refs_after(allocation_checkpoint);
target
.foreign_page_copy_orders
.entry(source_id)
.or_default()
.push((page_ref, new_objects));
}
}
let page_copy_map_before_catalog =
project_foreign_object_map(&target.foreign_object_map_snapshot(source_id));
if is_primary {
wire_primary_catalog(
input.source,
&mut target,
source_id,
remove_stale_generations,
)?; wire_primary_pages_root(
input.source,
&mut target,
source_id,
pages_root_ref,
remove_stale_generations,
)?; wire_primary_trailer(
input.source,
&mut target,
source_id,
remove_stale_generations,
)?; }
let page_copy_map = if is_primary && defer_foreign_acroform_fields {
project_foreign_object_map(&target.foreign_object_map_snapshot(source_id))
} else {
page_copy_map_before_catalog
};
if is_primary && preserve_primary_unreferenced {
for source_object in input.source.canonical_live_object_handles()? {
if source_object.try_is_stream_of_type(b"ObjStm", b"")? {
continue;
}
copy_foreign_object_for_preserve(&mut target, &source_object)?;
}
}
let raw_map = target.take_foreign_object_map(source_id);
let map = project_foreign_object_map(&raw_map);
if is_primary {
install_primary_object_stream_membership(
input.source,
&mut target,
&primary_source_xref_entries,
&map,
)?; }
let mut foreign_originals = BTreeMap::new();
if !is_primary {
let mut target_refs: Vec<ObjectRef> = map.values().copied().collect();
target_refs.sort_unstable();
for target_ref in target_refs {
foreign_originals.insert(target_ref, ObjectRef::new(next_foreign_original, 0));
next_foreign_original = next_foreign_original.checked_add(1).ok_or_else(|| {
Error::Unsupported("foreign QDF object identity overflows u32".to_owned())
})?;
}
}
for (&source_ref, &target_ref) in &map {
let order_key = if is_primary {
WriterObjectOrderKey::primary(source_ref)
} else {
WriterObjectOrderKey::foreign_with_allocation_identity(
target_ref,
foreign_originals
.get(&target_ref)
.copied()
.unwrap_or(target_ref),
)
};
writer_object_order.insert(target_ref, order_key);
}
null_copied_removed_pages(&mut target, &all, &seen, &map)?;
let pages_handle = target.get_object_handle(pages_root_ref);
for &src_ref in &unique {
let copied_page_ref = *map
.get(&src_ref)
.ok_or(Error::Missing("merged page missing from copy map"))?;
let page = target.get_object_handle(copied_page_ref);
page.try_dereference()?;
page.replace_key(b"/Parent", pages_handle.clone())?;
}
let mut orphan_pages: BTreeSet<ObjectRef> = BTreeSet::new();
let mut retained_widgets: BTreeSet<ObjectRef> = BTreeSet::new();
collect_retained_widget_refs(input.source, &seen, &mut retained_widgets)?;
for (src_field_ref, partial_name) in source_fields {
if defer_foreign_acroform_fields && !is_primary {
continue;
}
if page_copy_map.contains_key(&src_field_ref) {
if let Some(&target_ref) = map.get(&src_field_ref) {
let mut visited: BTreeSet<ObjectRef> = BTreeSet::new();
let trimmed = trim_field_kids(
input.source,
&mut target,
src_field_ref,
&seen,
&retained_widgets,
&map,
&mut orphan_pages,
0,
&mut visited,
)?; if let Some(survivors) = trimmed {
if survivors.is_empty() {
continue;
}
rewrite_field_kids(&mut target, src_field_ref, &survivors, &map)?;
}
kept_fields.push(KeptField {
target_ref,
partial_name,
is_primary,
});
}
}
}
for src_page_ref in &orphan_pages {
if let Some(&new_ref) = map.get(src_page_ref) {
target.replace_object(new_ref, ObjectHandle::null())?;
}
}
append_selection_kids(
&mut target,
&selected,
&map,
&mut used,
&mut kids,
&mut writer_object_order,
&mut next_foreign_original,
)?;
target.set_foreign_object_map(source_id, raw_map);
if is_primary && !preserve_primary_unreferenced && !all.is_empty() {
let target_max = target
.canonical_live_object_refs()
.into_iter()
.map(|object| object.number)
.max()
.unwrap_or(0);
if target_max < primary_max_object {
target
.replace_object(ObjectRef::new(primary_max_object, 0), ObjectHandle::null())?;
}
}
}
let root = target.get_object_handle(pages_root_ref);
root.try_dereference()?;
if !root.try_is_dictionary()? {
return Err(Error::Unsupported(
"target /Pages is not a dictionary".to_owned(),
));
}
let kid_handles = kids
.iter()
.map(|&kid| target.get_object_handle(kid))
.collect();
root.replace_key(b"/Kids", ObjectHandle::array(kid_handles))?;
root.replace_key(b"/Count", ObjectHandle::integer(kids.len() as i64))?;
build_merged_acroform(&mut target, &primary_acroform, &kept_fields)?;
target.set_writer_object_order(writer_object_order);
if any_page_labels {
let folded = merge_adjacent_raw_page_labels(label_entries)?;
let copied = copy_raw_page_label_entries(&mut target, &folded)?;
record_primary_label_provenance(&mut target, &folded);
target
.page_labels()
.write_reconstructed_labels_raw(&copied)?;
}
preserve_primary_root_shape(inputs[0].source, &mut target)?;
Ok(target)
}
#[cfg(test)]
mod tests {
use super::super::resource_pruning::RemoveUnreferencedResources;
use super::{
collect_retained_widget_refs, discover_primary_acroform, field_kid_refs,
install_primary_object_stream_membership, merge_documents,
merge_documents_with_resource_decisions_and_preserve_primary,
merge_documents_with_resource_mode_and_preserve_primary, preserve_primary_root_shape,
resolve_field_partial_name, rewrite_field_kids, trim_field_kids, unique_field_name,
widget_page_ref, MergeInput, DEFAULT_MAX_ACROFORM_DEPTH,
};
use crate::{Error, ObjectHandle, ObjectRef, Pdf};
use std::collections::{BTreeMap, BTreeSet};
fn build_pdf(objects: &[(u32, &str)], root: u32) -> Vec<u8> {
let mut out: Vec<u8> = b"%PDF-1.7\n".to_vec();
let mut offsets: BTreeMap<u32, u64> = BTreeMap::new();
let max = objects.iter().map(|(number, _)| *number).max().unwrap_or(0);
for (number, body) in objects {
offsets.insert(*number, out.len() as u64);
out.extend_from_slice(format!("{number} 0 obj\n{body}\nendobj\n").as_bytes());
}
let xref_start = out.len() as u64;
let size = max + 1;
out.extend_from_slice(format!("xref\n0 {size}\n").as_bytes());
out.extend_from_slice(b"0000000000 65535 f \n");
for number in 1..=max {
match offsets.get(&number) {
Some(offset) => {
out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes())
}
None => out.extend_from_slice(b"0000000000 65535 f \n"),
}
}
out.extend_from_slice(
format!(
"trailer\n<< /Size {size} /Root {root} 0 R >>\nstartxref\n{xref_start}\n%%EOF\n"
)
.as_bytes(),
);
out
}
fn used(names: &[&[u8]]) -> BTreeSet<Vec<u8>> {
names.iter().map(|n| n.to_vec()).collect()
}
fn decode_hex_fixture(hex: &str) -> Vec<u8> {
let digits: Vec<u8> = hex.bytes().filter(u8::is_ascii_hexdigit).collect();
digits
.chunks(2)
.map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap())
.collect()
}
#[test]
fn primary_objstm_membership_preserves_an_extends_chain() {
let mut source = Pdf::open_mem_owned(decode_hex_fixture(include_str!(
"../../../../tests/fixtures/compat/objstm-extends-chain.pdf.hex"
)))
.expect("open ObjStm source");
let mut target = Pdf::empty().expect("empty target");
let source_xref_entries = source.source_xref_entries();
let mut copied = BTreeMap::new();
for source_member in [ObjectRef::new(2, 0), ObjectRef::new(3, 0)] {
let copied_handle = target
.make_indirect_object_handle(ObjectHandle::dictionary(Vec::new()))
.expect("allocate copied member");
copied.insert(source_member, copied_handle.object_ref().unwrap());
}
install_primary_object_stream_membership(
&mut source,
&mut target,
&source_xref_entries,
&copied,
)
.expect("install source membership");
let member = *copied.values().next().expect("copied member");
let mut target_membership = BTreeMap::new();
target.get_object_stream_data(&mut target_membership);
let target_container = *target_membership
.get(&member.number)
.expect("copied member must have a compressed source row");
let stream_handle = target.get_object_handle(ObjectRef::new(target_container, 0));
stream_handle.try_is_scalar().unwrap();
let extends = stream_handle
.as_stream_dict()
.unwrap()
.try_get_key(b"/Extends")
.unwrap()
.object_ref()
.expect("source ObjStm /Extends must remain indirect");
assert_ne!(ObjectRef::new(target_container, 0), extends);
}
#[test]
fn direct_primary_root_removes_the_temporary_target_catalog() {
let mut source = Pdf::open_mem_owned(
include_bytes!("../../../../tests/fixtures/compat/direct-root-one-page.pdf").to_vec(),
)
.expect("open direct-root source");
assert_eq!(source.root_ref(), None);
let mut target = Pdf::empty().expect("empty merge target");
assert!(target.root_ref().is_some());
preserve_primary_root_shape(&mut source, &mut target)
.expect("preserve direct primary root shape");
assert_eq!(target.root_ref(), None);
assert!(target
.root_handle()
.expect("direct target Catalog")
.try_has_key(b"/Pages")
.expect("direct target Catalog keys"));
}
#[test]
fn page_merge_production_route_has_no_legacy_borrowed_resolution() {
let production = include_str!("page_merge.rs")
.split_once("#[cfg(test)]")
.expect("page_merge test module marker")
.0;
assert_eq!(
production.matches("resolve_borrowed").count(),
0,
"page_merge production must use the canonical ObjectHandle resolver"
);
}
#[test]
fn primary_field_snapshot_does_not_scan_pages_before_page_job_removes_them() {
let bytes = build_pdf(
&[
(
1,
"<< /Type /Catalog /Pages 2 0 R /AcroForm 5 0 R >>",
),
(2, "<< /Type /Pages /Count 1 /Kids [3 0 R] >>"),
(
3,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [<< /Type /Annot /Subtype /Widget /T (Direct) /Rect [0 0 10 10] >>] >>",
),
(5, "<< /Fields [] >>"),
],
1,
);
let mut source = Pdf::open_mem_owned(bytes).expect("open source");
discover_primary_acroform(&mut source).expect("snapshot primary AcroForm");
assert!(source.repair_diagnostics().entries().is_empty());
}
#[test]
fn merge_skips_page_reads_for_an_unused_secondary() {
let primary = build_pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Count 1 /Kids [3 0 R] >>"),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
],
1,
);
let mut primary = Pdf::open_mem_owned(primary).expect("open primary");
let mut secondary = Pdf::empty().expect("open unused secondary");
secondary.trailer().remove_key(b"/Root");
let mut inputs = [
MergeInput {
source: &mut primary,
pages: vec![0],
},
MergeInput {
source: &mut secondary,
pages: Vec::new(),
},
];
let mut merged = merge_documents(&mut inputs).expect("unused secondary is ignored");
assert_eq!(
crate::pages::page_refs(&mut merged)
.expect("read merged pages")
.len(),
1
);
}
#[test]
fn precomputed_resource_decisions_must_cover_every_merge_input() {
let mut source = Pdf::empty().expect("empty source");
let mut inputs = [MergeInput {
source: &mut source,
pages: vec![0],
}];
assert!(matches!(
merge_documents_with_resource_decisions_and_preserve_primary(
&mut inputs,
&[],
false,
),
Err(Error::Internal(message))
if message == "page merge resource decisions do not match source count"
));
}
#[test]
fn resource_mode_wrapper_evaluates_yes_and_auto_decisions() {
for mode in [
RemoveUnreferencedResources::Yes,
RemoveUnreferencedResources::Auto,
] {
let mut source = Pdf::open_mem_owned(build_pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Count 1 /Kids [3 0 R] >>"),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
],
1,
))
.expect("one-page source");
let mut inputs = [MergeInput {
source: &mut source,
pages: vec![0],
}];
let mut merged =
merge_documents_with_resource_mode_and_preserve_primary(&mut inputs, mode, false)
.expect("resource mode merge");
assert_eq!(crate::pages::page_refs(&mut merged).unwrap().len(), 1);
}
}
#[test]
fn unique_field_name_keeps_unused_base() {
assert_eq!(unique_field_name(b"name", &used(&[])), b"name".to_vec());
assert_eq!(
unique_field_name(b"name", &used(&[b"email"])),
b"name".to_vec()
);
}
#[test]
fn unique_field_name_appends_plus_one_on_collision() {
assert_eq!(
unique_field_name(b"name", &used(&[b"name"])),
b"name+1".to_vec()
);
}
#[test]
fn unique_field_name_finds_first_unused_in_sequence() {
assert_eq!(
unique_field_name(b"name", &used(&[b"name", b"name+1"])),
b"name+2".to_vec()
);
}
#[test]
fn unique_field_name_reresolves_colliding_candidate() {
assert_eq!(
unique_field_name(b"name+1", &used(&[b"name", b"name+1"])),
b"name+1+1".to_vec()
);
}
fn resolved_handle<R: std::io::Read + std::io::Seek>(
pdf: &mut Pdf<R>,
object_ref: ObjectRef,
) -> ObjectHandle {
let handle = pdf.get_object_handle(object_ref);
handle.try_is_scalar().expect("resolve object");
handle
}
#[test]
fn doc_level_page_root_is_null_boundary_without_contents_in_closure() {
let bytes = build_pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R /OpenAction 4 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>"),
(3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"),
(
4,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 10 0 R >>",
),
(10, "<< /Length 4 >>\nstream\nDROP\nendstream"),
],
1,
);
let mut merge_source = Pdf::open_mem_owned(bytes.clone()).unwrap();
let mut inputs = [MergeInput {
source: &mut merge_source,
pages: vec![0],
}];
let mut merged = merge_documents(&mut inputs).unwrap();
let catalog_ref = merged.root_ref().unwrap();
let catalog = resolved_handle(&mut merged, catalog_ref);
assert!(
catalog.as_dictionary().is_some(),
"catalog must be a dictionary"
);
let open_action_ref = catalog
.try_get_key(b"/OpenAction")
.unwrap()
.object_ref()
.expect("indirect /OpenAction carrier is retained");
assert!(
resolved_handle(&mut merged, open_action_ref).is_null(),
"the unselected page root is copied and nulled"
);
}
#[test]
fn merge_documents_reserves_unselected_primary_names_regardless_of_string_encoding() {
let primary_bytes = build_pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R /AcroForm 6 0 R >>"),
(2, "<< /Type /Pages /Count 2 /Kids [3 0 R 4 0 R] >>"),
(
3,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [5 0 R] >>",
),
(
4,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [7 0 R] >>",
),
(
5,
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (F) /Rect [0 0 10 10] /P 3 0 R >>",
),
(6, "<< /Fields [5 0 R 7 0 R] >>"),
(
7,
"<< /Type /Annot /Subtype /Widget /FT /Tx /T <FEFF0046002B0031> \
/Rect [0 0 10 10] /P 4 0 R >>",
),
],
1,
);
let secondary_bytes = build_pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R /AcroForm 5 0 R >>"),
(2, "<< /Type /Pages /Count 1 /Kids [3 0 R] >>"),
(
3,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [4 0 R] >>",
),
(
4,
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (F) /Rect [0 0 10 10] /P 3 0 R >>",
),
(5, "<< /Fields [4 0 R] >>"),
],
1,
);
let mut primary = Pdf::open_mem_owned(primary_bytes).unwrap();
let mut secondary = Pdf::open_mem_owned(secondary_bytes).unwrap();
let mut inputs = [
MergeInput {
source: &mut primary,
pages: vec![0],
},
MergeInput {
source: &mut secondary,
pages: vec![0],
},
];
let mut merged = merge_documents(&mut inputs).unwrap();
let catalog_ref = merged.root_ref().unwrap();
let catalog = resolved_handle(&mut merged, catalog_ref);
assert!(
catalog.as_dictionary().is_some(),
"catalog must be a dictionary"
);
let acroform_ref = catalog
.try_get_key(b"/AcroForm")
.unwrap()
.object_ref()
.expect("/AcroForm");
let acroform = resolved_handle(&mut merged, acroform_ref);
assert!(
acroform.as_dictionary().is_some(),
"AcroForm must be a dictionary"
);
let fields = acroform
.try_get_key(b"/Fields")
.unwrap()
.as_array()
.expect("/Fields array");
let names: Vec<Vec<u8>> = fields
.iter()
.map(|field| {
let field_ref = field.object_ref().expect("field is an indirect ref");
let field_dict = resolved_handle(&mut merged, field_ref);
assert!(
field_dict.as_dictionary().is_some(),
"field must be a dictionary"
);
let name = field_dict.try_get_key(b"/T").unwrap();
name.try_is_scalar().expect("resolve /T");
name.as_string().expect("/T string")
})
.collect();
assert_eq!(
names,
vec![b"F".to_vec(), b"F+2".to_vec()],
"the secondary's colliding field must resolve to F+2, matching qpdf's \
getUTF8Value()-decoded collision index, not F+1 from an undecoded byte \
comparison against the UTF-16BE-encoded reservation"
);
}
#[test]
fn field_kid_and_widget_page_routes_use_resolved_handle_refs() {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/compat/form-fields-and-annotations-p-and-inline.pdf");
let mut source = Pdf::open_mem_owned(std::fs::read(path).expect("fixture exists")).unwrap();
let kids = field_kid_refs(&mut source, ObjectRef::new(5, 0))
.expect("field kids")
.expect("non-terminal field");
assert_eq!(
kids,
vec![
ObjectRef::new(12, 0),
ObjectRef::new(13, 0),
ObjectRef::new(14, 0)
]
);
assert_eq!(
widget_page_ref(&mut source, ObjectRef::new(3, 0)).expect("widget page"),
Some(ObjectRef::new(10, 0))
);
let mut retained = BTreeSet::new();
collect_retained_widget_refs(
&mut source,
&BTreeSet::from([ObjectRef::new(10, 0)]),
&mut retained,
)
.expect("retained widgets");
assert!(retained.contains(&ObjectRef::new(12, 0)));
let mut target = Pdf::empty().expect("empty target");
let target_field = target
.make_indirect_object_handle(ObjectHandle::dictionary(Vec::new()))
.expect("target field");
let target_kid = target
.make_indirect_object_handle(ObjectHandle::dictionary(Vec::new()))
.expect("target kid");
let target_field_ref = target_field.object_ref().expect("target field ref");
let target_kid_ref = target_kid.object_ref().expect("target kid ref");
let map = BTreeMap::from([
(ObjectRef::new(5, 0), target_field_ref),
(kids[0], target_kid_ref),
]);
rewrite_field_kids(&mut target, ObjectRef::new(5, 0), &[kids[0]], &map)
.expect("rewrite copied field kids");
target_field
.try_is_scalar()
.expect("resolve rewritten field");
assert_eq!(
target_field
.try_get_key(b"/Kids")
.expect("kids key")
.as_array()
.expect("kids array")
.len(),
1
);
}
#[test]
fn field_helpers_return_none_for_a_non_dictionary_reference() {
let mut source = Pdf::empty().expect("empty source");
let non_dict = source
.make_indirect_object_handle(ObjectHandle::integer(42))
.expect("non-dictionary indirect object");
let non_dict_ref = non_dict.object_ref().expect("non-dictionary ref");
assert_eq!(
resolve_field_partial_name(&mut source, non_dict_ref).unwrap(),
None,
"a field ref that resolves to a non-dictionary must yield no /T"
);
assert_eq!(
field_kid_refs(&mut source, non_dict_ref).unwrap(),
None,
"a field ref that resolves to a non-dictionary must yield no kids"
);
assert_eq!(
widget_page_ref(&mut source, non_dict_ref).unwrap(),
None,
"a widget ref that resolves to a non-dictionary must yield no page"
);
}
#[test]
fn trim_field_kids_propagates_the_depth_guard_through_recursion() {
let bytes = build_pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, "<< /Type /Page /Parent 2 0 R >>"),
(4, "<< /Fields [5 0 R] >>"),
(5, "<< /FT /Tx /T (Parent) /Kids [6 0 R] >>"),
(6, "<< /FT /Tx /T (Child) >>"),
],
1,
);
let mut source = Pdf::open_mem_owned(bytes).expect("open source");
let mut target = Pdf::empty().expect("empty target");
let mut orphan_pages = BTreeSet::new();
let mut visited = BTreeSet::new();
let err = trim_field_kids(
&mut source,
&mut target,
ObjectRef::new(5, 0),
&BTreeSet::new(),
&BTreeSet::new(),
&BTreeMap::new(),
&mut orphan_pages,
DEFAULT_MAX_ACROFORM_DEPTH,
&mut visited,
)
.unwrap_err();
assert!(
matches!(err, crate::Error::Unsupported(ref message)
if message.contains("AcroForm field tree depth exceeds maximum")),
"recursing past the depth cap must surface the guard's error, not swallow it: {err:?}"
);
}
#[test]
fn trim_field_kids_treats_a_kids_cycle_as_no_survivors() {
let bytes = build_pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, "<< /Type /Page /Parent 2 0 R >>"),
(4, "<< /Fields [5 0 R] >>"),
(5, "<< /FT /Tx /T (Cyclic) /Kids [5 0 R] >>"),
],
1,
);
let mut source = Pdf::open_mem_owned(bytes).expect("open source");
let mut target = Pdf::empty().expect("empty target");
let mut orphan_pages = BTreeSet::new();
let mut visited = BTreeSet::new();
let survivors = trim_field_kids(
&mut source,
&mut target,
ObjectRef::new(5, 0),
&BTreeSet::new(),
&BTreeSet::new(),
&BTreeMap::new(),
&mut orphan_pages,
0,
&mut visited,
)
.expect("a self-referential /Kids must not hang or error");
assert_eq!(
survivors,
Some(Vec::new()),
"the cyclic re-entry must be treated as a childless sub-field, not retried"
);
}
#[test]
fn trim_field_kids_drops_a_dangling_widget_without_a_page_to_null() {
let bytes = build_pdf(
&[
(1, "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>"),
(2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>"),
(3, "<< /Type /Page /Parent 2 0 R >>"),
(4, "<< /Fields [5 0 R] >>"),
(5, "<< /FT /Tx /T (Field) /Kids [6 0 R] >>"),
(6, "<< /Subtype /Widget >>"),
],
1,
);
let mut source = Pdf::open_mem_owned(bytes).expect("open source");
let mut target = Pdf::empty().expect("empty target");
let mut orphan_pages = BTreeSet::new();
let mut visited = BTreeSet::new();
let survivors = trim_field_kids(
&mut source,
&mut target,
ObjectRef::new(5, 0),
&BTreeSet::new(),
&BTreeSet::new(),
&BTreeMap::new(),
&mut orphan_pages,
0,
&mut visited,
)
.expect("trim must not error");
assert_eq!(
survivors,
Some(Vec::new()),
"a widget with no /P and no /Annots retention must not survive"
);
assert!(
orphan_pages.is_empty(),
"a /P-less dropped widget carries no page to null"
);
}
}