Skip to content

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

Merge PR #4368: M6: check boxes, radio buttons and push buttons without an appearance are drawn, and comb fields show their cells

aiongg8a0319a24f5a
diff --cc crates/forms/src/tests.rs
index 96b7fabf9,e3c7a1d13..0c2daeb6d
--- a/crates/forms/src/tests.rs
+++ b/crates/forms/src/tests.rs
@@@ -3354,710 -3098,131 +3354,839 @@@ fn a_skipped_field_leaves_its_widget_to
assert_eq!(widgets, [("b", 1)]);
}
+/// #2696: a dotted name is a full name. `MASTER.first` is a field `first` under a parent field
+/// `MASTER` (a partial name can't contain a period, ISO 32000-2 §12.7.4.2); a second `MASTER.`
+/// name joins that parent; renaming to a dotted name moves the field, keeping what it inherited;
+/// and a name that would make one field both hold a value and hold fields is refused.
+#[test]
+fn dotted_field_names_are_made_with_parent_fields() {
+ let mut doc = fixture();
+ let top = |doc: &Document| {
+ let root = doc.root().unwrap();
+ let af = doc.get(root).as_dict().and_then(|d| d.reference(b"AcroForm")).unwrap();
+ doc.get(af).as_dict().and_then(|d| d.get(b"Fields").and_then(|o| o.as_array().map(|a| a.len()))).unwrap()
+ };
+ let own_name = |doc: &Document, f: &Field| doc.get(f.obj).as_dict().and_then(|d| d.get(b"T").and_then(text_of));
+ let parent_of = |doc: &Document, f: &Field| doc.get(f.obj).as_dict().and_then(|d| d.reference(b"Parent")).unwrap();
+ let text = NewField::Text { multiline: false };
+ let before = top(&doc);
+ assert_eq!(add_field(&mut doc, 0, [50.0, 300.0, 200.0, 320.0], &text, Some("MASTER.account_firstname")).unwrap(), "MASTER.account_firstname");
+ add_field(&mut doc, 0, [50.0, 260.0, 200.0, 280.0], &text, Some("MASTER.street1")).unwrap();
+ assert_eq!(top(&doc), before + 1, "one parent field at the top");
+ let saved = reopen(&doc);
+ let all = fields(&saved);
+ let (a, b) = (field(&all, "MASTER.account_firstname"), field(&all, "MASTER.street1"));
+ assert_eq!(own_name(&saved, b).as_deref(), Some("street1"), "the field's own name has no period");
+ let master = parent_of(&saved, a);
+ assert_eq!(parent_of(&saved, b), master, "both under one MASTER");
+ assert_eq!(saved.get(master).as_dict().and_then(|d| d.get(b"T").and_then(text_of)).as_deref(), Some("MASTER"));
+
+ // Renaming to a dotted name moves the field: zip joins the existing address parent.
+ assert_eq!(set_props(&mut doc, "zip", &FieldProps { name: Some("address.zip".into()), ..FieldProps::default() }).unwrap(), "address.zip");
+ assert_eq!(top(&doc), before, "zip left the top");
+ let all = fields(&doc);
+ let (zip, city) = (field(&all, "address.zip"), field(&all, "address.city"));
+ assert_eq!(parent_of(&doc, zip), parent_of(&doc, city));
+ assert_eq!(zip.max_len, Some(5), "its own settings move with it");
+
+ // What a moved field inherited stays; what a new field would inherit from a parent it
+ // joins doesn't apply to it.
+ let address = parent_of(&doc, city);
+ doc.update_dict(address, |d| {
+ d.set(b"Ff".to_vec(), Object::Int(flags::READ_ONLY as i64));
+ d.set(b"V".to_vec(), Object::String(PdfString::literal(b"Springfield".to_vec())));
+ })
+ .unwrap();
+ let city = field(&fields(&doc), "address.city").clone();
+ assert!(city.read_only() && city.value == ["Springfield"]);
+ set_props(&mut doc, "address.city", &FieldProps { name: Some("billing.city".into()), ..FieldProps::default() }).unwrap();
+ let moved = field(&fields(&doc), "billing.city").clone();
+ assert!(moved.read_only() && moved.value == ["Springfield"], "the moved field keeps what it inherited");
+ // A parent's value, reset value or length limit would pass to a new field under it (review
+ // on #2957), and a field can't turn them off: such a parent takes no new field.
+ let street = |doc: &mut Document| add_field(doc, 0, [300.0, 300.0, 450.0, 320.0], &text, Some("address.street"));
+ for (key, value) in [
+ (&b"V"[..], Object::String(PdfString::literal(b"x".to_vec()))),
+ (b"DV", Object::String(PdfString::literal(b"x".to_vec()))),
+ (b"MaxLen", Object::Int(3)),
+ ] {
+ doc.update_dict(address, |d| {
+ for k in [&b"V"[..], b"DV", b"MaxLen"] {
+ d.remove(k);
+ }
+ d.set(key.to_vec(), value);
+ })
+ .unwrap();
+ let mut copy = doc.clone();
+ assert!(street(&mut copy).is_err(), "address holds /{}", String::from_utf8_lossy(key));
+ }
+ doc.update_dict(address, |d| {
+ d.remove(b"MaxLen");
+ })
+ .unwrap();
+ street(&mut doc).unwrap();
+ let new = field(&fields(&doc), "address.street").clone();
+ assert!(!new.read_only(), "a new field doesn't take its parent's flags");
+ assert!(new.value.iter().all(|v| v.is_empty()) && new.max_len.is_none(), "nor a value or length limit: {:?} {:?}", new.value, new.max_len);
+
+ // A parent left empty by a move isn't a terminal field, but its name is still taken.
+ add_field(&mut doc, 0, [300.0, 340.0, 450.0, 360.0], &text, Some("box.only")).unwrap();
+ set_props(&mut doc, "box.only", &FieldProps { name: Some("elsewhere.only".into()), ..FieldProps::default() }).unwrap();
+ assert!(fields(&doc).iter().all(|f| !f.name.starts_with("box")), "box holds no field now");
+ let mut copy = doc.clone();
+ assert!(add_field(&mut copy, 0, [300.0, 380.0, 450.0, 400.0], &text, Some("box")).is_err(), "a new field named box");
+ let mut copy = doc.clone();
+ assert!(set_props(&mut copy, "name", &FieldProps { name: Some("box".into()), ..FieldProps::default() }).is_err(), "a rename to box");
+ // Under it, the name is free: the empty parent takes a field again.
+ add_field(&mut doc, 0, [300.0, 380.0, 450.0, 400.0], &text, Some("box.again")).unwrap();
+ // Only a whole path that exists can be taken: under box.sub, made new, "again" is free.
+ add_field(&mut doc, 0, [300.0, 420.0, 450.0, 440.0], &text, Some("box.sub.again")).unwrap();
+ // A field holding its own value may join a parent holding one; and the parents a new path
+ // makes are new, even where an existing field has the name of a later part.
+ doc.update_dict(address, |d| d.set(b"V".to_vec(), Object::String(PdfString::literal(b"x".to_vec())))).unwrap();
+ set_props(&mut doc, "billing.city", &FieldProps { name: Some("address.city".into()), ..FieldProps::default() }).unwrap();
+ assert_eq!(field(&fields(&doc), "address.city").value, ["Springfield"]);
+ add_field(&mut doc, 0, [300.0, 460.0, 450.0, 480.0], &text, Some("nope.address.x")).unwrap();
+ // Renaming the last part: to its own name is no change; to an empty parent's name beside it
+ // is taken.
+ assert_eq!(set_props(&mut doc, "address.city", &FieldProps { name: Some("city".into()), ..FieldProps::default() }).unwrap(), "address.city");
+ doc.update_dict(address, |d| {
+ d.remove(b"V");
+ })
+ .unwrap();
+ add_field(&mut doc, 0, [300.0, 500.0, 450.0, 520.0], &text, Some("address.grp.x")).unwrap();
+ set_props(&mut doc, "address.grp.x", &FieldProps { name: Some("elsewhere.x".into()), ..FieldProps::default() }).unwrap();
+ assert!(
+ set_props(&mut doc.clone(), "address.city", &FieldProps { name: Some("grp".into()), ..FieldProps::default() }).is_err(),
+ "address.grp is taken"
+ );
+ // A move the destination refuses leaves the field where it was (review on #2957): it was
+ // taken out of the tree before the destination was checked, and stayed out.
+ doc.update_dict(address, |d| d.set(b"MaxLen".to_vec(), Object::Int(3))).unwrap();
+ let at_top = top(&doc);
+ assert!(set_props(&mut doc, "name", &FieldProps { name: Some("address.name".into()), ..FieldProps::default() }).is_err());
+ assert_eq!(top(&doc), at_top, "name is still in the form's /Fields");
+ // Nor is what it inherits copied onto it first (review on #2957): src.f inherits /V from src.
+ add_field(&mut doc, 0, [300.0, 540.0, 450.0, 560.0], &text, Some("src.f")).unwrap();
+ let f = field(&fields(&doc), "src.f").obj;
+ let src = doc.get(f).as_dict().and_then(|d| d.reference(b"Parent")).unwrap();
+ doc.update_dict(src, |d| d.set(b"V".to_vec(), Object::String(PdfString::literal(b"inh".to_vec())))).unwrap();
+ assert!(set_props(&mut doc, "src.f", &FieldProps { name: Some("address.f".into()), ..FieldProps::default() }).is_err());
+ assert!(!doc.get(f).as_dict().unwrap().contains(b"V"), "src.f still only inherits its value");
+ // What it inherits counts as its own where it goes: with /V on address and no /MaxLen,
+ // src.f moves, keeping its value.
+ doc.update_dict(address, |d| {
+ d.remove(b"MaxLen");
+ d.set(b"V".to_vec(), Object::String(PdfString::literal(b"x".to_vec())));
+ })
+ .unwrap();
+ set_props(&mut doc, "src.f", &FieldProps { name: Some("address.f".into()), ..FieldProps::default() }).unwrap();
+ assert_eq!(field(&fields(&doc), "address.f").value, ["inh"]);
+ doc.update_dict(address, |d| {
+ d.remove(b"V");
+ })
+ .unwrap();
+ doc.update_dict(address, |d| {
+ d.remove(b"MaxLen");
+ })
+ .unwrap();
+
+ for bad in ["MASTER", "MASTER.street1.x", "MASTER..x", ".x", "x.", "MASTER. "] {
+ assert!(add_field(&mut doc, 0, [300.0, 200.0, 450.0, 220.0], &text, Some(bad)).is_err(), "{bad:?}");
+ assert!(set_props(&mut doc, "name", &FieldProps { name: Some(bad.into()), ..FieldProps::default() }).is_err(), "{bad:?}");
+ }
+ let deep = vec!["p"; 33].join(".");
+ assert!(add_field(&mut doc, 0, [300.0, 200.0, 450.0, 220.0], &text, Some(&deep)).is_err(), "too deep");
+ 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
+/// allows: only a period is barred from a partial name.
+#[test]
+fn a_typed_name_loses_its_ends_but_keeps_spaces_beside_periods() {
+ let mut doc = fixture();
+ let own_name = |doc: &Document, full: &str| {
+ let all = fields(doc);
+ doc.get(field(&all, full).obj).as_dict().and_then(|d| d.get(b"T").and_then(text_of))
+ };
+ let text = NewField::Text { multiline: false };
+ assert_eq!(add_field(&mut doc, 0, [50.0, 300.0, 200.0, 320.0], &text, Some(" plain ")).unwrap(), "plain");
+ assert_eq!(add_field(&mut doc, 0, [50.0, 260.0, 200.0, 280.0], &text, Some("a. b")).unwrap(), "a. b");
+ assert_eq!(add_field(&mut doc, 0, [50.0, 220.0, 200.0, 240.0], &text, Some("c .d")).unwrap(), "c .d");
+ assert_eq!(set_props(&mut doc, "zip", &FieldProps { name: Some(" e. f ".into()), ..FieldProps::default() }).unwrap(), "e. f");
+ let saved = reopen(&doc);
+ assert_eq!(own_name(&saved, "plain").as_deref(), Some("plain"));
+ assert_eq!(own_name(&saved, "a. b").as_deref(), Some(" b"));
+ assert_eq!(own_name(&saved, "c .d").as_deref(), Some("d"));
+ assert_eq!(own_name(&saved, "e. f").as_deref(), Some(" f"));
+ let parent = |full: &str| {
+ let all = fields(&saved);
+ let p = saved.get(field(&all, full).obj).as_dict().and_then(|d| d.reference(b"Parent")).unwrap();
+ saved.get(p).as_dict().and_then(|d| d.get(b"T").and_then(text_of))
+ };
+ assert_eq!(parent("c .d").as_deref(), Some("c "), "the space before the period is the parent's");
+ assert_eq!(parent("e. f").as_deref(), Some("e"));
+ // A part that is only spaces is still empty.
+ assert!(add_field(&mut doc, 0, [300.0, 300.0, 450.0, 320.0], &text, Some("g. .h")).is_err());
+}
+
+/// The form's `/DR /Font` entries, resolved through an indirect `/DR` or `/Font`.
+fn dr_fonts(doc: &Document) -> Dict {
+ let af = acroform(doc).unwrap();
+ let dr = doc.resolve(af.get(b"DR").unwrap());
+ doc.resolve(dr.as_dict().unwrap().get(b"Font").unwrap()).as_dict().cloned().unwrap()
+}
+
+/// #3441: Acrobat shows nothing in a text field it redraws after typing when the field's `/DR`
+/// font is a dictionary written inline. A form PdfCraft makes holds each font as its own object.
+#[test]
+fn a_new_form_holds_its_fonts_as_objects() {
+ let mut doc = document(&[
+ "<< /Type /Catalog /Pages 2 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R >>".into(),
+ ]);
+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();
+ let doc = reopen(&doc);
+ let fonts = dr_fonts(&doc);
+ for (name, base) in [("Helv", "Helvetica"), ("TiRo", "Times-Roman"), ("Cour", "Courier")] {
+ let r = fonts.reference(name.as_bytes()).unwrap_or_else(|| panic!("{name} is an object: {fonts:?}"));
+ assert_eq!(doc.get(r).as_dict().and_then(|f| f.name(b"BaseFont")), Some(base.as_bytes()));
+ }
+}
+
+/// #3441: a form saved earlier with inline `/DR` fonts gets them as objects once a field is
+/// added, saying the same; an indirect `/Font` dictionary stays the object it was.
+#[test]
+fn inline_form_fonts_become_objects_and_an_indirect_font_dictionary_stays_one() {
+ for indirect in [false, true] {
+ let font = "/Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> /Mine << /Type /Font /Subtype /Type1 /BaseFont /Symbol >>";
+ let (fonts_entry, extra) =
+ if indirect { ("6 0 R".to_string(), vec![format!("<< {font} >>")]) } else { (format!("<< {font} >>"), Vec::new()) };
+ let mut 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 >>".into(),
+ format!("<< /Fields [] /DA (/Helv 0 Tf 0 g) /DR << /Font {fonts_entry} >> >>"),
+ "null".into(),
+ ];
+ objs.extend(extra);
+ let mut doc = document(&objs);
+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();
+ let doc = reopen(&doc);
+ let fonts = dr_fonts(&doc);
+ for (name, base) in [("Helv", "Helvetica"), ("Mine", "Symbol"), ("TiRo", "Times-Roman")] {
+ let r = fonts.reference(name.as_bytes()).unwrap_or_else(|| panic!("{name} is an object (indirect {indirect}): {fonts:?}"));
+ assert_eq!(doc.get(r).as_dict().and_then(|f| f.name(b"BaseFont")), Some(base.as_bytes()), "{name} says the same");
+ }
+ let dr = doc.resolve(acroform(&doc).unwrap().get(b"DR").unwrap());
+ assert_eq!(dr.as_dict().unwrap().reference(b"Font").is_some(), indirect, "the /Font dictionary keeps its form");
+ }
+}
+
+/// #3441: an indirect `/DR` stays the object it is, and a form whose three standard fonts are
+/// all already there (inline) still gets them as objects, though none is added.
+#[test]
+fn an_indirect_resource_dictionary_and_a_complete_inline_set_are_handled() {
+ let inline = "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>";
+ let all = format!(
+ "/Helv {inline} /TiRo << /Type /Font /Subtype /Type1 /BaseFont /Times-Roman >> /Cour << /Type /Font /Subtype /Type1 /BaseFont /Courier >>"
+ );
+ for indirect_dr in [false, true] {
+ let dr = if indirect_dr { "5 0 R".to_string() } else { format!("<< /Font << {all} >> >>") };
+ let 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 >>".into(),
+ format!("<< /Fields [] /DA (/Helv 0 Tf 0 g) /DR {dr} >>"),
+ format!("<< /Font << {all} >> >>"),
+ ]);
+ let mut doc = doc;
+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();
+ let doc = reopen(&doc);
+ let fonts = dr_fonts(&doc);
+ for name in ["Helv", "TiRo", "Cour"] {
+ assert!(fonts.reference(name.as_bytes()).is_some(), "{name} is an object (indirect /DR {indirect_dr}): {fonts:?}");
+ }
+ assert_eq!(acroform(&doc).unwrap().reference(b"DR").is_some(), indirect_dr, "/DR keeps its form");
+ }
+}
+
+/// #3441: fonts the form already has are its own, not replaced by the standard ones: an inline
+/// `/Helv` that is Arial becomes an object that is still Arial, a `/TiRo` object stays that
+/// object, and a form needing no change leaves its `/DR` object unwritten. The fonts PdfCraft
+/// adds use WinAnsi, as Acrobat's do.
+#[test]
+fn existing_form_fonts_are_kept_and_an_unchanged_resource_dictionary_is_not_rewritten() {
+ 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 >>".into(),
+ "<< /Fields [] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv << /Type /Font /Subtype /Type1 /BaseFont /Arial >> /TiRo 5 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Times-Bold >>".into(),
+ ]);
+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();
+ let doc = reopen(&doc);
+ let fonts = dr_fonts(&doc);
+ let font = |name: &str| doc.get(fonts.reference(name.as_bytes()).unwrap()).as_dict().cloned().unwrap();
+ assert_eq!(font("Helv").name(b"BaseFont"), Some(&b"Arial"[..]), "the form's own Helv");
+ assert_eq!(fonts.reference(b"TiRo"), Some(pdfcraft_cos::ObjRef::new(5, 0)), "the same object");
+ assert_eq!(font("Cour").name(b"Encoding"), Some(&b"WinAnsiEncoding"[..]));
+
+ // Every font an object already, /DR an object: adding a field leaves /DR as it was.
+ 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 >>".into(),
+ "<< /Fields [] /DA (/Helv 0 Tf 0 g) /DR 5 0 R >>".into(),
+ "<< /Font << /Helv 6 0 R /TiRo 6 0 R /Cour 6 0 R >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ ]);
+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name")).unwrap();
+ assert!(!doc.modified_objects().contains(&5), "/DR unchanged: {:?}", doc.modified_objects());
+}
+
+/// #3441, exhaustively: every way a form's `/DR` may hold its fonts. `/DR` missing, inline or an
+/// object; its `/Font` missing, inline, an object or not a dictionary; `/Helv` missing, inline,
+/// an object, a reference to nothing, `null` or a number; and a font of the form's own, inline or
+/// an object. After a field is added, whatever the shape:
+/// - no font is a dictionary written inline;
+/// - a font that was an object is the same object, and one that was inline says the same as an
+/// object;
+/// - a `/DR` or `/Font` that was an object (and a dictionary) still is one;
+/// - an entry that is not a dictionary (`null`, a number, a reference to nothing) is left alone;
+/// - Helv, TiRo and Cour are there.
+#[test]
+fn every_shape_of_form_fonts_ends_as_objects() {
+ let font = |base: &str| format!("<< /Type /Font /Subtype /Type1 /BaseFont /{base} >>");
+ let mut cases = 0;
+ for dr_shape in ["missing", "inline", "object"] {
+ for font_shape in ["missing", "inline", "object", "number"] {
+ for helv in ["missing", "inline", "object", "dangling", "null", "number"] {
+ for mine in ["missing", "inline", "object"] {
+ if dr_shape == "missing" && (font_shape != "missing" || helv != "missing" || mine != "missing") {
+ continue;
+ }
+ if matches!(font_shape, "missing" | "number") && (helv != "missing" || mine != "missing") {
+ continue;
+ }
+ cases += 1;
+ let what = format!("/DR {dr_shape}, /Font {font_shape}, /Helv {helv}, /Mine {mine}");
+ let mut entries = String::new();
+ match helv {
+ "inline" => entries += &format!("/Helv {} ", font("Arial")),
+ "object" => entries += "/Helv 7 0 R ",
+ "dangling" => entries += "/Helv 99 0 R ",
+ "null" => entries += "/Helv null ",
+ "number" => entries += "/Helv 3 ",
+ _ => {}
+ }
+ match mine {
+ "inline" => entries += &format!("/Mine {} ", font("Symbol")),
+ "object" => entries += "/Mine 8 0 R ",
+ _ => {}
+ }
+ let fonts_value = match font_shape {
+ "inline" => format!("<< {entries}>>"),
+ "object" => "6 0 R".into(),
+ "number" => "7".into(),
+ _ => String::new(),
+ };
+ let dr_dict = if fonts_value.is_empty() { "<< >>".to_string() } else { format!("<< /Font {fonts_value} >>") };
+ let dr_value = match dr_shape {
+ "inline" => dr_dict.clone(),
+ "object" => "5 0 R".into(),
+ _ => String::new(),
+ };
+ let af = if dr_value.is_empty() { "<< /Fields [] >>".to_string() } else { format!("<< /Fields [] /DR {dr_value} >>") };
+ 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 >>".into(),
+ af,
+ if dr_shape == "object" { dr_dict } else { "null".into() },
+ if font_shape == "object" { format!("<< {entries}>>") } else { "null".into() },
+ font("Helvetica-Oblique"),
+ font("ZapfDingbats"),
+ ]);
+ add_field(&mut doc, 0, [40.0, 600.0, 300.0, 630.0], &NewField::Text { multiline: false }, Some("name"))
+ .unwrap_or_else(|e| panic!("{what}: {e}"));
+ let doc = reopen(&doc);
+ let af = acroform(&doc).unwrap();
+ let dr = doc.resolve(af.get(b"DR").unwrap_or_else(|| panic!("{what}: no /DR")));
+ let fonts = dr_fonts(&doc);
+ for (name, value) in fonts.iter() {
+ assert!(value.as_dict().is_none(), "{what}: {} is inline", String::from_utf8_lossy(name));
+ }
+ for name in ["Helv", "TiRo", "Cour"] {
+ assert!(fonts.contains(name.as_bytes()), "{what}: no {name}");
+ }
+ let base =
+ |name: &[u8]| fonts.reference(name).and_then(|r| doc.get(r).as_dict().and_then(|f| f.name(b"BaseFont").map(<[u8]>::to_vec)));
+ match helv {
+ "inline" => assert_eq!(base(b"Helv").as_deref(), Some(&b"Arial"[..]), "{what}"),
+ "object" => assert_eq!(fonts.reference(b"Helv"), Some(pdfcraft_cos::ObjRef::new(7, 0)), "{what}"),
+ "dangling" => assert_eq!(fonts.reference(b"Helv"), Some(pdfcraft_cos::ObjRef::new(99, 0)), "{what}"),
+ "null" => assert_eq!(fonts.get(b"Helv"), Some(&Object::Null), "{what}"),
+ "number" => assert_eq!(fonts.get(b"Helv"), Some(&Object::Int(3)), "{what}"),
+ _ => assert_eq!(base(b"Helv").as_deref(), Some(&b"Helvetica"[..]), "{what}"),
+ }
+ match mine {
+ "inline" => assert_eq!(base(b"Mine").as_deref(), Some(&b"Symbol"[..]), "{what}"),
+ "object" => assert_eq!(fonts.reference(b"Mine"), Some(pdfcraft_cos::ObjRef::new(8, 0)), "{what}"),
+ _ => assert!(!fonts.contains(b"Mine"), "{what}"),
+ }
+ if dr_shape == "object" {
+ assert_eq!(af.reference(b"DR"), Some(pdfcraft_cos::ObjRef::new(5, 0)), "{what}: /DR stays its object");
+ }
+ if font_shape == "object" {
+ assert_eq!(dr.as_dict().unwrap().reference(b"Font"), Some(pdfcraft_cos::ObjRef::new(6, 0)), "{what}: /Font stays its object");
+ }
+ }
+ }
+ }
+ }
+ assert_eq!(cases, 1 + 2 * (2 + 2 * 6 * 3), "every shape was tried");
+}
+
+/// #3441 (review follow-up): filling a field converts the form's inline `/DR` fonts, so a form
+/// an earlier PdfCraft made works in Acrobat once it has been filled here. Nothing is added. A
+/// form a signature covers keeps `/DR` as the signer saw it, and a form whose fonts are objects
+/// already leaves its `/DR` object unwritten.
+#[test]
+fn filling_a_field_makes_inline_form_fonts_objects_unless_the_form_is_signed() {
+ let inline = "/Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>";
+ let form = |signed: bool, dr: &str| {
+ let sig = if signed { "<< /Type /Annot /Subtype /Widget /FT /Sig /T (sig) /V 7 0 R /Rect [0 0 0 0] /P 3 0 R >>" } else { "null" };
+ let fields = if signed { "[5 0 R 6 0 R]" } else { "[5 0 R]" };
+ 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 [5 0 R] >>".into(),
+ format!("<< /Fields {fields} /DA (/Helv 0 Tf 0 g) /DR {dr} >>"),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /DA (/Helv 12 Tf 0 g) /Rect [50 700 300 720] /P 3 0 R >>".into(),
+ sig.into(),
+ "<< /Type /Sig /Filter /Adobe.PPKLite /Contents <00> >>".into(),
+ "<< /Font << /Helv 9 0 R >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ ])
+ };
+ let mut doc = form(false, &format!("<< /Font << {inline} >> >>"));
+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();
+ let doc = reopen(&doc);
+ let fonts = dr_fonts(&doc);
+ assert!(fonts.reference(b"Helv").is_some(), "Helv became an object: {fonts:?}");
+ assert_eq!(fonts.len(), 1, "nothing added: {fonts:?}");
+ assert_eq!(field(&fields(&doc), "name").value, ["Ada"]);
+
+ let mut doc = form(true, &format!("<< /Font << {inline} >> >>"));
+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();
+ let doc = reopen(&doc);
+ assert!(dr_fonts(&doc).get(b"Helv").is_some_and(|h| h.as_dict().is_some()), "a signed form keeps /DR as it was");
+
+ // An empty signature field signs nothing: the form is converted as an unsigned one.
+ let mut doc = form(true, &format!("<< /Font << {inline} >> >>"));
+ doc.update_dict(pdfcraft_cos::ObjRef::new(6, 0), |d| {
+ d.remove(b"V");
+ })
+ .unwrap();
+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();
+ assert!(dr_fonts(&reopen(&doc)).reference(b"Helv").is_some(), "an unsigned signature field doesn't hold /DR back");
+
+ let mut doc = form(false, "8 0 R");
+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();
+ assert!(!doc.modified_objects().contains(&8), "/DR unchanged: {:?}", doc.modified_objects());
+}
+
+/// #3441 (review follow-up): a signature value held by a parent field signs its kid too (`/V` is
+/// inheritable, ISO 32000-2 Table 226), so the form still counts as signed and keeps its `/DR`.
+#[test]
+fn a_signature_value_on_a_parent_field_keeps_the_form_fonts_as_signed() {
+ 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 [5 0 R 8 0 R] >>".into(),
+ "<< /Fields [5 0 R 6 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> >> >> >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /DA (/Helv 12 Tf 0 g) /Rect [50 700 300 720] /P 3 0 R >>".into(),
+ "<< /FT /Sig /T (sig) /V 7 0 R /Kids [8 0 R] >>".into(),
+ "<< /Type /Sig /Filter /Adobe.PPKLite /Contents <00> >>".into(),
+ "<< /Type /Annot /Subtype /Widget /T (s1) /Parent 6 0 R /Rect [0 0 0 0] /P 3 0 R >>".into(),
+ ]);
+ let kid = pdfcraft_cos::ObjRef::new(8, 0);
+ assert!(fields(&doc).iter().any(|f| f.obj == kid && f.kind == FieldKind::Signature), "the kid is the signature field");
+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();
+ let doc = reopen(&doc);
+ assert!(dr_fonts(&doc).get(b"Helv").is_some_and(|h| h.as_dict().is_some()), "an inherited signature value keeps /DR as it was");
+ assert_eq!(field(&fields(&doc), "name").value, ["Ada"]);
+}
+
+/// #3441 (review follow-up): a catalog that holds `/AcroForm` as a direct dictionary gets its
+/// inline `/DR` fonts converted too when a field is filled.
+#[test]
+fn filling_a_field_converts_inline_fonts_of_a_direct_form_dictionary() {
+ let mut doc = document(&[
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [4 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> >> >> >> >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [4 0 R] >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /DA (/Helv 12 Tf 0 g) /Rect [50 700 300 720] /P 3 0 R >>".into(),
+ ]);
+ set_value(&mut doc, "name", &FieldValue::Text("Ada".into())).unwrap();
+ let doc = reopen(&doc);
+ let fonts = dr_fonts(&doc);
+ assert!(fonts.reference(b"Helv").is_some(), "Helv became an object: {fonts:?}");
+ assert_eq!(fonts.len(), 1, "nothing added: {fonts:?}");
+ assert_eq!(field(&fields(&doc), "name").value, ["Ada"]);
+}
+
+/// #3926 / #3943 review: a password value can be inherited from an ancestor field or sit on a
+/// separate widget. Clearing removes both; an ancestor's value shared with a non-password field
+/// stays for that field, and the password field gets an empty value of its own instead.
+#[test]
+fn inherited_and_widget_password_values_are_cleared() {
+ 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 9 0 R 11 0 R] >>".into(), // 3
+ "<< /Fields [5 0 R 8 0 R 10 0 R] /DA (/Helv 0 Tf 0 g) >>".into(), // 4
+ "<< /T (acct) /FT /Tx /Ff 8192 /V (secret1) /Kids [6 0 R] >>".into(), // 5 flag and value inherited
+ "<< /Type /Annot /Subtype /Widget /T (pin) /Parent 5 0 R /Rect [50 700 150 720] /P 3 0 R >>".into(), // 6
+ "<< /Type /Annot /Subtype /Widget /Parent 8 0 R /V (secret3) /Rect [50 650 150 670] /P 3 0 R >>".into(), // 7 value on the widget
+ "<< /FT /Tx /T (code) /Ff 8192 /Kids [7 0 R] >>".into(), // 8
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (pw) /Ff 8192 /Parent 10 0 R /Rect [50 600 150 620] /P 3 0 R >>".into(), // 9
+ "<< /T (grp) /V (shared2) /Kids [9 0 R 11 0 R] >>".into(), // 10 shared with a plain field
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (plain) /Parent 10 0 R /Rect [50 550 150 570] /P 3 0 R >>".into(), // 11
+ ];
+ let mut doc = document(&objs);
+ assert!(has_password_values(&doc));
+ let value = |doc: &Document, n: &str| fields(doc).into_iter().find(|f| f.name == n).map(|f| f.value).unwrap_or_default();
+ assert_eq!(value(&doc, "acct.pin"), ["secret1"], "inherited before");
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 3);
+ assert!(!has_password_values(&doc));
+ for n in ["acct.pin", "code", "grp.pw"] {
+ assert!(value(&doc, n).iter().all(|v| v.is_empty()), "{n} cleared");
+ }
+ assert_eq!(value(&doc, "grp.plain"), ["shared2"], "the shared value stays for the plain field");
+ let has_v = |doc: &Document, n: u32| doc.get(pdfcraft_cos::ObjRef { num: n, generation: 0 }).as_dict().is_some_and(|d| d.get(b"V").is_some());
+ assert!(!has_v(&doc, 5), "an ancestor only password fields inherit from loses its value");
+ assert!(!has_v(&doc, 7), "a widget's value is removed");
+ assert!(has_v(&doc, 10), "a shared ancestor keeps its value");
+}
+
+/// #3943 review: a cleared password field saves as Acrobat saves it (black-box test). One with a
+/// default value gets it back, and its appearance shows as many masking characters as the
+/// default has, not as the typed password had; one without is left empty and draws none. The
+/// default value and the scripts stay, and a field already at its default needs no clearing.
+#[test]
+fn a_cleared_password_field_returns_to_its_default_value() {
+ 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] >>".into(), // 3
+ "<< /Fields [6 0 R 7 0 R 8 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(), // 4
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(), // 5
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (pw) /Ff 8192 /DV (DEF-1) /V (NEWPASS-77777) /AA << /K << /S /JavaScript /JS (1;) >> >> /Rect [50 700 250 720] /P 3 0 R >>".into(), // 6
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (pw3) /Ff 8192 /V (PW3-TYPED-9) /Rect [50 650 250 670] /P 3 0 R >>".into(), // 7
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (blank) /Ff 8192 /V [()] /Rect [50 600 250 620] /P 3 0 R >>".into(), // 8 holds nothing (an empty string in an array)
+ ];
+ let mut doc = document(&objs);
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 2);
+ let all = fields(&doc);
+ let (pw, pw3) = (field(&all, "pw"), field(&all, "pw3"));
+ assert_eq!(pw.value, ["DEF-1"], "back to its default");
+ assert_eq!(pw.default, ["DEF-1"], "the default stays");
+ assert!(pw.actions.scripts.keystroke.is_some(), "the scripts stay");
+ assert!(pw3.value.iter().all(|v| v.is_empty()), "no default: empty");
+ let shown = ap(&doc, &pw.widgets[0]);
+ assert!(shown.contains("(*****)") && !shown.contains("NEWPASS") && !shown.contains("******"), "{shown}");
+ let shown3 = ap(&doc, &pw3.widgets[0]);
+ assert!(!shown3.contains('*') && !shown3.contains("PW3"), "{shown3}");
+ assert!(!has_password_values(&doc), "a field at its default holds no typed password");
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 0);
+}
+
+/// #3943 review: the quick check that skips forms without a Password field still sees one whose
+/// widget is only on the page, not listed in `/Fields`; one that inherits the flag from a parent
+/// that is not listed either; and one deeper in the field tree whose widget is on no page. Each
+/// is alone in its own document, so each path of the check is needed.
+#[test]
+fn a_password_field_missing_from_the_field_list_is_still_cleared() {
+ let form = |fields: &str, annots: &str, rest: &[&str]| {
+ let mut 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(),
+ format!("<< /Type /Page /Parent 2 0 R /Annots [{annots}] >>"),
+ format!("<< /Fields [{fields}] /DA (/Helv 0 Tf 0 g) >>"),
+ ];
+ objs.extend(rest.iter().map(|o| o.to_string()));
+ document(&objs)
+ };
+ let page_only =
+ form("", "5 0 R", &["<< /Type /Annot /Subtype /Widget /FT /Tx /T (pin) /Ff 8192 /V (secret5) /Rect [50 700 150 720] /P 3 0 R >>"]);
+ let inherited = form(
+ "",
+ "5 0 R",
+ &[
+ "<< /Type /Annot /Subtype /Widget /T (kid) /Parent 6 0 R /Rect [50 650 150 670] /P 3 0 R >>",
+ "<< /FT /Tx /T (acct) /Ff 8192 /V (secret6) /Kids [5 0 R] >>",
+ ],
+ );
+ let off_page = form(
+ "5 0 R",
+ "",
+ &[
+ "<< /T (grp) /Kids [6 0 R] >>",
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (hidden) /Ff 8192 /V (secret7) /Parent 5 0 R /Rect [0 0 0 0] >>",
+ ],
+ );
+ for (what, mut doc) in [("page only", page_only), ("inherited", inherited), ("on no page", off_page)] {
+ assert!(has_password_values(&doc), "{what}");
+ assert_eq!(clear_password_values(&mut doc).unwrap(), 1, "{what}");
+ assert!(fields(&doc).iter().all(|f| f.value.iter().all(|v| v.is_empty())), "{what}: {:?}", fields(&doc));
+ }
+}
+
+/// #4018: a value that doesn't fit its box at the field's font size is reported (it is drawn cut
+/// at the box). An auto-sized field shrinks to fit, and a short or empty value fits.
+#[test]
+fn a_value_wider_or_taller_than_its_box_is_reported() {
+ let long = "Doe, Jane (represented by John Doe)";
+ let field = |name: &str, rect: &str, extra: &str, value: &str| {
+ format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /V ({value}) /Rect [{rect}] /P 3 0 R {extra} >>")
+ };
+ let 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 7 0 R 8 0 R 9 0 R 10 0 R] >>".into(),
+ "<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ field("single", "50 700 190 718", "", long),
+ field("multi", "50 650 190 668", "/Ff 4096", long),
+ field("auto", "50 600 190 618", "/DA (/Helv 0 Tf 0 g)", long),
+ field("wide", "50 550 350 568", "", long),
+ field("short", "50 500 190 518", "/Ff 4096", "Ada"),
+ ]);
+ let overflow = |name: &str| {
+ let f = fields(&doc).into_iter().find(|f| f.name == name).unwrap();
+ appearance::value_overflow(&doc, &f, &f.widgets[0])
+ };
+ match overflow("single") {
+ Some(appearance::Overflow::Wide { width, room, size }) => {
+ assert_eq!(size, 12.0);
+ assert!((width - 201.4).abs() < 1.0 && room < 140.0, "{width} in {room}");
+ }
+ other => panic!("single: {other:?}"),
+ }
+ assert_eq!(overflow("multi"), Some(appearance::Overflow::Tall { lines: 2, room: 1, size: 12.0 }));
+ assert_eq!(overflow("auto"), None, "auto size shrinks to fit");
+ assert_eq!(overflow("wide"), None);
+ assert_eq!(overflow("short"), None);
+}
+
+/// #4018: a single line taller than its box is cut at the top and bottom, and a character wider
+/// than a multiline box is a line of its own that is still cut at the sides; both are reported.
+/// An empty value draws nothing, so nothing is cut however small the box.
+#[test]
+fn a_line_taller_than_its_box_or_a_character_wider_than_it_is_reported() {
+ let field = |name: &str, rect: &str, extra: &str, value: &str| {
+ format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /V ({value}) /Rect [{rect}] /P 3 0 R {extra} >>")
+ };
+ let 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 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R] >>".into(),
+ "<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R] /DA (/Helv 12 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ field("low", "50 700 190 708", "", "Ada"),
+ field("comb", "50 650 190 658", "/Ff 16777216 /MaxLen 5", "Ada"),
+ field("narrow", "50 500 56 560", "/Ff 4096", "WW"),
+ field("roomy", "50 400 190 418", "", "Ada"),
+ field("empty", "50 350 190 358", "", ""),
+ field("empty-multi", "50 300 190 304", "/Ff 4096", ""),
+ ]);
+ let overflow = |name: &str| {
+ let f = fields(&doc).into_iter().find(|f| f.name == name).unwrap();
+ appearance::value_overflow(&doc, &f, &f.widgets[0])
+ };
+ for name in ["low", "comb"] {
+ match overflow(name) {
+ Some(o @ appearance::Overflow::High { height, room, size }) => {
+ assert_eq!(size, 12.0);
+ assert!((height - 11.1).abs() < 0.01 && room <= 8.0, "{name}: {height} in {room}");
+ assert!(o.to_string().starts_with("the value does not fit: 11.1 pt high at 12 pt"), "{o}");
+ }
+ other => panic!("{name}: {other:?}"),
+ }
+ }
+ match overflow("narrow") {
+ Some(appearance::Overflow::Wide { width, room, size }) => {
+ assert_eq!(size, 12.0);
+ assert!(width > room && (width - 11.32).abs() < 0.1, "{width} in {room}");
+ }
+ other => panic!("narrow: {other:?}"),
+ }
+ assert_eq!(overflow("roomy"), None);
+ assert_eq!(overflow("empty"), None);
+ assert_eq!(overflow("empty-multi"), None);
+}
++
+ /// Check boxes, radio buttons and push buttons whose file gives them no appearance, a comb field,
+ /// a combo box and a list box, for the display copy.
+ fn left_buttons() -> Document {
+ let widget = |n: &str, rest: &str| format!("<< /Type /Annot /Subtype /Widget /T ({n}) /F 4 /P 3 0 R {rest} >>");
+ 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 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R 15 0 R 16 0 R 17 0 R 18 0 R] >>".into(),
+ "<< /Fields [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R 13 0 R 14 0 R 15 0 R 16 0 R 17 0 R 18 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ widget("i", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 0 g) /MK << /CA (4) /BC [0 0 0] >> /Rect [50 700 74 724]"), // 6
+ widget("j", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 0 0 1 rg) /MK << /CA (l) /BC [0 0 0] >> /Rect [100 700 124 724]"),
+ widget("k", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 1 0 0 rg) /MK << /CA (8) /BC [0 0 0] >> /Rect [150 700 174 724]"),
+ widget("l", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 9 Tf 0 g) /MK << /CA (H) /BC [0 0 0] /BG [1 1 0] >> /Rect [200 700 224 724]"),
+ widget("off", "/FT /Btn /V /Off /AS /Off /DA (/ZaDb 0 Tf 0 g) /MK << /CA (4) /BC [0 0 0] >> /Rect [250 700 274 724]"), // 10
+ widget("radio", "/FT /Btn /Ff 32768 /V /A /AS /A /DA (/ZaDb 0 Tf 0 g) /MK << /BC [0 0 0] >> /Rect [300 700 324 724]"),
+ widget(
+ "o",
+ "/FT /Btn /Ff 65536 /DA (/Helv 12 Tf 0 g) /MK << /CA (Press me) /BG [0.8 0.8 0.8] /BC [0 0 0] >> /BS << /W 2 /S /B >> /Rect [50 600 170 624]",
+ ),
+ widget("own", "/FT /Btn /V /Yes /AS /Yes /MK << /CA (4) /BC [0 0 0] >> /Rect [350 700 374 724] /AP << /N << /Yes 19 0 R /Off 19 0 R >> >>"),
+ widget("half", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb 0 Tf 0 g) /MK << /CA (8) >> /Rect [400 700 424 724] /AP << /N << /Off 19 0 R >> >>"),
+ widget("bad", "/FT /Btn /V /Yes /AS /Yes /DA (/ZaDb nan Tf 1 x rg) /MK << /CA 42 /BC [(no) /Name] /BG 7 >> /BS << /W -3 >> /Rect [450 700 474 724]"), // 15
+ widget("d", "/FT /Tx /Ff 16777216 /MaxLen 6 /V (ABC123) /DA (/Helv 12 Tf 0 g) /MK << /BC [0 0 1] >> /Rect [50 500 170 524]"),
+ widget("m", "/FT /Ch /Ff 131072 /Opt [(Apple) (Banana)] /V (Banana) /Q 2 /DA (/Helv 12 Tf 0 g) /MK << /BC [0 0 0] >> /Rect [50 400 170 424]"),
+ widget("n", "/FT /Ch /Opt [(One) (Two)] /V (Two) /DA (/Helv 11 Tf 0 g) /MK << /BC [0 0 0] >> /Rect [200 400 320 460]"),
+ "<< /Length 4 >>\nstream\nq\nQ\nendstream".into(), // 19
+ ])
+ }
+
+ /// The appearance stream of widget `w` in `state` (a check box's `/AP /N /<state>`).
+ fn state_ap(doc: &Document, w: &Widget, state: &str) -> String {
+ let wd = doc.get(w.obj).as_dict().cloned().unwrap();
+ let ap = doc.resolve(wd.get(b"AP").unwrap()).as_dict().cloned().unwrap();
+ let n = doc.resolve(ap.get(b"N").unwrap()).as_dict().cloned().unwrap();
+ let r = n.reference(state.as_bytes()).expect("the state's appearance");
+ let Object::Stream(s) = &*doc.get(r) else { panic!("a stream") };
+ String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
+ }
+
+ /// The decoded appearance PdfCraft would save for text or choice field `name` of `doc`.
+ fn saved_look(doc: &Document, name: &str) -> String {
+ let all = fields(doc);
+ let f = field(&all, name);
+ String::from_utf8_lossy(&appearance::field_appearance(doc, f, &f.widgets[0], &f.value).decoded().unwrap()).into_owned()
+ }
+
+ /// ISO 32000-2 Table 192 and 12.7.5.2.3: a check box with no appearance shows its `/MK /BC`
+ /// border and, when on, its caption `/MK /CA` as a ZapfDingbats character in the `/DA` colour,
+ /// sized to the box when the `/DA` size is 0.
+ #[test]
+ fn check_boxes_without_an_appearance_show_their_caption_symbol() {
+ let doc = left_buttons();
+ let copy = with_field_appearances(&doc).expect("buttons to draw");
+ let all = fields(&copy);
+ for (name, symbol, colour) in [("i", "(4) Tj", "0 g"), ("j", "(l) Tj", "0 0 1 rg"), ("k", "(8) Tj", "1 0 0 rg"), ("l", "(H) Tj", "0 g")] {
+ let shown = state_ap(&copy, &field(&all, name).widgets[0], "Yes");
+ assert!(shown.contains(symbol), "{name}: {shown}");
+ assert!(shown.contains(&format!("{colour}\n")), "{name} in its colour: {shown}");
+ assert!(shown.contains("0 0 0 RG\n1 w\n0.5 0.5 23 23 re S"), "{name} has its border: {shown}");
+ }
+ // A /DA size is kept; the automatic one fills the box inside the border.
+ let l = state_ap(&copy, &field(&all, "l").widgets[0], "Yes");
+ assert!(l.contains("/ZaDb 9 Tf") && l.contains("1 1 0 rg\n0 0 24 24 re f"), "{l}");
+ let i = state_ap(&copy, &field(&all, "i").widgets[0], "Yes");
+ let size: f64 = i.split("/ZaDb ").nth(1).and_then(|s| s.split(' ').next()).and_then(|s| s.parse().ok()).unwrap();
+ assert!((18.0..=26.0).contains(&size), "{size}");
+ let w = copy.get(field(&all, "i").widgets[0].obj);
+ let ap = copy.resolve(w.as_dict().unwrap().get(b"AP").unwrap());
+ let n = copy.resolve(ap.as_dict().unwrap().get(b"N").unwrap());
+ let Object::Stream(s) = &*copy.get(n.as_dict().unwrap().reference(b"Yes").unwrap()) else { panic!() };
+ let font = s.dict.get(b"Resources").and_then(|r| r.as_dict()).and_then(|r| r.get(b"Font")).and_then(|f| f.as_dict()).and_then(|f| f.get(b"ZaDb"));
+ assert_eq!(font.and_then(|f| f.as_dict()).and_then(|f| f.name(b"BaseFont")), Some(&b"ZapfDingbats"[..]), "a standard-14 font, no program");
+ }
+
+ /// An Off check box shows only its border, a radio button without a caption a dot (`l`), a box
+ /// whose file has only an Off look gets an on look, and one with its own look keeps it.
+ #[test]
+ fn button_states_without_an_appearance() {
+ let doc = left_buttons();
+ let copy = with_field_appearances(&doc).expect("buttons to draw");
+ let all = fields(&copy);
+ let off = state_ap(&copy, &field(&all, "off").widgets[0], "Off");
+ assert!(off.contains("re S") && !off.contains("Tj"), "{off}");
+ assert!(state_ap(&copy, &field(&all, "radio").widgets[0], "A").contains("(l) Tj"));
+ assert!(state_ap(&copy, &field(&all, "half").widgets[0], "Yes").contains("(8) Tj"));
+ let own = |d: &Document| d.get(field(&fields(d), "own").widgets[0].obj).as_dict().and_then(|w| w.get(b"AP").cloned());
+ assert_eq!(own(&copy), own(&doc), "a check box with its own look keeps it");
+ // Nonsense in /MK, /DA and /BS: the default symbol, no border, and no panic.
+ let bad = state_ap(&copy, &field(&all, "bad").widgets[0], "Yes");
+ assert!(bad.contains("(4) Tj") && !bad.contains("re S"), "{bad}");
+ // The document itself is untouched.
+ assert!(doc.get(field(&fields(&doc), "i").widgets[0].obj).as_dict().is_some_and(|w| !w.contains(b"AP")));
+ }
+
+ /// Table 192 and Table 168: a push button with no appearance shows its `/MK /BG` background, its
+ /// beveled `/MK /BC` border in the `/BS` width, and its caption `/MK /CA` centred.
+ #[test]
+ fn push_buttons_without_an_appearance_show_their_caption_and_frame() {
+ let copy = with_field_appearances(&left_buttons()).expect("buttons to draw");
+ let shown = ap(&copy, &field(&fields(&copy), "o").widgets[0]);
+ for part in ["0.8 0.8 0.8 rg\n0 0 120 24 re f", "0 0 0 RG\n2 w\n1 1 118 22 re S", "1 g\n", "0.5 g\n", "(Press me) Tj", "/Helv 12.00 Tf"] {
+ assert!(shown.contains(part), "{part}: {shown}");
+ }
+ }
+
+ /// ISO 32000-2 Table 228, Comb: the field is divided into MaxLen equally spaced positions, and a
+ /// bordered comb field shows them: MaxLen - 1 lines in the border colour, in its saved look too.
+ #[test]
+ fn comb_fields_show_their_cells() {
+ let mut doc = left_buttons();
+ let shown = saved_look(&doc, "d");
+ let lines: Vec<&str> = shown.lines().filter(|l| l.ends_with(" l") && l.contains(" 1 m ")).collect();
+ assert_eq!(lines, ["20 1 m 20 23 l", "40 1 m 40 23 l", "60 1 m 60 23 l", "80 1 m 80 23 l", "100 1 m 100 23 l"], "{shown}");
+ assert!(shown.contains("0 0 1 RG\n1 w\n20 1 m"), "in the border colour: {shown}");
+ // Past the cap no lines, and a huge MaxLen is no trouble; without a border, none either.
+ let r = field(&fields(&doc), "d").widgets[0].obj;
+ doc.update_dict(r, |w| w.set(b"MaxLen".to_vec(), Object::Int(1 << 40))).unwrap();
+ let huge = saved_look(&doc, "d");
+ assert!(!huge.contains(" 1 m ") && huge.contains("(A) Tj"), "{huge}");
+ doc.update_dict(r, |w| {
+ w.set(b"MaxLen".to_vec(), Object::Int(6));
+ w.remove(b"MK");
+ })
+ .unwrap();
+ let plain = saved_look(&doc, "d");
+ assert!(!plain.contains(" m ") && plain.contains("(A) Tj"), "{plain}");
+ }
diff --cc parity/acrobat-features.toml
index 25281bc2b,9d98027d5..bcd83023a
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@@ -4440,8 -4440,8 +4440,8 @@@ milestone = "M6
status = "shipped"
commands = ["form.fields"]
tools = ["form_fill", "form_fields"]
- evidence = ["crates/ui-egui/tests/it/forms.rs::typing_into_a_text_field_and_tabbing_on", "crates/ui-egui/tests/it/forms.rs::auto_size_fields_shrink_and_wrap_typed_text_to_fit_their_box", "crates/forms/src/tests.rs::text_fields_get_new_appearances", "crates/engine/src/tests.rs::filling_a_form_shows_saves_and_undoes", "crates/automation/tests/it/automation.rs::orphan_form_fields_through_tools", "crates/forms/src/tests.rs::fields_sharing_a_name_take_the_same_value", "crates/ui-egui/tests/it/forms.rs::hovering_a_field_shows_its_tooltip", "crates/forms/src/tests.rs::zero_max_len_is_unlimited_and_overrides_inherited_limit", "crates/engine/src/tests.rs::password_field_values_are_kept_in_memory_but_written_to_no_file", "crates/forms/src/tests.rs::a_cleared_password_field_returns_to_its_default_value", "crates/forms/src/tests.rs::a_text_field_says_what_fits_it_as_its_appearance_draws_it", "crates/forms/src/tests.rs::an_edit_to_a_full_field_keeps_what_fits", "crates/ui-egui/tests/it/forms.rs::a_field_that_doesnt_scroll_stops_taking_text_when_full", "crates/ui-egui/tests/it/forms.rs::a_multi_line_auto_sized_field_that_doesnt_scroll_stops_when_full", "crates/engine/src/tests.rs::an_xfa_field_that_doesnt_scroll_opens_with_do_not_scroll_and_a_text_box", "crates/xfa/src/tests.rs::fields_that_dont_scroll_are_written_with_do_not_scroll"]
- notes = "in-place editor; Enter or clicking away commits, Escape cancels; auto-size (0 Tf) fields shrink, and multiline ones wrap, the text being typed to fit the box, on screen as on the page (the screen measures in the interface font, so its size can be a little smaller than the page's Helvetica fit); fixed sizes are kept and clip, as in Acrobat; a field that doesn't scroll (DoNotScroll, ISO 32000-2 Table 228, and XFA's hScrollPolicy/vScrollPolicy=\"off\", written as it) takes no more text than its appearance shows, measured in the field's own font, padding and size (the smallest automatic size, 4 pt, for 0 Tf): typing into a full field adds nothing, and a paste or a replaced selection keeps what fits (form_fill isn't interactive and still takes any value); no format/keystroke JavaScript yet (M6.4); resting the pointer on any field shows its tooltip (/TU), as Acrobat does (#3854); imported MaxLen 0 permits text input and overrides inherited limits; positive limits remain enforced. A text field with the Password flag is saved as Acrobat saves it (#3926, black-box test): the typed value is written to no file (Save, Save As, Reduce File Size, recovery, Extract/Split/Combine, signing); the field gets back its default value (/DV) or is left empty, and its asterisks are redrawn from that value. /DV and the field's scripts stay. Known limits, which Acrobat shares: a script that copies the password into an ordinary field saves it there (Acrobat recalculates a Calculate copy on save, PdfCraft does not), and an incremental save leaves a password stored by an earlier revision in that revision."
-evidence = ["crates/ui-egui/tests/it/forms.rs::typing_into_a_text_field_and_tabbing_on", "crates/ui-egui/tests/it/forms.rs::auto_size_fields_shrink_and_wrap_typed_text_to_fit_their_box", "crates/forms/src/tests.rs::text_fields_get_new_appearances", "crates/engine/src/tests.rs::filling_a_form_shows_saves_and_undoes", "crates/automation/tests/it/automation.rs::orphan_form_fields_through_tools", "crates/forms/src/tests.rs::fields_sharing_a_name_take_the_same_value", "crates/ui-egui/tests/it/forms.rs::hovering_a_field_shows_its_tooltip", "crates/forms/src/tests.rs::zero_max_len_is_unlimited_and_overrides_inherited_limit", "crates/forms/src/tests.rs::comb_fields_show_their_cells"]
-notes = "in-place editor; Enter or clicking away commits, Escape cancels; auto-size (0 Tf) fields shrink, and multiline ones wrap, the text being typed to fit the box, on screen as on the page (the screen measures in the interface font, so its size can be a little smaller than the page's Helvetica fit); fixed sizes are kept and clip, as in Acrobat; no format/keystroke JavaScript yet (M6.4); resting the pointer on any field shows its tooltip (/TU), as Acrobat does (#3854); imported MaxLen 0 permits text input and overrides inherited limits; positive limits remain enforced. A comb field with a border colour shows its MaxLen cells as lines in that colour, in the appearances PdfCraft saves and in display-only ones (up to 500 cells)."
++evidence = ["crates/ui-egui/tests/it/forms.rs::typing_into_a_text_field_and_tabbing_on", "crates/ui-egui/tests/it/forms.rs::auto_size_fields_shrink_and_wrap_typed_text_to_fit_their_box", "crates/forms/src/tests.rs::text_fields_get_new_appearances", "crates/engine/src/tests.rs::filling_a_form_shows_saves_and_undoes", "crates/automation/tests/it/automation.rs::orphan_form_fields_through_tools", "crates/forms/src/tests.rs::fields_sharing_a_name_take_the_same_value", "crates/ui-egui/tests/it/forms.rs::hovering_a_field_shows_its_tooltip", "crates/forms/src/tests.rs::zero_max_len_is_unlimited_and_overrides_inherited_limit", "crates/engine/src/tests.rs::password_field_values_are_kept_in_memory_but_written_to_no_file", "crates/forms/src/tests.rs::a_cleared_password_field_returns_to_its_default_value", "crates/forms/src/tests.rs::a_text_field_says_what_fits_it_as_its_appearance_draws_it", "crates/forms/src/tests.rs::an_edit_to_a_full_field_keeps_what_fits", "crates/ui-egui/tests/it/forms.rs::a_field_that_doesnt_scroll_stops_taking_text_when_full", "crates/ui-egui/tests/it/forms.rs::a_multi_line_auto_sized_field_that_doesnt_scroll_stops_when_full", "crates/engine/src/tests.rs::an_xfa_field_that_doesnt_scroll_opens_with_do_not_scroll_and_a_text_box", "crates/xfa/src/tests.rs::fields_that_dont_scroll_are_written_with_do_not_scroll", "crates/forms/src/tests.rs::comb_fields_show_their_cells"]
++notes = "in-place editor; Enter or clicking away commits, Escape cancels; auto-size (0 Tf) fields shrink, and multiline ones wrap, the text being typed to fit the box, on screen as on the page (the screen measures in the interface font, so its size can be a little smaller than the page's Helvetica fit); fixed sizes are kept and clip, as in Acrobat; a field that doesn't scroll (DoNotScroll, ISO 32000-2 Table 228, and XFA's hScrollPolicy/vScrollPolicy=\"off\", written as it) takes no more text than its appearance shows, measured in the field's own font, padding and size (the smallest automatic size, 4 pt, for 0 Tf): typing into a full field adds nothing, and a paste or a replaced selection keeps what fits (form_fill isn't interactive and still takes any value); no format/keystroke JavaScript yet (M6.4); resting the pointer on any field shows its tooltip (/TU), as Acrobat does (#3854); imported MaxLen 0 permits text input and overrides inherited limits; positive limits remain enforced. A text field with the Password flag is saved as Acrobat saves it (#3926, black-box test): the typed value is written to no file (Save, Save As, Reduce File Size, recovery, Extract/Split/Combine, signing); the field gets back its default value (/DV) or is left empty, and its asterisks are redrawn from that value. /DV and the field's scripts stay. Known limits, which Acrobat shares: a script that copies the password into an ordinary field saves it there (Acrobat recalculates a Calculate copy on save, PdfCraft does not), and an incremental save leaves a password stored by an earlier revision in that revision. A comb field with a border colour shows its MaxLen cells as lines in that colour, in the appearances PdfCraft saves and in display-only ones (up to 500 cells)."
[[feature]]
id = "form.fill-checkbox-radio"