Skip to content

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

Merge track r3-t03

aiongg9705e7a6c171
diff --cc crates/engine/src/tests.rs
index c61394ec2,3c6776a13..c90ab8fcd
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@@ -4887,25 -4773,61 +4985,80 @@@ fn measurement_edits_are_transactional_
);
}
+/// A laid-out XFA field that doesn't scroll (`hScrollPolicy="off"`) opens as a text field with
+/// DoNotScroll, and its text box says what fits it: what the editor takes no more than.
+#[test]
+fn an_xfa_field_that_doesnt_scroll_opens_with_do_not_scroll_and_a_text_box() {
+ let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
+<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
+<field name="code" w="1in" h="0.3in"><ui><textEdit hScrollPolicy="off"/></ui><font typeface="Arial" size="10pt"/></field>
+<field name="note" w="1in" h="0.3in"><ui><textEdit/></ui><font typeface="Arial" size="10pt"/></field>
+</subform></template></xdp:xdp>"##;
+ let mut s = Session::new();
+ let id = s.open("form.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(xdp)), None).expect("opens");
+ let doc = s.get(id).unwrap();
+ let field = |end: &str| doc.form.iter().find(|f| f.name.ends_with(end)).unwrap_or_else(|| panic!("no field {end}"));
+ assert!(field("code").has(field_flags::DO_NOT_SCROLL) && !field("note").has(field_flags::DO_NOT_SCROLL));
+ let tb = doc.field_text_box(&field("code").name, 0).expect("a text box");
+ assert!(tb.fits("A1B2") && !tb.fits(&"W".repeat(40)), "a 1-inch field at 10 pt");
+ assert!(doc.field_text_box("no such field", 0).is_none() && doc.field_text_box(&field("code").name, 5).is_none());
+}
+
+ /// A round XFA check button opens drawn round: the appearance its laid-out widget gets draws a
+ /// circle, the on state with its mark in it, while a square one keeps its box.
+ #[test]
+ fn round_xfa_check_buttons_open_drawn_round() {
+ let xdp = r##"<?xml version="1.0" encoding="UTF-8"?>
+ <xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
+ <field name="round" w="1in" h="0.3in"><ui><checkButton shape="round"/></ui><items><integer>1</integer><integer>0</integer></items></field>
+ <field name="square" w="1in" h="0.3in"><ui><checkButton/></ui><items><integer>1</integer><integer>0</integer></items></field>
+ </subform></template></xdp:xdp>"##;
+ let mut s = Session::new();
+ let id = s.open("form.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(xdp)), None).expect("opens");
+ let cos = s.get(id).unwrap().editor.as_ref().unwrap().cos.clone();
+ let all = pdfcraft_forms::fields(&cos);
+ // The decoded appearance of `name`'s widget in `state`.
+ let drawn = |name: &str, state: &[u8]| {
+ let w = all.iter().find(|f| f.name.ends_with(name)).unwrap_or_else(|| panic!("no field {name}")).widgets[0].obj;
+ let wd = cos.get(w).as_dict().cloned().unwrap();
+ let n = cos.resolve(wd.get(b"AP").unwrap().as_dict().unwrap().get(b"N").unwrap());
+ let r = n.as_dict().unwrap().reference(state).unwrap_or_else(|| panic!("{name} has no {} state", String::from_utf8_lossy(state)));
+ let pdfcraft_cos::Object::Stream(st) = &*cos.get(r) else { panic!("a stream") };
+ String::from_utf8_lossy(&st.decoded().unwrap()).into_owned()
+ };
+ for state in [&b"Off"[..], b"1"] {
+ let round = drawn("round", state);
+ assert!(round.contains(" c S") && !round.contains(" re S"), "the round one's border is a circle: {round}");
+ assert!(drawn("square", state).contains(" re S"), "the square one keeps its box");
+ }
+ }
+
+ #[test]
+ fn a_dynamic_xfa_form_is_saved_without_the_usage_rights_its_layout_voided() {
+ let xdp = pdfcraft_xfa::fixtures::template(3);
+ let original = Arc::new(pdfcraft_xfa::fixtures::usage_rights_shell(&xdp, "", false));
+ let mut s = Session::new().with_clock(|| 1_700_000_000);
+ let id = s.open("form.pdf", None, original.clone(), None).expect("opens");
+ let doc = s.get(id).unwrap();
+ let warnings = &doc.xfa.as_ref().expect("laid out from the template").warnings;
+ assert!(warnings.iter().any(|w| w.contains("usage rights")), "the user is told: {warnings:?}");
+ assert!(!doc.dirty, "laying out is still not an edit");
+ s.apply(id, Edit::SetFieldValue { name: "familyName".into(), value: FieldValue::Text("Singh".into()) }).unwrap();
+ let incremental = s.save_bytes(id).unwrap();
+ assert!(incremental.starts_with(&original[..]), "still an incremental save");
+ // Saved either way, the file no longer carries them, and keeps what was filled in.
+ for saved in [incremental, s.save_full_bytes(id).unwrap()] {
+ let cos = pdfcraft_cos::Document::open(saved.clone()).unwrap();
+ let catalog = cos.get(cos.root().unwrap()).as_dict().cloned().unwrap();
+ assert!(!catalog.contains(b"Perms"), "{catalog:?}");
+ let again = s.open("saved.pdf", None, saved, None).unwrap();
+ let d2 = s.get(again).unwrap();
+ assert_eq!(d2.form.iter().find(|f| f.name == "familyName").unwrap().value, vec!["Singh".to_string()]);
+ let warnings = &d2.xfa.as_ref().expect("the layout is remembered").warnings;
+ assert!(!warnings.iter().any(|w| w.contains("usage rights")), "nothing left to say: {warnings:?}");
+ }
+ }
+
#[test]
fn dynamic_xfa_forms_are_laid_out_on_open_filled_and_saved_incrementally() {
let original = Arc::new(pdfcraft_xfa::fixtures::shell(&pdfcraft_xfa::fixtures::template(3)));
diff --cc crates/forms/src/tests.rs
index 0c2daeb6d,c229d1515..b36657293
--- a/crates/forms/src/tests.rs
+++ b/crates/forms/src/tests.rs
@@@ -387,119 -387,58 +387,171 @@@ fn opt_export_values_select_button_stat
assert!(err.to_string().contains("options: Post, Pick-up"), "{err}");
}
+/// What fits a text field is measured as its appearance draws it: in the field's own font (its
+/// `/DR` font, Helvetica where that can't show the text), inside the border and padding, at its
+/// size, wrapped for multi-line, at the smallest automatic size, as asterisks for a password,
+/// and without a limit for a comb field.
+#[test]
+fn a_text_field_says_what_fits_it_as_its_appearance_draws_it() {
+ // Each widget is 100 x 20 pt (multi-line: 100 x 40 pt) with no border: 96 pt inside the 2 pt
+ // padding (36 pt high for the multi-line one).
+ let tx = |name: &str, da: &str, ff: u32, extra: &str, top: i32, h: i32| {
+ format!("<< /Type /Annot /Subtype /Widget /FT /Tx /T ({name}) /DA ({da}) /Ff {ff}{extra} /Rect [50 {} 150 {top}] /P 3 0 R >>", top - h)
+ };
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R] >>".into(),
+ "<< /Fields [7 0 R 8 0 R 9 0 R 10 0 R 11 0 R 12 0 R] /DA (/Helv 0 Tf 0 g) /DR << /Font << /Helv 5 0 R /Cour 6 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Courier /Encoding /WinAnsiEncoding >>".into(),
+ tx("one", "/Helv 12 Tf 0 g", 0, "", 780, 20),
+ tx("auto", "/Helv 0 Tf 0 g", 0, "", 750, 20),
+ tx("many", "/Helv 12 Tf 0 g", flags::MULTILINE, "", 720, 40),
+ tx("cour", "/Cour 12 Tf 0 g", 0, "", 670, 20),
+ tx("pin", "/Helv 12 Tf 0 g", flags::PASSWORD, "", 640, 20),
+ tx("comb", "/Helv 12 Tf 0 g", flags::COMB, " /MaxLen 5", 610, 20),
+ ];
+ let doc = document(&objs);
+ let all = fields(&doc);
+ let tb = |name: &str| {
+ let f = field(&all, name);
+ appearance::text_box(&doc, f, &f.widgets[0])
+ };
+ let helv = |s: &str, size: f64| pdfcraft_fonts::helvetica_width(s, size);
+ // Single line at 12 pt: as wide as the 96 pt inside, and no wider.
+ let fits_12: String = std::iter::repeat_n('W', (96.0 / helv("W", 12.0)) as usize).collect();
+ assert!(tb("one").fits(&fits_12) && !tb("one").fits(&format!("{fits_12}W")), "{}", fits_12.len());
+ // An automatic size shrinks first: full only when 4 pt no longer fits.
+ let fits_4: String = std::iter::repeat_n('W', (96.0 / helv("W", 4.0)) as usize).collect();
+ assert!(!tb("one").fits(&fits_4) && tb("auto").fits(&fits_4) && !tb("auto").fits(&format!("{fits_4}W")));
+ // Multi-line: lines of 12 x 1.15 pt each in 36 pt, so two lines fit and three don't.
+ assert!(tb("many").fits("one\ntwo") && !tb("many").fits("one\ntwo\nthree"));
+ let two_lines_of_words = "word ".repeat(((96.0 / helv("word ", 12.0)) as usize) * 2);
+ assert!(tb("many").fits(two_lines_of_words.trim_end()) && !tb("many").fits(&format!("{two_lines_of_words}word")));
+ // The field's own font: narrow i's that Helvetica fits are too wide in Courier (600/1000 em).
+ let i_s: String = std::iter::repeat_n('i', 14).collect();
+ assert!(tb("one").fits(&i_s) && !tb("cour").fits(&i_s), "Courier is 0.6 em a character: {}", 14.0 * 0.6 * 12.0);
+ // A password is drawn, so measured, as asterisks.
+ let thirty_i: String = std::iter::repeat_n('i', 30).collect();
+ assert!(tb("one").fits(&thirty_i) && !tb("pin").fits(&thirty_i), "{} pt of asterisks", helv(&"*".repeat(30), 12.0));
+ // A comb field's cells bound it, not its width.
+ assert!(tb("comb").fits(&"W".repeat(50)));
+}
+
+/// An edit to a field that doesn't scroll keeps as much of what it inserted as fits, wherever the
+/// caret was, and always keeps a deletion.
+#[test]
+fn an_edit_to_a_full_field_keeps_what_fits() {
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R] >>".into(),
+ "<< /Fields [5 0 R] /DA (/Helv 12 Tf 0 g) >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (one) /DA (/Helv 12 Tf 0 g) /Rect [50 760 150 780] /P 3 0 R >>".into(),
+ ];
+ let doc = document(&objs);
+ let all = fields(&doc);
+ let f = field(&all, "one");
+ let tb = appearance::text_box(&doc, f, &f.widgets[0]);
+ // Typing in the middle of "Short": the X's go in until the field is full, the end stays.
+ let typed = format!("Sh{}ort", "X".repeat(40));
+ let (kept, caret) = tb.fitted_edit("Short", &typed);
+ let xs = kept.chars().filter(|c| *c == 'X').count();
+ assert!(kept.starts_with("ShX") && kept.ends_with("Xort") && xs < 40, "{kept}");
+ assert!(tb.fits(&kept) && !tb.fits(&format!("Sh{}ort", "X".repeat(xs + 1))), "as many as fit: {xs}");
+ assert_eq!(caret, 2 + xs, "the caret after the last X kept");
+ // What fits is kept whole.
+ assert_eq!(tb.fitted_edit("Short", "Shorter"), ("Shorter".to_string(), 7));
+ // A deletion is kept even from text that already overflows (set by a script, say).
+ let long = "W".repeat(20);
+ assert!(!tb.fits(&long));
+ assert_eq!(tb.fitted_edit(&long, &"W".repeat(19)), ("W".repeat(19), 19));
+ // Replacing a selection with too much keeps the removal and what fits of the replacement.
+ let (kept, _) = tb.fitted_edit("Short", &format!("S{}t", "W".repeat(30)));
+ assert!(kept.starts_with("SW") && kept.ends_with('t') && tb.fits(&kept), "{kept}");
+}
+
+/// When the field's own font can't show a character of a paste, the text from there on is drawn
+/// in Helvetica, which can be narrower: the longest part that fits may come after that point, and
+/// is still the one kept.
+#[test]
+fn an_edit_keeps_the_longest_part_that_fits_across_a_change_of_font() {
+ // A subset font holding only A, 1 em wide: 12 pt an A at 12 pt, against Helvetica's 8 pt.
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [6 0 R] >>".into(),
+ "<< /Fields [6 0 R] /DA (/Wide 12 Tf 0 g) /DR << /Font << /Wide 5 0 R >> >> >>".into(),
+ "<< /Type /Font /Subtype /Type1 /BaseFont /ABCDEF+Wide /FirstChar 65 /LastChar 65 /Widths [1000] /Encoding /WinAnsiEncoding >>".into(),
+ "<< /Type /Annot /Subtype /Widget /FT /Tx /T (one) /DA (/Wide 12 Tf 0 g) /Rect [50 760 150 780] /P 3 0 R >>".into(),
+ ];
+ let doc = document(&objs);
+ let all = fields(&doc);
+ let f = field(&all, "one");
+ let tb = appearance::text_box(&doc, f, &f.widgets[0]);
+ // 96 pt inside: 8 A's in the subset font, or 11 characters (8.004 pt each) once a B brings
+ // Helvetica in.
+ assert!(tb.fits(&"A".repeat(8)) && !tb.fits(&"A".repeat(9)));
+ let pasted = format!("{}B{}", "A".repeat(10), "A".repeat(30));
+ let (kept, caret) = tb.fitted_edit("", &pasted);
+ assert_eq!(kept, format!("{}B", "A".repeat(10)), "the 11 characters that fit in Helvetica, not the 8 before the B");
+ assert!(!tb.fits(&format!("{}BA", "A".repeat(10))), "and no more");
+ assert_eq!(caret, 11);
+}
+
+ /// A check box laid out for a round XFA check button (`/PCXfaRound true`) draws its background
+ /// and border as a circle inside the widget, inset by half the border so the stroke stays in,
+ /// or a disc when the border is as wide as the circle (an underline stays one); one without the
+ /// key keeps its rectangle.
+ #[test]
+ fn a_round_xfa_check_button_draws_a_round_background_and_border() {
+ let widget = |name: &str, extra: &str| {
+ format!(
+ "<< /Type /Annot /Subtype /Widget /FT /Btn /T ({name}) /Rect [50 700 70 720] /P 3 0 R /MK << /BG [0.8 0.85 1] /BC [1 0 0] >> /BS << /W 1 /S /S >>{extra} >>"
+ )
+ };
+ let objs: Vec<String> = vec![
+ "<< /Type /Catalog /Pages 2 0 R /AcroForm 4 0 R >>".into(),
+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 600 800] >>".into(),
+ "<< /Type /Page /Parent 2 0 R /Annots [5 0 R 6 0 R 7 0 R 8 0 R 9 0 R] >>".into(),
+ "<< /Fields [5 0 R 6 0 R 7 0 R 8 0 R 9 0 R] >>".into(),
+ widget("round", " /PCXfaRound true"),
+ widget("square", ""),
+ widget("dashed", " /PCXfaRound true /BS << /W 2 /S /D >>").replace("/BS << /W 1 /S /S >>", ""),
+ widget("thick", " /PCXfaRound true /BS << /W 30 /S /S >>").replace("/BS << /W 1 /S /S >>", ""),
+ widget("underlined", " /PCXfaRound true /BS << /W 1 /S /U >>").replace("/BS << /W 1 /S /S >>", ""),
+ ];
+ let mut doc = document(&objs);
+ for name in ["round", "square", "dashed", "thick", "underlined"] {
+ redraw_field(&mut doc, name).unwrap();
+ }
+ // The Off state: only the frame.
+ let off = |name: &str| {
+ let all = fields(&doc);
+ let w = field(&all, name).widgets[0].obj;
+ let wd = doc.get(w).as_dict().cloned().unwrap();
+ let n = doc.resolve(wd.get(b"AP").unwrap().as_dict().unwrap().get(b"N").unwrap());
+ let r = n.as_dict().unwrap().reference(b"Off").expect("an Off appearance");
+ let Object::Stream(s) = &*doc.get(r) else { panic!("Off is a stream") };
+ String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
+ };
+ let round = off("round");
+ assert!(!round.contains(" re "), "no rectangle: {round}");
+ assert!(round.contains("0.8 0.85 1 rg\n20 10 m"), "the background is a disc as wide as the box: {round}");
+ assert!(round.contains("1 0 0 RG\n1 w\n19.5 10 m") && round.contains(" c S"), "the border is a circle inset by half its width: {round}");
+ let square = off("square");
+ assert!(square.contains("0 0 20 20 re f") && square.contains("re S"), "a square box keeps its rectangle: {square}");
+ let dashed = off("dashed");
+ assert!(dashed.contains("[3] 0 d\n19 10 m"), "a dashed round border stays dashed: {dashed}");
+ // A border wider than the 20pt circle fills it: a disc in the border's colour, no stroke.
+ let thick = off("thick");
+ assert!(thick.contains("1 0 0 rg\n20 10 m") && !thick.contains(" S\n"), "a border as wide as the circle is a disc: {thick}");
+ // An underline stays the bottom edge, under a round background.
+ let underlined = off("underlined");
+ assert!(underlined.contains("1 0 0 RG\n1 w\n0 0.5 m 20 0.5 l S"), "an underline stays an underline: {underlined}");
+ }
+
/// Issue #1323: a text field without a format keeps a whitespace-only value as typed; only an
/// empty value clears it.
#[test]
diff --cc crates/xfa/src/tests.rs
index 6231cbf78,8a9bff88d..8421c6554
--- a/crates/xfa/src/tests.rs
+++ b/crates/xfa/src/tests.rs
@@@ -356,45 -350,223 +356,262 @@@ fn form_text_the_standard_fonts_cannot_
assert!(!render_into(&mut doc).unwrap().warnings.iter().any(|w| w.contains("standard fonts")));
}
+/// A field whose ui doesn't scroll in the direction its text runs out (`hScrollPolicy="off"` for
+/// one line, `vScrollPolicy="off"` for several) is written with DoNotScroll (`/Ff` bit 24), so it
+/// takes no more text than it shows; the other direction's policy, or the default, doesn't.
+#[test]
+fn fields_that_dont_scroll_are_written_with_do_not_scroll() {
+ let field = |name: &str, ui: &str| format!(r#"<field name="{name}" w="2in" h="0.4in"><ui>{ui}</ui></field>"#);
+ let xdp = format!(
+ r##"<?xml version="1.0" encoding="UTF-8"?>
+<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
+{}{}{}{}{}{}{}
+</subform></template></xdp:xdp>"##,
+ field("line", r#"<textEdit hScrollPolicy="off"/>"#),
+ field("lines", r#"<textEdit multiLine="1" vScrollPolicy="off"/>"#),
+ field("number", r#"<numericEdit hScrollPolicy="off"/>"#),
+ field("when", r#"<dateTimeEdit hScrollPolicy="off"/>"#),
+ field("linesAcross", r#"<textEdit multiLine="1" hScrollPolicy="off"/>"#),
+ field("lineDown", r#"<textEdit vScrollPolicy="off"/>"#),
+ field("free", r#"<textEdit/>"#),
+ );
+ let mut doc = Document::open(Arc::new(shell(&xdp))).unwrap();
+ render_into(&mut doc).unwrap();
+ let catalog = doc.get(doc.root().unwrap());
+ let acro = doc.resolve(catalog.as_dict().unwrap().get(b"AcroForm").unwrap());
+ let fields = doc.resolve(acro.as_dict().unwrap().get(b"Fields").unwrap()).as_array().unwrap().clone();
+ let mut no_scroll = std::collections::BTreeMap::new();
+ for r in fields.iter().filter_map(Object::as_ref) {
+ let f = doc.get(r);
+ let d = f.as_dict().unwrap();
+ let name = d.get(b"T").and_then(Object::as_string).map(|t| t.to_text()).unwrap_or_default();
+ no_scroll.insert(name, d.int(b"Ff").unwrap_or(0) & (1 << 23) != 0);
+ }
+ let expected: std::collections::BTreeMap<String, bool> =
+ [("line", true), ("lines", true), ("number", true), ("when", true), ("linesAcross", false), ("lineDown", false), ("free", false)]
+ .into_iter()
+ .map(|(n, v)| (n.to_string(), v))
+ .collect();
+ assert_eq!(no_scroll, expected);
+}
+
+ /// A check box or radio button laid out from a round check button (`shape="round"`) carries
+ /// `ROUND_KEY`, so the forms layer draws its background and border round; a square one (the
+ /// default) doesn't.
+ #[test]
+ fn round_check_buttons_are_marked_for_a_round_appearance() {
+ let check = |name: &str, shape: &str, items: &str| {
+ format!(r#"<field name="{name}" w="1in" h="0.3in"><ui><checkButton{shape}/></ui><items>{items}</items></field>"#)
+ };
+ let on_off = "<integer>1</integer><integer>0</integer>";
+ let xdp = format!(
+ r##"<?xml version="1.0" encoding="UTF-8"?>
+ <xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
+ {}{}<exclGroup name="pick" layout="tb">{}{}</exclGroup>
+ </subform></template></xdp:xdp>"##,
+ check("roundBox", r#" shape="round""#, on_off),
+ check("squareBox", "", on_off),
+ check("roundRadio", r#" shape="round""#, "<text>a</text>"),
+ check("squareRadio", r#" shape="square""#, "<text>b</text>"),
+ );
+ let mut doc = Document::open(Arc::new(shell(&xdp))).unwrap();
+ render_into(&mut doc).unwrap();
+ // Every widget among the form's fields and their kids (a radio group's buttons), by the
+ // last step of its SOM path.
+ let catalog = doc.get(doc.root().unwrap());
+ let acro = doc.resolve(catalog.as_dict().unwrap().get(b"AcroForm").unwrap());
+ let mut todo: Vec<_> =
+ doc.resolve(acro.as_dict().unwrap().get(b"Fields").unwrap()).as_array().unwrap().iter().filter_map(Object::as_ref).collect();
+ let mut round = std::collections::BTreeMap::new();
+ while let Some(r) = todo.pop() {
+ let node = doc.get(r);
+ let d = node.as_dict().unwrap();
+ if let Some(kids) = d.get(b"Kids").map(|k| doc.resolve(k)) {
+ todo.extend(kids.as_array().unwrap().iter().filter_map(Object::as_ref));
+ continue;
+ }
+ let som = d.get(SOM_KEY).and_then(Object::as_string).map(|s| s.to_text()).unwrap_or_default();
+ let name = som.rsplit('.').next().unwrap_or_default().split('[').next().unwrap_or_default().to_string();
+ round.insert(name, matches!(d.get(crate::pdf::ROUND_KEY), Some(Object::Bool(true))));
+ }
+ let expected: std::collections::BTreeMap<String, bool> = [("roundBox", true), ("squareBox", false), ("roundRadio", true), ("squareRadio", false)]
+ .into_iter()
+ .map(|(n, r)| (n.to_string(), r))
+ .collect();
+ assert_eq!(round, expected);
+ }
+
+ /// A template whose one draw holds `body` as rich text, in a box `w` wide.
+ fn rich_draw_form(w: &str, body: &str) -> String {
+ format!(
+ r##"<?xml version="1.0" encoding="UTF-8"?>
+ <xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
+ <pageSet><pageArea name="page"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
+ <draw name="note" w="{w}"><font typeface="Arial" size="10pt"/><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>{body}</p></body></exData></value></draw>
+ </subform></template></xdp:xdp>"##
+ )
+ }
+
+ /// The link annotations on the pages of `doc`: each one's URI and rectangle.
+ fn text_links(doc: &Document) -> Vec<(String, [f64; 4])> {
+ let catalog = doc.get(doc.root().unwrap());
+ let pages = doc.resolve(catalog.as_dict().unwrap().get(b"Pages").unwrap());
+ let kids = doc.resolve(pages.as_dict().unwrap().get(b"Kids").unwrap()).as_array().unwrap().clone();
+ let mut out = Vec::new();
+ for page in &kids {
+ let page = doc.resolve(page);
+ let Some(annots) = page.as_dict().unwrap().get(b"Annots").map(|a| doc.resolve(a).as_array().unwrap().clone()) else { continue };
+ for a in &annots {
+ let a = doc.resolve(a);
+ let d = a.as_dict().unwrap();
+ if d.name(b"Subtype") != Some(&b"Link"[..]) {
+ continue;
+ }
+ let action = doc.resolve(d.get(b"A").unwrap());
+ let uri =
+ action.as_dict().unwrap().get(b"URI").and_then(Object::as_string).map(|s| String::from_utf8_lossy(&s.bytes).into_owned()).unwrap();
+ let r: Vec<f64> = doc.resolve(d.get(b"Rect").unwrap()).as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
+ out.push((uri, [r[0], r[1], r[2], r[3]]));
+ }
+ }
+ out
+ }
+
+ /// An `<a href>` in rich text keeps where it links to on every run of its text, styled or not;
+ /// the text around it and a named anchor without an address link nowhere.
+ #[test]
+ fn rich_text_links_keep_their_address() {
+ let (tpl, _) = crate::parse(&rich_draw_form(
+ "4in",
+ r#"Write to <a href=" mailto:[email protected] ">forms@<b>example</b>.com</a> or see <a name="top">the top</a>."#,
+ ))
+ .unwrap();
+ let Node::Draw(d) = &tpl.root.children[0] else { panic!("the draw") };
+ let Value::Rich(rich) = &d.value else { panic!("rich text") };
+ let runs: Vec<(&str, Option<&str>)> = rich.paragraphs.iter().flat_map(|p| &p.runs).map(|r| (r.text.as_str(), r.link.as_deref())).collect();
+ assert_eq!(
+ runs,
+ [
+ ("Write to ", None),
+ ("forms@", Some("mailto:[email protected]")),
+ ("example", Some("mailto:[email protected]")),
+ (".com", Some("mailto:[email protected]")),
+ (" or see ", None),
+ ("the top", None),
+ (".", None),
+ ]
+ );
+ }
+
+ /// A link's address is held once, however many runs, words and lines its text takes: every
+ /// piece shares it rather than copying it, so a long address over many words stays one string.
+ #[test]
+ fn a_links_pieces_share_one_address() {
+ let words = "one two three four five six seven eight nine ten ".repeat(8);
+ let href = format!("https://example.com/{}", "x".repeat(1500));
+ let xdp = rich_draw_form("2in", &format!(r#"<a href="{href}">{words}<b>bold</b> {words}</a>"#));
+ let form = layout_xml(&xdp).unwrap();
+ let links: Vec<std::sync::Arc<str>> =
+ form.pages.iter().flat_map(|p| &p.items).filter_map(|i| if let Item::Text(s) = i { s.link.clone() } else { None }).collect();
+ assert!(links.len() > 10, "the link's text takes many lines: {}", links.len());
+ assert!(links.iter().all(|l| std::sync::Arc::ptr_eq(l, &links[0]) && **l == *href), "every piece shares one address");
+ }
+
+ /// A link's text becomes a link annotation on the page, one over each line it takes when it
+ /// wraps, each over its own text; a second layout replaces them rather than adding more.
+ #[test]
+ fn links_in_rich_text_become_link_annotations_one_per_line() {
+ let body = r#"See <a href="https://example.com/forms/help">the help pages for this form, which explain every block</a> first."#;
+ let mut doc = Document::open(Arc::new(shell(&rich_draw_form("2in", body)))).unwrap();
+ let report = render_into(&mut doc).unwrap();
+ assert!(report.warnings.iter().all(|w| !w.contains("link")), "{:?}", report.warnings);
+ let links = text_links(&doc);
+ assert!(links.len() >= 2, "the link wraps onto at least two lines: {links:?}");
+ assert!(links.iter().all(|(uri, _)| uri == "https://example.com/forms/help"));
+ // One per line: each below the one before, all inside the 2-inch box (from x = 36pt).
+ for pair in links.windows(2) {
+ assert!(pair[1].1[3] <= pair[0].1[1] + 0.01, "a line below the one before: {pair:?}");
+ }
+ for (_, r) in &links {
+ assert!(r[0] >= 36.0 - 0.01 && r[2] <= 36.0 + 144.0 + 0.01 && r[2] > r[0] && r[3] > r[1], "{r:?}");
+ }
+ // The first line's link starts after "See ", not at the box's edge.
+ assert!(links[0].1[0] > 36.0 + 5.0, "{:?}", links[0].1);
+ // A second layout replaces the pages, and their links with them.
+ let tpl = crate::script::template_of(&doc).unwrap();
+ rerender(&mut doc, &tpl).unwrap();
+ assert_eq!(text_links(&doc), links, "laid out again: the same links, not twice as many");
+ // Saved and opened again, they are still there.
+ let bytes = write_incremental(&doc, &SaveOptions::default()).unwrap();
+ assert_eq!(text_links(&Document::open(Arc::new(bytes)).unwrap()), links);
+
+ // A link whose text changes style partway is one link on its line, over all its text.
+ let mut doc =
+ Document::open(Arc::new(shell(&rich_draw_form("4in", r#"Write to <a href="mailto:[email protected]">forms@<b>example</b>.com</a> today."#))))
+ .unwrap();
+ render_into(&mut doc).unwrap();
+ let links = text_links(&doc);
+ assert_eq!(links.len(), 1, "{links:?}");
+ let arial = Font { typeface: "Arial".into(), size: 10.0, ..Default::default() };
+ let plain = crate::text::Face::of(&arial);
+ let bold = crate::text::Face::of(&Font { bold: true, ..arial.clone() });
+ let width = plain.width("forms@") + bold.width("example") + plain.width(".com");
+ let r = links[0].1;
+ assert!((r[2] - r[0] - width).abs() < 0.01, "over the whole address: {} against {width}", r[2] - r[0]);
+ }
+
+ /// Two pieces of one link side by side on a line join into one link, but a rule drawn between
+ /// them keeps them apart, so the link never covers what lies between its pieces; an underline
+ /// (a level line drawn with its text) doesn't.
+ #[test]
+ fn a_rule_between_two_pieces_of_a_link_keeps_them_apart() {
+ let piece = |name: &str, x: &str, underline: bool| {
+ let u = if underline { ";text-decoration:underline" } else { "" };
+ format!(
+ r#"<draw name="{name}" x="{x}" y="0in" w="0.4in" h="0.3in"><font typeface="Arial" size="10pt"/><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p style="margin:0{u}"><a href="https://example.com/form">Go</a></p></body></exData></value></draw>"#
+ )
+ };
+ let rule = r#"<draw name="rule" x="0.21in" y="0in" w="0in" h="0.3in"><value><line><edge/></line></value></draw>"#;
+ let level_rule = r#"<draw name="dash" x="0.2in" y="0.1in" w="0.04in" h="0in"><value><line><edge/></line></value></draw>"#;
+ let form = |between: &str, underline: bool| {
+ format!(
+ r##"<?xml version="1.0" encoding="UTF-8"?>
+ <xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="position">
+ <pageSet><pageArea name="page"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
+ {}{between}{}
+ </subform></template></xdp:xdp>"##,
+ piece("first", "0in", underline),
+ piece("second", "0.25in", underline)
+ )
+ };
+ let links = |xdp: &str| {
+ let mut doc = Document::open(Arc::new(shell(xdp))).unwrap();
+ render_into(&mut doc).unwrap();
+ text_links(&doc).len()
+ };
+ assert_eq!(links(&form("", false)), 1, "side by side, the pieces join");
+ assert_eq!(links(&form("", true)), 1, "an underline doesn't part them");
+ assert_eq!(links(&form(rule, false)), 2, "a rule between them does");
+ assert_eq!(links(&form(level_rule, false)), 2, "and so does a level one, which isn't an underline");
+ }
+
+ /// Only web and email addresses become links. Scripts, files, data, relative paths, web
+ /// addresses without a host, and empty or overlong addresses stay plain text (still drawn), with
+ /// one warning for the form.
+ #[test]
+ fn links_to_anything_but_web_and_email_addresses_stay_plain_text() {
+ let long = format!("https://example.com/{}", "a".repeat(2100));
+ let body = format!(
+ r#"<a href="javascript:app.alert(1)">one</a> <a href="file:///etc/passwd">two</a> <a href="data:text/html,x">three</a> <a href="help.html">four</a> <a href="HTTPS:">five</a> <a href="{long}">six</a> <a href="MailTo:[email protected]">seven</a> <a href="https:///path">eight</a> <a href="https://user@:8080/x">nine</a> <a href="https://\example.com/path">nine and a half</a> <a href="https://[email protected]:8443/x">ten</a>"#
+ );
+ let mut doc = Document::open(Arc::new(shell(&rich_draw_form("7in", &body)))).unwrap();
+ let report = render_into(&mut doc).unwrap();
+ assert_eq!(text_links(&doc).into_iter().map(|(u, _)| u).collect::<Vec<_>>(), ["MailTo:[email protected]", "https://[email protected]:8443/x"]);
+ let warned: Vec<&String> = report.warnings.iter().filter(|w| w.contains("link")).collect();
+ assert_eq!(warned.len(), 1, "one warning for the form: {:?}", report.warnings);
+ assert!(warned[0].contains("http, https") && warned[0].contains("mailto"), "{warned:?}");
+ }
+
#[test]
fn documents_without_xfa_are_not_touched() {
let mut doc = Document::new_empty();
@@@ -2878,38 -3408,42 +3453,79 @@@ fn long_names_repeated_by_an_index_are_
assert!(data.len() < 2_000_000, "{} bytes of data built", data.len());
}
+/// #3441: a font the form already holds as an object stays that object when the XFA layout
+/// writes its fields' fonts into `/DR`.
+#[test]
+fn rendering_keeps_the_forms_own_font_objects() {
+ let mut doc = Document::open(Arc::new(shell(&template(2)))).unwrap();
+ let mut font = Dict::new();
+ font.set(b"Type".to_vec(), Object::name("Font"));
+ font.set(b"Subtype".to_vec(), Object::name("Type1"));
+ font.set(b"BaseFont".to_vec(), Object::name("Symbol"));
+ let mine = doc.add(Object::Dict(font));
+ let mut fonts = Dict::new();
+ fonts.set(b"Mine".to_vec(), Object::Ref(mine));
+ let mut dr = Dict::new();
+ dr.set(b"Font".to_vec(), Object::Dict(fonts));
+ let root = doc.root().unwrap();
+ match doc.get(root).as_dict().unwrap().get(b"AcroForm").cloned().unwrap() {
+ Object::Ref(af) => doc.update_dict(af, |d| d.set(b"DR".to_vec(), Object::Dict(dr))).unwrap(),
+ _ => doc
+ .update_dict(root, |c| {
+ if let Some(Object::Dict(af)) = c.get(b"AcroForm").cloned() {
+ let mut af = af;
+ af.set(b"DR".to_vec(), Object::Dict(dr));
+ c.set(b"AcroForm".to_vec(), Object::Dict(af));
+ }
+ })
+ .unwrap(),
+ }
+ render_into(&mut doc).unwrap();
+ let catalog = doc.get(root);
+ let acro = doc.resolve(catalog.as_dict().unwrap().get(b"AcroForm").unwrap());
+ let dr = doc.resolve(acro.as_dict().unwrap().get(b"DR").unwrap());
+ let fonts = doc.resolve(dr.as_dict().unwrap().get(b"Font").unwrap());
+ assert_eq!(fonts.as_dict().unwrap().reference(b"Mine"), Some(mine), "the form's own font object");
+ assert!(fonts.as_dict().unwrap().reference(b"Helv").is_some(), "and the layout's fonts as objects");
+}
++
++
+ /// Text is measured in the standard-14 face it is drawn in, at the widths ISO 32000-2 Annex D
+ /// gives: bold and Times are no longer Helvetica scaled, and the horizontal scale still applies.
+ #[test]
+ fn faces_measure_text_at_their_standard_14_widths() {
+ use pdfcraft_fonts::Std14;
+ let face = |family: text::Family, bold: bool, italic: bool| text::Face {
+ family,
+ bold,
+ italic,
+ size: 10.0,
+ color: [0.0; 3],
+ underline: false,
+ h_scale: 1.0,
+ };
+ let sample = "Mill Wax 0123 Departure Date";
+ for (family, bold, italic, std14) in [
+ (text::Family::Helvetica, false, false, Std14::Helvetica),
+ (text::Family::Helvetica, true, false, Std14::HelveticaBold),
+ (text::Family::Helvetica, true, true, Std14::HelveticaBoldOblique),
+ (text::Family::Times, false, false, Std14::TimesRoman),
+ (text::Family::Times, true, false, Std14::TimesBold),
+ (text::Family::Times, false, true, Std14::TimesItalic),
+ (text::Family::Times, true, true, Std14::TimesBoldItalic),
+ (text::Family::Courier, true, false, Std14::CourierBold),
+ ] {
+ let f = face(family, bold, italic);
+ assert!(
+ (f.width(sample) - std14.text_width(sample, 10.0)).abs() < 1e-9,
+ "{std14:?}: {} vs {}",
+ f.width(sample),
+ std14.text_width(sample, 10.0)
+ );
+ assert_eq!(f.family.std14(bold, italic), std14);
+ assert_eq!(f.family.base_font(bold, italic), std14.base_font());
+ }
+ // A condensed face is narrower by its scale.
+ let condensed = text::Face { h_scale: 0.8, ..face(text::Family::Times, true, false) };
+ assert!((condensed.width(sample) - 0.8 * Std14::TimesBold.text_width(sample, 10.0)).abs() < 1e-9);
+ }