Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

fix(edit): prune each form-field node once after flattening

aionggdc7a195dda67
diff --git a/crates/edit/src/flatten.rs b/crates/edit/src/flatten.rs
index 3ac546805..1be77abef 100644
--- a/crates/edit/src/flatten.rs
+++ b/crates/edit/src/flatten.rs
@@ -9,7 +9,7 @@
//! form's field tree. An annotation whose appearance cannot be drawn is not flattened: it stays
//! as it is, so no comment or field value is lost with nothing in its place.
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use pdfcraft_cos::{Dict, Document, ObjRef, Object};
@@ -295,6 +295,12 @@ fn flatten_which(doc: &mut Document, pages: &[usize], which: Which) -> Result<us
Ok(drawn)
}
+#[cfg(test)]
+thread_local! {
+ /// How many field-tree nodes `prune_fields` visited on this thread.
+ pub(crate) static KEEP_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
+}
+
/// Remove flattened widgets from the AcroForm field tree, and fields left without widgets. With
/// `on_page`, also the widgets (fields without kids) that are on no page.
fn prune_fields(doc: &mut Document, widgets: &HashSet<ObjRef>, on_page: Option<&HashSet<ObjRef>>) -> Result<(), EditError> {
@@ -303,23 +309,42 @@ fn prune_fields(doc: &mut Document, widgets: &HashSet<ObjRef>, on_page: Option<&
let af_ref = af.as_ref();
let mut af_dict = doc.resolve(&af).as_dict().cloned().unwrap_or_default();
let fields = af_dict.get(b"Fields").map(|f| doc.resolve(f)).and_then(|f| f.as_array().cloned()).unwrap_or_default();
- // Returns whether the node survives.
- fn keep(doc: &mut Document, r: ObjRef, widgets: &HashSet<ObjRef>, on_page: Option<&HashSet<ObjRef>>, depth: usize) -> bool {
+ // Returns whether the node survives. `known` holds each node's answer once it is visited, so
+ // a node listed twice is pruned once, and one still being visited (a cycle) survives.
+ fn keep(
+ doc: &mut Document,
+ r: ObjRef,
+ widgets: &HashSet<ObjRef>,
+ on_page: Option<&HashSet<ObjRef>>,
+ known: &mut HashMap<ObjRef, bool>,
+ depth: usize,
+ ) -> bool {
+ #[cfg(test)]
+ KEEP_CALLS.with(|c| c.set(c.get().saturating_add(1)));
if widgets.contains(&r) || depth > 64 {
return depth > 64;
}
+ if let Some(&survives) = known.get(&r) {
+ return survives;
+ }
+ known.insert(r, true);
let Some(d) = doc.get(r).as_dict().cloned() else { return true };
let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()) else {
- return on_page.is_none_or(|p| p.contains(&r));
+ let survives = on_page.is_none_or(|p| p.contains(&r));
+ known.insert(r, survives);
+ return survives;
};
let survivors: Vec<Object> =
- kids.iter().filter(|k| k.as_ref().is_none_or(|kr| keep(doc, kr, widgets, on_page, depth + 1))).cloned().collect();
+ kids.iter().filter(|k| k.as_ref().is_none_or(|kr| keep(doc, kr, widgets, on_page, known, depth + 1))).cloned().collect();
if survivors.len() != kids.len() {
let _ = doc.update_dict(r, |d| d.set(b"Kids".to_vec(), Object::Array(survivors.clone())));
}
+ known.insert(r, !survivors.is_empty());
!survivors.is_empty()
}
- let survivors: Vec<Object> = fields.iter().filter(|f| f.as_ref().is_none_or(|r| keep(doc, r, widgets, on_page, 0))).cloned().collect();
+ let mut known = HashMap::new();
+ let survivors: Vec<Object> =
+ fields.iter().filter(|f| f.as_ref().is_none_or(|r| keep(doc, r, widgets, on_page, &mut known, 0))).cloned().collect();
if survivors.len() == fields.len() && widgets.is_empty() {
return Ok(()); // only looked for fields on no page, and there were none
}
diff --git a/crates/edit/src/tests.rs b/crates/edit/src/tests.rs
index 73b818be4..905c3f480 100644
--- a/crates/edit/src/tests.rs
+++ b/crates/edit/src/tests.rs
@@ -6366,3 +6366,39 @@ fn added_text_is_wrapped_once_per_write() {
let calls = added::WRAP_CALLS.with(std::cell::Cell::get);
assert!(calls <= 4, "the text was wrapped {calls} times for 40 lines");
}
+
+/// A field tree whose every node lists its child twice is pruned in work linear in its nodes, not
+/// in its paths, and a node listing itself is visited once.
+#[test]
+fn flattening_prunes_a_field_tree_with_repeated_kids_once_per_node() {
+ let levels = 16;
+ let page = stream("", " ");
+ // 5: the flattened widget; 6…: the chain; then the hidden widget at its end, on the page.
+ let leaf = 6 + levels;
+ let fields = format!("<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R {} 0 R] >> >>", leaf + 2);
+ let annots = format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R /Annots [5 0 R {leaf} 0 R] >>");
+ let mut objs: Vec<String> = vec![
+ fields,
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".into(),
+ annots,
+ page,
+ format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T (shown) /Rect [10 10 150 40] /F 4 /AP << /N {} 0 R >> >>", leaf + 1),
+ ];
+ for i in 0..levels {
+ let next = 7 + i;
+ objs.push(format!("<< /T (n{i}) /Kids [{next} 0 R {next} 0 R] >>"));
+ }
+ objs.push("<< /Type /Annot /Subtype /Widget /FT /Tx /T (hidden) /Rect [10 90 150 120] /F 2 >>".into());
+ objs.push("<< /Type /XObject /Subtype /Form /BBox [0 0 140 30] /Length 0 >>\nstream\n\nendstream".into());
+ objs.push(format!("<< /T (loop) /Kids [{} 0 R] >>", leaf + 2));
+ let objs: Vec<&str> = objs.iter().map(String::as_str).collect();
+ let mut doc = build(&objs);
+ flatten::KEEP_CALLS.with(|c| c.set(0));
+ assert_eq!(flatten(&mut doc, &[0], false, true).unwrap(), 1);
+ let calls = flatten::KEEP_CALLS.with(std::cell::Cell::get);
+ assert!(calls <= 2 * (levels + 4), "{calls} field-tree visits");
+ let root = doc.root().unwrap();
+ let af = doc.resolve(doc.get(root).as_dict().unwrap().get(b"AcroForm").unwrap());
+ let left = doc.resolve(af.as_dict().unwrap().get(b"Fields").unwrap()).as_array().unwrap().len();
+ assert_eq!(left, 2, "the chain to the hidden widget and the self-listing node stay");
+}