use crate::page_tree_rebuild::RebuildResult;
use crate::ref_chain::resolve_ref_chain;
use crate::{Dictionary, Object, ObjectRef, Pdf, Result};
use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Seek};
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 mut visited: BTreeSet<ObjectRef> = BTreeSet::new();
for &start in objr_obj_targets {
if !visited.insert(start) {
continue;
}
let (concrete, terminal) = resolve_ref_chain(pdf, &Object::Reference(start))?;
let annot_ref = terminal.unwrap_or(start);
if annot_ref != start && !visited.insert(annot_ref) {
continue;
}
let Some(mut annot) = concrete.into_dict() else {
continue;
};
if remap_or_drop_annot_p(pdf, &mut annot, &surviving)? {
pdf.set_object(annot_ref, Object::Dictionary(annot));
}
}
Ok(())
}
fn remap_or_drop_annot_p<R: Read + Seek>(
pdf: &mut Pdf<R>,
annot: &mut Dictionary,
surviving: &BTreeMap<ObjectRef, ObjectRef>,
) -> Result<bool> {
let p_ref = match annot.get("P") {
Some(Object::Reference(r)) => *r,
_ => return Ok(false),
};
let (p_concrete, terminal) = resolve_ref_chain(pdf, &Object::Reference(p_ref))?;
let page_ref = terminal.unwrap_or(p_ref);
if !is_page_dict(&p_concrete) && !matches!(p_concrete, Object::Null) {
return Ok(false);
}
match surviving.get(&page_ref) {
Some(&new) => {
if new != page_ref {
annot.insert("P", Object::Reference(new));
return Ok(true);
}
Ok(false)
}
None => {
annot.remove("P");
Ok(true)
}
}
}
fn is_page_dict(obj: &Object) -> bool {
obj.as_dict()
.and_then(|d| d.get("Type"))
.is_some_and(|t| matches!(t, Object::Name(n) if n == b"Page"))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::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>>> {
let mut pdf = Pdf::open(Cursor::new(build_pdf(objs))).expect("open fixture");
for (&number, body) in objs {
if let Ok(Object::Reference(target)) = crate::parse_object(body.as_bytes()) {
pdf.set_object(ObjectRef::new(number, 0), Object::Reference(target));
}
}
pdf
}
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,
..Default::default()
}
}
fn annot(pdf: &mut Pdf<Cursor<Vec<u8>>>, num: u32) -> Dictionary {
pdf.resolve(ObjectRef::new(num, 0))
.expect("resolve annot")
.into_dict()
.expect("annot object is a dictionary")
}
#[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).get("P").is_none(),
"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!(
matches!(annot(&mut pdf, 30).get("P"), Some(Object::Reference(r)) if r.number == 3),
"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!(
matches!(annot(&mut pdf, 30).get("P"), Some(Object::Reference(r)) if r.number == 7),
"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.get("P").is_none() && a.get("Subtype").is_some(),
"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).get("P").is_some(),
"no targets ⇒ no change"
);
}
#[test]
fn chained_obj_and_p_normalized() {
let mut objs = base();
objs.insert(
30,
"<< /Type /Annot /Subtype /Text /P 50 0 R /Rect [0 0 10 10] >>".into(),
);
objs.insert(40, "30 0 R".into());
objs.insert(50, "4 0 R".into());
let mut pdf = open(&objs);
drop_objr_obj_annot_dangling_p(&mut pdf, &keep_3_and_5(), &[ObjectRef::new(40, 0)])
.expect("drop");
assert!(
annot(&mut pdf, 30).get("P").is_none(),
"chained /P to removed page must drop"
);
}
#[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!(
matches!(annot(&mut pdf, 30).get("P"), Some(Object::Reference(r)) if r.number == 7),
"remapped /P 7 must survive the duplicate target; dedup guard prevents re-drop",
);
}
#[test]
fn distinct_starts_to_same_terminal_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(),
);
objs.insert(40, "30 0 R".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(40, 0)],
)
.expect("drop");
assert!(
matches!(annot(&mut pdf, 30).get("P"), Some(Object::Reference(r)) if r.number == 7),
"remapped /P 7 must survive a distinct start reaching the same terminal",
);
}
#[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");
assert_eq!(
pdf.resolve(ObjectRef::new(30, 0)).expect("resolve"),
Object::Integer(42),
"a non-dict OBJR /Obj target must be left unchanged",
);
}
#[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!(
matches!(annot(&mut pdf, 30).get("P"), Some(Object::Integer(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!(
matches!(annot(&mut pdf, 30).get("P"), Some(Object::Reference(r)) if r.number == 60),
"a /P resolving to a non-page object 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).get("P").is_none(),
"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");
assert!(
matches!(pdf.resolve(ObjectRef::new(30, 0)), Ok(Object::Stream(_))),
"a stream OBJR /Obj target must be left unchanged",
);
}
}