Skip to content

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

M6: default names skip empty parents; a full name under the same parents is a plain rename (#2696)

mtlcl4109efc1727a1b7
diff --git a/crates/forms/src/author.rs b/crates/forms/src/author.rs
index 5370f2590..56df0dc9d 100644
--- a/crates/forms/src/author.rs
+++ b/crates/forms/src/author.rs
@@ -689,14 +689,25 @@ fn detach(doc: &mut Document, field: ObjRef) -> Result<(), FormError> {
Ok(())
}
-/// The first free "<base>N" name.
-fn free_name(existing: &[Field], base: &str) -> String {
+/// The first free "<base>N" name: not a field's, and not held by a node at the top of the field
+/// tree (`held`), such as a parent field left empty by a move, which isn't in `existing`.
+fn free_name(existing: &[Field], held: &[String], base: &str) -> String {
(1..=u64::MAX)
.map(|n| format!("{base}{n}"))
- .find(|c| !existing.iter().any(|f| f.name == *c || f.name.starts_with(&format!("{c}."))))
+ .find(|c| !held.contains(c) && !existing.iter().any(|f| f.name == *c || f.name.starts_with(&format!("{c}."))))
.unwrap_or_else(|| base.to_string())
}
+/// The own names (`/T`) of the nodes in the form's `/Fields`, changing nothing.
+fn top_names(doc: &Document) -> Vec<String> {
+ let Some(root) = doc.root() else { return Vec::new() };
+ let Some(af) = doc.get(root).as_dict().and_then(|d| d.get(b"AcroForm").map(|o| doc.resolve(o))).and_then(|o| o.as_dict().cloned()) else {
+ return Vec::new();
+ };
+ let list = af.get(b"Fields").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned()).unwrap_or_default();
+ list.iter().filter_map(|o| doc.resolve(o).as_dict().and_then(|d| d.get(b"T").cloned())).filter_map(|t| crate::text_of(&doc.resolve(&t))).collect()
+}
+
fn widget_dict(page: ObjRef, rect: [f64; 4]) -> Dict {
let mut d = Dict::new();
d.set(b"Type".to_vec(), Object::name("Annot"));
@@ -731,7 +742,7 @@ pub fn add_field(doc: &mut Document, page: usize, rect: [f64; 4], kind: &NewFiel
};
let name = match name.map(str::trim) {
Some(n) if !n.is_empty() => n.to_string(),
- _ => free_name(&existing, kind.base_name()),
+ _ => free_name(&existing, &top_names(doc), kind.base_name()),
};
let parts = name_parts(&name)?;
let radio_group = match kind {
@@ -1116,6 +1127,13 @@ pub fn set_props(doc: &mut Document, name: &str, props: &FieldProps) -> Result<S
}
let mut new_name = name.to_string();
if let Some(n) = props.name.as_deref().map(str::trim).filter(|n| *n != f.name) {
+ // A full name under the same parents only renames the field's own part (the editor
+ // shows nested fields by their full name): it isn't moved, so it keeps its place and
+ // goes on inheriting from its parents.
+ let n = match (n.rsplit_once('.'), f.name.rsplit_once('.')) {
+ (Some((parents, own)), Some((current, _))) if parents == current => own,
+ _ => n,
+ };
if n.contains('.') {
// A full name: the field moves under the parent fields it names (#2696).
let parts = name_parts(n)?;
diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs
index ae532f8ff..a5bc2b17a 100644
--- a/crates/forms/src/tests.rs
+++ b/crates/forms/src/tests.rs
@@ -3229,6 +3229,37 @@ fn dotted_field_names_are_made_with_parent_fields() {
assert!(set_props(&mut doc, "name", &FieldProps { name: Some("MASTER.street1".into()), ..FieldProps::default() }).is_err(), "taken");
}
+/// Review on #2957: a parent left empty by a move keeps its name from the next default name
+/// (`Text1` after `Text1.x` moved away); and a full name that keeps the parents is a plain
+/// rename, so the field stays in its place among its parent's /Kids and keeps inheriting.
+#[test]
+fn empty_parents_and_same_parent_renames() {
+ let mut doc = fixture();
+ let text = NewField::Text { multiline: false };
+ let auto = |doc: &mut Document, y: f64| add_field(doc, 0, [50.0, y, 200.0, y + 20.0], &text, None);
+ let mut copy = doc.clone();
+ let first = auto(&mut copy, 100.0).unwrap();
+ add_field(&mut doc, 0, [50.0, 140.0, 200.0, 160.0], &text, Some(&format!("{first}.x"))).unwrap();
+ set_props(&mut doc, &format!("{first}.x"), &FieldProps { name: Some("other.x".into()), ..FieldProps::default() }).unwrap();
+ assert!(fields(&doc).iter().all(|f| !f.name.starts_with(&first)), "{first} is an empty parent now");
+ let next = auto(&mut doc, 100.0).expect("a default name the empty parent doesn't hold");
+ assert_ne!(next, first);
+
+ let all = fields(&doc);
+ let city = field(&all, "address.city").obj;
+ let address = doc.get(city).as_dict().and_then(|d| d.reference(b"Parent")).unwrap();
+ doc.update_dict(address, |d| d.set(b"V".to_vec(), Object::String(PdfString::literal(b"Springfield".to_vec())))).unwrap();
+ let kids = |doc: &Document| doc.get(address).as_dict().and_then(|d| d.get(b"Kids").and_then(|o| o.as_array().cloned())).unwrap();
+ let before = kids(&doc);
+ assert_eq!(
+ set_props(&mut doc, "address.city", &FieldProps { name: Some("address.town".into()), ..FieldProps::default() }).unwrap(),
+ "address.town"
+ );
+ assert_eq!(kids(&doc), before, "same place among the kids");
+ assert!(!doc.get(city).as_dict().unwrap().contains(b"V"), "still inherits its value rather than owning a copy");
+ assert_eq!(field(&fields(&doc), "address.town").value, ["Springfield"]);
+}
+
/// Review on #2957: spaces in a typed name. The ends of the whole name are dropped, as Acrobat
/// does when a field is renamed; a space beside a period stays in the part it belongs to (`a. b`
/// is `b` with a leading space under `a`), as Acrobat keeps it and as ISO 32000-2 §12.7.4.2