PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
fix(annot,redact): inline replies and pop-ups go with what they point at
alehel195a2c9bab34
diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rsindex d05c2ca41..b235df7cd 100644--- a/crates/annot/src/lib.rs+++ b/crates/annot/src/lib.rs@@ -1650,23 +1650,40 @@ pub fn delete_annotation(doc: &mut Document, page: usize, index: usize) -> Resulif let Some(r) = target.as_ref() {unlocked(doc, r)?;}- let doomed = with_replies_and_popups(doc, &list, target.as_ref());- let kept: Vec<Object> =- list.into_iter().enumerate().filter(|(i, e)| *i != index && !e.as_ref().is_some_and(|r| doomed.contains(&r))).map(|(_, e)| e).collect();+ // An inline comment has no reference to collect; the pop-up it names still goes.+ let seed = target.as_ref().or_else(|| target.as_dict().and_then(|d| d.reference(b"Popup")));+ let doomed = with_replies_and_popups(doc, &list, seed);+ let kept: Vec<Object> = list.into_iter().enumerate().filter(|(i, e)| *i != index && !goes_with(e, &doomed)).map(|(_, e)| e).collect();Ok(set_annots(doc, p, kept)?)}+/// Whether the `/Annots` entry `entry` goes with `going` (from [`with_replies_and_popups`]): it is+/// one of them, or it is written inline (a file can, though the standard asks for references) and+/// replies to (`/IRT`) or pops up for (`/Parent`) one of them. An inline entry has no reference+/// for the walk to collect, so it is matched here.+pub fn goes_with(entry: &Object, going: &HashSet<ObjRef>) -> bool {+ match entry.as_ref() {+ Some(r) => going.contains(&r),+ None => entry.as_dict().is_some_and(|d| [d.reference(b"IRT"), d.reference(b"Parent")].into_iter().flatten().any(|r| going.contains(&r))),+ }+}+/// `doomed` and what goes with it, as Acrobat deletes a comment: the entries of `list` (one or/// more pages' `/Annots`) that reply to (`/IRT`) or pop up for (`/Parent`) anything going, their-/// own replies, and the pop-ups going annotations name (`/Popup`). Each annotation is visited-/// once, so a long or cyclic chain costs no more than its length.+/// own replies, and the pop-ups going annotations name (`/Popup`). An inline reply has no+/// reference to collect, but the pop-up it names is. Each annotation is visited once, so a long or+/// cyclic chain costs no more than its length. Filter a list with [`goes_with`], which also+/// matches inline entries.pub fn with_replies_and_popups(doc: &Document, list: &[Object], doomed: impl IntoIterator<Item = ObjRef>) -> HashSet<ObjRef> {let mut hanging: HashMap<ObjRef, Vec<ObjRef>> = HashMap::new();- for r in list.iter().filter_map(Object::as_ref) {- let obj = doc.get(r);+ for e in list {+ let obj = doc.resolve(e);let Some(d) = obj.as_dict() else { continue };+ // What goes with the annotation this entry hangs off: the entry, or for an inline one the+ // pop-up it names.+ let Some(goes) = e.as_ref().or_else(|| d.reference(b"Popup")) else { continue };for on in [d.reference(b"IRT"), d.reference(b"Parent")].into_iter().flatten() {- hanging.entry(on).or_default().push(r);+ hanging.entry(on).or_default().push(goes);}}let mut going = HashSet::new();diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rsindex 20cc89b10..71cc44e20 100644--- a/crates/annot/src/tests.rs+++ b/crates/annot/src/tests.rs@@ -229,6 +229,47 @@ fn delete_takes_popup_and_reply_chain() {assert_eq!(delete_annotation(&mut doc, 0, 9), Err(AnnotError::NoSuchAnnotation { page: 0, index: 9 }));}+/// A reply or pop-up written inline in `/Annots` (a file can, though the standard asks for+/// references) goes with the comment it points at, and so does a pop-up an inline reply or an+/// inline comment names. An unrelated inline comment stays until it is deleted itself.+#[test]+fn delete_takes_inline_replies_and_popups() {+ let mut doc = fixture();+ let mut popup = |note: &str| {+ let mut d = Dict::new();+ d.set(b"Type".to_vec(), Object::name("Annot"));+ d.set(b"Subtype".to_vec(), Object::name("Popup"));+ d.set(b"Contents".to_vec(), PdfString::text(note));+ doc.add(Object::Dict(d))+ };+ let (reply_popup, square_popup) = (popup("of the reply"), popup("of the square"));+ let inline = |subtype: &str, links: &[(&[u8], ObjRef)]| {+ let mut d = Dict::new();+ d.set(b"Type".to_vec(), Object::name("Annot"));+ d.set(b"Subtype".to_vec(), Object::name(subtype));+ links.iter().for_each(|(key, r)| d.set(key.to_vec(), Object::Ref(*r)));+ Object::Dict(d)+ };+ let stamp = ObjRef::new(6, 0);+ let entries = vec![+ Object::Ref(stamp),+ inline("Text", &[(b"IRT", stamp), (b"Popup", reply_popup)]),+ Object::Ref(reply_popup),+ inline("Popup", &[(b"Parent", stamp)]),+ inline("Square", &[(b"Popup", square_popup)]),+ Object::Ref(square_popup),+ ];+ doc.set(ObjRef::new(5, 0), Object::Array(entries));+ let subtypes = |doc: &Document| -> Vec<String> {+ list(doc, 1).iter().map(|d| String::from_utf8_lossy(d.name(b"Subtype").unwrap()).into_owned() + ":" + &text(d, b"Contents")).collect()+ };+ delete_annotation(&mut doc, 1, 0).unwrap();+ let mut doc = reopen(&doc);+ assert_eq!(subtypes(&doc), ["Square:", "Popup:of the square"]);+ delete_annotation(&mut doc, 1, 0).unwrap();+ assert!(subtypes(&reopen(&doc)).is_empty(), "the inline comment's pop-up went with it");+}+#[test]fn deleting_the_last_comment_removes_annots() {let mut doc = fixture();diff --git a/crates/redact/src/lib.rs b/crates/redact/src/lib.rsindex f4e22d6b3..bdf1db873 100644--- a/crates/redact/src/lib.rs+++ b/crates/redact/src/lib.rs@@ -711,7 +711,7 @@ pub fn clear_marks(doc: &mut Document, pages: Option<&[usize]>) -> Result<usize,let doomed = pdfcraft_annot::with_replies_and_popups(doc, &listed, targets.iter().copied());for p in pdfcraft_model::pages(doc) {let annots = annots_of(doc, &p.dict);- let kept: Vec<Object> = annots.iter().filter(|a| !a.as_ref().is_some_and(|r| doomed.contains(&r))).cloned().collect();+ let kept: Vec<Object> = annots.iter().filter(|a| !pdfcraft_annot::goes_with(a, &doomed)).cloned().collect();// As deleting a comment does: a page whose marks were all it had loses `/Annots` again,// and an indirect array stays the one object the page points to.if kept.len() != annots.len() {diff --git a/crates/redact/src/tests.rs b/crates/redact/src/tests.rsindex 1424656c9..2efe81475 100644--- a/crates/redact/src/tests.rs+++ b/crates/redact/src/tests.rs@@ -1051,8 +1051,15 @@ fn clearing_marks_leaves_the_annotation_list_as_it_was() {let before = doc.get(page);mark(&mut doc, 0, &[[0.0, 0.0, 50.0, 50.0]], "");pdfcraft_annot::add_reply(&mut doc, 0, 0, "a reply", "Tester", &Meta::default()).unwrap();+ // And a reply written inline, as a file can.+ let mut inline = Dict::new();+ inline.set(b"Subtype".to_vec(), Object::name("Text"));+ inline.set(b"IRT".to_vec(), Object::Ref(marks(&doc)[0].obj));+ let mut listed = annots_of(&doc, doc.get(page).as_dict().unwrap());+ listed.push(Object::Dict(inline));+ doc.update_dict(page, |d| d.set(b"Annots".to_vec(), Object::Array(listed))).unwrap();assert_eq!(clear_marks(&mut doc, None), Ok(1), "one mark");- assert_eq!(doc.get(page), before, "the page has no /Annots again: the reply went with its mark");+ assert_eq!(doc.get(page), before, "the page has no /Annots again: both replies went with their mark");let mut doc = pdf(vec![b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),