Skip to content

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

M6: editing or sorting a list's items keeps its selected indices on its items

KenM760ea9a2346626
diff --git a/crates/automation/tests/it/automation.rs b/crates/automation/tests/it/automation.rs
index 23351db9a..8641684ef 100644
--- a/crates/automation/tests/it/automation.rs
+++ b/crates/automation/tests/it/automation.rs
@@ -9175,3 +9175,30 @@ fn page_render_draws_stamps_without_an_appearance() {
let grey = custom.iter().filter(|p| p[0].abs_diff(p[1]) < 24 && p[1].abs_diff(p[2]) < 24).count();
assert!(grey > 100 && grey == custom.len(), "an unknown name is a grey placeholder: {grey} of {}", custom.len());
}
+
+/// `/I` of the top-level field `name` in the saved file `path`.
+fn saved_selection_indices(path: &Path, name: &str) -> Option<Vec<i64>> {
+ let d = pdfcraft_cos::Document::open(std::sync::Arc::new(std::fs::read(path).unwrap())).unwrap();
+ let root = d.get(d.root().unwrap()).as_dict().cloned().unwrap();
+ let form = d.resolve(root.get(b"AcroForm").unwrap()).as_dict().cloned().unwrap();
+ let all = d.resolve(form.get(b"Fields").unwrap()).as_array().cloned().unwrap();
+ let f = all
+ .iter()
+ .filter_map(|o| d.resolve(o).as_dict().cloned())
+ .find(|f| f.get(b"T").and_then(|t| d.resolve(t).as_string().map(|s| s.to_text())).as_deref() == Some(name))
+ .unwrap();
+ f.get(b"I").map(|i| d.resolve(i).as_array().unwrap().iter().map(|o| o.as_int().unwrap()).collect())
+}
+
+#[test]
+fn changing_a_lists_options_through_tools_keeps_its_saved_selection_on_the_same_items() {
+ let dir = workdir("choice-index");
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ let args = json!({ "doc": doc, "page": 1, "type": "list", "rect": [20, 60, 180, 140], "options": ["A", "B", "C"], "multi_select": true, "name": "letters" });
+ ok(&mut a, "form_add_field", args);
+ ok(&mut a, "form_fill", json!({ "doc": doc, "values": { "letters": ["B", "C"] } }));
+ ok(&mut a, "form_set_props", json!({ "doc": doc, "field": "letters", "options": ["B", "C", "D"] }));
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "letters.pdf" }));
+ assert_eq!(saved_selection_indices(&dir.join("letters.pdf"), "letters"), Some(vec![0, 1]), "B and C are now items 0 and 1");
+}
diff --git a/crates/forms/src/author/edit.rs b/crates/forms/src/author/edit.rs
index dc7d91d4f..c7df5481c 100644
--- a/crates/forms/src/author/edit.rs
+++ b/crates/forms/src/author/edit.rs
@@ -14,6 +14,24 @@ fn swapped_around_center(r: [f64; 4]) -> Option<[f64; 4]> {
(out.iter().all(|v| v.is_finite()) && out[2] - out[0] >= MIN_FIELD_SIDE && out[3] - out[1] >= MIN_FIELD_SIDE).then_some(out)
}
+/// Re-point a choice field's `/I` (and `/TI`), which are positions in `/Opt`, at the new list
+/// `exports` after `/Opt` was replaced (ISO 32000-2 §12.7.5.4): `/I` names the positions of the
+/// selected `values` still offered, and a `/TI` past the end is dropped.
+fn repoint_selection(d: &mut Dict, values: &[String], exports: &[String]) {
+ let mut indices: Vec<usize> = values.iter().filter_map(|v| exports.iter().position(|e| e == v)).collect();
+ indices.sort_unstable();
+ indices.dedup();
+ if indices.is_empty() {
+ d.remove(b"I");
+ } else {
+ d.set(b"I".to_vec(), Object::Array(indices.into_iter().map(|i| Object::Int(i64::try_from(i).unwrap_or(i64::MAX))).collect()));
+ }
+ let top = d.get(b"TI").and_then(Object::as_int);
+ if top.is_some_and(|t| usize::try_from(t).map_or(true, |t| t >= exports.len())) {
+ d.remove(b"TI");
+ }
+}
+
/// Change a field's properties (General and Options tabs) and redraw it.
pub fn set_props(doc: &mut Document, name: &str, props: &FieldProps) -> Result<String, FormError> {
if props.font_size.is_some_and(|size| !size.is_finite() || size < 0.0) {
@@ -190,8 +208,11 @@ pub fn set_props(doc: &mut Document, name: &str, props: &FieldProps) -> Result<S
}
}
}
+ // The export values in `/Opt` order once it is rewritten, for re-pointing `/I`.
+ let mut new_exports: Option<Vec<String>> = None;
if let Some(opts) = &props.options {
d.set(b"Opt".to_vec(), Object::Array(opts.iter().map(|o| Object::String(PdfString::text(o))).collect()));
+ new_exports = Some(opts.clone());
}
// "Sort items": the list itself is kept in order (export values stay with their items).
if ff & flags::SORT != 0 && matches!(f.kind, FieldKind::Combo | FieldKind::List) {
@@ -211,6 +232,12 @@ pub fn set_props(doc: &mut Document, name: &str, props: &FieldProps) -> Result<S
})
.collect();
d.set(b"Opt".to_vec(), Object::Array(opt));
+ new_exports = Some(items.into_iter().map(|(e, _)| e).collect());
+ }
+ if let Some(exports) = &new_exports
+ && matches!(f.kind, FieldKind::Combo | FieldKind::List)
+ {
+ repoint_selection(d, &f.value, exports);
}
if let Some(q) = props.quadding {
d.set(b"Q".to_vec(), Object::Int(q));
diff --git a/crates/forms/src/tests.rs b/crates/forms/src/tests.rs
index 61dab131e..252bae9df 100644
--- a/crates/forms/src/tests.rs
+++ b/crates/forms/src/tests.rs
@@ -4577,3 +4577,55 @@ fn set_values_reads_the_form_once_not_per_value() {
let reads = form_reads() - before;
assert_eq!(reads, 3, "one to fill, one when f0 comes again, one to recalculate");
}
+
+/// `/I` of field `name`: the selected positions in `/Opt`, or `None` when absent.
+fn selection_indices(doc: &Document, name: &str) -> Option<Vec<i64>> {
+ let f = field(&fields(doc), name).clone();
+ let d = doc.get(f.obj).as_dict().cloned().unwrap();
+ d.get(b"I").map(|i| doc.resolve(i).as_array().unwrap().iter().map(|o| o.as_int().unwrap()).collect())
+}
+
+#[test]
+fn changing_a_lists_options_repoints_its_selected_indices() {
+ let mut doc = one_page();
+ let list =
+ add_field(&mut doc, 0, [50.0, 600.0, 250.0, 680.0], &NewField::List { options: vec!["A".into(), "B".into(), "C".into()], multi: true }, None)
+ .unwrap();
+ set_value(&mut doc, &list, &FieldValue::Choice(vec!["C".into(), "B".into()])).unwrap();
+ assert_eq!(selection_indices(&doc, &list), Some(vec![1, 2]));
+ let f = field(&fields(&doc), &list).clone();
+ doc.update_dict(f.obj, |d| d.set(b"TI".to_vec(), Object::Int(2))).unwrap();
+ // Removing A moves B and C up one place.
+ let opts = |o: &[&str]| FieldProps { options: Some(o.iter().map(|s| s.to_string()).collect()), ..FieldProps::default() };
+ set_props(&mut doc, &list, &opts(&["B", "C", "D"])).unwrap();
+ assert_eq!(selection_indices(&doc, &list), Some(vec![0, 1]));
+ assert!(doc.get(f.obj).as_dict().unwrap().get(b"TI").is_some(), "row 2 still exists");
+ // Removing B leaves only C selected; the top row now points past the end.
+ set_props(&mut doc, &list, &opts(&["C"])).unwrap();
+ assert_eq!(selection_indices(&doc, &list), Some(vec![0]));
+ assert!(doc.get(f.obj).as_dict().unwrap().get(b"TI").is_none(), "a /TI past the list is dropped");
+ // No selected value is offered any more.
+ set_props(&mut doc, &list, &opts(&["X", "Y"])).unwrap();
+ assert_eq!(selection_indices(&doc, &list), None);
+ let doc = reopen(&doc);
+ assert_eq!(selection_indices(&doc, &list), None);
+}
+
+#[test]
+fn sorting_a_combo_boxs_items_repoints_its_selected_index() {
+ let mut doc = one_page();
+ let combo = add_field(
+ &mut doc,
+ 0,
+ [50.0, 600.0, 250.0, 620.0],
+ &NewField::Combo { options: vec!["Pear".into(), "apple".into(), "Fig".into()], editable: false },
+ None,
+ )
+ .unwrap();
+ set_value(&mut doc, &combo, &FieldValue::Choice(vec!["Pear".into()])).unwrap();
+ assert_eq!(selection_indices(&doc, &combo), Some(vec![0]));
+ set_props(&mut doc, &combo, &FieldProps { flags: vec![(flags::SORT, true)], ..FieldProps::default() }).unwrap();
+ // apple, Fig, Pear: the selection follows Pear to the end.
+ assert_eq!(selection_indices(&doc, &combo), Some(vec![2]));
+ assert_eq!(field(&fields(&doc), &combo).value, vec!["Pear".to_string()]);
+}
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index bcba7a0ec..2511971f8 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -4991,8 +4991,8 @@ milestone = "M6"
status = "shipped"
commands = ["form.field.properties"]
tools = ["form_set_props"]
-evidence = ["crates/forms/src/tests.rs::button_caption_preserves_other_widgets_and_shared_dictionaries", "crates/forms/src/tests.rs::a_button_caption_is_drawn_in_its_fields_font_size_and_color", "crates/ui-egui/tests/it/prepare.rs::button_label_is_editable_without_renaming_the_field", "crates/automation/tests/it/button_caption.rs::button_caption_can_be_changed_after_creation", "crates/forms/src/tests.rs::properties_rename_and_delete", "crates/automation/tests/it/automation.rs::preparing_a_form_through_tools", "crates/forms/src/tests.rs::options_tab_flags_alignment_and_defaults", "crates/ui-egui/tests/it/prepare.rs::options_tab_sets_flags_alignment_and_defaults", "crates/automation/tests/it/form_bulk.rs::bulk_options_apply_per_field_and_refuse_an_invalid_comb_atomically"]
-notes = "push buttons: per-widget normal label independent of the field name, including clearing and save/reopen, drawn in the font, size and color of the button's /DA (the form's /DR font, else Helvetica; an automatic size fits the button) and centered by Helvetica's widths; icon-only layout retained, rollover/down labels and icon layout editing remain unavailable; text: alignment, default, multi-line, scroll, rich text flag, limit, password, file selection, spell check, comb; choices: items, default, sort, custom text, multiple selection, commit immediately; check boxes and radios: checked by default, radios in unison. Shared GUI offers applicable text/choice flags, alignment, text limits and check styles; choices/defaults remain individual GUI edits"
+evidence = ["crates/forms/src/tests.rs::button_caption_preserves_other_widgets_and_shared_dictionaries", "crates/forms/src/tests.rs::a_button_caption_is_drawn_in_its_fields_font_size_and_color", "crates/ui-egui/tests/it/prepare.rs::button_label_is_editable_without_renaming_the_field", "crates/automation/tests/it/button_caption.rs::button_caption_can_be_changed_after_creation", "crates/forms/src/tests.rs::properties_rename_and_delete", "crates/automation/tests/it/automation.rs::preparing_a_form_through_tools", "crates/forms/src/tests.rs::options_tab_flags_alignment_and_defaults", "crates/ui-egui/tests/it/prepare.rs::options_tab_sets_flags_alignment_and_defaults", "crates/automation/tests/it/form_bulk.rs::bulk_options_apply_per_field_and_refuse_an_invalid_comb_atomically", "crates/forms/src/tests.rs::changing_a_lists_options_repoints_its_selected_indices", "crates/forms/src/tests.rs::sorting_a_combo_boxs_items_repoints_its_selected_index", "crates/automation/tests/it/automation.rs::changing_a_lists_options_through_tools_keeps_its_saved_selection_on_the_same_items"]
+notes = "push buttons: per-widget normal label independent of the field name, including clearing and save/reopen, drawn in the font, size and color of the button's /DA (the form's /DR font, else Helvetica; an automatic size fits the button) and centered by Helvetica's widths; icon-only layout retained, rollover/down labels and icon layout editing remain unavailable; text: alignment, default, multi-line, scroll, rich text flag, limit, password, file selection, spell check, comb; choices: items (the selected indices /I follow their items when the list is edited or sorted), default, sort, custom text, multiple selection, commit immediately; check boxes and radios: checked by default, radios in unison. Shared GUI offers applicable text/choice flags, alignment, text limits and check styles; choices/defaults remain individual GUI edits"
[[feature]]
id = "form.props-actions"