use crate::object_handle::ObjectHandle;
use crate::pages::tree_rebuild::RebuildResult;
use crate::{ObjectRef, Pdf, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Seek};
fn raw_child(parent: &ObjectHandle, key: &[u8]) -> Result<Option<ObjectHandle>> {
Ok(parent
.try_as_dictionary()?
.and_then(|entries| entries.get(key).cloned()))
}
pub fn drop_objr_obj_annot_dangling_p<R: Read + Seek>(
pdf: &mut Pdf<R>,
result: &RebuildResult,
objr_obj_targets: &[ObjectRef],
) -> Result<()> {
let surviving: BTreeMap<ObjectRef, ObjectRef> = result
.ref_map
.iter()
.filter_map(|(&old, new_refs)| new_refs.first().map(|&new| (old, new)))
.collect();
let removed_pages = &result.removed_pages;
let mut visited: BTreeSet<ObjectRef> = BTreeSet::new();
for &start in objr_obj_targets {
if !visited.insert(start) {
continue;
}
let annot = pdf.get_object_handle(start);
annot.try_dereference()?;
if !annot.try_is_dictionary()? {
continue;
}
remap_or_drop_annot_p(pdf, &annot, &surviving, removed_pages)?;
}
Ok(())
}
fn remap_or_drop_annot_p<R: Read + Seek>(
pdf: &mut Pdf<R>,
annot: &ObjectHandle,
surviving: &BTreeMap<ObjectRef, ObjectRef>,
removed_pages: &BTreeSet<ObjectRef>,
) -> Result<bool> {
let Some(p) = raw_child(annot, b"/P")? else {
return Ok(false);
};
let Some(page_ref) = p.object_ref() else {
return Ok(false);
};
if !surviving.contains_key(&page_ref) && !removed_pages.contains(&page_ref) {
return Ok(false);
}
match surviving.get(&page_ref) {
Some(&new) => {
if new != page_ref {
annot.replace_key(b"/P", pdf.get_object_handle(new))?;
return Ok(true);
}
Ok(false)
}
None => {
annot.remove_key(b"/P");
Ok(true)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{ObjectHandle, Pdf};
use std::collections::BTreeMap;
use std::io::Cursor;
fn build_pdf(objs: &BTreeMap<u32, String>) -> Vec<u8> {
let mut raw: Vec<u8> = b"%PDF-1.5\n".to_vec();
let mut offs: BTreeMap<u32, usize> = BTreeMap::new();
for (n, body) in objs {
offs.insert(*n, raw.len());
raw.extend_from_slice(format!("{n} 0 obj\n{body}\nendobj\n").as_bytes());
}
let max_num = *objs.keys().max().unwrap();
let xref_pos = raw.len();
raw.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", max_num + 1).as_bytes());
for i in 1..=max_num {
if let Some(&off) = offs.get(&i) {
raw.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes());
} else {
raw.extend_from_slice(b"0000000000 65535 f \n");
}
}
raw.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n",
max_num + 1
)
.as_bytes(),
);
raw
}
fn open(objs: &BTreeMap<u32, String>) -> Pdf<Cursor<Vec<u8>>> {
Pdf::open(Cursor::new(build_pdf(objs))).expect("open fixture")
}
fn base() -> BTreeMap<u32, String> {
let mut objs: BTreeMap<u32, String> = BTreeMap::new();
objs.insert(1, "<< /Type /Catalog /Pages 2 0 R >>".into());
objs.insert(
2,
"<< /Type /Pages /Kids [3 0 R 4 0 R 5 0 R] /Count 3 >>".into(),
);
for n in 3..=5 {
objs.insert(
n,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".into(),
);
}
objs
}
fn keep_3_and_5() -> RebuildResult {
let mut ref_map: BTreeMap<ObjectRef, Vec<ObjectRef>> = BTreeMap::new();
ref_map.insert(ObjectRef::new(3, 0), vec![ObjectRef::new(3, 0)]);
ref_map.insert(ObjectRef::new(5, 0), vec![ObjectRef::new(5, 0)]);
RebuildResult {
new_kids: vec![ObjectRef::new(3, 0), ObjectRef::new(5, 0)],
ref_map,
removed_pages: [ObjectRef::new(4, 0)].into_iter().collect(),
..Default::default()
}
}
fn annot(pdf: &mut Pdf<Cursor<Vec<u8>>>, num: u32) -> ObjectHandle {
let annot = pdf.get_object_handle(ObjectRef::new(num, 0));
annot.try_is_scalar().expect("resolve annot");
assert!(
annot.as_dictionary().is_some(),
"annot object is not a dictionary"
);
annot
}
#[test]
fn dangling_p_to_removed_page_dropped() {
let mut objs = base();
objs.insert(
30,
"<< /Type /Annot /Subtype /Text /P 4 0 R /Rect [0 0 10 10] >>".into(),
);
let mut pdf = open(&objs);
drop_objr_obj_annot_dangling_p(&mut pdf, &keep_3_and_5(), &[ObjectRef::new(30, 0)])
.expect("drop");
assert!(
!annot(&mut pdf, 30).try_has_key(b"/P").unwrap(),
"removed-page /P must be dropped"
);
}
#[test]
fn p_to_surviving_page_kept() {
let mut objs = base();
objs.insert(
30,
"<< /Type /Annot /Subtype /Text /P 3 0 R /Rect [0 0 10 10] >>".into(),
);
let mut pdf = open(&objs);
drop_objr_obj_annot_dangling_p(&mut pdf, &keep_3_and_5(), &[ObjectRef::new(30, 0)])
.expect("drop");
assert!(
annot(&mut pdf, 30).try_get_key(b"/P").unwrap().object_ref()
== Some(ObjectRef::new(3, 0)),
"surviving-page /P must be kept",
);
}
#[test]
fn p_to_surviving_page_remapped_to_new_ref() {
let mut objs = base();
objs.insert(
30,
"<< /Type /Annot /Subtype /Text /P 3 0 R /Rect [0 0 10 10] >>".into(),
);
let mut pdf = open(&objs);
let mut ref_map: BTreeMap<ObjectRef, Vec<ObjectRef>> = BTreeMap::new();
ref_map.insert(ObjectRef::new(3, 0), vec![ObjectRef::new(7, 0)]);
let result = RebuildResult {
new_kids: vec![ObjectRef::new(7, 0)],
ref_map,
..Default::default()
};
drop_objr_obj_annot_dangling_p(&mut pdf, &result, &[ObjectRef::new(30, 0)]).expect("drop");
assert!(
annot(&mut pdf, 30).try_get_key(b"/P").unwrap().object_ref()
== Some(ObjectRef::new(7, 0)),
"surviving-page /P must be remapped to the new ref",
);
}
#[test]
fn target_without_p_left_unchanged() {
let mut objs = base();
objs.insert(
30,
"<< /Type /Annot /Subtype /Text /Rect [0 0 10 10] >>".into(),
);
let mut pdf = open(&objs);
drop_objr_obj_annot_dangling_p(&mut pdf, &keep_3_and_5(), &[ObjectRef::new(30, 0)])
.expect("drop");
let a = annot(&mut pdf, 30);
assert!(
!a.try_has_key(b"/P").unwrap() && a.try_has_key(b"/Subtype").unwrap(),
"non-/P annot untouched"
);
}
#[test]
fn empty_targets_is_noop() {
let mut objs = base();
objs.insert(30, "<< /Type /Annot /Subtype /Text /P 4 0 R >>".into());
let mut pdf = open(&objs);
drop_objr_obj_annot_dangling_p(&mut pdf, &keep_3_and_5(), &[]).expect("noop");
assert!(
annot(&mut pdf, 30).try_has_key(b"/P").unwrap(),
"no targets ⇒ no change"
);
}
#[test]
fn shared_target_deduped_non_identity() {
let mut objs = base();
objs.insert(
7,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".into(),
);
objs.insert(
30,
"<< /Type /Annot /Subtype /Text /P 3 0 R /Rect [0 0 10 10] >>".into(),
);
let mut pdf = open(&objs);
let mut ref_map: BTreeMap<ObjectRef, Vec<ObjectRef>> = BTreeMap::new();
ref_map.insert(ObjectRef::new(3, 0), vec![ObjectRef::new(7, 0)]);
let result = RebuildResult {
new_kids: vec![ObjectRef::new(7, 0)],
ref_map,
..Default::default()
};
drop_objr_obj_annot_dangling_p(
&mut pdf,
&result,
&[ObjectRef::new(30, 0), ObjectRef::new(30, 0)],
)
.expect("drop");
assert!(
annot(&mut pdf, 30).try_get_key(b"/P").unwrap().object_ref()
== Some(ObjectRef::new(7, 0)),
"remapped /P 7 must survive the duplicate target; dedup guard prevents re-drop",
);
}
#[test]
fn non_dict_target_skipped() {
let mut objs = base();
objs.insert(30, "42".into());
let mut pdf = open(&objs);
drop_objr_obj_annot_dangling_p(&mut pdf, &keep_3_and_5(), &[ObjectRef::new(30, 0)])
.expect("non-dict target skipped");
let target = pdf.get_object_handle(ObjectRef::new(30, 0));
target.try_is_scalar().expect("resolve");
assert_eq!(
target.as_integer(),
Some(42),
"a non-dict OBJR /Obj target must be left unchanged",
);
}
#[test]
fn unresolved_target_skipped() {
let mut pdf = open(&base());
drop_objr_obj_annot_dangling_p(&mut pdf, &keep_3_and_5(), &[ObjectRef::new(4096, 0)])
.expect("an unresolved OBJR target must be skipped");
}
#[test]
fn non_reference_p_left_unchanged() {
let mut objs = base();
objs.insert(
30,
"<< /Type /Annot /Subtype /Text /P 999 /Rect [0 0 10 10] >>".into(),
);
let mut pdf = open(&objs);
drop_objr_obj_annot_dangling_p(&mut pdf, &keep_3_and_5(), &[ObjectRef::new(30, 0)])
.expect("drop");
assert!(
annot(&mut pdf, 30).try_get_key(b"/P").unwrap().as_integer() == Some(999),
"a non-reference /P must be left unchanged",
);
}
#[test]
fn p_resolving_to_non_page_left_unchanged() {
let mut objs = base();
objs.insert(
30,
"<< /Type /Annot /Subtype /Text /P 60 0 R /Rect [0 0 10 10] >>".into(),
);
objs.insert(60, "<< /Type /StructElem /S /P >>".into());
let mut pdf = open(&objs);
drop_objr_obj_annot_dangling_p(&mut pdf, &keep_3_and_5(), &[ObjectRef::new(30, 0)])
.expect("drop");
assert!(
annot(&mut pdf, 30).try_get_key(b"/P").unwrap().object_ref()
== Some(ObjectRef::new(60, 0)),
"a /P resolving to a non-page object must be left unchanged",
);
}
#[test]
fn p_resolving_to_orphan_page_left_unchanged() {
let mut objs = base();
objs.insert(
30,
"<< /Type /Annot /Subtype /Text /P 60 0 R /Rect [0 0 10 10] >>".into(),
);
objs.insert(
60,
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>".into(),
);
let mut pdf = open(&objs);
drop_objr_obj_annot_dangling_p(&mut pdf, &keep_3_and_5(), &[ObjectRef::new(30, 0)])
.expect("orphan-page /P");
assert!(
annot(&mut pdf, 30).try_get_key(b"/P").unwrap().object_ref()
== Some(ObjectRef::new(60, 0)),
"a /P to a page outside the original page tree must be left unchanged",
);
}
#[test]
fn p_to_nulled_removed_page_still_dropped() {
let mut objs = base();
objs.insert(4, "null".into());
objs.insert(
30,
"<< /Type /Annot /Subtype /Text /P 4 0 R /Rect [0 0 10 10] >>".into(),
);
let mut pdf = open(&objs);
drop_objr_obj_annot_dangling_p(&mut pdf, &keep_3_and_5(), &[ObjectRef::new(30, 0)])
.expect("drop");
assert!(
!annot(&mut pdf, 30).try_has_key(b"/P").unwrap(),
"a /P to a removed page nulled by the dest null-out pass must still be dropped",
);
}
#[test]
fn stream_target_skipped() {
let mut objs = base();
objs.insert(30, "<< /Length 3 >>\nstream\nabc\nendstream".into());
let mut pdf = open(&objs);
drop_objr_obj_annot_dangling_p(&mut pdf, &keep_3_and_5(), &[ObjectRef::new(30, 0)])
.expect("stream target skipped without error");
let target = pdf.get_object_handle(ObjectRef::new(30, 0));
target.try_is_scalar().expect("resolve stream target");
assert!(
target.as_stream_dict().is_some(),
"a stream OBJR /Obj target must be left unchanged"
);
}
}