PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
Merge PR #4053: fix: Issue #4018, form_fill warns when a value does not fit its field (#4018)
aiongg01dc49c13c7e
diff --cc crates/forms/src/tests.rsindex 53e0b60ae,237b9d109..f215eb78c--- a/crates/forms/src/tests.rs+++ b/crates/forms/src/tests.rs@@@ -3032,718 -2982,86 +3032,802 @@@ fn page_walk_skips_repeated_and_cyclic_assert_eq!(page_refs(&doc), [page]);}+/// A Calculate script naming thousands of fields is merged with the field's other reads in one+/// pass, not by searching the names so far for each one.+#[test]+fn a_script_reading_many_fields_merges_its_reads_in_one_pass() {+ use crate::calc_order::NAMES_COMPARED;+ let mut doc = one_page();+ add_field(&mut doc, 0, [50.0, 700.0, 250.0, 720.0], &NewField::Text { multiline: false }, Some("total")).unwrap();+ let n = 2_000;+ let script: String = (0..n).map(|i| format!("getField(\"f{i}\").value + ")).collect::<String>() + "0";+ set_field_script(&mut doc, "total", "calculate", Some(&format!("event.value = {script};"))).unwrap();+ NAMES_COMPARED.with(|c| c.set(0));+ let order = calculation_order(&doc, &fields(&doc));+ assert_eq!(order.fields[0].reads.len(), n);+ let compared = NAMES_COMPARED.with(std::cell::Cell::get);+ assert!(compared <= 4 * n, "{compared} names compared for {n} reads");+}++/// 300 fields and 300 document scripts that all name one 1 MiB JavaScript stream.+fn repeated_script_references() -> Document {+ use pdfcraft_cos::Stream;+ let dict = |entries: Vec<(&[u8], Object)>| -> Object { Object::Dict(entries.into_iter().map(|(k, v)| (k.to_vec(), v)).collect()) };+ let mut doc = Document::new_empty();+ let js = doc.add(Stream::flate(pdfcraft_cos::Dict::new(), &vec![b'x'; 1 << 20]));+ let action = doc.add(dict(vec![(b"S", Object::Name(b"JavaScript".to_vec())), (b"JS", Object::Ref(js))]));+ let fields: Vec<Object> = (0..300)+ .map(|i| {+ Object::Ref(doc.add(dict(vec![+ (b"FT", Object::Name(b"Tx".to_vec())),+ (b"T", Object::String(pdfcraft_cos::PdfString::literal(format!("f{i}")))),+ (b"Rect", Object::Array([0, 0, 10, 10].map(Object::from).to_vec())),+ (b"AA", dict(vec![(b"C", Object::Ref(action))])),+ ])))+ })+ .collect();+ let names: Vec<Object> =+ (0..300).flat_map(|i| [Object::String(pdfcraft_cos::PdfString::literal(format!("s{i:03}"))), Object::Ref(action)]).collect();+ let catalog = doc.add(dict(vec![+ (b"Type", Object::Name(b"Catalog".to_vec())),+ (b"AcroForm", dict(vec![(b"Fields", Object::Array(fields))])),+ (b"Names", dict(vec![(b"JavaScript", dict(vec![(b"Names", Object::Array(names))]))])),+ ]));+ doc.trailer_mut().set(b"Root".to_vec(), Object::Ref(catalog));+ doc+}++#[test]+fn repeated_script_references_share_one_decode_budget() {+ let doc = repeated_script_references();+ let limit = MAX_SCRIPT_BYTES;+ let named: usize = document_scripts_named(&doc).iter().map(|(_, js)| js.len()).sum();+ assert!(named > 0 && named <= limit, "{named} bytes of document scripts");+ let all = fields(&doc);+ assert_eq!(all.len(), 300);+ let calculate: usize = all.iter().filter_map(|f| f.actions.scripts.calculate.as_ref()).map(String::len).sum();+ assert!(calculate > 0 && calculate <= limit, "{calculate} bytes of field scripts");+}++/// A widget listed many times, by one field's `/Kids` or by a `/Kids` array several fields share,+/// is read once: the first field to list it owns it.+#[test]+fn a_widget_listed_repeatedly_is_read_once() {+ let kids = "7 0 R ".repeat(500);+ let doc = document(&[+ "<< /Type /Catalog /Pages 4 0 R /AcroForm << /Fields [2 0 R 3 0 R] >> >>".into(),+ "<< /FT /Tx /T (a) /Kids 6 0 R >>".into(),+ "<< /FT /Tx /T (b) /Kids 6 0 R >>".into(),+ "<< /Type /Pages /Kids [5 0 R] /Count 1 >>".into(),+ "<< /Type /Page /Parent 4 0 R /MediaBox [0 0 100 100] /Annots [7 0 R] >>".into(),+ format!("[{kids}]"),+ "<< /Type /Annot /Subtype /Widget /Parent 2 0 R /Rect [0 0 10 10] >>".into(),+ ]);+ let all = fields(&doc);+ let widgets: Vec<usize> = all.iter().map(|f| f.widgets.len()).collect();+ assert_eq!(widgets, [1, 0], "{:?}", all.iter().map(|f| &f.name).collect::<Vec<_>>());+}++/// A field of a kind that isn't read doesn't claim the widget it shares with a field that is.+#[test]+fn a_skipped_field_leaves_its_widget_to_the_next() {+ let doc = document(&[+ "<< /Type /Catalog /Pages 4 0 R /AcroForm << /Fields [2 0 R 3 0 R] >> >>".into(),+ "<< /FT /Zz /T (odd) /Kids [6 0 R] >>".into(),+ "<< /FT /Tx /T (b) /Kids [6 0 R] >>".into(),+ "<< /Type /Pages /Kids [5 0 R] /Count 1 >>".into(),+ "<< /Type /Page /Parent 4 0 R /MediaBox [0 0 100 100] /Annots [6 0 R] >>".into(),+ "<< /Type /Annot /Subtype /Widget /Parent 3 0 R /Rect [0 0 10 10] >>".into(),+ ]);+ let all = fields(&doc);+ let widgets: Vec<(&str, usize)> = all.iter().map(|f| (f.name.as_str(), f.widgets.len())).collect();+ 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);+ }