PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge origin/main into fix/choice-index-follows-options
KenM76304f27fd0b74
diff --cc crates/automation/tests/it/automation.rsindex 4f8e4dd26,9a27d9eef..f133822ab--- a/crates/automation/tests/it/automation.rs+++ b/crates/automation/tests/it/automation.rs@@@ -9240,29 -9340,23 +9340,49 @@@ 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");+ }+/// `/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 --cc crates/forms/src/tests.rsindex 8326f62cb,49c9384b7..a10837de9--- a/crates/forms/src/tests.rs+++ b/crates/forms/src/tests.rs@@@ -4621,146 -4688,149 +4688,292 @@@ fn set_values_reads_the_form_once_not_passert_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);+ }+/// `/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]));+ // Removing B leaves only C selected; the top row would point past the end.+ set_props(&mut doc, &list, &opts(&["C"])).unwrap();+ assert_eq!(selection_indices(&doc, &list), Some(vec![0]));+ assert_eq!(top_row(&doc, f.obj), Some(0), "the list scrolls back to its only row");+ // 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);+}++fn top_row(doc: &Document, obj: ObjRef) -> Option<i64> {+ doc.get(obj).as_dict().and_then(|d| d.get(b"TI")).and_then(|o| o.as_int())+}++#[test]+fn shrinking_a_lists_options_scrolls_a_widget_with_its_own_top_row() {+ let objs: Vec<String> = vec![+ "<< /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 [7 0 R] >>".into(),+ "<< /Fields [6 0 R] /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into(),+ "<< /FT /Ch /T (pick) /Opt [(A) (B) (C) (D) (E) (F)] /V (F) /I [5] /Kids [7 0 R] >>".into(),+ "<< /Type /Annot /Subtype /Widget /Parent 6 0 R /TI 5 /Rect [50 700 250 720] /P 3 0 R >>".into(),+ ];+ let mut doc = document(&objs);+ let widget = ObjRef::new(7, 0);+ set_props(&mut doc, "pick", &FieldProps { options: Some(vec!["F".into(), "A".into()]), ..FieldProps::default() }).unwrap();+ assert_eq!(selection_indices(&doc, "pick"), Some(vec![0]));+ // The widget's own /TI is read before the field's; row 5 no longer exists.+ assert_eq!(top_row(&doc, widget), Some(0), "the widget scrolls to F, now row 0");+ let doc = reopen(&doc);+ assert_eq!(top_row(&doc, widget), Some(0));+}++#[test]+fn each_widget_with_its_own_top_row_scrolls_by_itself() {+ // Widget 7 shows from the field's top row; widget 8 keeps its own /TI 4.+ let objs = |v: &str| -> Vec<String> {+ vec![+ "<< /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 [7 0 R 8 0 R] >>".into(),+ "<< /Fields [6 0 R] /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into(),+ format!("<< /FT /Ch /T (pick) /Opt [(A) (B) (C) (D) (E) (F)] {v} /Kids [7 0 R 8 0 R] >>"),+ "<< /Type /Annot /Subtype /Widget /Parent 6 0 R /Rect [50 700 250 740] /P 3 0 R >>".into(),+ "<< /Type /Annot /Subtype /Widget /Parent 6 0 R /TI 4 /Rect [50 600 250 620] /P 3 0 R >>".into(),+ ]+ };+ let (first, other) = (ObjRef::new(7, 0), ObjRef::new(8, 0));+ // The options shrink: the first widget already shows A, the other's row 4 is gone.+ let mut doc = document(&objs("/V (A) /I [0]"));+ set_props(&mut doc, "pick", &FieldProps { options: Some(vec!["A".into(), "B".into()]), ..FieldProps::default() }).unwrap();+ assert_eq!(top_row(&doc, first), None);+ assert_eq!(top_row(&reopen(&doc), other), Some(0), "options: the other widget scrolls to A");+ // A new value the first widget already shows, below the other's view.+ let mut doc = document(&objs("/V (B) /I [1]"));+ set_value(&mut doc, "pick", &FieldValue::Choice(vec!["A".into()])).unwrap();+ assert_eq!(top_row(&doc, ObjRef::new(6, 0)), None, "the field's top row did not move");+ assert_eq!(top_row(&reopen(&doc), other), Some(0), "value: the other widget scrolls to A");+}++/// A list box's top row is chosen with the font size set in the same edit: at the larger size+/// fewer rows fit, so it scrolls further to keep the selection in view.+#[test]+fn a_list_boxs_top_row_follows_a_font_size_changed_with_its_items() {+ 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 [6 0 R] /DA (/Helv 10 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".into(),+ "<< /FT /Ch /T (pick) /Opt [(A) (B) (C) (D) (E)] /V (C) /I [2] /Type /Annot /Subtype /Widget /Rect [50 700 250 740] /P 3 0 R >>".into(),+ ]);+ let items = ["Z", "A", "B", "C", "D"].map(String::from).to_vec();+ set_props(&mut doc, "pick", &FieldProps { options: Some(items), font_size: Some(20.0), ..FieldProps::default() }).unwrap();+ let doc = reopen(&doc);+ let g = field(&fields(&doc), "pick").clone();+ let w = &g.widgets[0];+ let rows = w.list.unwrap();+ let shown = rows.top..rows.top + rows.visible(w.rect[3] - w.rect[1]);+ assert!(shown.contains(&3), "C is row 3; rows {shown:?} show");+}++#[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()]);+}++#[test]+fn sorting_keeps_which_of_two_items_with_one_export_value_is_selected() {+ 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()], multi: false }, None).unwrap();+ let f = field(&fields(&doc), &list).clone();+ let item = |e: &str, shown: &str| Object::Array(vec![Object::String(PdfString::text(e)), Object::String(PdfString::text(shown))]);+ // Zeta and Alpha both export "x"; `/I` says Zeta is the one selected.+ doc.update_dict(f.obj, |d| {+ d.set(b"Opt".to_vec(), Object::Array(vec![item("x", "Zeta"), item("x", "Alpha"), item("y", "Mid")]));+ d.set(b"V".to_vec(), PdfString::text("x"));+ d.set(b"I".to_vec(), Object::Array(vec![Object::Int(0)]));+ })+ .unwrap();+ set_props(&mut doc, &list, &FieldProps { flags: vec![(flags::SORT, true)], ..FieldProps::default() }).unwrap();+ // Alpha, Mid, Zeta: the selection follows Zeta, not the first item exporting "x".+ assert_eq!(selection_indices(&doc, &list), Some(vec![2]));+}