Skip to content

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

Merge origin/main into fix/cleared-default-stays-cleared

KenM763aeafeb09edb
diff --cc crates/automation/tests/it/automation.rs
index 3057c135f,9a27d9eef..56b3804f0
--- a/crates/automation/tests/it/automation.rs
+++ b/crates/automation/tests/it/automation.rs
@@@ -9240,27 -9340,23 +9340,47 @@@ fn page_render_draws_stamps_without_an_
assert!(grey > 100 && grey == custom.len(), "an unknown name is a grey placeholder: {grey} of {}", custom.len());
}
+ #[test]
+ fn deleting_one_radio_button_through_tools_keeps_the_group() {
+ let dir = workdir("delete-radio");
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ for (x, export) in [(20, "S"), (40, "M"), (60, "L")] {
+ let args = json!({ "doc": doc, "page": 1, "type": "radio", "rect": [x, 100, x + 14, 114], "group": "size", "export": export });
+ ok(&mut a, "form_add_field", args);
+ }
+ ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "size": "L" } }));
+ ok(&mut a, "form_delete_field", json!({ "doc": doc, "field": "size", "widget": 2 }));
+ let size = |a: &mut Automation| ok(a, "form_fields", json!({ "doc": doc }))["fields"][0].clone();
+ assert_eq!((size(&mut a)["options"].clone(), size(&mut a)["value"].clone()), (json!(["S", "L"]), json!("L")), "only M is gone");
+ for widget in [0, 3, -1] {
+ let r = a.call("form_delete_field", &json!({ "doc": doc, "field": "size", "widget": widget }));
+ assert!(matches!(r, Err(ToolError::InvalidArgs(_))), "widget {widget}: {r:?}");
+ }
+ ok(&mut a, "edit_undo", json!({ "doc": doc }));
+ assert_eq!(size(&mut a)["options"], json!(["S", "M", "L"]), "one undo step brings it back");
+ }
+/// Clearing a field's default through `form_set_props` (`"default": ""`) leaves it with none,
+/// even when its parent field has one it would otherwise inherit.
+#[test]
+fn clearing_a_kids_default_through_tools_does_not_bring_back_its_parents() {
+ let objs = [
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>",
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 400 300] >>",
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>",
+ "<< /Fields [5 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 7 0 R >> >> >>",
+ "<< /T (address) /FT /Tx /DV (Main St) /Kids [6 0 R] >>",
+ "<< /Type /Annot /Subtype /Widget /T (city) /Parent 5 0 R /DV (Elm) /V (Elm) /Rect [10 250 150 268] /P 3 0 R >>",
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>",
+ ];
+ let dir = workdir("kid-default");
+ std::fs::write(dir.join("form.pdf"), pdf_of(&objs)).unwrap();
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap();
+ ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "address.city", "default": "" }));
+ ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "address.city": "Oak" } }));
+ ok(&mut a, "form_reset", json!({ "doc": doc }));
+ let fields = ok(&mut a, "form_fields", json!({ "doc": doc }));
+ let city = fields["fields"].as_array().unwrap().iter().find(|f| f["name"] == "address.city").unwrap().clone();
+ assert!(city["value"].is_null() || city["value"] == "", "reset clears it rather than restoring the parent's Main St: {}", city["value"]);
+}
diff --cc crates/forms/src/author.rs
index 76ae93724,79bf4eac1..1420da72b
--- a/crates/forms/src/author.rs
+++ b/crates/forms/src/author.rs
@@@ -15,10 -15,8 +15,10 @@@ mod lifecycle
mod look;
mod tree;
+pub(crate) use tree::ancestor_sets;
+
pub use edit::set_props;
- pub use lifecycle::{add_field, delete_field, delete_field_object, duplicate_field};
+ pub use lifecycle::{add_field, delete_field, delete_field_object, delete_widget, duplicate_field};
pub(crate) use look::button_appearance;
pub use look::{BorderStyle, CheckStyle, FieldFont, Look, LookPatch, check_style, look, redraw_field, set_button_icon};
pub(crate) use tree::{ensure_form, form_fonts_as_objects};
diff --cc crates/forms/src/tests.rs
index dea60c4e8,49c9384b7..d768cadd9
--- a/crates/forms/src/tests.rs
+++ b/crates/forms/src/tests.rs
@@@ -4621,88 -4688,149 +4688,234 @@@ fn set_values_reads_the_form_once_not_p
assert_eq!(reads, 3, "one to fill, one when f0 comes again, one to recalculate");
}
+ /// A radio group `size` with the buttons Small (on), Medium and Large, a per-widget `/Opt`, and
+ /// the group's buttons in the calculation order; and a text field `name` with two widgets.
+ fn radio_group_form() -> Document {
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(), // 1
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(), // 2
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R 7 0 R 8 0 R 10 0 R 11 0 R] >>".into(), // 3
+ "<< /Fields [5 0 R 9 0 R] /DA (/Helv 0 Tf 0 g) /CO [7 0 R] >>".into(), // 4
+ "<< /FT /Btn /Ff 49152 /T (size) /V /S /Opt [(small) (medium) (large)] /Kids [6 0 R 7 0 R 8 0 R] >>".into(), // 5
+ "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Rect [50 700 64 714] /P 3 0 R /AS /S /AP << /N << /S 12 0 R /Off 12 0 R >> >> >>".into(), // 6
+ "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Rect [80 700 94 714] /P 3 0 R /AS /Off /AP << /N << /M 12 0 R /Off 12 0 R >> >> >>".into(), // 7
+ "<< /Type /Annot /Subtype /Widget /Parent 5 0 R /Rect [110 700 124 714] /P 3 0 R /AS /Off /AP << /N << /L 12 0 R /Off 12 0 R >> >> >>".into(), // 8
+ "<< /FT /Tx /T (name) /V (Ann) /Kids [10 0 R 11 0 R] >>".into(), // 9
+ "<< /Type /Annot /Subtype /Widget /Parent 9 0 R /Rect [50 600 250 620] /P 3 0 R >>".into(), // 10
+ "<< /Type /Annot /Subtype /Widget /Parent 9 0 R /Rect [300 600 500 620] /P 3 0 R >>".into(), // 11
+ "<< /Length 0 >>\nstream\n\nendstream".into(), // 12
+ ];
+ document(&objs)
+ }
+
+ fn annots(doc: &Document) -> Vec<u32> {
+ let p = page_refs(doc)[0];
+ let a = doc.resolve(doc.get(p).as_dict().unwrap().get(b"Annots").unwrap());
+ a.as_array().unwrap().iter().map(|o| o.as_ref().unwrap().num).collect()
+ }
+
+ #[test]
+ fn deleting_one_radio_button_keeps_the_group_and_its_other_buttons() {
+ let mut doc = radio_group_form();
+ delete_widget(&mut doc, "size", 1).unwrap();
+ let doc = reopen(&doc);
+ let all = fields(&doc);
+ let size = field(&all, "size");
+ assert_eq!(size.widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), [6, 8], "only Medium is gone");
+ assert_eq!(size.value, ["S"], "the group keeps its choice");
+ // The per-widget /Opt loses Medium's entry, so the others keep their export values.
+ assert_eq!((size.export_of(0), size.export_of(1)), (Some("small"), Some("large")));
+ assert_eq!(annots(&doc), [6, 8, 10, 11], "the button left the page");
+ let co = doc.resolve(doc.get(ObjRef::new(4, 0)).as_dict().unwrap().get(b"CO").unwrap()).as_array().cloned().unwrap();
+ assert!(co.is_empty(), "and the calculation order");
+ assert!(field(&all, "name").widgets.len() == 2, "other fields are untouched");
+ }
+
+ #[test]
+ fn deleting_the_chosen_radio_button_turns_the_group_off() {
+ let mut doc = radio_group_form();
+ delete_widget(&mut doc, "size", 0).unwrap();
+ let all = fields(&reopen(&doc));
+ let size = field(&all, "size");
+ assert_eq!(size.widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), [7, 8]);
+ assert!(size.value.is_empty(), "no button is on any more: {:?}", size.value);
+ assert_eq!((size.export_of(0), size.export_of(1)), (Some("medium"), Some("large")));
+ }
+
+ #[test]
+ fn deleting_the_chosen_radio_button_turns_the_group_off_when_a_twin_is_not_shown_on() {
+ // Medium shares Small's on-state name but shows Off: once Small is gone, no button shows
+ // the group's /V, so the group must not keep reporting it.
+ let mut doc = radio_group_form();
+ let twin = ObjRef::new(7, 0);
+ let blank = Object::Ref(ObjRef::new(12, 0));
+ let mut n = Dict::new();
+ n.set(b"S".to_vec(), blank.clone());
+ n.set(b"Off".to_vec(), blank);
+ let mut ap = Dict::new();
+ ap.set(b"N".to_vec(), Object::Dict(n));
+ let mut w = doc.get(twin).as_dict().cloned().unwrap();
+ w.set(b"AP".to_vec(), Object::Dict(ap));
+ doc.set(twin, Object::Dict(w));
+ delete_widget(&mut doc, "size", 0).unwrap();
+ let all = fields(&reopen(&doc));
+ let size = field(&all, "size");
+ assert_eq!(size.widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), [7, 8]);
+ assert!(size.value.is_empty(), "no button shows S any more: {:?}", size.value);
+ }
+
+ #[test]
+ fn deleting_the_default_radio_button_clears_the_default_too() {
+ // The group is off, but Reset would put back Small, which no button has once it is gone.
+ let mut doc = radio_group_form();
+ let size = ObjRef::new(5, 0);
+ let mut d = doc.get(size).as_dict().cloned().unwrap();
+ d.set(b"V".to_vec(), Object::name("Off"));
+ d.set(b"DV".to_vec(), Object::name("S"));
+ doc.set(size, Object::Dict(d));
+ delete_widget(&mut doc, "size", 0).unwrap();
+ let doc = reopen(&doc);
+ let dv = doc.get(size).as_dict().and_then(|d| d.get(b"DV").cloned());
+ assert_eq!(dv, Some(Object::name("Off")));
+ // A default another button still has stays.
+ let mut doc = radio_group_form();
+ let mut d = doc.get(size).as_dict().cloned().unwrap();
+ d.set(b"DV".to_vec(), Object::name("S"));
+ doc.set(size, Object::Dict(d));
+ delete_widget(&mut doc, "size", 1).unwrap();
+ assert_eq!(doc.get(size).as_dict().and_then(|d| d.get(b"DV").cloned()), Some(Object::name("S")));
+ }
+
+ #[test]
+ fn deleting_one_copy_of_a_field_keeps_the_field_and_its_value() {
+ let mut doc = radio_group_form();
+ delete_widget(&mut doc, "name", 0).unwrap();
+ let doc = reopen(&doc);
+ let all = fields(&doc);
+ let name = field(&all, "name");
+ assert_eq!((name.widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), name.value.clone()), (vec![11], vec!["Ann".to_string()]));
+ assert_eq!(annots(&doc), [6, 7, 8, 11]);
+ // The last widget takes the field with it, as deleting the field does.
+ let mut doc = doc;
+ delete_widget(&mut doc, "name", 0).unwrap();
+ let doc = reopen(&doc);
+ assert!(!fields(&doc).iter().any(|f| f.name == "name"));
+ assert_eq!(annots(&doc), [6, 7, 8]);
+ }
+
+ #[test]
+ fn deleting_a_radio_button_without_its_parent_link_takes_it_out_of_the_group() {
+ // A damaged file: the group lists Medium in its /Kids, but Medium has no /Parent.
+ for parent in [None, Some(Object::Ref(ObjRef::new(9, 0)))] {
+ let mut doc = radio_group_form();
+ let medium = ObjRef::new(7, 0);
+ let mut w = doc.get(medium).as_dict().cloned().unwrap();
+ w.remove(b"Parent");
+ if let Some(p) = parent.clone() {
+ w.set(b"Parent".to_vec(), p);
+ }
+ doc.set(medium, Object::Dict(w));
+ delete_widget(&mut doc, "size", 1).unwrap();
+ let doc = reopen(&doc);
+ let all = fields(&doc);
+ assert_eq!(field(&all, "size").widgets.iter().map(|w| w.obj.num).collect::<Vec<_>>(), [6, 8], "/Parent {parent:?}");
+ let kids = doc.resolve(doc.get(ObjRef::new(5, 0)).as_dict().unwrap().get(b"Kids").unwrap()).as_array().cloned().unwrap();
+ assert!(!kids.iter().any(|k| k.as_ref() == Some(medium)), "/Parent {parent:?}: {kids:?}");
+ assert_eq!(field(&all, "name").widgets.len(), 2, "/Parent {parent:?}: the other field is untouched");
+ assert_eq!(annots(&doc), [6, 8, 10, 11]);
+ }
+ }
+
+ #[test]
+ fn deleting_a_widget_that_is_not_there_changes_nothing() {
+ let mut doc = radio_group_form();
+ assert_eq!(delete_widget(&mut doc, "size", 3), Err(FormError::Invalid("size has no widget 4".into())));
+ assert_eq!(delete_widget(&mut doc, "nope", 0), Err(FormError::NoSuchField("nope".into())));
+ assert_eq!(delete_widget(&mut doc, "size", usize::MAX), Err(FormError::Invalid(format!("size has no widget {}", usize::MAX))));
+ assert_eq!(field(&fields(&doc), "size").widgets.len(), 3);
+ }
+#[test]
+fn clearing_a_kids_default_does_not_bring_back_its_parents() {
+ let mut doc = fixture();
+ let all = fields(&doc);
+ let city = field(&all, "address.city").clone();
+ let parent = doc.get(city.obj).as_dict().unwrap().reference(b"Parent").unwrap();
+ doc.update_dict(parent, |d| d.set(b"DV".to_vec(), PdfString::text("Main St"))).unwrap();
+ set_props(&mut doc, "address.city", &FieldProps { default_value: Some(Some("Elm".into())), ..FieldProps::default() }).unwrap();
+ assert_eq!(field(&fields(&doc), "address.city").default, ["Elm"]);
+ set_props(&mut doc, "address.city", &FieldProps { default_value: Some(None), ..FieldProps::default() }).unwrap();
+ let mut doc = reopen(&doc);
+ let f = field(&fields(&doc), "address.city").clone();
+ assert!(f.default.iter().all(String::is_empty), "no default, not the parent's: {:?}", f.default);
+ let own = doc.get(f.obj).as_dict().and_then(|d| d.get(b"DV")).and_then(|o| o.as_string()).map(PdfString::to_text);
+ assert_eq!(own.as_deref(), Some(""), "the kid holds an empty default of its own");
+ set_value(&mut doc, "address.city", &FieldValue::Text("Oak".into())).unwrap();
+ reset(&mut doc, None).unwrap();
+ assert!(field(&fields(&doc), "address.city").value.iter().all(String::is_empty), "reset clears it");
+ // Without a parent default, clearing still removes the key.
+ set_props(&mut doc, "name", &FieldProps { default_value: Some(None), ..FieldProps::default() }).unwrap();
+ let name = field(&fields(&doc), "name").clone();
+ assert!(doc.get(name.obj).as_dict().unwrap().get(b"DV").is_none());
+}
+
+#[test]
+fn clearing_a_kids_value_does_not_bring_back_its_parents() {
+ // A text kid, then a list box kid, under a parent with both a value and a default.
+ for (ft, set) in [("/FT /Tx", FieldValue::Text("Oak".into())), ("/FT /Ch /Opt [(Main St) (Oak)]", FieldValue::Choice(vec!["Oak".into()]))] {
+ let mut doc = document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),
+ "<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>".into(),
+ format!("<< /T (address) {ft} /V (Main St) /DV (Main St) /Kids [6 0 R] >>"),
+ "<< /Type /Annot /Subtype /Widget /T (city) /Parent 5 0 R /Rect [10 10 110 60] /P 3 0 R >>".into(),
+ ]);
+ set_props(&mut doc, "address.city", &FieldProps { default_value: Some(None), ..FieldProps::default() }).unwrap();
+ set_value(&mut doc, "address.city", &set).unwrap();
+ assert_eq!(field(&fields(&doc), "address.city").value, ["Oak"], "{ft}");
+ reset(&mut doc, None).unwrap();
+ let doc = reopen(&doc);
+ let f = field(&fields(&doc), "address.city").clone();
+ assert!(f.value.iter().all(String::is_empty), "{ft}: reset leaves it empty, not the parent's: {:?}", f.value);
+ let mut doc = doc;
+ set_value(&mut doc, "address.city", &set).unwrap();
+ let clear = if ft.contains("Ch") { FieldValue::Choice(Vec::new()) } else { FieldValue::Text(String::new()) };
+ set_value(&mut doc, "address.city", &clear).unwrap();
+ let f = field(&fields(&reopen(&doc)), "address.city").clone();
+ if ft.contains("Ch") {
+ assert!(f.value.is_empty(), "{ft}: clearing leaves no choice selected: {:?}", f.value);
+ } else {
+ assert!(f.value.iter().all(String::is_empty), "{ft}: clearing leaves it empty: {:?}", f.value);
+ }
+ }
+}
+
+#[test]
+fn clearing_a_buttons_default_under_a_parent_with_one_leaves_it_off() {
+ // A check box, then a radio button (flags 49152, inherited from the parent).
+ for flags in ["", "/Ff 49152"] {
+ let mut doc = document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),
+ "<< /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >>".into(),
+ format!("<< /T (opts) /FT /Btn {flags} /DV /Yes /Kids [6 0 R] >>"),
+ "<< /Type /Annot /Subtype /Widget /T (a) /Parent 5 0 R /V /Off /AS /Off /Rect [10 10 25 25] /P 3 0 R /AP << /N << /Yes 7 0 R /Off 7 0 R >> >> >>".into(),
+ "<< /Length 0 >>
+stream
+
+endstream".into(),
+ ]);
+ let kind = field(&fields(&doc), "opts.a").kind;
+ assert_eq!(kind == FieldKind::Radio, !flags.is_empty());
+ set_props(&mut doc, "opts.a", &FieldProps { default_value: Some(None), ..FieldProps::default() }).unwrap();
+ let f = field(&fields(&doc), "opts.a").clone();
+ assert_eq!(doc.get(f.obj).as_dict().and_then(|d| d.get(b"DV")).and_then(|o| o.as_name()), Some(&b"Off"[..]), "{kind:?}");
+ let on = if kind == FieldKind::Radio { FieldValue::Radio(Some("Yes".into())) } else { FieldValue::Check(true) };
+ set_value(&mut doc, "opts.a", &on).unwrap();
+ assert_eq!(field(&fields(&doc), "opts.a").value, ["Yes"]);
+ reset(&mut doc, None).unwrap();
+ let f = field(&fields(&doc), "opts.a").clone();
+ assert!(f.value.iter().all(String::is_empty), "{kind:?}: reset leaves it off, not the parent's Yes: {:?}", f.value);
+ }
+}