Files
pdfcraft/crates/xfa/src/tests.rs
T
2026-11-09 18:40:50 +07:00

7757 lines
448 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use std::sync::Arc;
use pdfcraft_cos::{Dict, Document, Object, SaveOptions, write_incremental};
use super::*;
use crate::data::{
DatasetsWrite, FieldData, FieldDatum, build_data, iso_to_pattern, parse_datasets, pattern_to_iso, read_values, som_to_path, write_datasets,
};
use crate::data::{add_data_instances, remove_data_instance, write_data_value};
use crate::fixtures::{
TINY_GIF, bound_date_template, fields_template, scripted_template, shell, static_shell, template, template_with_data, tiny_bmp, tiny_png,
tiny_tiff, unnamed_hidden_template,
};
use crate::layout::Item;
use crate::layout::WidgetKind;
use crate::model::*;
use crate::script::{NodeKind, Overrides, apply_overrides, fields_by_som, form_tree, overrides, rerender, set_overrides};
/// The widgets laid out on `page`, in order.
fn widgets(page: &Page) -> Vec<&Widget> {
page.items.iter().filter_map(|i| if let Item::Widget(w) = i { Some(w.as_ref()) } else { None }).collect()
}
/// The text of each text span laid out on `page`, in order.
fn texts(page: &Page) -> Vec<String> {
page.items.iter().filter_map(|i| if let Item::Text(s) = i { Some(s.text.clone()) } else { None }).collect()
}
/// Measurements in points, inches, millimeters and centimeters convert to points, a bare
/// number is points, and an `em` length, a non-number or a NaN is `None`.
#[test]
fn measurements_convert_to_points() {
assert_eq!(measure("72pt"), Some(72.0));
assert_eq!(measure("1in"), Some(72.0));
assert!((measure("25.4mm").unwrap() - 72.0).abs() < 1e-9);
assert!((measure("2.54cm").unwrap() - 72.0).abs() < 1e-9);
assert_eq!(measure(" 12 "), Some(12.0));
assert_eq!(measure("3em"), None);
assert_eq!(measure("abc"), None);
assert_eq!(measure("NaNpt"), None);
}
/// Two draws of the same text, one at `fontHorizontalScale="80%"`, each 90% as wide as the
/// text is at full width, and a rich-text draw condensed to half by its span style.
fn scaled_text_template() -> (String, &'static str) {
const TEXT: &str = "Approving authority name and title";
let w = pdfcraft_fonts::helvetica_width(TEXT, 10.0) * 0.9;
let xdp = format!(
r##"<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="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<draw name="narrow" w="{w}pt" h="0.5in"><value><text>{TEXT}</text></value><font typeface="Arial" size="10pt" fontHorizontalScale="80%"/></draw>
<draw name="plain" w="{w}pt" h="0.5in"><value><text>{TEXT}</text></value><font typeface="Arial" size="10pt"/></draw>
<draw name="rich" w="7in" h="0.3in"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>Full <span style="xfa-font-horizontal-scale:50%">half</span></p></body></exData></value><font typeface="Arial" size="10pt"/></draw>
</subform>
</template></xdp:xdp>"##
);
(xdp, TEXT)
}
/// `fontHorizontalScale` is read as a percentage and text is measured at it: the 80% draw
/// fits its box on one line where the full-width one takes two, and a span's own scale
/// applies to that span alone.
#[test]
fn horizontally_scaled_text_is_measured_and_drawn_narrower() {
let (xdp, text) = scaled_text_template();
let (tpl, _) = parse(&xdp).unwrap();
let Node::Draw(narrow) = &tpl.root.children[0] else { panic!() };
assert_eq!(narrow.common.font.h_scale, Some(0.8), "fontHorizontalScale is a percentage");
let form = layout_xml(&xdp).unwrap();
let spans: Vec<&text::Span> = form.pages[0].items.iter().filter_map(|i| if let Item::Text(s) = i { Some(s) } else { None }).collect();
let lines = |scale: f64, words: &[&str]| {
let mut b: Vec<i64> = spans
.iter()
.filter(|s| s.face.h_scale == scale && words.iter().any(|w| s.text.contains(w)))
.map(|s| (s.baseline * 100.0).round() as i64)
.collect();
b.dedup();
b.len()
};
let words: Vec<&str> = text.split(' ').collect();
// At 80% the text is 72% of its full width: it fits the 90% box on one line.
assert_eq!(lines(0.8, &words), 1, "{spans:?}");
// At full width it doesn't: two lines.
assert_eq!(lines(1.0, &["Approving", "title"]), 2, "{spans:?}");
// A span's own scale applies to it alone.
let half = spans.iter().find(|s| s.text.contains("half")).expect("the half span");
let full = spans.iter().find(|s| s.text.contains("Full")).expect("the full span");
assert_eq!((half.face.h_scale, full.face.h_scale), (0.5, 1.0));
assert!((half.face.width("half") - full.face.width("half") / 2.0).abs() < 1e-9);
}
/// A growing non-interactive field is measured in the face its text is drawn in: condensed,
/// its text takes fewer lines and the field grows only to hold them.
#[test]
fn a_non_interactive_field_is_measured_at_the_scale_its_text_is_drawn() {
// A growing, non-interactive text field (drawn as text by the layout, not as a widget),
// then a draw below it. However condensed the field's text is, the draw sits the same
// distance below its last line: the field is as tall as the lines it shows.
// Long enough to take more than a multi-line field's three lines at either scale.
const TEXT: &str = "Remarks that run over several lines of a narrow box, and then over several more lines again, until the box has grown well past the three lines it starts with";
let gap = |scale: u32| {
let xdp = format!(
r##"<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="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<field name="note" w="100pt" access="nonInteractive"><ui><textEdit multiLine="1"/></ui><value><text>{TEXT}</text></value><font typeface="Arial" size="10pt" fontHorizontalScale="{scale}%"/></field>
<draw name="after" w="100pt" h="20pt"><value><text>AFTER</text></value><font typeface="Arial" size="10pt"/></draw>
</subform>
</template></xdp:xdp>"##
);
let form = layout_xml(&xdp).unwrap();
let spans: Vec<&text::Span> = form.pages[0].items.iter().filter_map(|i| if let Item::Text(s) = i { Some(s) } else { None }).collect();
let after = spans.iter().find(|s| s.text.contains("AFTER")).expect("the draw").baseline;
let lines: std::collections::BTreeSet<i64> =
spans.iter().filter(|s| !s.text.contains("AFTER")).map(|s| (s.baseline * 100.0).round() as i64).collect();
let last = *lines.iter().next_back().expect("the field's lines") as f64 / 100.0;
(lines.len(), after - last)
};
let (full_lines, full_gap) = gap(100);
let (narrow_lines, narrow_gap) = gap(60);
assert!(narrow_lines < full_lines, "condensed, the text takes fewer lines: {narrow_lines} vs {full_lines}");
assert!((narrow_gap - full_gap).abs() < 0.01, "the field shrinks with its text: gap {narrow_gap} vs {full_gap}");
}
/// Condensed text is written with `Tz` inside a `q`/`Q` pair of its own, and full-width text
/// sets no scale, so none carries over from the text before it.
#[test]
fn horizontally_scaled_text_is_written_with_tz_inside_its_own_graphics_state() {
let (xdp, _) = scaled_text_template();
let mut doc = Document::open(Arc::new(shell(&xdp))).unwrap();
render_into(&mut doc).unwrap();
let root = doc.get(doc.root().unwrap());
let pages = doc.resolve(root.as_dict().unwrap().get(b"Pages").unwrap());
let kid = pages.as_dict().unwrap().get(b"Kids").unwrap().as_array().unwrap()[0].clone();
let page = doc.resolve(&kid);
let contents = doc.resolve(page.as_dict().unwrap().get(b"Contents").unwrap());
let Object::Stream(c) = &*contents else { panic!("a content stream") };
let ops = String::from_utf8_lossy(&c.decoded().unwrap()).into_owned();
let scaled: Vec<&str> = ops.lines().filter(|l| l.contains(" Tz ")).collect();
assert!(!scaled.is_empty() && scaled.iter().all(|l| l.starts_with("q BT ") && l.ends_with(" ET Q")), "{ops}");
assert!(scaled.iter().any(|l| l.contains(" 80 Tz ")) && scaled.iter().any(|l| l.contains(" 50 Tz ")), "{ops}");
// Full-width text sets no scale, and none is left over from the condensed text before it.
assert!(ops.lines().filter(|l| l.contains(" Tj ") && !l.contains(" Tz ")).all(|l| l.starts_with("BT ")), "{ops}");
}
/// The sample template parses without warnings into what the layout uses: its page areas,
/// page-number draws, rich-text title, field font, caption and widget border, check box,
/// date field, radio group, table columns and page break all come through.
/// Floating fields (XFA 3.3 p. 1222): the template knows which field ids rich text embeds,
/// whether in a draw, a field's value or its caption; and a field that shows the sheet number
/// (`sheet(this)+1`, however spaced) or the sheet count plays the page role, as every page is a
/// sheet of its own on screen. A script that reads `sheet(this)` alone plays none.
#[test]
fn the_template_knows_its_floating_fields_and_sheet_roles() {
let span = |id: &str| format!(r##"<span xfa:embed="#{id}" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"/>"##);
let rich =
|id: &str| format!(r#"<exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>x {}</p></body></exData>"#, span(id));
let ready = |id: &str, script: &str| {
format!(
r#"<field id="{id}" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><event activity="ready" ref="$layout"><script contentType="application/x-javascript">{script}</script></event></field>"#
)
};
let tpl = format!(
r#"<template><subform name="form" layout="tb"><subform>
{}{}{}
<draw w="2in" h="0.3in"><value>{}</value></draw>
<field name="f" w="2in" h="0.3in"><ui><textEdit/></ui><caption><value>{}</value></caption><value>{}</value></field>
</subform></subform></template>"#,
ready("sheet", "this.rawValue = xfa.layout.sheet(this) + 1"),
ready("sheets", "this.rawValue = xfa.layout.sheetCount()"),
ready("bare", "this.rawValue = xfa.layout.sheet(this)"),
rich("inDraw"),
rich("inCaption"),
rich("inValue"),
);
let (tpl, _) = parse(&tpl).unwrap();
assert_eq!(tpl.embedded.iter().map(String::as_str).collect::<Vec<_>>(), ["inCaption", "inDraw", "inValue"]);
assert_eq!(tpl.page_roles, vec![("sheet".to_string(), PageRole::Number), ("sheets".to_string(), PageRole::Count)]);
}
/// An embedded sheet number is the page's own on every page, not a constant 1, and the sheet
/// count is the number of pages.
#[test]
fn an_embedded_sheet_number_counts_the_pages() {
let span = |id: &str| format!(r##"<span xfa:embed="#{id}" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"/>"##);
let ready = |id: &str, script: &str| {
format!(
r#"<field id="{id}" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><event activity="ready" ref="$layout"><script contentType="application/x-javascript">{script}</script></event></field>"#
)
};
let tpl = format!(
r#"<template><subform name="form" layout="tb">
<pageSet><pageArea name="front"><contentArea x="0.5in" y="1in" w="7.5in" h="9in"/><medium short="8.5in" long="11in"/>
{}{}
<draw x="0.5in" y="0.2in" w="4in" h="0.3in"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>Sheet {} of {}</p></body></exData></value></draw>
</pageArea></pageSet>
<subform name="one" w="7in" h="6in"><draw w="2in" h="0.3in"><value><text>first</text></value></draw></subform>
<subform name="two" w="7in" h="6in"><draw w="2in" h="0.3in"><value><text>second</text></value></draw></subform>
</subform></template>"#,
ready("sheet", "this.rawValue = xfa.layout.sheet(this)+1"),
ready("sheets", "this.rawValue = xfa.layout.sheetCount()"),
span("sheet"),
span("sheets")
);
let form = layout_xml(&tpl).unwrap();
assert_eq!(form.pages.len(), 2);
for (i, page) in form.pages.iter().enumerate() {
let shown = texts(page).join(" ");
assert!(shown.contains(&format!("Sheet {} of 2", i + 1)), "page {}: {shown}", i + 1);
}
}
/// A FormCalc script names the field `$`, and a field may have a ready script that does
/// something else before the one that gives the sheet number: both still play the role.
#[test]
fn sheet_roles_are_read_from_formcalc_and_from_any_ready_script() {
let tpl = r#"<template><subform name="form" layout="tb">
<field id="fc" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><event activity="ready" ref="$layout"><script>$.rawValue = xfa.layout.sheet($) + 1</script></event></field>
<field id="fcCase" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><event activity="ready" ref="$layout"><script>$.rawValue = xfa.layout.Sheet($) + 1</script></event></field>
<field id="jsCase" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><event activity="ready" ref="$layout"><script contentType="application/x-javascript">this.rawValue = xfa.layout.Sheet(this)+1</script></event></field>
<field id="fcCount" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><event activity="ready" ref="$layout"><script>$.rawValue = xfa.layout.SheetCount()</script></event></field>
<field id="jsCount" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><event activity="ready" ref="$layout"><script contentType="application/x-javascript">this.rawValue = xfa.layout.SheetCount()</script></event></field>
<field id="second" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui>
<event activity="ready" ref="$form"><script contentType="application/x-javascript">this.rawValue = 0;</script></event>
<event activity="ready" ref="$layout"><script contentType="application/x-javascript">this.rawValue = xfa.layout.sheet(this)+1</script></event></field>
</subform></template>"#;
let (tpl, _) = parse(tpl).unwrap();
// FormCalc names methods case-insensitively, JavaScript does not.
assert_eq!(
tpl.page_roles,
vec![
("fc".to_string(), PageRole::Number),
("fcCase".to_string(), PageRole::Number),
("fcCount".to_string(), PageRole::Count),
("second".to_string(), PageRole::Number)
]
);
}
/// The data paths of embedded fields are the ones scripts write: a page area's field under the
/// area, as master pages lay it out; a field in a repeating row by name, whatever its instance.
#[test]
fn embedded_fields_are_known_by_the_data_paths_scripts_write() {
let span = |id: &str| format!(r##"<span xfa:embed="#{id}" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"/>"##);
let tpl = format!(
r#"<template><subform name="form" layout="tb">
<pageSet><pageArea name="front"><contentArea w="8in" h="10in"/><medium short="8.5in" long="11in"/>
<field name="stamp" id="stamp" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui></field>
<draw w="3in" h="0.3in"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>Stamp {}</p></body></exData></value></draw>
</pageArea></pageSet>
<subform name="row" layout="tb"><occur min="1" max="-1"/>
<field name="amount" id="amount" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui></field>
<draw w="3in" h="0.3in"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>Amount {}</p></body></exData></value></draw>
</subform>
<field name="plain" w="1in" h="0.2in"><ui><textEdit/></ui></field>
</subform></template>"#,
span("stamp"),
span("amount")
);
let (tpl, _) = parse(&tpl).unwrap();
let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(tpl.embedded_paths.iter().cloned().collect::<Vec<_>>(), [names(&["form", "row", "amount"]), names(&["front", "stamp"])]);
assert!(crate::script::field_is_embedded(&tpl, "front[0].stamp[0]"), "a page area's field");
assert!(crate::script::field_is_embedded(&tpl, "form[0].row[3].amount[0]"), "any row");
assert!(!crate::script::field_is_embedded(&tpl, "form[0].plain[0]"));
}
/// Text embedding a field shows the value the data gives it: each row of a repeating subform
/// its own row's, a page area's field the value scripts write under the area, a multi-select
/// list its picks, a date in its display picture (XFA 3.3 p. 221) in every row; a row without
/// data shows the template's default, not the first row's value.
#[test]
fn embedded_text_shows_each_instances_data() {
let span = |id: &str| format!(r##"<span xfa:embed="#{id}" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"/>"##);
let rich = |label: &str, id: &str| {
format!(r#"<exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>{label} {}</p></body></exData>"#, span(id))
};
let xml = 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="front"><contentArea x="0.5in" y="1in" w="7.5in" h="9in"/><medium short="8.5in" long="11in"/>
<field name="stamp" id="stamp" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui></field>
<draw x="0.5in" y="0.2in" w="4in" h="0.3in"><value>{}</value></draw>
</pageArea></pageSet>
<subform name="row" layout="tb"><occur min="1" max="-1" initial="3"/>
<field name="amount" id="amount" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><value><text>none</text></value></field>
<field name="due" id="due" presence="hidden" w="1in" h="0.2in"><ui><dateTimeEdit/></ui><format><picture>date{{MM/DD/YYYY}}</picture></format></field>
<draw w="4in" h="0.3in"><value>{}</value></draw>
<draw w="4in" h="0.3in"><value>{}</value></draw>
</subform>
<field name="picks" id="picks" presence="hidden" w="1in" h="0.6in"><ui><choiceList open="multiSelect"/></ui><items><text>A</text><text>B</text></items></field>
<draw w="4in" h="0.6in"><value>{}</value></draw>
</subform></template>
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"><xfa:data>
<form><row><amount>10</amount><due>2026-11-04</due></row><row><amount>20</amount><due>2026-12-25</due></row><row/><picks><value>A</value><value>B</value></picks></form>
<front><stamp>Paid</stamp></front>
</xfa:data></xfa:datasets></xdp:xdp>"#,
rich("Stamp", "stamp"),
rich("Amount", "amount"),
rich("Due", "due"),
rich("Picks", "picks")
);
let (tpl, _) = parse(&xml).unwrap();
let data = parse_datasets(&xml).unwrap();
let form = crate::layout::layout(&tpl, Some(&data)).unwrap();
let all: Vec<String> = form.pages.iter().flat_map(texts).collect();
let joined = all.join(" | ");
for want in ["Stamp Paid", "Amount 10", "Amount 20", "Amount none", "Due 11/04/2026", "Due 12/25/2026", "Picks A"] {
assert!(joined.contains(want), "{want} in {joined}");
}
assert!(joined.contains('B'), "both picks: {joined}");
}
#[test]
fn the_template_parses_with_fonts_captions_and_rich_text() {
let (tpl, warnings) = parse(&template(2)).unwrap();
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(tpl.root.layout, Layout::Tb);
let ps = tpl.root.page_set.as_ref().unwrap();
assert_eq!(ps.areas.len(), 2);
assert_eq!((ps.areas[0].width, ps.areas[0].height), (612.0, 792.0));
assert_eq!(ps.areas[0].occur_max, Some(1));
assert_eq!(ps.areas[1].occur_max, None);
assert_eq!(ps.areas[0].content[0], Rect::new(36.0, 36.0, 540.0, 720.0));
assert_eq!(tpl.page_roles, vec![("pageNo".to_string(), PageRole::Number), ("pageCount".to_string(), PageRole::Count)]);
let Node::Subform(head) = &tpl.root.children[0] else { panic!() };
assert_eq!(head.layout, Layout::LrTb);
let Node::Draw(title) = &head.children[0] else { panic!() };
let Value::Rich(r) = &title.value else { panic!("rich text") };
assert_eq!(r.paragraphs.len(), 2, "{r:?}");
assert_eq!(r.paragraphs[0].runs[0].bold, Some(true));
assert_eq!(r.plain(), "Sample Form\nSecond line");
let Node::Field(f) = &head.children[2] else { panic!() };
assert_eq!(f.common.name.as_deref(), Some("familyName"));
assert_eq!(f.common.font.typeface.as_deref(), Some("Courier New"));
assert_eq!(f.max_chars, Some(30));
assert_eq!(f.tooltip.as_deref(), Some("Your family name"));
let cap = f.caption.as_ref().unwrap();
assert_eq!((cap.placement, cap.reserve), (Placement::Top, Some(14.4)));
// The widget border: three hidden edges and a visible bottom one.
assert_eq!(f.ui_border.as_ref().unwrap().visible_edges(), [false, false, true, false]);
let Node::Field(check) = &head.children[3] else { panic!() };
assert_eq!((check.ui.clone(), check.items.clone()), (Ui::CheckButton, vec!["1".to_string(), "0".to_string()]));
let Node::Field(date) = &head.children[4] else { panic!() };
assert_eq!((date.ui.clone(), date.picture.as_deref()), (Ui::DateTimeEdit, Some("date{YYYY-MM-DD}")));
let Node::ExclGroup(g) = &head.children[6] else { panic!() };
assert_eq!(g.fields.len(), 2);
let Node::Subform(table) = &tpl.root.children[1] else { panic!() };
assert_eq!(table.column_widths, vec![144.0, 216.0, 180.0]);
assert_eq!(table.overflow_leader.as_deref(), Some("header"));
let Node::Subform(last) = &tpl.root.children[2] else { panic!() };
assert!(last.break_before_page);
}
/// A page area that declares far more content areas than any real master keeps only the first
/// 128, with a warning. `split_block` walks every content area of a page before starting a new
/// one, re-scanning the unplaced items each time, so tens of thousands of them cost time
/// quadratic in a splittable subform's paragraphs. Capping the count bounds that walk.
#[test]
fn a_page_area_keeps_at_most_a_hundred_and_twenty_eight_content_areas() {
let areas = (0..200).map(|i| format!("<contentArea x=\"0.5in\" y=\"{}pt\" w=\"7in\" h=\"1pt\"/>", i)).collect::<String>();
let xml = 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="front"><medium stock="letter" short="8.5in" long="11in"/>{areas}</pageArea>
</pageSet>
</subform>
</template>
</xdp:xdp>
"##
);
let (tpl, warnings) = parse(&xml).unwrap();
let ps = tpl.root.page_set.as_ref().unwrap();
assert_eq!(ps.areas[0].content.len(), 128, "the content areas are capped");
assert!(warnings.iter().any(|w| w.contains("content areas")), "a warning records the cap: {warnings:?}");
// Still said after a hundred other warnings (CodeRabbit review on #5844): images that can't
// be decoded, parsed before the page set, fill the warnings' shared cap first.
let bad = "<draw w=\"1in\" h=\"1in\"><value><image contentType=\"image/png\">!!!</image></value></draw>".repeat(120);
let crowded = xml.replace("<subform name=\"form\" layout=\"tb\">", &format!("<subform name=\"form\" layout=\"tb\">{bad}"));
let (_, warnings) = parse(&crowded).unwrap();
assert!(warnings.len() > 100, "the other warnings came first: {}", warnings.len());
assert!(warnings.iter().any(|w| w.contains("content areas")), "the cap is still recorded");
// Many capped page areas say it once, found without scanning every warning (it comes first).
let page_area = |n: usize| format!(r#"<pageArea name="p{n}"><medium stock="letter" short="8.5in" long="11in"/>{areas}</pageArea>"#);
let many: String = (0..50).map(page_area).collect();
let crowded = crowded.replacen(&page_area(0).replace("p0", "front"), &many, 1);
let (_, warnings) = parse(&crowded).unwrap();
assert_eq!(warnings.iter().filter(|w| w.contains("content areas")).count(), 1, "said once");
assert!(warnings[0].contains("content areas"), "kept first: {:?}", warnings.first());
}
#[test]
fn rich_text_max_length_reaches_the_field_and_layout() {
for (attribute, expected) in [
(r#"maxLength="5250""#, Some(5250)),
(r#"maxLength=" 10500 ""#, Some(10500)),
(r#"maxLength="0""#, None),
(r#"maxLength="-1""#, None),
(r#"maxLength="invalid""#, None),
(r#"maxLength="999999999999999999999999999999999999""#, None),
("", None),
] {
let xml = template(0).replace(
r#"<text maxChars="30"/>"#,
&format!(r#"<exData contentType="text/html" {attribute}><body xmlns="http://www.w3.org/1999/xhtml"><p>Hello</p></body></exData>"#),
);
let (tpl, _) = parse(&xml).unwrap();
let Node::Subform(head) = &tpl.root.children[0] else { panic!() };
let Node::Field(field) = &head.children[2] else { panic!() };
assert_eq!(field.max_chars, expected, "{attribute}");
assert_eq!(field.value.plain().as_deref(), Some("Hello"));
let form = layout_xml(&xml).unwrap();
let field = form.pages.iter().flat_map(widgets).find(|w| w.name == "familyName").unwrap();
assert_eq!(field.max_chars, expected, "{attribute}");
}
}
#[test]
fn the_xdp_template_wins_over_the_config_packets_template_element() {
// The config packet has a <template> too; the real one is in the xfa-template namespace.
let (tpl, _) = parse(&template(0)).unwrap();
assert_eq!(tpl.root.common.name.as_deref(), Some("form"));
}
#[test]
fn layout_places_captions_fields_and_sizes_containers_to_their_content() {
let form = layout_xml(&template(1)).unwrap();
assert_eq!(form.pages.len(), 2, "head and table on page 1, the last section after its break");
let p1 = &form.pages[0];
let t = texts(p1);
assert!(t.iter().any(|s| s == "Sample Form") && t.iter().any(|s| s == "Second line"), "{t:?}");
assert!(t.iter().any(|s| s == "Family name"), "caption drawn: {t:?}");
assert!(!t.iter().any(|s| s.contains("never shown")), "hidden draws take no space and draw nothing");
assert!(t.iter().any(|s| s == "Page 1 of 2"), "embedded page number and count: {t:?}");
assert!(!texts(&form.pages[1]).iter().any(|s| s.starts_with("Page ")), "the second master has no page-number draw");
let w = widgets(p1);
let family = w.iter().find(|w| w.name == "familyName").unwrap();
// Below the 0.4in title, on a line of its own (3in × 0.5in); the caption takes the top 0.2in.
assert!((family.rect.x - 36.0).abs() < 0.01 && (family.rect.y - 79.2).abs() < 0.01, "{:?}", family.rect);
assert!((family.rect.w - 216.0).abs() < 0.01 && (family.rect.h - 21.6).abs() < 0.01, "{:?}", family.rect);
assert_eq!(family.kind, WidgetKind::Text);
assert_eq!(family.border.shape, BorderShape::Underline);
assert_eq!(family.max_chars, Some(30));
assert_eq!(family.tooltip.as_deref(), Some("Your family name"));
assert_eq!(family.face.family, crate::text::Family::Courier);
assert_eq!(family.som, "form[0].head[0].familyName[0]");
let agree = w.iter().find(|w| w.name == "agree").unwrap();
assert_eq!(agree.kind, WidgetKind::CheckBox { on: "1".into(), round: false });
assert!((agree.rect.w - 10.0).abs() < 0.01, "a 10 pt square: {:?}", agree.rect);
let born = w.iter().find(|w| w.name == "born").unwrap();
assert_eq!(born.kind, WidgetKind::Date("yyyy-mm-dd".into()));
// The radio group has no width: it sits beside the question on the same line.
let q_y = p1
.items
.iter()
.find_map(|i| {
if let Item::Text(s) = i
&& s.text == "Have you ever?"
{
Some(s.baseline)
} else {
None
}
})
.unwrap();
let yes = w.iter().find(|w| matches!(&w.kind, WidgetKind::Radio { group, on, .. } if group == "answer" && on == "Y")).unwrap();
assert!(yes.rect.x > 6.5 * 72.0 && yes.rect.y < q_y, "beside the question, not under it: {:?} vs baseline {q_y}", yes.rect);
let go = w.iter().find(|w| w.name == "go").unwrap();
assert_eq!(go.kind, WidgetKind::Button { caption: "Reset".into() });
assert_eq!(go.action, Some(Action::Reset));
assert_eq!(go.border.fill, Some([212.0 / 255.0, 208.0 / 255.0, 200.0 / 255.0]));
// Table cells take the column widths; the second column has no width of its own.
let what = w.iter().find(|w| w.name == "what0").unwrap();
assert!((what.rect.x - (36.0 + 144.0)).abs() < 0.01 && (what.rect.w - 216.0).abs() < 0.01, "{:?}", what.rect);
assert_eq!(
form.fields,
9,
"familyName, agree, born, yes, no, go, 3 cells; pageNo/pageCount are hidden: {:?}",
w.iter().map(|w| &w.name).collect::<Vec<_>>()
);
}
#[test]
fn tables_break_across_pages_and_repeat_their_header_row() {
let form = layout_xml(&template(40)).unwrap();
assert!(form.pages.len() >= 3, "{} pages", form.pages.len());
// The header row's "Activity" cell appears at the top of every page the table continues on.
for (i, p) in form.pages.iter().enumerate().take(form.pages.len() - 1) {
let headers = p.items.iter().filter(|it| matches!(it, Item::Text(s) if s.text == "Activity")).count();
assert_eq!(headers, 1, "page {}: header rows {headers}", i + 1);
}
// Rows are whole: no cell straddles the bottom of the content area.
for p in &form.pages {
for w in widgets(p) {
assert!(w.rect.bottom() <= 36.0 + 720.0 + 0.01, "{} ends below the content area: {:?}", w.name, w.rect);
}
}
let all: Vec<&str> = form.pages.iter().flat_map(|p| widgets(p).into_iter().map(|w| w.name.as_str()).collect::<Vec<_>>()).collect();
assert_eq!(all.iter().filter(|n| n.starts_with("from")).count(), 40);
assert_eq!(all.len(), all.iter().collect::<std::collections::HashSet<_>>().len(), "field names are unique");
}
/// Laying a dynamic form out into its PDF replaces the placeholder page with the template's pages
/// and adds its fields (a radio group once), keeps the XFA packets and `/NeedsRendering` for Adobe's
/// viewers, writes each `/DR` font as an object of its own, and marks the form so it isn't laid out
/// twice.
#[test]
fn rendering_into_the_pdf_replaces_the_placeholder_page_and_adds_fields() {
let mut doc = Document::open(Arc::new(shell(&template(2)))).unwrap();
assert!(is_dynamic(&doc));
let report = render_into(&mut doc).unwrap();
assert_eq!((report.pages, report.fields), (2, 11), "fields: 5 on the head, the radio group once, 6 cells");
let bytes = write_incremental(&doc, &SaveOptions::default()).unwrap();
let doc = Document::open(Arc::new(bytes)).unwrap();
let root = doc.get(doc.root().unwrap());
let catalog = root.as_dict().unwrap();
let pages = doc.resolve(catalog.get(b"Pages").unwrap());
assert_eq!(pages.as_dict().unwrap().int(b"Count"), Some(2));
let kids = doc.resolve(pages.as_dict().unwrap().get(b"Kids").unwrap()).as_array().unwrap().clone();
let page1 = doc.resolve(&kids[0]);
let annots = doc.resolve(page1.as_dict().unwrap().get(b"Annots").unwrap()).as_array().unwrap().len();
assert!(annots >= 8, "{annots} widgets on page 1");
let acro = doc.resolve(catalog.get(b"AcroForm").unwrap());
let acro = acro.as_dict().unwrap();
assert!(acro.contains(b"XFA"), "the XFA packets stay");
assert_eq!(catalog.get(b"NeedsRendering"), Some(&Object::Bool(true)), "still a dynamic form for Adobe's viewers");
let fields = doc.resolve(acro.get(b"Fields").unwrap()).as_array().unwrap().len();
assert_eq!(fields, 11, "top-level fields (the radio group counts once)");
let dr = doc.resolve(acro.get(b"DR").unwrap());
let fonts = doc.resolve(dr.as_dict().unwrap().get(b"Font").unwrap());
assert!(fonts.as_dict().unwrap().contains(b"Cour") && fonts.as_dict().unwrap().contains(b"ZaDb"));
// Each one its own object: Acrobat shows nothing in a text field it redraws after typing
// when the /DR font is written inline (#3441).
for (name, font) in fonts.as_dict().unwrap().iter() {
let r = font.as_ref().unwrap_or_else(|| panic!("{} is an object", String::from_utf8_lossy(name)));
assert_eq!(doc.get(r).as_dict().and_then(|f| f.name(b"Type")), Some(&b"Font"[..]));
}
// A field carries its SOM path for data round trips.
let first = doc.resolve(&doc.resolve(acro.get(b"Fields").unwrap()).as_array().unwrap()[0]);
assert!(first.as_dict().unwrap().contains(SOM_KEY));
// Not dynamic twice: a second pass is refused rather than doubling the pages.
assert!(!is_dynamic(&doc));
}
/// A field or exclusion group that must be filled in (`<validate nullTest="error">`) becomes a
/// Required field, which viewers outline when they highlight a form's fields: a radio group on the
/// group field, its buttons' flags being the group's (a button of its own that must be chosen
/// makes the group required too). `nullTest="warning"` only recommends a value,
/// so it, like no test, leaves the field optional. A push button keeps no value (ISO 32000-2
/// §12.7.5.2.2), so it is never required.
#[test]
fn fields_that_must_be_filled_in_are_required() {
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">
<pageSet><pageArea name="p"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<field name="must" w="2in" h="0.3in"><ui><textEdit/></ui><validate nullTest="error"/></field>
<field name="should" w="2in" h="0.3in"><ui><textEdit/></ui><validate nullTest="warning"/></field>
<field name="may" w="2in" h="0.3in"><ui><textEdit/></ui></field>
<field name="agree" w="2in" h="0.3in"><ui><checkButton/></ui><items><integer>1</integer><integer>0</integer></items><validate nullTest="error"/></field>
<field name="go" w="1in" h="0.3in"><ui><button/></ui><caption><value><text>Go</text></value></caption><validate nullTest="error"/></field>
<exclGroup name="answer" layout="lr-tb"><validate nullTest="error"/>
<field name="yes" w="1in" h="0.3in"><ui><checkButton shape="round"/></ui><items><text>Y</text></items></field>
<field name="no" w="1in" h="0.3in"><ui><checkButton shape="round"/></ui><items><text>N</text></items></field>
</exclGroup>
<exclGroup name="optional" layout="lr-tb">
<field name="a" w="1in" h="0.3in"><ui><checkButton shape="round"/></ui><items><text>A</text></items></field>
</exclGroup>
<exclGroup name="second" layout="lr-tb">
<field name="b" w="1in" h="0.3in"><ui><checkButton shape="round"/></ui><items><text>B</text></items></field>
<field name="c" w="1in" h="0.3in"><ui><checkButton shape="round"/></ui><items><text>C</text></items><validate nullTest="error"/></field>
</exclGroup>
</subform></template></xdp:xdp>"##;
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 required: std::collections::BTreeMap<String, bool> = fields
.iter()
.map(|f| {
let d = doc.resolve(f).as_dict().unwrap().clone();
let name = d.get(b"T").and_then(|t| doc.resolve(t).as_string().map(|s| s.to_text())).unwrap_or_default();
(name, d.int(b"Ff").unwrap_or(0) & 2 != 0)
})
.collect();
let leaf = |n: &str| required.iter().find(|(k, _)| k.contains(n)).map(|(_, r)| *r);
assert_eq!(leaf("must"), Some(true), "{required:?}");
assert_eq!(leaf("should"), Some(false), "a warning only recommends a value");
assert_eq!(leaf("may"), Some(false));
assert_eq!(leaf("agree"), Some(true), "a check box too");
assert_eq!(leaf("go"), Some(false), "a push button holds no value to fill in");
assert_eq!(leaf("answer"), Some(true), "the radio group field");
assert_eq!(leaf("optional"), Some(false));
assert_eq!(leaf("second"), Some(true), "a later button that must be chosen makes its group required");
// The buttons themselves carry no Required flag: theirs are the group's.
for group in ["answer", "second"] {
let field = fields
.iter()
.map(|f| doc.resolve(f).as_dict().unwrap().clone())
.find(|d| d.get(b"T").and_then(|t| doc.resolve(t).as_string().map(|s| s.to_text())).is_some_and(|t| t.contains(group)));
let kids = field.and_then(|d| d.get(b"Kids").map(|k| doc.resolve(k).as_array().cloned().unwrap_or_default())).unwrap_or_default();
assert!(!kids.is_empty(), "{group} has its buttons as kids");
for kid in &kids {
let ff = doc.resolve(kid).as_dict().and_then(|d| d.int(b"Ff")).unwrap_or(0);
assert_eq!(ff & 2, 0, "{group}: a button is not Required itself");
}
}
}
/// A dynamic form's own text that the standard fonts can't draw is laid out anyway and reported
/// once, never written as `?` silently.
#[test]
fn form_text_the_standard_fonts_cannot_draw_is_reported() {
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">
<draw w="3in" h="0.3in"><value><text>申请表</text></value></draw><draw w="3in" h="0.3in"><value><text>签名</text></value></draw><draw w="3in" h="0.3in"><value><text>Name</text></value></draw>
</subform></template></xdp:xdp>"##;
let mut doc = Document::open(Arc::new(shell(xdp))).unwrap();
let report = render_into(&mut doc).unwrap();
let hits: Vec<&String> = report.warnings.iter().filter(|w| w.contains("standard fonts can't draw")).collect();
assert_eq!(hits.len(), 1, "reported once: {:?}", report.warnings);
assert!(hits[0].contains("\"申\" (U+7533)"), "{hits:?}");
// Latin text alone reports nothing.
let latin = xdp.replace("申请表", "Application").replace("签名", "Signature");
let mut doc = Document::open(Arc::new(shell(&latin))).unwrap();
assert!(!render_into(&mut doc).unwrap().warnings.iter().any(|w| w.contains("standard fonts")));
}
/// A template whose page shows objects only on screen (`relevant="-print"`), only in print
/// (`presence="invisible" relevant="+print"`) and everywhere, as fields and as draws, some of
/// them inside a screen-only subform. `others` is put in the catalog (its own layers).
fn relevant_template() -> String {
let field = |name: &str, attrs: &str| {
format!(r#"<field name="{name}" w="2in" h="0.3in" {attrs}><ui><textEdit/></ui><value><text>{name}</text></value></field>"#)
};
let draw = |name: &str, attrs: &str| format!(r#"<draw name="{name}" w="2in" h="0.3in" {attrs}><value><text>{name} text</text></value></draw>"#);
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>
{}{}{}{}{}{}{}{}
<subform name="screenBox" layout="tb" w="7.5in" relevant="-print">{}{}</subform>
</subform></template></xdp:xdp>"##,
field("everywhere", ""),
field("screenOnly", r#"relevant="-print""#),
field("printOnly", r#"presence="invisible" relevant="+print""#),
field("nowhere", r#"presence="invisible""#),
draw("shown", ""),
draw("screenDraw", r#"relevant="-print""#),
draw("paperDraw", r#"presence="invisible" relevant="+print""#),
draw("otherView", r#"relevant="-screen""#),
field("inScreenBox", ""),
field("printInScreenBox", r#"relevant="+print""#),
)
}
/// `relevant` decides printing (`+print` prints even what its presence hides on screen, `-print`
/// never prints) and presence decides the screen, inside containers too: a field's widget says
/// where it shows, and a draw shown only on screen or only in print is wrapped as such. A token
/// about another view is left aside with one warning.
#[test]
fn relevant_and_presence_say_where_fields_and_draws_show() {
let form = layout_xml(&relevant_template()).unwrap();
let page = &form.pages[0];
let views_of = |name: &str| widgets(page).iter().find(|w| w.name == name).map(|w| w.views);
let (screen, print) = (Views { screen: true, print: false }, Views { screen: false, print: true });
assert_eq!(views_of("everywhere"), Some(Views::ALL));
assert_eq!(views_of("screenOnly"), Some(screen));
assert_eq!(views_of("printOnly"), Some(print), "an invisible field that +print prints is drawn for print only");
assert_eq!(views_of("nowhere"), None, "an invisible field is still drawn nowhere");
assert_eq!(views_of("inScreenBox"), Some(screen), "inside a screen-only subform");
assert_eq!(views_of("printInScreenBox"), Some(screen), "+print can't print what its container keeps off paper");
// Draws: wrapped where they show only on screen or only in print.
let text = |want: &str| {
page.items.iter().find_map(|i| match i {
Item::Text(s) if s.text.contains(want) => Some(Views::ALL),
Item::Only { views, item } => matches!(item.as_ref(), Item::Text(s) if s.text.contains(want)).then_some(*views),
_ => None,
})
};
assert_eq!(text("shown text"), Some(Views::ALL));
assert_eq!(text("screenDraw text"), Some(screen));
assert_eq!(text("paperDraw text"), Some(print));
assert_eq!(text("otherView text"), Some(Views::ALL), "a view other than print is left aside");
let warned: Vec<&String> = form.warnings.iter().filter(|w| w.contains("relevant")).collect();
assert_eq!(warned.len(), 1, "{:?}", form.warnings);
assert!(warned[0].contains("-screen"), "{warned:?}");
}
/// The buttons of an exclusion group show where each one's own `relevant` and presence say,
/// inside what the group says, as other fields do; a view other than print is warned about.
#[test]
fn exclusion_group_buttons_show_where_each_says() {
let button = |name: &str, on: &str, attrs: &str| {
format!(r#"<field name="{name}" w="2in" h="0.3in" {attrs}><ui><checkButton shape="round"/></ui><items><text>{on}</text></items></field>"#)
};
let body = format!(
r#"<subform name="body" layout="tb" w="7.5in">
<exclGroup name="choice" layout="tb" w="3in">{}{}{}{}{}</exclGroup>
<exclGroup name="screenGroup" layout="tb" w="3in" relevant="-print">{}</exclGroup>
</subform>"#,
button("plain", "1", ""),
button("screenOnly", "2", r#"relevant="-print""#),
button("printOnly", "3", r#"presence="invisible" relevant="+print""#),
button("nowhere", "4", r#"presence="invisible""#),
button("otherView", "5", r#"relevant="-preview""#),
button("printInScreenGroup", "1", r#"relevant="+print""#),
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let views_of = |name: &str| widgets(&form.pages[0]).iter().find(|w| w.som.ends_with(&format!(".{name}[0]"))).map(|w| w.views);
let (screen, print) = (Views { screen: true, print: false }, Views { screen: false, print: true });
assert_eq!(views_of("plain"), Some(Views::ALL));
assert_eq!(views_of("screenOnly"), Some(screen));
assert_eq!(views_of("printOnly"), Some(print), "an invisible button that +print prints is drawn for print only");
assert_eq!(views_of("nowhere"), None, "an invisible button is drawn nowhere");
assert_eq!(views_of("otherView"), Some(Views::ALL), "a view other than print is left aside");
assert_eq!(views_of("printInScreenGroup"), Some(screen), "+print can't print what its group keeps off paper");
let warned: Vec<&String> = form.warnings.iter().filter(|w| w.contains("relevant")).collect();
assert!(warned.len() == 1 && warned[0].contains("-preview"), "{:?}", form.warnings);
}
/// A page count shown only on screen or only in print is filled in like any other, and a view
/// other than print named on a flowed subform or a table row is warned about as on a draw.
#[test]
fn restricted_page_counts_are_filled_in_and_other_views_warned_about_everywhere() {
let xfa_ns = r#"xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/""#;
let body = format!(
r##"<subform name="body" layout="tb" w="7.5in">
<subform name="screenOnly" layout="position" w="7.5in" h="1in" relevant="-print">
<draw name="pn" x="0in" y="0in" w="2in" h="0.3in"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>Pages: <span xfa:embed="#pageCount" {xfa_ns}/></p></body></exData></value><font typeface="Arial" size="10pt"/></draw>
</subform>
<field name="pageCount" id="pageCount" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><event activity="ready" ref="$layout"><script contentType="application/x-javascript">this.rawValue = xfa.layout.pageCount();</script></event></field>
<subform name="flowed" layout="tb" w="7.5in" relevant="-screen"><draw name="f" w="2in" h="0.3in"><value><text>Flowed</text></value></draw></subform>
<subform name="grid" layout="table" columnWidths="2in" w="2in"><subform name="row" layout="row" relevant="-preview"><draw name="c" h="0.3in"><value><text>Cell</text></value></draw></subform></subform>
</subform>"##
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let texts: Vec<String> = form.pages[0]
.items
.iter()
.filter_map(|i| match i {
Item::Only { item, .. } => match item.as_ref() {
Item::Text(s) => Some(s.text.clone()),
_ => None,
},
_ => None,
})
.collect();
assert!(texts.iter().any(|t| t.contains("Pages:") && t.contains('1')), "{texts:?}");
assert!(
form.pages
.iter()
.flat_map(|p| &p.items)
.all(|i| !matches!(i, Item::Only { item, .. } if matches!(item.as_ref(), Item::Text(s) if s.text.contains('\u{E000}')))),
"no page-count mark left"
);
for token in ["-screen", "-preview"] {
assert!(form.warnings.iter().any(|w| w.contains(token)), "{token}: {:?}", form.warnings);
}
}
/// A master page's own objects show where they say, even when the page was started by a
/// screen-only subform that ran onto it: its footer isn't made screen-only too.
#[test]
fn a_master_page_started_by_a_screen_only_subform_keeps_its_own_objects_everywhere() {
let rows: String = (0..30).map(|i| format!(r#"<draw name="row{i}" w="7in" h="0.5in"><value><text>Row {i}</text></value></draw>"#)).collect();
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">
<pageSet><pageArea name="page"><contentArea x="0.5in" y="0.5in" w="7.5in" h="9.5in"/><medium short="8.5in" long="11in"/>
<draw name="footer" x="0.5in" y="10.3in" w="3in" h="0.3in"><value><text>Footer</text></value></draw></pageArea></pageSet>
<subform name="screenRows" layout="tb" w="7.5in" relevant="-print">{rows}</subform>
</subform></template></xdp:xdp>"##
);
let form = layout_xml(&xdp).unwrap();
assert!(form.pages.len() >= 2, "{} pages", form.pages.len());
for (i, page) in form.pages.iter().enumerate() {
let footer = page.items.iter().any(|it| matches!(it, Item::Text(s) if s.text.contains("Footer")));
assert!(footer, "page {i}'s footer shows everywhere, not wrapped as screen-only");
assert!(page.items.iter().any(|it| matches!(it, Item::Only { .. })), "page {i} has the screen-only rows");
}
}
/// The widgets' annotation flags, the draws' optional content and the catalog's layers: shown
/// everywhere prints (`/F 4`), screen only doesn't print (`/F 0`), print only is NoView too
/// (`/F 36`); screen-only and print-only draws are marked content in groups whose `/Usage` and the
/// default configuration's `/AS` say where they show, the print-only one off on screen; the
/// document's own layer stays as it was; and laying the form out again adds nothing twice.
#[test]
fn screen_only_and_print_only_objects_are_written_with_flags_and_layers() {
let xdp = relevant_template();
let mut bytes = shell(&xdp);
// A layer of the document's own, off, listed in /Order.
let s = String::from_utf8_lossy(&bytes).into_owned();
let s = s.replacen(
"/AcroForm << /XFA 5 0 R /Fields [] >> >>",
"/AcroForm << /XFA 5 0 R /Fields [] >> /OCProperties << /OCGs [<< /Type /OCG /Name (Mine) >>] /D << /Order [] /OFF [] >> >> >>",
1,
);
assert_ne!(s.as_bytes(), bytes.as_slice(), "the shell's catalog was found");
bytes = s.into_bytes();
let mut doc = Document::open(Arc::new(bytes)).unwrap();
render_into(&mut doc).unwrap();
let check = |doc: &Document| {
// Widget flags by field name.
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 flags: std::collections::BTreeMap<String, i64> = fields
.iter()
.map(|f| doc.resolve(f))
.filter_map(|f| {
let d = f.as_dict()?;
Some((d.get(b"T").and_then(Object::as_string)?.to_text(), d.int(b"F").unwrap_or(-1)))
})
.collect();
assert_eq!(flags.get("everywhere"), Some(&4));
assert_eq!(flags.get("screenOnly"), Some(&0));
assert_eq!(flags.get("printOnly"), Some(&36));
// The groups, the configuration and the usage applications.
let props = doc.resolve(catalog.as_dict().unwrap().get(b"OCProperties").unwrap()).as_dict().unwrap().clone();
let ocgs = doc.resolve(props.get(b"OCGs").unwrap()).as_array().unwrap().clone();
assert_eq!(ocgs.len(), 3, "the document's own layer and the two groups, each once");
let mine = doc.resolve(ocgs.first().unwrap());
assert_eq!(mine.as_dict().unwrap().get(b"Name").and_then(Object::as_string).map(|s| s.to_text()).as_deref(), Some("Mine"));
let group = |key: &[u8]| {
ocgs.iter()
.filter_map(Object::as_ref)
.find(|r| doc.get(*r).as_dict().is_some_and(|d| d.name(crate::pdf::RELEVANT_KEY) == Some(key)))
.unwrap()
};
let (screen, print) = (group(b"Screen"), group(b"Print"));
let state = |r: pdfcraft_cos::ObjRef, event: &[u8], key: &[u8]| {
let g = doc.get(r);
let usage = g.as_dict().unwrap().get(b"Usage").unwrap().as_dict().unwrap().clone();
usage.get(event).unwrap().as_dict().unwrap().name(key).unwrap().to_vec()
};
assert_eq!((state(screen, b"View", b"ViewState"), state(screen, b"Print", b"PrintState")), (b"ON".to_vec(), b"OFF".to_vec()));
assert_eq!((state(print, b"View", b"ViewState"), state(print, b"Print", b"PrintState")), (b"OFF".to_vec(), b"ON".to_vec()));
let d = doc.resolve(props.get(b"D").unwrap()).as_dict().unwrap().clone();
let refs = |o: Option<&Object>| doc.resolve(o.unwrap()).as_array().unwrap().iter().filter_map(Object::as_ref).collect::<Vec<_>>();
assert_eq!(refs(d.get(b"OFF")), [print], "only the print-only group starts off");
assert!(refs(d.get(b"Order")).is_empty(), "the document's /Order is left as it was");
let apps = doc.resolve(d.get(b"AS").unwrap()).as_array().unwrap().clone();
assert_eq!(apps.len(), 2, "one usage application per event");
for (app, event) in apps.iter().zip([&b"View"[..], b"Print"]) {
let app = doc.resolve(app).as_dict().unwrap().clone();
assert_eq!(app.name(b"Event"), Some(event));
assert_eq!(refs(app.get(b"OCGs")), [screen, print]);
}
// The page's marked content and resources.
let kids = doc
.resolve(doc.resolve(catalog.as_dict().unwrap().get(b"Pages").unwrap()).as_dict().unwrap().get(b"Kids").unwrap())
.as_array()
.unwrap()
.clone();
let page = doc.resolve(kids.first().unwrap()).as_dict().unwrap().clone();
let res = doc.resolve(page.get(b"Resources").unwrap()).as_dict().unwrap().clone();
let properties = res.get(b"Properties").unwrap().as_dict().unwrap().clone();
assert_eq!((properties.reference(b"PCXfaScreen"), properties.reference(b"PCXfaPrint")), (Some(screen), Some(print)));
let Object::Stream(c) = &*doc.resolve(page.get(b"Contents").unwrap()) else { panic!("a content stream") };
let ops = String::from_utf8_lossy(&c.decoded().unwrap()).into_owned();
let inside = |group: &str, text: &str| {
let start = ops.find(&format!("/OC /{group} BDC")).unwrap_or(usize::MAX);
let at = ops.find(text).unwrap_or(0);
let end = ops.get(start.min(ops.len())..).and_then(|rest| rest.find("EMC")).map(|e| start + e).unwrap_or(0);
start < at && at < end
};
assert!(inside("PCXfaScreen", "(screenDraw text)") && inside("PCXfaPrint", "(paperDraw text)"), "{ops}");
// Shown everywhere: outside any marked content (here, before the first).
assert!(ops.find("(shown text)") < ops.find("/OC /"), "{ops}");
};
check(&doc);
// Laid out again: the same groups, nothing added twice.
let (tpl, _) = parse(&xdp).unwrap();
rerender(&mut doc, &tpl).unwrap();
check(&doc);
// Stripping the XFA keeps the layers the pages use, without PdfCraft's key.
strip(&mut doc).unwrap();
let catalog = doc.get(doc.root().unwrap());
let props = doc.resolve(catalog.as_dict().unwrap().get(b"OCProperties").unwrap()).as_dict().unwrap().clone();
let ocgs = doc.resolve(props.get(b"OCGs").unwrap()).as_array().unwrap().clone();
assert_eq!(ocgs.len(), 3);
assert!(ocgs.iter().all(|g| !doc.resolve(g).as_dict().unwrap().contains(crate::pdf::RELEVANT_KEY)));
}
/// 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:forms@example.com ">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:forms@example.com")),
("example", Some("mailto:forms@example.com")),
(".com", Some("mailto:forms@example.com")),
(" 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:forms@example.com">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:a@example.com">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://user@example.com: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:a@example.com", "https://user@example.com: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:?}");
}
/// A link in text shown only on screen or only in print works only where its text shows: in
/// print-only text it is NoView (`/F 36`), so it can't be clicked on screen over nothing, and in
/// screen-only text it doesn't print (`/F 0`). Its pieces still join into one link across a change
/// of style and the underline drawn with them.
#[test]
fn links_in_screen_only_and_print_only_text_work_where_their_text_shows() {
let draw = |name: &str, attrs: &str| {
format!(
r#"<draw name="{name}" w="4in" {attrs}><font typeface="Arial" size="10pt"/><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p style="text-decoration:underline"><a href="https://example.com/{name}">forms@<b>example</b>.com</a></p></body></exData></value></draw>"#
)
};
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">
<pageSet><pageArea name="page"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
{}{}{}
</subform></template></xdp:xdp>"##,
draw("everywhere", ""),
draw("screen", r#"relevant="-print""#),
draw("paper", r#"presence="invisible" relevant="+print""#),
);
let mut doc = Document::open(Arc::new(shell(&xdp))).unwrap();
render_into(&mut doc).unwrap();
// Each link annotation's address and flags.
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 page = doc.resolve(kids.first().unwrap());
let annots = doc.resolve(page.as_dict().unwrap().get(b"Annots").unwrap()).as_array().unwrap().clone();
let links: Vec<(String, i64)> = annots
.iter()
.map(|a| doc.resolve(a).as_dict().unwrap().clone())
.filter(|d| d.name(b"Subtype") == Some(&b"Link"[..]))
.map(|d| {
let action = doc.resolve(d.get(b"A").unwrap()).as_dict().unwrap().clone();
(String::from_utf8_lossy(&action.get(b"URI").and_then(Object::as_string).unwrap().bytes).into_owned(), d.int(b"F").unwrap())
})
.collect();
let expected = [("https://example.com/everywhere", 4), ("https://example.com/screen", 0), ("https://example.com/paper", 36)];
assert_eq!(links, expected.map(|(u, f)| (u.to_string(), f)), "one link each, with flags where its text shows");
}
#[test]
fn documents_without_xfa_are_not_touched() {
let mut doc = Document::new_empty();
assert!(!is_dynamic(&doc));
assert!(matches!(render_into(&mut doc), Err(XfaError::NotXfa)));
}
#[test]
fn hostile_templates_fail_without_panicking() {
assert!(layout_xml("not xml").is_err());
assert!(layout_xml("<template/>").is_err());
assert!(layout_xml("<template><subform/></template>").is_ok(), "an empty form is one empty page");
// Deep nesting is cut off, not followed.
let deep = format!("<template><subform layout=\"tb\">{}{}</subform></template>", "<subform layout=\"tb\">".repeat(500), "</subform>".repeat(500));
assert!(layout_xml(&deep).is_ok());
// Absurd sizes are clamped; a page can't be a mile wide.
let huge = r##"<template><subform layout="tb"><pageSet><pageArea><medium short="1e9in" long="-5in"/></pageArea></pageSet><draw w="1e12pt" h="1e12pt"><value><text>x</text></value></draw></subform></template>"##;
let f = layout_xml(huge).unwrap();
assert!(f.pages[0].width <= 14_400.0 && f.pages[0].height >= 1.0);
// Too many pages is an error, not an endless loop.
let many = format!(
"<template><subform layout=\"tb\"><pageSet><pageArea><contentArea w=\"100pt\" h=\"100pt\"/><medium short=\"100pt\" long=\"100pt\"/></pageArea></pageSet>{}</subform></template>",
"<draw h=\"90pt\"><value><text>x</text></value></draw>".repeat(MAX_PAGES + 5)
);
assert!(matches!(layout_xml(&many), Err(XfaError::TooLarge(_))));
// A bad image and a bad base64 are warnings, not failures.
let img = r##"<template><subform layout="tb"><draw w="1in" h="1in"><value><image contentType="image/png">!!!notbase64</image></value></draw></subform></template>"##;
let f = layout_xml(img).unwrap();
assert!(!f.warnings.is_empty());
}
#[test]
fn repeated_pictures_are_bounded_in_total_bytes() {
// Each laid-out picture keeps its own copy of the bytes, so one picture in a repeating
// subform used to multiply without bound and exhaust memory (a failed allocation aborts the
// app). "AAAA" base64 decodes to zero bytes; 2_097_152 groups is 6 MiB, under the 32 MiB
// per-picture cap. 50 instances (occur initial, clamped to MAX_INSTANCES) would be ~300 MiB,
// past the aggregate cap, so layout must stop with TooLarge rather than retain it all.
let big = "AAAA".repeat(2_097_152);
let tpl = format!(
"<template><subform layout=\"tb\"><subform layout=\"tb\"><occur initial=\"50\" max=\"-1\"/>\
<draw w=\"0.2in\" h=\"0.2in\"><value><image contentType=\"image/png\">{big}</image></value></draw>\
</subform></subform></template>"
);
assert!(matches!(layout_xml(&tpl), Err(XfaError::TooLarge(m)) if m.contains("too large")), "the repeated picture must be refused");
// A single small picture still lays out: the cap does not reject an ordinary form.
let small = "AAAA".repeat(8);
let ok = format!(
"<template><subform layout=\"tb\"><draw w=\"1in\" h=\"1in\"><value><image contentType=\"image/png\">{small}</image></value></draw></subform></template>"
);
assert!(layout_xml(&ok).is_ok(), "one small picture must lay out");
}
#[test]
fn empty_repeating_subforms_spend_the_layout_budget() {
// Four nested levels of 50 empty instances are 6.25 million instances that place nothing
// and measure nothing; each one counts against the layout budget.
let level = "<subform layout=\"tb\"><occur initial=\"50\" max=\"-1\"/>";
let tpl = format!("<template><subform layout=\"tb\">{}{}</subform></template>", level.repeat(4), "</subform>".repeat(4));
assert!(matches!(layout_xml(&tpl), Err(XfaError::TooLarge(_))));
// Three levels (125,000 instances) still lay out.
let tpl = format!("<template><subform layout=\"tb\">{}{}</subform></template>", level.repeat(3), "</subform>".repeat(3));
assert!(layout_xml(&tpl).is_ok());
}
#[test]
fn a_block_split_across_very_many_pages_spends_the_layout_budget() {
// One-point content areas slice a flowed subform's paragraphs one line to a page, so the
// block is split across hundreds of pages; split_block rescans the still-unplaced
// paragraphs once per page, which is quadratic in their number. Fewer paragraphs than this
// lay out (188 pages here), so the page limit does not catch it; the rescans spend the
// work budget instead.
let areas: String = (0..128).map(|i| format!("<contentArea x=\"0.5in\" y=\"{i}pt\" w=\"7in\" h=\"1pt\"/>")).collect();
let paras: String = (0..2500).map(|i| format!("<p>Paragraph number {i} with a few words to fill a line.</p>")).collect();
let tpl = format!(
"<template><subform name=\"form\" layout=\"tb\"><pageSet><pageArea name=\"p\">\
<medium stock=\"letter\" short=\"8.5in\" long=\"11in\"/>{areas}</pageArea></pageSet>\
<subform name=\"body\" layout=\"tb\"><field name=\"t\" w=\"7in\"><ui><textEdit multiLine=\"1\"/></ui>\
<value><exData contentType=\"text/html\"><body xmlns=\"http://www.w3.org/1999/xhtml\">{paras}</body></exData></value>\
</field></subform></subform></template>"
);
match layout_xml(&tpl) {
// It says what ran out, not that the form is nested too deeply (CodeRabbit review on #5844).
Err(XfaError::TooLarge(m)) => assert!(m.contains("split across"), "{m}"),
other => panic!("a block split across very many pages must be refused: {other:?}"),
}
}
#[test]
fn large_text_drawn_in_many_instances_spends_the_draw_budget() {
// A draw whose text overflows its fixed height is re-measured up to six times to shrink it,
// and a repeating subform draws it once per instance. Large text drawn in many instances
// used to cost one full text layout per instance per pass, for seconds of work on a small
// file; each pass now counts its characters against the draw budget.
let words = "word ".repeat(4000); // 20,000 characters
let draw = format!("<draw w=\"1in\" h=\"0.5in\"><value><text>{words}</text></value></draw>");
let many =
format!("<template><subform layout=\"tb\"><subform layout=\"tb\"><occur initial=\"50\" max=\"-1\"/>{draw}</subform></subform></template>");
assert!(matches!(layout_xml(&many), Err(XfaError::TooLarge(_))), "large text in many instances must be refused");
// One copy of the same draw lays out: the budget does not reject an ordinary form.
let one = format!("<template><subform layout=\"tb\">{draw}</subform></template>");
assert!(layout_xml(&one).is_ok(), "a single large draw must lay out");
}
/// The draw budget counts the values of embedded fields as well as the text around them: a short
/// text embedding a long value, drawn in many instances, is as much work as the value written out
/// each time (CodeRabbit review on #5852).
#[test]
fn embedded_values_drawn_in_many_instances_spend_the_draw_budget() {
let value = "word ".repeat(4000); // 20,000 characters
let span = r##"<span xfa:embed="#long" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"/>"##;
let draw = format!(
r#"<draw w="1in" h="0.5in"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>x {span}</p></body></exData></value></draw>"#
);
let field = format!(r#"<field id="long" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><value><text>{value}</text></value></field>"#);
let many =
format!(r#"<template><subform layout="tb">{field}<subform layout="tb"><occur initial="50" max="-1"/>{draw}</subform></subform></template>"#);
assert!(matches!(layout_xml(&many), Err(XfaError::TooLarge(_))), "a long embedded value in many instances must be refused");
// One copy lays out: the budget does not reject an ordinary form.
let one = format!(r#"<template><subform layout="tb">{field}{draw}</subform></template>"#);
assert!(layout_xml(&one).is_ok(), "a single draw embedding a long value must lay out");
}
/// The last layout pass of a draw counts against the budget too: a draw that fits is measured
/// once and laid out once, each pass expanding its embedded value, and when the form's last draw
/// crosses the budget in that final pass it is still refused (CodeRabbit review on #5852).
#[test]
fn the_draw_that_crosses_the_budget_in_its_last_pass_is_refused() {
// 15,000 characters: with the 1 MiB test budget, the tenth such draw crosses it during its
// final layout pass, after every check before that pass has passed.
let value = "word ".repeat(3000);
let span = r##"<span xfa:embed="#long" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"/>"##;
let form = |n: usize| {
format!(
r#"<template><subform layout="tb"><field id="long" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><value><text>{value}</text></value></field><subform layout="tb"><occur initial="{n}" max="-1"/><draw w="7in" h="9in"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>x {span}</p></body></exData></value></draw></subform></subform></template>"#
)
};
assert!(layout_xml(&form(9)).is_ok());
assert!(matches!(layout_xml(&form(10)), Err(XfaError::TooLarge(_))), "the draw crossing the budget in its last pass must be refused");
}
/// Once a fit pass spends the budget, no more passes are made: a draw that doesn't fit and embeds
/// a long value is measured once, not seven times, before it is refused (CodeRabbit review on
/// #5852).
#[test]
fn fit_passes_stop_once_the_draw_budget_is_spent() {
let value = "word ".repeat(text::MAX_EMBEDDED / 5 + 1000);
let span = r##"<span xfa:embed="#long" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"/>"##;
let tpl = format!(
r#"<template><subform layout="tb"><field id="long" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><value><text>{value}</text></value></field><draw w="1in" h="0.5in"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>x {span}</p></body></exData></value></draw></subform></template>"#
);
crate::layout::EMBED_COPIED.with(|c| c.set(0));
assert!(matches!(layout_xml(&tpl), Err(XfaError::TooLarge(_))));
let copied = crate::layout::EMBED_COPIED.with(|c| c.get());
assert!(copied <= 2 * text::MAX_EMBEDDED as u64, "{copied} bytes copied: more passes after the budget was spent");
}
#[test]
fn a_packet_stream_listed_many_times_is_read_once() {
let mut doc = Document::open(Arc::new(shell("<template><subform/></template>"))).unwrap();
let packet = pdfcraft_cos::ObjRef::new(5, 0);
let items: Vec<Object> =
(0..1000).flat_map(|_| [Object::String(pdfcraft_cos::PdfString::literal(b"template".to_vec())), Object::Ref(packet)]).collect();
let root = doc.root().unwrap();
doc.update_dict(root, |c| {
let mut acro = c.get(b"AcroForm").and_then(Object::as_dict).cloned().unwrap();
acro.set(b"XFA".to_vec(), Object::Array(items));
c.set(b"AcroForm".to_vec(), Object::Dict(acro));
})
.unwrap();
let p = read_packets(&doc).unwrap().unwrap();
assert_eq!(p.xdp.matches("<template").count(), 1);
}
#[test]
fn empty_repeating_subforms_drawn_in_a_positioned_root_spend_the_layout_budget() {
// The same four levels inside a positioned root are drawn, not flowed.
let level = "<subform layout=\"tb\"><occur initial=\"50\" max=\"-1\"/>";
let nest =
|n: usize| format!("<template><subform><subform layout=\"tb\">{}{}</subform></subform></template>", level.repeat(n), "</subform>".repeat(n));
assert!(matches!(layout_xml(&nest(4)), Err(XfaError::TooLarge(_))));
assert!(layout_xml(&nest(3)).is_ok());
}
#[test]
fn the_packets_can_be_one_stream_or_named_parts() {
// Named parts, with the template split from the rest.
let doc = Document::open(Arc::new(shell(&template(0)))).unwrap();
let p = read_packets(&doc).unwrap().unwrap();
assert!(p.needs_rendering && !p.has_fields);
assert!(p.xdp.contains("<template"));
// UTF-16 packets are read too.
let mut utf16 = vec![0xFF, 0xFE];
for u in "<template><subform/></template>".encode_utf16() {
utf16.extend_from_slice(&u.to_le_bytes());
}
let xdp = String::from_utf8_lossy(&utf16).into_owned();
let _ = xdp;
let doc = Document::open(Arc::new(shell_bytes(&utf16))).unwrap();
let p = read_packets(&doc).unwrap().unwrap();
assert!(p.xdp.starts_with("<template>"), "{:?}", &p.xdp[..20.min(p.xdp.len())]);
}
/// Like [`shell`], but the packet bytes are given as-is.
fn shell_bytes(packet: &[u8]) -> Vec<u8> {
let text = shell("PLACEHOLDER");
let needle = b"<< /Length 11 >>\nstream\nPLACEHOLDER\nendstream";
let pos = text.windows(needle.len()).position(|w| w == needle).unwrap();
let mut out = text[..pos].to_vec();
out.extend_from_slice(format!("<< /Length {} >>\nstream\n", packet.len()).as_bytes());
out.extend_from_slice(packet);
out.extend_from_slice(b"\nendstream");
out.extend_from_slice(&text[pos + needle.len()..]);
// The xref offsets after the stream are off; the reader reconstructs them.
out
}
#[test]
fn jpeg_headers_give_the_size() {
// A minimal SOF0 header: 300 × 200, 3 components.
let mut j = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10];
j.extend_from_slice(&[0; 14]);
j.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x11, 0x08, 0x00, 0xC8, 0x01, 0x2C, 0x03]);
assert_eq!(pdf::jpeg_size(&j), Some((300, 200)));
assert_eq!(pdf::jpeg_size(b"\x89PNG"), None);
assert_eq!(pdf::jpeg_size(&[0xFF, 0xD8, 0xFF]), None);
}
const DATA: &str = "<form><head><familyName>Singh</familyName><agree>1</agree><born>2001-02-03</born><answer>N</answer></head><table><row><from0>2019</from0><what0>Studied</what0><where0>Delhi</where0></row><row><from0>2021</from0><what0>Worked</what0><where0>Toronto</where0></row><row><from0>2023</from0><what0>Moved</what0><where0>Ottawa</where0></row></table></form>";
/// The datasets packet parses into a tree whose nodes the fields' data paths find.
#[test]
fn datasets_parse_into_a_tree_and_som_paths_find_their_nodes() {
let d = parse_datasets(&template_with_data(1, DATA)).expect("datasets");
assert_eq!(d.name, "data");
assert_eq!(d.text_at(&som_to_path("form[0].head[0].familyName[0]")), Some("Singh"));
assert_eq!(d.text_at(&som_to_path("form[0].#subform[0].head[0].answer[0]")), Some("N"), "unnamed containers have no data node");
assert_eq!(d.text_at(&som_to_path("form[0].table[0].row[2].where0[0]")), Some("Ottawa"));
assert_eq!(d.text_at(&som_to_path("form[0].table[0].row[3].where0[0]")), None);
assert_eq!(d.count(&som_to_path("form[0].table[0]"), "row"), 3);
assert_eq!(som_to_path("a[1].b"), vec![("a".to_string(), 1), ("b".to_string(), 0)]);
assert!(parse_datasets("<xdp:xdp xmlns:xdp=\"x\"/>").is_none());
}
/// ISO dates convert to and from the date patterns fields show; text that isn't a date is left
/// alone or refused.
#[test]
fn dates_convert_between_iso_and_acrobat_patterns() {
assert_eq!(iso_to_pattern("2001-02-03", "yyyy-mm-dd"), "2001-02-03");
assert_eq!(iso_to_pattern("2001-02-03", "mm/dd/yyyy"), "02/03/2001");
assert_eq!(iso_to_pattern("2001-02-03", "d.m.yy"), "3.2.01");
assert_eq!(iso_to_pattern("not a date", "mm/dd/yyyy"), "not a date");
assert_eq!(pattern_to_iso("02/03/2001", "mm/dd/yyyy").as_deref(), Some("2001-02-03"));
assert_eq!(pattern_to_iso("3.2.01", "d.m.yy").as_deref(), Some("2001-02-03"));
assert_eq!(pattern_to_iso("2001-02-03", "yyyy-mm-dd").as_deref(), Some("2001-02-03"));
assert_eq!(pattern_to_iso("13/40/2001", "mm/dd/yyyy"), None);
assert_eq!(pattern_to_iso("hello", "mm/dd/yyyy"), None);
}
/// What scripts read as `formattedValue`: a date display picture shows the ISO value in its
/// pattern (the first of several alternatives); other kinds of picture, and values that aren't
/// ISO dates, leave the raw value.
#[test]
fn formatted_values_follow_date_display_pictures() {
assert_eq!(crate::formatted_value("date{YYYYMMDD}", "2026-10-20").as_deref(), Some("20261020"));
assert_eq!(crate::formatted_value("date{MM/DD/YYYY}", "2026-10-20").as_deref(), Some("10/20/2026"));
assert_eq!(crate::formatted_value("date{YYYYMMDD}|date{DDMMMYY}", "2026-10-20").as_deref(), Some("20261020"));
assert_eq!(crate::formatted_value("date{YYYY-MM-DD}", "2026-10-20"), None, "shown as it is");
assert_eq!(crate::formatted_value("num{zzz9}", "2026-10-20"), None);
assert_eq!(crate::formatted_value("date{YYYYMMDD}", "20261020"), None, "not an ISO date");
assert_eq!(crate::formatted_value("date{YYYYMMDD}", ""), None);
// Month and weekday names aren't shown yet: the raw value stands rather than `20 mmm 2026`.
assert_eq!(crate::formatted_value("date{DD MMM YYYY}", "2026-10-20"), None);
assert_eq!(crate::formatted_value("date{EEE MM/DD/YYYY}", "2026-10-20"), None);
// Only the ISO date's own shape is formatted.
assert_eq!(crate::formatted_value("date{YYYYMMDD}", "2026-1-2"), None);
// Parentheses hold the picture's locale and braces its pattern: one without braces has none.
assert_eq!(crate::formatted_value("date(en_US){YYYYMMDD}", "2026-10-20").as_deref(), Some("20261020"));
assert_eq!(crate::formatted_value("date(YYYYMMDD)", "2026-10-20"), None);
}
/// A field's `<format><picture>` is its display picture, kept apart from its `<ui>` edit
/// picture; a field without one has none.
#[test]
fn display_pictures_are_parsed_apart_from_edit_pictures() {
let (tpl, _) = parse(&crate::fixtures::date_row_template()).unwrap();
let Node::Subform(page) = &tpl.root.children[0] else { panic!() };
let Node::Field(from) = &page.children[0] else { panic!() };
assert_eq!((from.picture.as_deref(), from.display_picture.as_deref()), (Some("date{YYYYMMDD}"), Some("date{YYYYMMDD}")));
let Node::Field(days) = &page.children[1] else { panic!() };
assert_eq!(days.display_picture, None);
}
/// A date field's data picture (`<bind><picture>`) is how its value is written in the data:
/// `due` keeps `20261018` there and shows `10/18/2026`. The stored text used to be shown as it
/// was, because the data was taken to hold ISO dates only.
#[test]
fn a_date_is_read_from_the_data_in_its_data_picture() {
let form = layout_xml(&bound_date_template("<form><page><due>20261018</due><when>2026-10-18</when></page></form>")).unwrap();
let all: Vec<&Widget> = form.pages.iter().flat_map(widgets).collect();
let by = |n: &str| all.iter().find(|w| w.name == n).unwrap_or_else(|| panic!("no widget {n}"));
assert_eq!(by("due").value.as_deref(), Some("10/18/2026"));
assert_eq!(by("when").value.as_deref(), Some("10/18/2026"), "no data picture: the data holds ISO");
}
/// A SOM path names the template field its segment numbers count to, repeating rows included.
#[test]
fn som_paths_name_the_template_field_their_numbers_count_to() {
let xml = r#"<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
<subform name="form">
<field name="x"><bind><picture>first</picture></bind></field>
<subform name="row"><occur min="1" max="-1"/><field name="d"><bind><picture>row</picture></bind></field></subform>
<field name="x"><bind><picture>second</picture></bind></field>
<subform><field name="u"><bind><picture>inner</picture></bind></field></subform>
</subform>
</template></xdp:xdp>"#;
let (tpl, _) = parse(xml).unwrap();
let picture = |som: &str| crate::data::template_field(&tpl, som).and_then(|f| f.data_picture.clone());
// Same-named siblings count up; each SOM number is its own field.
assert_eq!(picture("form[0].x[0]").as_deref(), Some("first"));
assert_eq!(picture("form[0].x[1]").as_deref(), Some("second"));
assert_eq!(picture("form[0].x[2]"), None, "no third x");
// The instances of a repeating subform follow its number: all are the one template node.
assert_eq!(picture("form[0].row[0].d[0]").as_deref(), Some("row"));
assert_eq!(picture("form[0].row[3].d[0]").as_deref(), Some("row"));
// An unnamed subform is looked through, as data paths do.
assert_eq!(picture("form[0].u[0]").as_deref(), Some("inner"));
}
/// Refreshing a value in place uses the field's own template field, not a same-named one's.
#[test]
fn a_refreshed_field_takes_its_value_from_its_own_template_field() {
// Two text fields named `x` with different defaults; the data holds only the first.
let xml = r#"<xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/"><template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">
<subform name="form">
<field name="x"><ui><textEdit/></ui><value><text>first</text></value></field>
<field name="x"><ui><textEdit/></ui><value><text>second</text></value></field>
</subform>
</template><xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"><xfa:data><form><x>a</x></form></xfa:data></xfa:datasets></xdp:xdp>"#;
let (tpl, _) = parse(xml).unwrap();
let data = parse_datasets(xml).unwrap();
let mut live = form_tree(&tpl, Some(&data), &Overrides::default()).root;
let value = |live: &crate::script::FormNode, som: &str| node_at(live, som).map(|n| n.value.clone());
assert_eq!(value(&live, "form[0].x[1]").as_deref(), Some("second"));
assert_eq!(crate::script::refresh_value(&mut live, &tpl, Some(&data), "form[0].x[1]"), Some(false), "nothing to change");
assert_eq!(value(&live, "form[0].x[1]").as_deref(), Some("second"), "not the first x's default");
}
/// Scripts read a date as the ISO date another viewer gives them as `rawValue`
/// (`2026-10-18`), whatever the field's data picture writes in the data (`20261018`), so a
/// script's `String(rawValue).length == 10` holds. A field without a data picture keeps the
/// data's ISO date, and refreshing a value in place reads it the same way.
#[test]
fn scripts_read_a_date_as_iso_whatever_its_data_picture_writes() {
let xml = bound_date_template("<form><page><due>20261018</due><when>2026-10-18</when></page></form>");
let (tpl, _) = parse(&xml).unwrap();
let data = parse_datasets(&xml).unwrap();
let mut live = form_tree(&tpl, Some(&data), &Overrides::default()).root;
let value = |live: &crate::script::FormNode, som: &str| node_at(live, som).map(|n| n.value.clone());
assert_eq!(value(&live, "form[0].page[0].due[0]").as_deref(), Some("2026-10-18"));
assert_eq!(value(&live, "form[0].page[0].when[0]").as_deref(), Some("2026-10-18"));
let later = parse_datasets(&bound_date_template("<form><page><due>20261019</due><when>2026-10-18</when></page></form>")).unwrap();
assert_eq!(crate::script::refresh_value(&mut live, &tpl, Some(&later), "form[0].page[0].due[0]"), Some(true));
assert_eq!(value(&live, "form[0].page[0].due[0]").as_deref(), Some("2026-10-19"));
}
/// The node of `live` at `som`.
fn node_at<'a>(live: &'a crate::script::FormNode, som: &str) -> Option<&'a crate::script::FormNode> {
if live.som == som {
return Some(live);
}
live.children.iter().find_map(|c| node_at(c, som))
}
/// A date its data picture can't hold (2030 in a two-digit year) is written as ISO and reads
/// back as written.
#[test]
fn a_date_its_data_picture_cant_hold_is_written_as_iso() {
use crate::data::{data_to_iso, iso_to_data};
assert_eq!(iso_to_data("2026-01-02".into(), Some("yymmdd")), "260102");
// A two-digit year reads back as 1930 to 2029, so those years are written in it.
for (iso, data) in [("2029-12-31", "291231"), ("1930-01-01", "300101"), ("1949-12-31", "491231"), ("1950-01-01", "500101")] {
assert_eq!(iso_to_data(iso.into(), Some("yymmdd")), data, "{iso}");
}
// 2030 and 1929 keep ISO, and read back as written.
for iso in ["2030-01-01", "1929-12-31", "2050-01-02"] {
assert_eq!(iso_to_data(iso.into(), Some("yymmdd")), iso);
assert_eq!(data_to_iso(iso, Some("yymmdd")), iso);
}
}
/// A two-digit year splits its century at 30, the XFA picture clause default: `00` to `29` are
/// 2000 to 2029 and `30` to `99` are 1930 to 1999, typed and in the data alike.
#[test]
fn a_two_digit_year_splits_its_century_at_30() {
use crate::data::data_to_iso;
for (text, iso) in [("291231", "2029-12-31"), ("300101", "1930-01-01"), ("491231", "1949-12-31"), ("500101", "1950-01-01")] {
assert_eq!(pattern_to_iso(text, "yymmdd").as_deref(), Some(iso), "{text}");
assert_eq!(data_to_iso(text, Some("yymmdd")), iso, "{text}");
}
}
/// The datasets fill the fields and add the rows of repeating subforms.
#[test]
fn month_and_weekday_names_in_date_patterns() {
// 2001-02-03 was a Saturday.
assert_eq!(iso_to_pattern("2001-02-03", "mmm d, yyyy"), "Feb 3, 2001");
assert_eq!(iso_to_pattern("2001-02-03", "mmmm d, yyyy"), "February 3, 2001");
assert_eq!(iso_to_pattern("2001-02-03", "ddd, mmm d"), "Sat, Feb 3");
assert_eq!(iso_to_pattern("2001-02-03", "dddd, mmmm dd, yyyy"), "Saturday, February 03, 2001");
assert_eq!(pattern_to_iso("Feb 3, 2001", "mmm d, yyyy").as_deref(), Some("2001-02-03"));
assert_eq!(pattern_to_iso("February 3, 2001", "mmmm d, yyyy").as_deref(), Some("2001-02-03"));
assert_eq!(pattern_to_iso("Saturday, February 03, 2001", "dddd, mmmm dd, yyyy").as_deref(), Some("2001-02-03"));
assert_eq!(pattern_to_iso("Smarch 3, 2001", "mmm d, yyyy"), None);
// A token the converter can't render leaves the value as it is.
assert_eq!(iso_to_pattern("2001-02-03", "mmmmm d"), "2001-02-03");
assert_eq!(pattern_to_iso("Feb 3", "mmmmm d"), None);
}
#[test]
fn data_fills_the_fields_and_adds_rows() {
let form = layout_xml(&template_with_data(1, DATA)).unwrap();
let all: Vec<&Widget> = form.pages.iter().flat_map(widgets).collect();
let by = |n: &str| all.iter().find(|w| w.name == n).unwrap_or_else(|| panic!("no widget {n}"));
assert_eq!(by("familyName").value.as_deref(), Some("Singh"));
assert_eq!(by("agree").value.as_deref(), Some("1"), "checked by its on value");
assert_eq!(by("born").value.as_deref(), Some("2001-02-03"));
let no = all.iter().find(|w| matches!(&w.kind, WidgetKind::Radio { on, .. } if on == "N")).unwrap();
let yes = all.iter().find(|w| matches!(&w.kind, WidgetKind::Radio { on, .. } if on == "Y")).unwrap();
assert!(no.value.is_some() && yes.value.is_none(), "the group's data picks the N button");
// One row in the template, three in the data: three rows laid out, each with its values.
let wheres: Vec<&str> = all.iter().filter(|w| w.name.starts_with("where0")).filter_map(|w| w.value.as_deref()).collect();
assert_eq!(wheres, ["Delhi", "Toronto", "Ottawa"]);
assert_eq!(by("where0_3").som, "form[0].table[0].row[2].where0[0]");
assert_eq!(by("agree").items, vec!["1".to_string(), "0".to_string()]);
}
/// The AcroForm's terminal fields as the engine would hand them over.
fn field_data(doc: &Document) -> Vec<FieldDatum> {
let root = doc.get(doc.root().unwrap());
let acro = doc.resolve(root.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 out = Vec::new();
for f in fields {
let r = f.as_ref().unwrap();
let d = doc.get(r);
let d = d.as_dict().unwrap();
let name = d.get(b"T").and_then(|t| t.as_string()).map(|s| s.to_text()).unwrap_or_default();
let v = d.get(b"V").map(|v| doc.resolve(v));
let data = match d.name(b"FT") {
Some(b"Tx") => FieldData::Text(v.and_then(|v| v.as_string().map(|s| s.to_text())).unwrap_or_default()),
Some(b"Btn") if d.int(b"Ff").unwrap_or(0) & (1 << 15) != 0 => {
FieldData::Radio(v.and_then(|v| v.as_name().map(|n| String::from_utf8_lossy(n).into_owned())).filter(|n| n != "Off"))
}
Some(b"Btn") if d.int(b"Ff").unwrap_or(0) & (1 << 16) != 0 => FieldData::None,
Some(b"Btn") => FieldData::Check(v.and_then(|v| v.as_name().map(|n| n != b"Off")).unwrap_or(false)),
_ => FieldData::None,
};
out.push(FieldDatum { obj: r, name, data });
}
out
}
#[test]
fn the_datasets_packet_is_written_from_the_fields_and_read_back() {
let mut doc = Document::open(Arc::new(shell(&template_with_data(1, DATA)))).unwrap();
render_into(&mut doc).unwrap();
// The laid-out fields hold the data's values; writing them back reproduces it.
let fields = field_data(&doc);
assert!(fields.iter().any(|f| f.name == "familyName" && f.data == FieldData::Text("Singh".into())), "{fields:?}");
assert!(fields.iter().any(|f| f.name == "answer" && f.data == FieldData::Radio(Some("N".into()))), "{fields:?}");
// The data already holds what the fields hold: nothing to write.
assert_eq!(write_datasets(&mut doc, &fields).unwrap(), DatasetsWrite::default());
let doc = Document::open(Arc::new(write_incremental(&doc, &SaveOptions::default()).unwrap())).unwrap();
let p = read_packets(&doc).unwrap().unwrap();
let d = parse_datasets(&p.xdp).unwrap();
assert_eq!(d.text_at(&som_to_path("form[0].head[0].familyName[0]")), Some("Singh"));
assert_eq!(d.text_at(&som_to_path("form[0].head[0].agree[0]")), Some("1"));
assert_eq!(d.text_at(&som_to_path("form[0].head[0].answer[0]")), Some("N"));
assert_eq!(d.text_at(&som_to_path("form[0].table[0].row[2].where0[0]")), Some("Ottawa"));
assert_eq!(p.xdp.matches("<xfa:datasets").count(), 1, "the packet is replaced, not duplicated");
// Change a value, write again: the data follows, and reading gives the field its value.
let mut doc = doc;
let mut fields = field_data(&doc);
for f in &mut fields {
if f.name == "familyName" {
f.data = FieldData::Text("Kaur".into());
}
if f.name == "agree" {
f.data = FieldData::Check(false);
}
}
let w = write_datasets(&mut doc, &fields).unwrap();
assert!(w.written && w.warnings.is_empty(), "{w:?}");
let values = read_values(&doc, &fields);
assert!(values.contains(&("familyName".to_string(), FieldData::Text("Kaur".into()))), "{values:?}");
assert!(values.contains(&("agree".to_string(), FieldData::Check(false))), "{values:?}");
// A form without a datasets packet gets one, before the postamble.
let mut doc = Document::open(Arc::new(shell(&template(1)))).unwrap();
render_into(&mut doc).unwrap();
let fields = field_data(&doc);
assert!(write_datasets(&mut doc, &fields).unwrap().written);
let p = read_packets(&doc).unwrap().unwrap();
assert!(parse_datasets(&p.xdp).is_some());
// No XFA at all: nothing to write.
let mut plain = Document::new_empty();
assert!(!write_datasets(&mut plain, &[]).unwrap().written);
}
/// A radio item whose text contains a space keeps that text in the datasets. The appearance
/// state is a PDF name (`New_York`); writing it back used to clear the selection on the next layout.
#[test]
fn spaced_radio_values_stay_in_the_datasets() {
for (value, state) in [("New York", "New_York"), ("Y", "Y")] {
let xdp = format!(
r#"<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="36pt" y="36pt" w="540pt" h="720pt"/><medium short="612pt" long="792pt"/></pageArea></pageSet>
<exclGroup name="city" layout="lr-tb">
<field name="first" w="108pt" h="18pt"><ui><checkButton/></ui><items><text>{value}</text></items></field>
<field name="second" w="108pt" h="18pt"><ui><checkButton/></ui><items><text>Boston</text></items></field>
</exclGroup>
<field name="note" w="108pt" h="18pt"><ui><textEdit/></ui></field>
<field name="agree" w="108pt" h="18pt"><ui><checkButton/></ui><items><text>{value}</text><text>No</text></items></field>
</subform>
</template>
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"><xfa:data><form><city>{value}</city><note>before</note><agree>{value}</agree></form></xfa:data></xfa:datasets>
</xdp:xdp>"#
);
let mut doc = Document::open(Arc::new(shell(&xdp))).unwrap();
let report = render_into(&mut doc).unwrap();
assert!(report.warnings.is_empty(), "{value:?} {:?}", report.warnings);
let fields = field_data(&doc);
assert!(fields.iter().any(|f| f.name == "city" && f.data == FieldData::Radio(Some(state.into()))), "{value:?} {fields:?}");
let unchanged = write_datasets(&mut doc, &fields).unwrap();
assert!(!unchanged.written && unchanged.warnings.is_empty(), "{value:?} {unchanged:?}");
let mut fields = fields;
for f in &mut fields {
if f.name == "note" {
f.data = FieldData::Text("after".into());
}
}
let write = write_datasets(&mut doc, &fields).unwrap();
assert!(write.written && write.warnings.is_empty(), "{value:?} {write:?}");
let packets = read_packets(&doc).unwrap().unwrap();
let data = parse_datasets(&packets.xdp).unwrap();
assert_eq!(data.text_at(&som_to_path("form[0].city[0]")), Some(value));
assert_eq!(data.text_at(&som_to_path("form[0].agree[0]")), Some(value));
assert_eq!(data.text_at(&som_to_path("form[0].note[0]")), Some("after"));
let selected: Vec<(String, Option<String>)> = layout_xml(&packets.xdp)
.unwrap()
.pages
.iter()
.flat_map(|p| &p.items)
.filter_map(|item| match item {
Item::Widget(w) if w.name == "first" || w.name == "second" => Some((w.name.clone(), w.value.clone())),
_ => None,
})
.collect();
assert_eq!(selected, vec![("first".into(), Some(value.into())), ("second".into(), None)], "{value:?}");
}
}
#[test]
fn static_forms_read_their_values_from_the_datasets() {
let doc = Document::open(Arc::new(static_shell("<form1><page1><name>Ada</name><agree>1</agree></page1></form1>"))).unwrap();
assert!(!is_dynamic(&doc));
let fields = vec![
FieldDatum { obj: pdfcraft_cos::ObjRef::new(8, 0), name: "form1[0].page1[0].name[0]".into(), data: FieldData::Text(String::new()) },
FieldDatum { obj: pdfcraft_cos::ObjRef::new(9, 0), name: "form1[0].page1[0].agree[0]".into(), data: FieldData::Check(false) },
];
let values = read_values(&doc, &fields);
assert_eq!(
values,
vec![
("form1[0].page1[0].name[0]".to_string(), FieldData::Text("Ada".into())),
("form1[0].page1[0].agree[0]".to_string(), FieldData::Check(true))
]
);
assert_eq!(build_data(&doc, &fields), "<xfa:data><form1><page1><name></name><agree></agree></page1></form1></xfa:data>");
}
#[test]
fn nested_width_less_subforms_lay_out_in_polynomial_time() {
// Regression: a container without a width measured its content once for its width and
// again for its height, at every level: 2^depth measurements. Two children per level make
// it worse still. This must finish at once, and lay the innermost fields out.
for depth in [40, 60] {
let open = "<subform layout=\"lr-tb\"><field name=\"a\" w=\"20pt\" h=\"10pt\"/>".repeat(depth);
let xml = format!(
"<template><subform layout=\"tb\" name=\"form\">{open}<field name=\"inner\" w=\"30pt\" h=\"10pt\"/>{}</subform></template>",
"</subform>".repeat(depth)
);
let start = std::time::Instant::now();
let form = layout_xml(&xml).expect("lays out");
assert!(start.elapsed() < std::time::Duration::from_secs(20), "took {:?}", start.elapsed());
let names: Vec<String> = form.pages.iter().flat_map(widgets).map(|w| w.name.clone()).collect();
assert!(names.iter().any(|n| n == "inner") || depth > 60, "{depth}: {names:?}");
assert!(names.len() > 1);
}
}
/// The static fixture's two fields, holding `name` and `agree`.
fn static_fields(name: &str, agree: bool) -> Vec<FieldDatum> {
vec![
FieldDatum { obj: pdfcraft_cos::ObjRef::new(8, 0), name: "form1[0].page1[0].name[0]".into(), data: FieldData::Text(name.into()) },
FieldDatum { obj: pdfcraft_cos::ObjRef::new(9, 0), name: "form1[0].page1[0].agree[0]".into(), data: FieldData::Check(agree) },
]
}
/// The decoded XFA stream (object 5 in the static fixture, or whatever `/XFA` now points to).
fn xfa_bytes(doc: &Document) -> Vec<u8> {
let root = doc.get(doc.root().unwrap());
let acro = doc.resolve(root.as_dict().unwrap().get(b"AcroForm").unwrap());
let xfa = doc.resolve(acro.as_dict().unwrap().get(b"XFA").unwrap());
let Object::Stream(s) = &*xfa else { panic!("a stream") };
s.decoded_within(1 << 20).unwrap()
}
/// Writing field values into the datasets keeps every data node no field binds to as written,
/// changes the bound values in place and adds a missing one beside them. Writing the same values
/// again changes nothing, and a field bound to structured content is reported, not flattened.
#[test]
fn writing_values_keeps_the_data_no_field_binds_to() {
// Regression: the data element was rebuilt from the fields alone, dropping everything else.
let data = concat!(
"<form1 a=\"1\"><page1><name>Ada</name><notes xmlns:my=\"urn:my\"><my:extra kind='x>y'>keep me</my:extra></notes>",
"<rich><p>bold <b>text</b></p></rich></page1><deep><a><b><c>deep value</c></b></a></deep></form1>",
"<other xmlns=\"urn:other\"><x>unbound</x></other><!-- a comment --><empty/>"
);
let mut doc = Document::open(Arc::new(static_shell(data))).unwrap();
let w = write_datasets(&mut doc, &static_fields("Grace & <Co>\r\n", true)).unwrap();
assert!(w.written && w.warnings.is_empty(), "{w:?}");
let saved = Document::open(Arc::new(write_incremental(&doc, &SaveOptions::default()).unwrap())).unwrap();
let xdp = String::from_utf8(xfa_bytes(&saved)).unwrap();
// Everything no field binds to is still there, as written.
for kept in [
"<form1 a=\"1\">",
"<notes xmlns:my=\"urn:my\"><my:extra kind='x>y'>keep me</my:extra></notes>",
"<rich><p>bold <b>text</b></p></rich>",
"<deep><a><b><c>deep value</c></b></a></deep>",
"<other xmlns=\"urn:other\"><x>unbound</x></other><!-- a comment --><empty/>",
"<template xmlns=",
] {
assert!(xdp.contains(kept), "lost {kept:?}: {xdp}");
}
// The bound value changed in place; the missing check box node was added beside it.
assert!(xdp.contains("<name>Grace &amp; &lt;Co&gt;&#xD;\n</name>"), "{xdp}");
let d = parse_datasets(&xdp).unwrap();
assert_eq!(d.text_at(&som_to_path("form1[0].page1[0].name[0]")), Some("Grace & <Co>\r\n"));
assert_eq!(d.text_at(&som_to_path("form1[0].page1[0].agree[0]")), Some("1"));
assert_eq!(xdp.matches("<page1>").count(), 1, "added into the existing node, not a second one");
// Writing the same values again changes nothing.
let mut again = saved;
assert_eq!(write_datasets(&mut again, &static_fields("Grace & <Co>\r\n", true)).unwrap(), DatasetsWrite::default());
// A field bound to a node holding structured content is reported, not flattened.
let mut doc = Document::open(Arc::new(static_shell("<form1><page1><name><p>rich</p></name></page1></form1>"))).unwrap();
let w = write_datasets(&mut doc, &static_fields("plain", false)).unwrap();
assert!(w.warnings.iter().any(|m| m.contains("structured content") && m.contains("name[0]")), "{w:?}");
assert!(String::from_utf8(xfa_bytes(&doc)).unwrap().contains("<name><p>rich</p></name>"));
}
/// A UTF-16 packet in either byte order, with a byte order mark, has its values read exactly and
/// is written back as UTF-16 with its mark. A packet in neither UTF-8 nor UTF-16 is left alone,
/// and that is reported.
#[test]
fn structured_data_whitespace_changes_are_reported_without_flattening() {
let data = "<form1><page1><name>\n<p>Short</p>\n</name><agree/></page1></form1>";
for value in ["Short", "Short\n", "\nShort", " Short ", "\tShort\t"] {
let mut doc = Document::open(Arc::new(static_shell(data))).unwrap();
let before = xfa_bytes(&doc);
let result = write_datasets(&mut doc, &static_fields(value, false)).unwrap();
assert!(!result.written, "{value:?}: {result:?}");
assert_eq!(xfa_bytes(&doc), before, "structured XML must stay intact");
if value == "Short" {
assert!(result.warnings.is_empty(), "existing XML indentation is not a field edit: {result:?}");
} else {
assert!(result.warnings.iter().any(|w| w.contains("structured content")), "{value:?}: {result:?}");
}
}
}
#[test]
fn utf16_packets_are_read_and_written_back_as_utf16() {
let mut doc = Document::open(Arc::new(static_shell("<form1><page1><name>Zoë 日本</name><other>ünbound</other></page1></form1>"))).unwrap();
let text = String::from_utf8(xfa_bytes(&doc)).unwrap();
for (encoding, bom) in [(Encoding::Utf16Le { bom: true }, &[0xFF, 0xFE][..]), (Encoding::Utf16Be { bom: true }, &[0xFE, 0xFF][..])] {
let mut doc16 = doc.clone();
doc16.set(
pdfcraft_cos::ObjRef::new(5, 0),
Object::Stream(pdfcraft_cos::Stream::flate(pdfcraft_cos::Dict::new(), &encode_packet(&text, encoding))),
);
// Read exactly, not as mojibake.
let values = read_values(&doc16, &static_fields("", false));
assert_eq!(values.first(), Some(&("form1[0].page1[0].name[0]".to_string(), FieldData::Text("Zoë 日本".into()))));
let w = write_datasets(&mut doc16, &static_fields("Łódź", false)).unwrap();
assert!(w.written && w.warnings.is_empty(), "{w:?}");
let bytes = xfa_bytes(&doc16);
assert!(bytes.starts_with(bom), "still UTF-16 with its byte order mark");
let (back, enc) = decode_packet(&bytes).unwrap();
assert_eq!(enc, encoding);
assert!(back.contains("<name>Łódź</name>") && back.contains("<other>ünbound</other>"), "{back}");
}
// A packet in neither UTF-8 nor UTF-16 (Latin-1 here) is left alone, and that is reported.
let latin1: Vec<u8> = text.replace("Zoë 日本", "Zo\u{eb}").chars().map(|c| c as u32 as u8).collect();
doc.set(pdfcraft_cos::ObjRef::new(5, 0), Object::Stream(pdfcraft_cos::Stream::flate(pdfcraft_cos::Dict::new(), &latin1)));
let w = write_datasets(&mut doc, &static_fields("x", true)).unwrap();
assert!(!w.written && !w.warnings.is_empty(), "{w:?}");
assert_eq!(xfa_bytes(&doc), latin1);
}
/// Hundreds of fields with absurd SOM indices finish within seconds, both writing the datasets and
/// building fresh data, create at most the node budget and report what they could not write. A
/// moderate index still works, creating the empty instances before it.
#[test]
fn huge_som_indices_are_capped_not_built() {
// Regression: each index created its missing siblings one count at a time (quadratic), with
// no limit on the total. Many fields with absurd indices must finish at once, reporting
// what they could not write.
let mut doc = Document::open(Arc::new(static_shell("<form1/>"))).unwrap();
let start = std::time::Instant::now();
let fields: Vec<FieldDatum> = (0..300)
.map(|i| FieldDatum {
obj: pdfcraft_cos::ObjRef::new(1000 + i, 0),
name: format!("form1[0].a[{}].b[99999].c[99999].d[{i}]", 9_000 + i),
data: FieldData::Text("v".into()),
})
.collect();
let w = write_datasets(&mut doc, &fields).unwrap();
assert!(start.elapsed() < std::time::Duration::from_secs(10), "took {:?}", start.elapsed());
assert!(w.warnings.iter().any(|m| m.contains("repeats too often")), "{w:?}");
let xdp = String::from_utf8(xfa_bytes(&doc)).unwrap();
assert!(xdp.matches("<a>").count() <= 20_000, "at most the node budget is created");
// Building fresh data is capped the same way.
let start = std::time::Instant::now();
let data = build_data(&doc, &fields);
assert!(start.elapsed() < std::time::Duration::from_secs(10));
assert!(data.len() < 2_000_000);
// And a moderate index still works.
let mut doc = Document::open(Arc::new(static_shell("<form1><row><v>1</v></row></form1>"))).unwrap();
let row = |i: usize| FieldDatum {
obj: pdfcraft_cos::ObjRef::new(500, 0),
name: format!("form1[0].row[{i}].v[0]"),
data: FieldData::Text(i.to_string()),
};
let w = write_datasets(&mut doc, &[row(0), row(3)]).unwrap();
assert!(w.written && w.warnings.is_empty(), "{w:?}");
let d = parse_datasets(&String::from_utf8(xfa_bytes(&doc)).unwrap()).unwrap();
assert_eq!(d.count(&som_to_path("form1[0]"), "row"), 4);
assert_eq!(d.text_at(&som_to_path("form1[0].row[3].v[0]")), Some("3"));
assert!(d.get(&som_to_path("form1[0].row[2]")).is_some(), "the instances in between exist, empty");
}
/// The live form tree carries each object's SOM path, value, presence and access, one instance of
/// a repeating row without data, and the template's event, calculate and validate scripts (FormCalc
/// when no content type is given). Data adds rows and values, and an override changes presence.
#[test]
fn the_form_tree_carries_values_presence_instances_and_the_events() {
let xml = scripted_template();
let (tpl, _) = parse(&xml).unwrap();
let crate::script::LiveForm { root, events, truncated } = form_tree(&tpl, None, &Overrides::default());
assert!(!truncated);
assert_eq!((root.name.as_str(), root.som.as_str()), ("form", "form[0]"));
let page = &root.children[0];
assert_eq!(page.som, "form[0].page1[0]");
let by = |n: &str| page.children.iter().find(|c| c.name == n).unwrap_or_else(|| panic!("no {n}"));
assert_eq!((by("price").value.as_str(), by("price").numeric, by("total").access.as_str()), ("5", true, "readOnly"));
assert_eq!(by("details").presence, "hidden");
let table = by("table");
assert_eq!(table.children.len(), 1, "one row without data");
assert!(table.children[0].repeatable && table.children[0].occur_max.is_none());
assert_eq!(table.children[0].children[1].som, "form[0].page1[0].table[0].row[0].amount[0]");
let ev = |som: &str, act: &str| events.iter().find(|e| e.som == som && e.activity == act).unwrap_or_else(|| panic!("no {act} on {som}"));
assert!(ev("form[0].page1[0]", "initialize").script.contains("qty.rawValue = 2"));
assert!(ev("form[0].page1[0].total[0]", "calculate").script.contains("qty.rawValue * price.rawValue"));
assert_eq!(ev("form[0].page1[0].qty[0]", "validate").message.as_deref(), Some("Quantity must be 100 or less"));
assert!(!ev("form[0].page1[0].addRow[0]", "click").formcalc);
assert!(ev("form[0].page1[0].legacy[0]", "click").formcalc, "no contentType means FormCalc");
// Data adds rows and values; overrides change presence.
let data = parse_datasets("<xfa:datasets xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><xfa:data><form><page1><qty>7</qty><table><row><amount>1</amount></row><row><amount>2</amount></row><row><amount>3</amount></row></table></page1></form></xfa:data></xfa:datasets>").unwrap();
let mut ov = Overrides::default();
ov.presence.insert("form[0].page1[0].details[0]".into(), "visible".into());
let root = form_tree(&tpl, Some(&data), &ov).root;
let page = &root.children[0];
assert_eq!(page.children.iter().find(|c| c.name == "qty").unwrap().value, "7");
assert_eq!(page.children.iter().find(|c| c.name == "table").unwrap().children.len(), 3);
assert_eq!(page.children.iter().find(|c| c.name == "details").unwrap().presence, "visible");
assert_eq!(page.children.iter().find(|c| c.name == "details").unwrap().kind, Some(NodeKind::Subform));
}
/// Presence and access overrides are kept on the AcroForm and applied to the template: `note` has
/// no widget while `details` is hidden and gets one once an override shows it and the form is laid
/// out again. Saving and reopening keeps the overrides and one set of fields; storing none removes the key.
#[test]
fn overrides_live_in_the_acroform_and_hide_objects_in_the_layout() {
let mut doc = Document::open(Arc::new(shell(&scripted_template()))).unwrap();
render_into(&mut doc).unwrap();
assert!(overrides(&doc).is_empty());
let names = |doc: &Document| fields_by_som(doc).into_values().collect::<Vec<_>>();
assert!(!names(&doc).iter().any(|n| n == "note"), "details is hidden: {:?}", names(&doc));
let mut ov = Overrides::default();
ov.presence.insert("form[0].page1[0].details[0]".into(), "visible".into());
ov.access.insert("form[0].page1[0].qty[0]".into(), "readOnly".into());
set_overrides(&mut doc, &ov).unwrap();
assert_eq!(overrides(&doc), ov);
let (tpl, _) = parse(&scripted_template()).unwrap();
let laid = apply_overrides(&tpl, &ov);
let Node::Subform(page) = &laid.root.children[0] else { panic!() };
let Node::Subform(details) = page.children.iter().find(|c| c.common().name.as_deref() == Some("details")).unwrap() else { panic!() };
assert_eq!(details.common.presence, Presence::Visible);
let Node::Field(qty) = page.children.iter().find(|c| c.common().name.as_deref() == Some("qty")).unwrap() else { panic!() };
assert_eq!(qty.access, Access::ReadOnly);
// Laying out again shows the note field and keeps the others.
let report = rerender(&mut doc, &tpl).unwrap();
let after = names(&doc);
assert!(after.iter().any(|n| n == "note"), "{after:?}");
assert!(after.iter().any(|n| n == "qty"));
assert_eq!(report.fields, after.len());
// Reopening the written bytes finds one set of fields, not two.
let doc = Document::open(Arc::new(write_incremental(&doc, &SaveOptions::default()).unwrap())).unwrap();
assert_eq!(names(&doc).len(), after.len());
assert_eq!(overrides(&doc), ov);
// Clearing removes the key.
let mut doc = doc;
set_overrides(&mut doc, &Overrides::default()).unwrap();
assert!(overrides(&doc).is_empty());
}
/// Showing a hidden subform through an override leaves its unnamed hidden draw and subform hidden,
/// in the layout and in the live form scripts see: they share the subform's SOM path, so its
/// override is not theirs.
#[test]
fn showing_a_subform_leaves_its_unnamed_hidden_objects_hidden() {
let (tpl, _) = parse(&unnamed_hidden_template()).unwrap();
let mut ov = Overrides::default();
ov.presence.insert("form[0].page1[0].details[0]".into(), "visible".into());
let form = layout(&apply_overrides(&tpl, &ov), None).unwrap();
let shown = texts(&form.pages[0]);
assert!(shown.iter().any(|t| t == "Current caption"), "{shown:?}");
assert!(!shown.iter().any(|t| t == "Old caption" || t == "Old section"), "{shown:?}");
assert_eq!(form.fields, 1);
// Scripts see the same: the hidden draw stays hidden in the live form.
let root = form_tree(&tpl, None, &ov).root;
let details = &root.children[0].children[0];
assert_eq!(details.presence, "visible");
let presence = |text: &str| details.children.iter().find(|c| c.value == text).map(|c| c.presence.clone());
assert_eq!(presence("Current caption").as_deref(), Some("visible"));
assert_eq!(presence("Old caption").as_deref(), Some("hidden"));
assert_eq!(details.children.iter().find(|c| c.kind == Some(NodeKind::Subform)).map(|c| c.presence.as_str()), Some("hidden"));
}
/// Adding and removing data instances edits the datasets packet, creating it when missing: asking
/// for no more rows than exist, or removing one that is not there, changes nothing, and removing a
/// row moves the later ones up. The layout follows the data, and an absurd count is capped, not built.
#[test]
fn data_instances_are_added_and_removed_in_the_packet() {
let mut doc = Document::open(Arc::new(shell(&scripted_template()))).unwrap();
render_into(&mut doc).unwrap();
let parent = som_to_path("form[0].page1[0].table[0]");
// No datasets packet yet: one is created with the rows.
assert!(add_data_instances(&mut doc, &parent, "row", 3).unwrap().written);
let data = crate::script::data_of(&doc).unwrap();
assert_eq!(data.count(&parent, "row"), 3);
// Asking for fewer changes nothing; more adds.
assert!(!add_data_instances(&mut doc, &parent, "row", 2).unwrap().written);
assert!(add_data_instances(&mut doc, &parent, "row", 4).unwrap().written);
let mut p = parent.clone();
p.push(("row".into(), 1));
p.push(("amount".into(), 0));
write_data_value(&mut doc, &p, "42").unwrap();
let data = crate::script::data_of(&doc).unwrap();
assert_eq!((data.count(&parent, "row"), data.text_at(&p)), (4, Some("42")));
// Remove the second row: the third's value moves up.
let mut second = parent.clone();
second.push(("row".into(), 1));
assert!(remove_data_instance(&mut doc, &second).unwrap().written);
let data = crate::script::data_of(&doc).unwrap();
assert_eq!(data.count(&parent, "row"), 3);
assert_eq!(data.text_at(&p), None, "the row holding 42 is gone");
// Removing what isn't there is nothing.
let mut tenth = parent.clone();
tenth.push(("row".into(), 9));
assert!(!remove_data_instance(&mut doc, &tenth).unwrap().written);
// The layout follows the data: three rows of fields.
let (tpl, _) = parse(&scripted_template()).unwrap();
rerender(&mut doc, &tpl).unwrap();
let names: Vec<String> = fields_by_som(&doc).into_values().collect();
assert_eq!(names.iter().filter(|n| n.starts_with("amount")).count(), 3, "{names:?}");
// Hostile: absurd indices are capped, not built.
assert!(add_data_instances(&mut doc, &parent, "row", 1_000_000).is_ok());
}
#[test]
fn formcalc_button_idioms_keep_their_native_actions() {
let xml = scripted_template()
.replace("<script>$host.messageBox(\"FormCalc\")</script>", "<script>$host.resetData()</script>")
.replace("xfa.host.messageBox(\"Hello \" + qty.rawValue);", "if (qty.rawValue > 1) { xfa.host.resetData(); }");
let form = layout_xml(&xml).unwrap();
let w: Vec<&Widget> = form.pages.iter().flat_map(widgets).collect();
let by = |n: &str| w.iter().find(|w| w.name == n).unwrap_or_else(|| panic!("no {n}"));
assert_eq!(by("legacy").action, Some(Action::Reset), "a one-statement FormCalc idiom is a native action");
assert!(matches!(by("hello").action, Some(Action::Script(_))), "anything else runs as a script: {:?}", by("hello").action);
assert!(matches!(by("addRow").action, Some(Action::Script(_))));
}
/// Five levels of subforms that each repeat 50 times, with a scripted field at the bottom:
/// 50⁵ instances if nothing stopped the walk.
fn nested_repeats_template() -> String {
let mut body = r#"<field name="leaf" w="1in" h="0.3in"><ui><textEdit/></ui><calculate><script contentType="application/x-javascript">1</script></calculate></field>"#.to_string();
for level in (0..5).rev() {
body = format!(r#"<subform name="s{level}" layout="tb"><occur min="1" max="-1" initial="50"/>{body}</subform>"#);
}
format!(
r#"<?xml version="1.0"?><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="p"><contentArea x="0" y="0" w="8in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>{body}</subform></template></xdp:xdp>"#
)
}
#[test]
fn the_live_form_of_nested_repeating_subforms_stops_at_its_node_budget() {
fn count(n: &crate::script::FormNode) -> usize {
1 + n.children.iter().map(count).sum::<usize>()
}
let (tpl, _) = parse(&nested_repeats_template()).unwrap();
assert!(crate::script::has_scripts(&tpl));
let started = std::time::Instant::now();
let live = form_tree(&tpl, None, &Overrides::default());
assert!(live.truncated, "the walk was cut short");
assert!(count(&live.root) <= crate::script::MAX_FORM_NODES + 1, "{} nodes", count(&live.root));
assert!(live.events.len() <= 20_000);
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
// A template without scripts has nothing to run.
let plain_xml = nested_repeats_template().replace(r#"<calculate><script contentType="application/x-javascript">1</script></calculate>"#, "");
let (plain, _) = parse(&plain_xml).unwrap();
assert!(!crate::script::has_scripts(&plain));
}
#[test]
fn data_ops_of_one_event_are_one_datasets_rewrite() {
use crate::data::{DataOp, write_data_ops};
let mut doc = Document::open(Arc::new(shell(&scripted_template()))).unwrap();
render_into(&mut doc).unwrap();
let before = doc.object_numbers().len();
let ops = vec![
DataOp::Value { path: som_to_path("form[0].page1[0].qty[0]"), text: "1".into() },
DataOp::Value { path: som_to_path("form[0].page1[0].qty[0]"), text: "7".into() },
DataOp::Instances { parent: som_to_path("form[0].page1[0].table[0]"), name: "row".into(), count: 3 },
DataOp::Value { path: som_to_path("form[0].page1[0].table[0].row[2].amount[0]"), text: "5".into() },
DataOp::Remove(som_to_path("form[0].page1[0].table[0].row[0]")),
];
let r = write_data_ops(&mut doc, &ops, None).unwrap();
assert!(r.written && r.stream.is_some(), "{r:?}");
assert_eq!(doc.object_numbers().len(), before + 1, "one new datasets stream");
let data = crate::data_of(&doc).unwrap();
assert_eq!(data.text_at(&som_to_path("form[0].page1[0].qty[0]")), Some("7"), "the last value wins");
assert_eq!(data.count(&som_to_path("form[0].page1[0].table[0]"), "row"), 2);
assert_eq!(data.text_at(&som_to_path("form[0].page1[0].table[0].row[1].amount[0]")), Some("5"));
// The in-memory model agrees with what was written.
let mut model = DataNode::default();
model.children.push(DataNode { name: "form".into(), ..Default::default() });
for op in &ops {
model.apply(op);
}
assert_eq!(model.text_at(&som_to_path("form[0].page1[0].qty[0]")), Some("7"));
assert_eq!(model.count(&som_to_path("form[0].page1[0].table[0]"), "row"), 2);
assert_eq!(model.text_at(&som_to_path("form[0].page1[0].table[0].row[1].amount[0]")), Some("5"));
// A second write for the same event replaces that stream instead of adding another; an
// empty value clears the node.
let again = write_data_ops(&mut doc, &[DataOp::Value { path: som_to_path("form[0].page1[0].qty[0]"), text: String::new() }], r.stream).unwrap();
assert_eq!(again.stream, r.stream);
assert_eq!(doc.object_numbers().len(), before + 1);
assert_eq!(crate::data_of(&doc).unwrap().text_at(&som_to_path("form[0].page1[0].qty[0]")), Some(""));
}
#[test]
fn script_buttons_carry_no_javascript_action_for_other_viewers() {
let mut doc = Document::open(Arc::new(shell(&scripted_template()))).unwrap();
render_into(&mut doc).unwrap();
let fields = top_fields(&doc);
let add_row = fields.iter().find(|(name, _)| name == "addRow").map(|(_, d)| d.clone()).expect("addRow");
assert!(add_row.contains(crate::CLICK_KEY), "found by its SOM path");
assert!(add_row.get(b"A").is_none() && add_row.get(b"AA").is_none(), "no XFA source as a PDF JavaScript action");
}
/// The generated fields' dictionaries by name (top-level fields only).
fn top_fields(doc: &Document) -> Vec<(String, pdfcraft_cos::Dict)> {
let root = doc.root().unwrap();
let catalog = doc.get(root);
let acro = doc.resolve(catalog.as_dict().unwrap().get(b"AcroForm").unwrap());
let fields = doc.resolve(acro.as_dict().unwrap().get(b"Fields").unwrap());
fields
.as_array()
.unwrap()
.iter()
.filter_map(|f| {
let d = doc.resolve(f).as_dict().cloned()?;
let t = d.get(b"T").and_then(|t| t.as_string()).map(|t| t.to_text())?;
Some((t, d))
})
.collect()
}
/// Choice lists, a password, a signature and pictures in the template become their kinds of
/// widget, and their AcroForm fields and image XObjects once written.
#[test]
fn choice_lists_signatures_passwords_and_pictures_become_fields_and_images() {
assert_choice_widget_layout();
assert_choice_fields_and_picture_streams();
}
fn assert_choice_widget_layout() {
let form = layout_xml(&fields_template("")).unwrap();
let p1 = &form.pages[0];
let w = widgets(p1);
let country = w.iter().find(|w| w.name == "country").unwrap();
assert_eq!(
country.kind,
WidgetKind::Choice {
options: vec![("CA".into(), "Canada".into()), ("FR".into(), "France".into()), ("JP".into(), "Japan".into())],
list_box: false,
multi: false,
editable: false,
}
);
assert_eq!(country.value.as_deref(), Some("FR"), "the template default, as a saved value");
let langs = w.iter().find(|w| w.name == "langs").unwrap();
assert!(
matches!(&langs.kind, WidgetKind::Choice { options, list_box: true, multi: true, editable: false } if options.len() == 3 && options[0] == ("English".into(), "English".into()))
);
let other = w.iter().find(|w| w.name == "other").unwrap();
assert!(matches!(&other.kind, WidgetKind::Choice { list_box: false, multi: false, editable: true, .. }));
assert_eq!(w.iter().find(|w| w.name == "pin").unwrap().kind, WidgetKind::Password);
assert_eq!(w.iter().find(|w| w.name == "sign").unwrap().kind, WidgetKind::Signature);
assert_eq!(w.iter().find(|w| w.name == "photo").unwrap().kind, WidgetKind::Image, "an image field is a button that picks a picture");
assert!(w.iter().all(|w| w.name != "code"), "barcode fields make no widget");
// The PNG in the image field and the GIF in the draw are pictures, fitted to their boxes.
let images: Vec<(&Rect, usize)> =
p1.items.iter().filter_map(|i| if let Item::Image { rect, data, .. } = i { Some((rect, data.len())) } else { None }).collect();
assert_eq!(images.len(), 2, "{images:?}");
assert!((images[0].0.w - 72.0).abs() < 0.01 && (images[0].0.h - 72.0).abs() < 0.01, "a square picture fills a 1in square: {:?}", images[0].0);
assert_eq!(images[1].1, TINY_GIF.len());
let t = texts(p1);
assert!(t.iter().any(|s| s == "12345"), "the barcode's value as text: {t:?}");
assert!(form.warnings.iter().any(|w| w.contains("barcode")), "{:?}", form.warnings);
assert!(!form.warnings.iter().any(|w| w.contains("can't be chosen")), "pictures can be chosen now: {:?}", form.warnings);
}
fn assert_choice_fields_and_picture_streams() {
// Written into the PDF: /Ch fields with their options and flags, a /Sig field, a password
// field, and Flate images (the PNG with a soft mask).
let mut doc = Document::open(Arc::new(shell(&fields_template("")))).unwrap();
let report = render_into(&mut doc).unwrap();
assert_eq!(report.fields, 7, "country, langs, other, pin, sign, photo, summary");
let bytes = write_incremental(&doc, &SaveOptions::default()).unwrap();
let doc = Document::open(Arc::new(bytes)).unwrap();
let fields = pdfcraft_forms_free_fields(&doc);
let field = |n: &str| fields.iter().find(|(name, _)| name == n).map(|(_, d)| d.clone()).unwrap_or_else(|| panic!("no field {n}"));
let country = field("country");
assert_eq!(country.name(b"FT"), Some(b"Ch".as_slice()));
assert_eq!(country.int(b"Ff"), Some(1 << 17), "a combo box");
let opt = doc.resolve(country.get(b"Opt").unwrap()).as_array().unwrap().clone();
assert_eq!(opt.len(), 3);
let pair = doc.resolve(&opt[1]).as_array().unwrap().clone();
assert_eq!(pair[0].as_string().unwrap().to_text(), "FR");
assert_eq!(pair[1].as_string().unwrap().to_text(), "France");
assert_eq!(country.get(b"V").and_then(|v| v.as_string()).map(|s| s.to_text()).as_deref(), Some("FR"));
assert_eq!(country.get(b"DV").and_then(|v| v.as_string()).map(|s| s.to_text()).as_deref(), Some("FR"));
let langs = field("langs");
assert_eq!(langs.int(b"Ff"), Some(1 << 21), "a multi-select list box");
let opt = doc.resolve(langs.get(b"Opt").unwrap()).as_array().unwrap().clone();
assert_eq!(opt[0].as_string().unwrap().to_text(), "English", "same shown text and value: a plain string");
assert_eq!(field("other").int(b"Ff"), Some((1 << 17) | (1 << 18)), "an editable combo box");
assert_eq!(field("pin").int(b"Ff"), Some(1 << 13), "a password field");
// The signature field is named by its SOM path, under a generated field for each step above it.
assert!(fields.iter().all(|(name, _)| name != "sign"));
let named = full_names(&doc);
let sign = named.iter().find(|(name, _)| name == "form[0].page1[0].sign[0]").map(|(_, d)| d).expect("named by its SOM path");
assert_eq!(sign.name(b"FT"), Some(b"Sig".as_slice()));
let streams: Vec<pdfcraft_cos::Stream> = doc
.object_numbers()
.into_iter()
.filter_map(|n| if let Object::Stream(st) = &*doc.get(pdfcraft_cos::ObjRef { num: n, generation: 0 }) { Some(st.clone()) } else { None })
.filter(|s| s.dict.name(b"Subtype") == Some(b"Image"))
.collect();
assert_eq!(streams.len(), 3, "the PNG, its soft mask, the GIF");
let png = streams.iter().find(|s| s.dict.contains(b"SMask")).expect("the PNG has a soft mask");
assert_eq!(png.dict.name(b"ColorSpace"), Some(b"DeviceRGB".as_slice()));
assert_eq!(png.dict.name(b"Filter"), Some(b"FlateDecode".as_slice()));
assert_eq!(png.decoded().unwrap().len(), 12, "2 × 2 RGB samples");
let gif = streams.iter().find(|s| s.dict.int(b"Width") == Some(1)).expect("the 1 × 1 GIF");
assert_eq!(gif.dict.name(b"ColorSpace"), Some(b"DeviceGray".as_slice()), "a white pixel is gray");
assert_eq!(gif.decoded().unwrap(), vec![255]);
}
/// The terminal field dictionaries by name (one level: this fixture has no hierarchy).
fn pdfcraft_forms_free_fields(doc: &Document) -> Vec<(String, pdfcraft_cos::Dict)> {
let root = doc.get(doc.root().unwrap());
let acro = doc.resolve(root.as_dict().unwrap().get(b"AcroForm").unwrap());
let fields = doc.resolve(acro.as_dict().unwrap().get(b"Fields").unwrap()).as_array().unwrap().clone();
fields
.iter()
.filter_map(|f| {
let d = doc.resolve(f).as_dict()?.clone();
let name = d.get(b"T").map(|t| doc.resolve(t)).and_then(|t| t.as_string().map(|s| s.to_text()))?;
Some((name, d))
})
.collect()
}
#[test]
fn choice_values_come_from_the_data_as_saved_values_and_several_for_lists() {
// Shown text in the data is taken too (an editable list the user typed into saves text).
let xml = fields_template("<form><page1><country>Japan</country><langs>English\nSpanish</langs><other>typed</other></page1></form>");
let form = layout_xml(&xml).unwrap();
let w = widgets(&form.pages[0]);
assert_eq!(w.iter().find(|w| w.name == "country").unwrap().value.as_deref(), Some("JP"));
assert_eq!(w.iter().find(|w| w.name == "langs").unwrap().value.as_deref(), Some("English\nSpanish"));
assert_eq!(w.iter().find(|w| w.name == "other").unwrap().value.as_deref(), Some("typed"));
let mut doc = Document::open(Arc::new(shell(&xml))).unwrap();
render_into(&mut doc).unwrap();
let bytes = write_incremental(&doc, &SaveOptions::default()).unwrap();
let doc = Document::open(Arc::new(bytes)).unwrap();
let fields = pdfcraft_forms_free_fields(&doc);
let langs = &fields.iter().find(|(n, _)| n == "langs").unwrap().1;
let v = doc.resolve(langs.get(b"V").unwrap()).as_array().unwrap().clone();
assert_eq!(v.iter().map(|s| s.as_string().unwrap().to_text()).collect::<Vec<_>>(), vec!["English", "Spanish"]);
let i = doc.resolve(langs.get(b"I").unwrap()).as_array().unwrap().clone();
assert_eq!(i.iter().map(|o| o.as_int().unwrap()).collect::<Vec<_>>(), vec![0, 2]);
}
#[test]
fn pictures_are_sized_from_their_headers_and_hostile_ones_are_refused_unallocated() {
use crate::image::{Kind, decode, kind, size};
assert_eq!(kind(&tiny_png()), Some(Kind::Png));
assert_eq!(size(&tiny_png()), Some((2, 2)));
assert_eq!(kind(TINY_GIF), Some(Kind::Gif));
assert_eq!(size(TINY_GIF), Some((1, 1)));
assert_eq!(kind(b"BM..."), None);
assert_eq!(size(b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR"), None, "a header cut short");
let decoded = decode(&tiny_png()).unwrap();
assert_eq!((decoded.width, decoded.height, decoded.color_space), (2, 2, "DeviceRGB"));
assert_eq!(decoded.samples, vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0]);
assert_eq!(decoded.alpha, Some(vec![255, 255, 255, 0]));
assert_eq!(decode(TINY_GIF).unwrap().samples, vec![255]);
// A PNG claiming 100,000 × 100,000 pixels is refused from its header, before any buffer.
let mut huge = tiny_png();
huge[16..20].copy_from_slice(&100_000u32.to_be_bytes());
huge[20..24].copy_from_slice(&100_000u32.to_be_bytes());
assert_eq!(size(&huge), None, "no size for layout: the box is used");
assert!(decode(&huge).unwrap_err().contains("million pixels"));
// Truncated and corrupt data are errors, not panics.
let cut = &tiny_png()[..30];
assert!(decode(cut).is_err());
let mut bad = tiny_png();
for b in bad.iter_mut().skip(40) {
*b ^= 0x55;
}
assert!(decode(&bad).is_err() || decode(&bad).is_ok());
let mut gif = TINY_GIF.to_vec();
gif.truncate(12);
assert!(decode(&gif).is_err());
// A form whose picture is broken still lays out, with a warning, and keeps the rest.
let xml = fields_template("")
.replace("image/gif", "image/gif\" transferEncoding=\"none")
.replace("<image contentType=\"image/png\">", "<image contentType=\"image/png\">AAAA");
let mut doc = Document::open(Arc::new(shell(&xml))).unwrap();
let report = render_into(&mut doc).unwrap();
assert_eq!(report.fields, 7);
assert!(report.warnings.iter().any(|w| w.contains("image")), "{:?}", report.warnings);
}
#[test]
fn choice_values_are_saved_values_first_deduplicated_and_defaults_are_saved_values_too() {
// Designer's "specify item values": shown 0..3, saved 1..4. The data's 1 means the item
// shown as 0, not the item shown as 1.
let tpl = fields_template("<form><page1><country>1</country></page1></form>")
.replace("<text>Canada</text><text>France</text><text>Japan</text>", "<text>0</text><text>1</text><text>2</text><text>3</text>")
.replace("<text>CA</text><text>FR</text><text>JP</text>", "<text>1</text><text>2</text><text>3</text><text>4</text>")
.replace("<value><text>FR</text></value></field>", "<value><text>1</text></value></field>");
let form = layout_xml(&tpl).unwrap();
let w = widgets(&form.pages[0]);
assert_eq!(w.iter().find(|w| w.name == "country").unwrap().value.as_deref(), Some("1"));
let (t, _) = parse(&tpl).unwrap();
let tree = form_tree(&t, parse_datasets(&tpl).as_ref(), &Overrides::default());
let node = tree.root.children.iter().find(|n| n.name == "page1").unwrap().children.iter().find(|n| n.name == "country").unwrap();
assert_eq!(node.value, "1", "scripts read the saved value");
// Several values: each once, never more than there are items, written as ascending indices;
// a single-select list takes the first line; defaults are saved values.
let tpl = fields_template("<form><page1><country>Japan\nCanada</country><langs>Spanish\nEnglish\nEnglish\nSpanish</langs></page1></form>")
.replace("<value><text>FR</text></value></field>", "<value><text>France</text></value></field>")
.replace(
"<items><text>English</text><text>French</text><text>Spanish</text></items>",
"<items><text>English</text><text>French</text><text>Spanish</text></items><value><text>English\nFrench</text></value>",
);
let form = layout_xml(&tpl).unwrap();
let w = widgets(&form.pages[0]);
assert_eq!(w.iter().find(|w| w.name == "langs").unwrap().value.as_deref(), Some("Spanish\nEnglish"));
assert_eq!(w.iter().find(|w| w.name == "country").unwrap().value.as_deref(), Some("JP"));
assert_eq!(w.iter().find(|w| w.name == "country").unwrap().default.as_deref(), Some("FR"));
let mut doc = Document::open(Arc::new(shell(&tpl))).unwrap();
render_into(&mut doc).unwrap();
let doc = Document::open(Arc::new(write_incremental(&doc, &SaveOptions::default()).unwrap())).unwrap();
let fields = pdfcraft_forms_free_fields(&doc);
let langs = &fields.iter().find(|(n, _)| n == "langs").unwrap().1;
let i = doc.resolve(langs.get(b"I").unwrap()).as_array().unwrap().clone();
assert_eq!(i.iter().map(|o| o.as_int().unwrap()).collect::<Vec<_>>(), vec![0, 2]);
let dv = doc.resolve(langs.get(b"DV").unwrap()).as_array().unwrap().clone();
assert_eq!(dv.iter().map(|s| s.as_string().unwrap().to_text()).collect::<Vec<_>>(), vec!["English", "French"]);
let country = &fields.iter().find(|(n, _)| n == "country").unwrap().1;
assert_eq!(country.get(b"DV").and_then(|v| v.as_string()).map(|s| s.to_text()).as_deref(), Some("FR"));
assert_eq!(doc.resolve(country.get(b"I").unwrap()).as_array().unwrap().len(), 1);
// Picks stored as <value> children are read too.
let tpl = fields_template("<form><page1><langs><value>English</value><value>Spanish</value></langs></page1></form>");
let form = layout_xml(&tpl).unwrap();
assert_eq!(widgets(&form.pages[0]).iter().find(|w| w.name == "langs").unwrap().value.as_deref(), Some("English\nSpanish"));
// More items than the cap: kept to the cap, and said so.
let many: String = (0..1500).map(|i| format!("<text>i{i}</text>")).collect();
let tpl = fields_template("").replace("<items><text>A</text><text>B</text></items>", &format!("<items>{many}</items>"));
let form = layout_xml(&tpl).unwrap();
let other = widgets(&form.pages[0]).into_iter().find(|w| w.name == "other").unwrap();
assert!(matches!(&other.kind, WidgetKind::Choice { options, .. } if options.len() == 1000));
assert!(form.warnings.iter().any(|w| w.contains("other") && w.contains("1000 items")), "{:?}", form.warnings);
}
#[test]
fn pictures_are_embedded_once_across_relayouts_and_bad_data_pictures_are_reported() {
use crate::image::{decode, size};
let tpl = fields_template("<form><page1><country>JP</country></page1></form>");
let mut doc = Document::open(Arc::new(shell(&tpl))).unwrap();
render_into(&mut doc).unwrap();
let (t, _) = parse(&tpl).unwrap();
rerender(&mut doc, &t).unwrap();
rerender(&mut doc, &t).unwrap();
let bytes = write_incremental(&doc, &SaveOptions::default()).unwrap();
let doc = Document::open(Arc::new(bytes)).unwrap();
let images = doc
.object_numbers()
.into_iter()
.filter(
|n| matches!(&*doc.get(pdfcraft_cos::ObjRef { num: *n, generation: 0 }), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image")),
)
.count();
assert_eq!(images, 3, "the PNG, its soft mask and the GIF, however many times the form was laid out");
// No private map in the catalog: earlier pictures are found on the pages, by their hash.
let root = doc.get(doc.root().unwrap());
assert!(!root.as_dict().unwrap().contains(b"PCXfaImages"));
// Pictures in the data that aren't pictures: a warning naming the field, the template's
// picture shown instead.
for (data, what) in [("Qk0AAAAA", "not a JPEG, PNG, GIF, BMP or TIFF"), ("not base64!", "not base64")] {
let tpl = fields_template(&format!("<form><page1><photo>{data}</photo></page1></form>"));
let form = layout_xml(&tpl).unwrap();
assert!(form.warnings.iter().any(|w| w.contains("photo") && w.contains(what)), "{what}: {:?}", form.warnings);
assert_eq!(form.pages[0].items.iter().filter(|i| matches!(i, Item::Image { .. })).count(), 2);
}
// A hostile PNG header: no size for layout (the draw keeps its box), refused at decode.
let mut tall = tiny_png();
tall[16..20].copy_from_slice(&1u32.to_be_bytes());
tall[20..24].copy_from_slice(&4_000_000_000u32.to_be_bytes());
assert_eq!(size(&tall), None);
assert!(decode(&tall).unwrap_err().contains("million pixels"));
use base64::Engine;
let b64 = base64::engine::general_purpose::STANDARD.encode(&tall);
let tpl = fields_template("").replace(
r#"<draw name="logo" w="0.5in" h="0.5in">"#,
&format!(
r#"<draw name="tall" w="2in"><value><image contentType="image/png">{b64}</image></value></draw><draw name="logo" w="0.5in" h="0.5in">"#
),
);
let form = layout_xml(&tpl).unwrap();
assert_eq!(form.pages.len(), 1, "a picture of unknown size takes its box, not a page");
// A GIF whose frame is far larger than its 1 × 1 screen is refused before it is allocated.
let mut gif = b"GIF89a\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00,\x00\x00\x00\x00".to_vec();
gif.extend_from_slice(&11_000u16.to_le_bytes());
gif.extend_from_slice(&11_000u16.to_le_bytes());
gif.extend_from_slice(b"\x00\x02\x02D\x01\x00;");
let started = std::time::Instant::now();
assert!(decode(&gif).unwrap_err().contains("million pixels"));
assert!(started.elapsed() < std::time::Duration::from_secs(2));
// A template picture over 1 MiB is read whole (text is cut at 1 MiB, pictures are not).
let big = "A".repeat(1_600_000);
let tpl = fields_template("").replace(r#"<image contentType="image/gif">"#, &format!(r#"<image contentType="image/gif">{big}"#));
let (t, _) = parse(&tpl).unwrap();
fn find_image(nodes: &[Node]) -> Option<usize> {
nodes.iter().find_map(|n| match n {
Node::Draw(d) => match &d.value {
Value::Image { data, .. } => Some(data.len()),
_ => None,
},
Node::Subform(s) => find_image(&s.children),
_ => None,
})
}
assert!(find_image(&t.root.children).is_some_and(|n| n > 1_200_000));
}
/// #4937: LiveCycle wrote BMPs whose header gives the pixel data's offset as 0. Read literally,
/// the pixels start at the file header, so the image is drawn shifted and wrapped around.
#[test]
fn a_bmp_whose_pixel_offset_points_into_its_headers_is_read_from_after_them() {
use crate::image::{bmp_with_pixel_offset, decode, size};
for palette in [false, true] {
let intact = tiny_bmp(palette);
assert!(matches!(bmp_with_pixel_offset(&intact), std::borrow::Cow::Borrowed(_)), "an intact file is not copied");
for bad in [0u32, 14, 53] {
let mut bmp = intact.clone();
bmp[10..14].copy_from_slice(&bad.to_le_bytes());
let d = decode(&bmp).unwrap();
assert_eq!(d.samples, vec![255, 0, 0, 0, 0, 255], "offset {bad}, palette: {palette}");
assert_eq!(size(&bmp), Some((2, 1)));
assert_eq!(bmp_with_pixel_offset(&bmp).as_ref(), &intact[..], "offset {bad}, palette: {palette}");
}
}
// Too short to hold the pixels after the headers: left alone, not grown.
let mut cut = tiny_bmp(true);
cut[10..14].copy_from_slice(&0u32.to_le_bytes());
cut.truncate(60);
assert_eq!(bmp_with_pixel_offset(&cut).as_ref(), &cut[..]);
// A truncated header, and bytes that are not a BMP: left alone.
assert_eq!(bmp_with_pixel_offset(b"BM").as_ref(), b"BM");
assert_eq!(bmp_with_pixel_offset(TINY_GIF).as_ref(), TINY_GIF);
// BI_BITFIELDS in a 40-byte header: three masks follow the header.
let mut fields = tiny_bmp(false);
fields[30..34].copy_from_slice(&3u32.to_le_bytes());
fields[10..14].copy_from_slice(&0u32.to_le_bytes());
fields.splice(54..54, [0u8; 12]);
assert_eq!(bmp_with_pixel_offset(&fields).get(10..14), Some(&66u32.to_le_bytes()[..]));
// Pointing at the end of the 40-byte header, before the masks.
fields[10..14].copy_from_slice(&54u32.to_le_bytes());
assert_eq!(bmp_with_pixel_offset(&fields).get(10..14), Some(&66u32.to_le_bytes()[..]));
// A colour count no file could hold: left alone.
let mut huge = tiny_bmp(true);
huge[46..50].copy_from_slice(&u32::MAX.to_le_bytes());
huge[10..14].copy_from_slice(&0u32.to_le_bytes());
assert_eq!(bmp_with_pixel_offset(&huge).as_ref(), &huge[..]);
// A 12-byte core header: 16-bit fields and 3-byte palette entries, `1 << bpp` of them.
let mut core = b"BM".to_vec();
core.extend_from_slice(&[0; 8]);
core.extend_from_slice(&0u32.to_le_bytes());
core.extend_from_slice(&12u32.to_le_bytes());
for v in [2u16, 1, 1, 1] {
core.extend_from_slice(&v.to_le_bytes());
}
core.extend_from_slice(&[0, 0, 255, 255, 0, 0, 0b0100_0000, 0, 0, 0]);
assert_eq!(bmp_with_pixel_offset(&core).get(10..14), Some(&32u32.to_le_bytes()[..]));
let mut at_table = core.clone();
at_table[10..14].copy_from_slice(&26u32.to_le_bytes());
assert_eq!(bmp_with_pixel_offset(&at_table).get(10..14), Some(&32u32.to_le_bytes()[..]), "before the colour table");
let d = decode(&bmp_with_pixel_offset(&core)).unwrap();
assert_eq!(d.samples, vec![255, 0, 0, 0, 0, 255], "core header");
}
/// Designer forms often carry BMP and TIFF pictures, declared as `image/bmp` and `image/tif`
/// (the Government of Canada's IMM 5257 and IMM 5710 have both). They were left out.
#[test]
fn bmp_and_tiff_pictures_are_decoded_and_drawn() {
use crate::image::{Kind, decode, kind, size};
for palette in [false, true] {
let bmp = tiny_bmp(palette);
assert_eq!(kind(&bmp), Some(Kind::Bmp));
assert_eq!(size(&bmp), Some((2, 1)));
let d = decode(&bmp).unwrap();
assert_eq!((d.width, d.height, d.color_space), (2, 1, "DeviceRGB"), "palette: {palette}");
assert_eq!(d.samples, vec![255, 0, 0, 0, 0, 255], "red then blue, palette: {palette}");
assert_eq!(d.alpha, None);
}
for lzw in [false, true] {
let tiff = tiny_tiff(lzw);
assert_eq!(kind(&tiff), Some(Kind::Tiff));
assert_eq!(size(&tiff), Some((1, 1)));
let d = decode(&tiff).unwrap();
assert_eq!((d.width, d.height, d.color_space), (1, 1, "DeviceRGB"), "lzw: {lzw}");
assert_eq!(d.samples, vec![0x12, 0x34, 0x56], "lzw: {lzw}");
}
assert_eq!(kind(b"MM\0*\0\0\0\x08"), Some(Kind::Tiff), "big-endian");
let mut cut = tiny_tiff(true);
cut.truncate(60);
assert!(decode(&cut).is_err());
// In a form: drawn, with no warning, whatever the declared type says.
use base64::Engine;
for (data, declared) in
[(tiny_bmp(false), "image/bmp"), (tiny_bmp(true), "image/x-ms-bmp"), (tiny_tiff(false), "image/tif"), (tiny_tiff(true), "image/tiff")]
{
let b64 = base64::engine::general_purpose::STANDARD.encode(&data);
let gif = base64::engine::general_purpose::STANDARD.encode(TINY_GIF);
let xml =
fields_template("").replace(&format!(r#"<image contentType="image/gif">{gif}"#), &format!(r#"<image contentType="{declared}">{b64}"#));
assert!(xml.contains(declared));
let mut doc = Document::open(Arc::new(shell(&xml))).unwrap();
let report = render_into(&mut doc).unwrap();
assert!(!report.warnings.iter().any(|w| w.contains("left out")), "{declared}: {:?}", report.warnings);
let samples: Vec<u8> = if declared.contains("bmp") { vec![255, 0, 0, 0, 0, 255] } else { vec![0x12, 0x34, 0x56] };
let drawn = doc.object_numbers().into_iter().any(|n| {
matches!(&*doc.get(pdfcraft_cos::ObjRef { num: n, generation: 0 }), Object::Stream(st)
if st.dict.name(b"Subtype") == Some(b"Image") && st.decoded().ok().as_ref() == Some(&samples))
});
assert!(drawn, "{declared}: its pixels are an image XObject");
}
}
/// A repeating subform drawn inside positioned content (a top-to-bottom table in an area of a
/// positioned subform) gets its `occur` instances, as in Adobe's viewers: real Designer forms
/// have tables like this whose calculations read every row. Before, only one row was laid
/// out, and the field after the table was placed as if there were one.
#[test]
fn repeating_subforms_inside_positioned_content_get_their_instances() {
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">
<pageSet><pageArea name="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<subform name="page1" w="7.5in" h="8in">
<area name="box" x="0.5in" y="1in">
<subform name="wrap" layout="tb" w="4in">
<subform name="table" layout="tb" w="4in">
<subform name="row" w="4in" h="0.3in"><occur min="3" max="-1"/>
<field name="reason" w="4in" h="0.3in"><ui><textEdit/></ui></field>
</subform>
</subform>
<field name="after" w="4in" h="0.3in"><ui><textEdit/></ui></field>
</subform>
</area>
</subform>
</subform>
</template>
</xdp:xdp>
"##;
let form = layout_xml(xdp).unwrap();
let all: Vec<&Widget> = form.pages.iter().flat_map(widgets).collect();
let rows: Vec<&Widget> = all.iter().copied().filter(|w| w.som.ends_with(".reason[0]")).collect();
let soms: Vec<&str> = rows.iter().map(|w| w.som.as_str()).collect();
assert_eq!(
soms,
[
"form[0].page1[0].box[0].wrap[0].table[0].row[0].reason[0]",
"form[0].page1[0].box[0].wrap[0].table[0].row[1].reason[0]",
"form[0].page1[0].box[0].wrap[0].table[0].row[2].reason[0]",
],
"one widget per instance, each with its own SOM index"
);
// The rows are stacked, not drawn on top of each other…
let step = rows[1].rect.y - rows[0].rect.y;
assert!(step.abs() > 1.0, "rows overlap: {:?}", rows.iter().map(|w| w.rect).collect::<Vec<_>>());
assert!(((rows[2].rect.y - rows[1].rect.y) - step).abs() < 0.01, "rows are evenly spaced");
// …and what follows the table is placed after all of them (the table was measured with
// its instances, not with one row).
let after = all.iter().find(|w| w.som.ends_with(".after[0]")).expect("the field after the table");
assert!(((after.rect.y - rows[2].rect.y) - step).abs() < 0.01, "after: {:?}, last row: {:?}", after.rect, rows[2].rect);
}
/// A positioned subform holding `body`, laid out; its page's items.
fn positioned(body: &str) -> Vec<Item> {
let xdp = format!(
r##"<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="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<subform name="box" w="7.5in" h="3in">{body}</subform>
</subform>
</template></xdp:xdp>"##
);
layout_xml(&xdp).unwrap().pages.into_iter().next().unwrap().items
}
/// A text draw without a width is as wide as its text, so right-aligned text starts at its x; a
/// minimum width wider than the text still wins, and text longer than the room left still wraps.
#[test]
fn a_label_without_a_width_is_as_wide_as_its_text() {
const TEXT: &str = "PERSONNEL ONLY: from date (YYYYMMDD):";
let natural = pdfcraft_fonts::helvetica_width(TEXT, 8.0);
// Right-aligned, with a minimum narrower than the text: the box is as wide as the text and
// starts where it is placed, so the text does too (not at the far right of the subform).
let items = positioned(&format!(
r#"<draw name="a" x="1in" y="0" minW="50pt"><value><text>{TEXT}</text></value><font typeface="Arial" size="8pt"/><para hAlign="right"/></draw>"#
));
let span = items.iter().find_map(|i| if let Item::Text(s) = i { Some(s) } else { None }).expect("the text");
assert!((span.x - (36.0 + 72.0)).abs() < 0.05, "starts at its x: {}", span.x);
// With a minimum wider than the text, the box is that wide and the text ends at its right.
let items = positioned(&format!(
r#"<draw name="a" x="1in" y="0" minW="{}pt"><value><text>{TEXT}</text></value><font typeface="Arial" size="8pt"/><para hAlign="right"/></draw>"#,
natural + 40.0
));
let span = items.iter().find_map(|i| if let Item::Text(s) = i { Some(s) } else { None }).expect("the text");
assert!((span.x + span.face.width(&span.text) - (36.0 + 72.0 + natural + 40.0)).abs() < 0.05, "ends at its right: {}", span.x);
// Text longer than the room left still wraps at the container's width.
let long = "word ".repeat(200);
let items = positioned(&format!(r#"<draw name="a" x="0" y="0"><value><text>{long}</text></value><font typeface="Arial" size="8pt"/></draw>"#));
let lines: std::collections::BTreeSet<i64> =
items.iter().filter_map(|i| if let Item::Text(s) = i { Some((s.baseline * 100.0).round() as i64) } else { None }).collect();
assert!(lines.len() > 1, "wraps: {} line(s)", lines.len());
// And within the room it has: no line's drawn text runs past the subform's right edge.
let right = items
.iter()
.filter_map(|i| if let Item::Text(s) = i { Some(s.x + s.face.width(s.text.trim_end())) } else { None })
.fold(f64::NEG_INFINITY, f64::max);
assert!(right <= 36.0 + 7.5 * 72.0 + 0.05, "the text stays within the available width: {right}");
}
/// A draw without a width and without text (a bordered spacer or rule) keeps the width it has
/// room for: with no text to size it to, it doesn't shrink to its margins.
#[test]
fn an_empty_draw_without_a_width_keeps_the_width_it_has_room_for() {
let items = positioned(r#"<draw name="rule" x="0" y="0" h="12pt"><value><text></text></value><border><edge thickness="1pt"/></border></draw>"#);
let widest =
items.iter().filter_map(|i| if let Item::Line { from, to, .. } = i { Some((to.0 - from.0).abs()) } else { None }).fold(0.0_f64, f64::max);
assert!((widest - 540.0).abs() < 0.5, "the border spans the 7.5in box: {widest}");
}
/// A button without a width is as wide as its caption, not the subform it sits in, unless its
/// minimum width is wider.
#[test]
fn a_button_without_a_width_is_as_wide_as_its_caption() {
// No width, a minimum narrower than its caption: as wide as the caption, not the subform.
let caption = "Open the instructions for this form";
let items = positioned(&format!(
r#"<field name="help" x="1in" y="0" minW="40pt" minH="12pt"><ui><button/></ui><caption><value><text>{caption}</text></value><font typeface="Arial" size="8pt"/></caption></field>"#
));
let button = items.iter().find_map(|i| if let Item::Widget(w) = i { Some(w) } else { None }).expect("the button");
let natural = pdfcraft_fonts::helvetica_width(caption, 8.0);
assert!(button.rect.w >= natural && button.rect.w < natural + 10.0, "{} for a caption of {natural}", button.rect.w);
// A minimum wider than the caption wins.
let items = positioned(
r#"<field name="help" x="1in" y="0" minW="200pt" minH="12pt"><ui><button/></ui><caption><value><text>Help</text></value><font typeface="Arial" size="8pt"/></caption></field>"#,
);
let button = items.iter().find_map(|i| if let Item::Widget(w) = i { Some(w) } else { None }).expect("the button");
assert!((button.rect.w - 200.0).abs() < 0.05, "{}", button.rect.w);
}
/// A button without a height is as tall as one line of its caption in the caption's own font,
/// with none of a text field's padding, and never shorter than its minimum height.
#[test]
fn a_button_without_a_height_is_as_tall_as_its_caption() {
// A 10pt field font, an 8pt caption: the button is as tall as its caption's line (no
// text-field padding), and never below its minimum height.
let button = |min_h: &str| {
let items = positioned(&format!(
r#"<field name="help" x="1in" y="0" w="100pt" minH="{min_h}"><ui><button/></ui><font typeface="Times New Roman" size="10pt"/><caption><value><text>Help</text></value><font typeface="Arial" size="8pt"/></caption></field>"#
));
items.iter().find_map(|i| if let Item::Widget(w) = i { Some(w.rect.h) } else { None }).expect("the button")
};
assert!((button("2pt") - text::line_height(8.0)).abs() < 0.05, "{}", button("2pt"));
assert!((button("10.5pt") - 10.5).abs() < 0.05, "{}", button("10.5pt"));
}
/// A button's widget is its whole field, at the field's position and size: the field's margins
/// pad the caption, not the box.
#[test]
fn a_buttons_box_is_the_whole_field_whatever_its_margins() {
// The button's box is its field's border: its margins pad the caption, not the box.
let items = positioned(
r#"<field name="help" x="1in" y="10pt" w="100pt" h="20pt"><ui><button/></ui><margin topInset="5pt" leftInset="3pt"/><border><edge/></border><caption><value><text>Help</text></value><font typeface="Arial" size="8pt"/></caption></field>"#,
);
let button = items.iter().find_map(|i| if let Item::Widget(w) = i { Some(w.rect) } else { None }).expect("the button");
assert!((button.w - 100.0).abs() < 0.05 && (button.h - 20.0).abs() < 0.05, "{button:?}");
assert!((button.x - (36.0 + 72.0)).abs() < 0.05, "{button:?}");
}
/// A page area without an `<occur>` repeats for as long as the body needs pages. Before, it was
/// treated like a subform (at most once), so once the first body page was out the layout fell
/// back to the last page area, here one limited to a single use, and drew its content over every
/// body page (and listed a copy of its fields per page).
#[test]
fn page_area_without_occur_serves_every_body_page() {
let section = |n: u32| {
format!(
r#"<subform name="s{n}" layout="tb"><breakBefore targetType="pageArea" startNew="1"/><field name="f{n}" w="2in" h="0.3in"><ui><textEdit/></ui></field></subform>"#
)
};
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">
<pageSet>
<pageArea name="Body"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea>
<pageArea name="Once"><occur min="1" max="1"/><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/>
<field name="PrintButton" x="1in" y="1in" w="1in" h="0.3in"><ui><button/></ui></field>
</pageArea>
</pageSet>
{}{}{}{}
</subform>
</template>
</xdp:xdp>
"##,
section(1),
section(2),
section(3),
section(4)
);
let form = layout_xml(&xdp).unwrap();
let soms: Vec<Vec<String>> = form.pages.iter().map(|p| widgets(p).iter().map(|w| w.som.clone()).collect()).collect();
let has_button = |page: &Vec<String>| page.iter().any(|s| s.contains("PrintButton"));
// Four body pages, then the once-only page: its button is on that page alone, not over the body.
assert_eq!(form.pages.len(), 5, "{soms:?}");
assert!(soms[..4].iter().all(|p| !has_button(p)), "the single-use page area is not drawn over body pages: {soms:?}");
assert_eq!(soms[4].iter().filter(|s| s.contains("PrintButton")).count(), 1, "the required page is laid out once: {soms:?}");
}
#[test]
fn page_master_content_repeated_on_each_page_has_its_own_som_index() {
// One page area (no occur limit) serves three body pages and carries a field in its own
// master content. Each page's copy of that field gets the page area's instance index, so the
// three do not share one SOM path (and one data node).
let section = |n: u32| {
format!(
r#"<subform name="s{n}" layout="tb"><breakBefore targetType="pageArea" startNew="1"/><field name="f{n}" w="2in" h="0.3in"><ui><textEdit/></ui></field></subform>"#
)
};
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">
<pageSet>
<pageArea name="Body"><contentArea x="0.5in" y="0.5in" w="7.5in" h="2in"/><medium short="8.5in" long="11in"/>
<field name="pageNo" x="7in" y="10in" w="1in" h="0.3in"><ui><textEdit/></ui></field>
<field name="total" x="1in" y="10in" w="1in" h="0.3in"><ui><textEdit/></ui><bind match="global"/></field>
</pageArea>
</pageSet>
{}{}{}
</subform>
</template>
</xdp:xdp>
"##,
section(1),
section(2),
section(3)
);
let form = layout_xml(&xdp).unwrap();
let page_nos: Vec<String> = form.pages.iter().flat_map(|p| widgets(p)).filter(|w| w.som.contains("pageNo")).map(|w| w.som.clone()).collect();
assert_eq!(page_nos, ["Body[0].pageNo[0]", "Body[1].pageNo[0]", "Body[2].pageNo[0]"], "each page's master field has its own index");
// Its data path keeps that index, so each page binds apart; a field whose bind is global
// shares one data node, so every page binds it as instance 0 (XFA 3.3, "Page Background").
let (tpl, _) = crate::parse(&xdp).unwrap();
let dp = |som: &str| crate::data_path(&tpl, som);
assert_eq!(dp("Body[2].pageNo[0]"), crate::som_to_path("Body[2].pageNo[0]"));
assert_eq!(dp("Body[2].total[0]"), crate::som_to_path("Body[0].total[0]"), "a global field binds as instance 0 on each page");
}
/// A page area's `occur min` is a page it must have even when the body never reaches it, and a
/// body that already used it does not get another. An area with no `<occur>` needs none.
#[test]
fn page_area_minimum_adds_pages_after_the_body_only_when_unused() {
let area = |name: &str, occur: &str| {
format!(
r#"<pageArea name="{name}">{occur}<contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea>"#
)
};
let pages = |areas: String| {
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"><pageSet>{areas}</pageSet><field name="f" w="2in" h="0.3in"><ui><textEdit/></ui></field></subform>
</template></xdp:xdp>"##
);
layout_xml(&xdp).unwrap().pages.len()
};
// The body is one page; the required second master adds one, a third with min 2 adds two.
assert_eq!(pages(area("A", "") + &area("B", r#"<occur min="1" max="1"/>"#)), 2);
assert_eq!(pages(area("A", "") + &area("B", r#"<occur min="1" max="1"/>"#) + &area("C", r#"<occur min="2" max="3"/>"#)), 4);
// An area the body already used (it is first, so page 1 is its own) adds nothing.
assert_eq!(pages(area("A", r#"<occur min="1" max="1"/>"#)), 1);
assert_eq!(pages(area("A", r#"<occur min="1" max="1"/>"#) + &area("B", "")), 1);
// No `<occur>` and `min="0"` need no page.
assert_eq!(pages(area("A", "") + &area("B", r#"<occur min="0" max="1"/>"#)), 1);
}
/// Areas are named in SOM expressions but are not data scopes; unnamed subforms and areas have
/// no segment at all. What the template doesn't have is kept as it is.
#[test]
fn data_paths_leave_areas_out() {
let (tpl, _) = parse(&crate::fixtures::leave_template("")).unwrap();
let path = |som: &str| data_path(&tpl, som).into_iter().map(|(n, i)| format!("{n}[{i}]")).collect::<Vec<_>>().join(".");
// The area `box` (inside an unnamed subform) is dropped; indexes are kept.
assert_eq!(path("form[0].page[0].box[0].table[0].row[2].days[0]"), "form[0].page[0].table[0].row[2].days[0]");
assert_eq!(path("form[0].page[0].box[0].rest[0]"), "form[0].page[0].rest[0]");
// No area on the way: as som_to_path.
assert_eq!(path("form[0].page[0]"), "form[0].page[0]");
// Unknown segments, past a leaf, or a SOM from another template: kept.
assert_eq!(path("form[0].page[0].box[0].nothing[0].x[1]"), "form[0].page[0].nothing[0].x[1]");
assert_eq!(path("form[0].page[0].box[0].rest[0].box[0]"), "form[0].page[0].rest[0].box[0]");
assert_eq!(path("other[0].box[0].rest[0]"), "other[0].box[0].rest[0]");
assert_eq!(data_path(&tpl, ""), Vec::new());
}
/// A template nested thousands of elements deep must be refused. roxmltree recurses with the
/// nesting depth, so it used to overflow the stack - and a stack overflow aborts the process,
/// which no `catch_unwind` can intercept.
#[test]
fn deeply_nested_template_is_refused_instead_of_overflowing_the_stack() {
let mut xml = String::from(r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">"#);
for i in 0..10_000 {
xml.push_str(&format!(r#"<subform name="s{i}">"#));
}
xml.push_str(&"</subform>".repeat(10_000));
xml.push_str("</template>");
assert!(matches!(crate::parse::parse(&xml), Err(crate::XfaError::Malformed(_))), "ten thousand nested subforms must be refused, not parsed");
}
/// The depth scanner skips what is not an element and cannot under-count one.
#[test]
fn nesting_depth_scanner_counts_what_matters() {
use crate::xml_nesting_depth as d;
assert_eq!(d(""), 0);
assert_eq!(d("<a><b><c/></b></a>"), 3);
assert_eq!(d(r#"<?xml version="1.0"?><!-- <x> --><a/>"#), 1);
assert_eq!(d("<a><![CDATA[<not-an-element>]]></a>"), 1);
assert_eq!(d(r#"<a b="<"><c/></a>"#), 2);
assert_eq!(d("<a/>"), 1);
assert_eq!(d("<a><b/></a>"), 2);
assert_eq!(d(&"<empty/>".repeat(2_000)), 1, "elements that close themselves must not accumulate");
}
/// A template holding thousands of self-closing elements is two levels deep, not thousands. Before
/// the scanner knew that, a form with a lot of styling elements was refused as too deeply nested.
#[test]
fn many_self_closing_elements_do_not_accumulate_into_the_bound() {
let mut xml = String::from(r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform layout="tb">"#);
for i in 0..2_000 {
xml.push_str(&format!(r#"<draw name="d{i}"/>"#));
}
xml.push_str("</subform></template>");
assert!(crate::parse::parse(&xml).is_ok(), "two thousand self-closing draws are two levels deep, not two thousand");
}
/// The bound must hold on a worker thread too, whose default stack (2 MiB) is a quarter of the
/// main thread's: a template exactly at the limit parses there without overflowing.
#[test]
fn template_at_the_depth_limit_parses_on_a_worker_thread() {
let depth = crate::MAX_XML_DEPTH - 1;
let mut xml = String::from(r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/">"#);
for i in 0..depth {
xml.push_str(&format!(r#"<subform name="s{i}">"#));
}
xml.push_str(&"</subform>".repeat(depth));
xml.push_str("</template>");
let parsed = std::thread::spawn(move || crate::parse::parse(&xml).is_ok()).join();
assert!(matches!(parsed, Ok(true)), "a template at the limit parses on a default-stack thread");
}
/// A form of one page area (7.5in × 10in of content from 0.5in) around `body`.
fn one_area_form(root_attrs: &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" {root_attrs}>
<pageSet><pageArea name="page"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
{body}
</subform>
</template>
</xdp:xdp>
"##
)
}
/// Every field is inside the content area of its page, and the fields come in template order.
fn assert_paginated(form: &Form, fields: usize, min_pages: usize) {
assert!(form.pages.len() >= min_pages, "{} pages", form.pages.len());
let mut names = Vec::new();
for (i, p) in form.pages.iter().enumerate() {
for w in widgets(p) {
assert!(
w.rect.y >= 36.0 - 0.01 && w.rect.bottom() <= 36.0 + 720.0 + 0.01,
"page {}: {} is outside the content area: {:?}",
i + 1,
w.name,
w.rect
);
names.push(w.som.clone());
}
}
assert_eq!(names.len(), fields, "{names:?}");
let expected: Vec<String> = (0..fields).map(|i| format!("f{i}[0]")).collect();
for (n, e) in names.iter().zip(&expected) {
assert!(n.ends_with(e), "{n} where {e} belongs: {names:?}");
}
}
#[test]
fn a_positioned_subform_taller_than_a_page_continues_on_the_next_pages() {
// 30 fields 0.9in apart: 27in of positioned content, where a content area holds 10in.
let fields: String =
(0..30).map(|i| format!(r#"<field name="f{i}" x="0.5in" y="{}in" w="4in" h="0.4in"><ui><textEdit/></ui></field>"#, i as f64 * 0.9)).collect();
// As the only child of a flowed root …
let form = layout_xml(&one_area_form(
r#"layout="tb""#,
&format!(r#"<subform name="body"><border><fill><color value="200,200,200"/></fill></border>{fields}</subform>"#),
))
.unwrap();
assert_paginated(&form, 30, 3);
// … its fill is cut at the breaks, a piece on every page, none past the content area.
for (i, p) in form.pages.iter().enumerate() {
let fills: Vec<&Rect> = p.items.iter().filter_map(|it| if let Item::Fill { rect, .. } = it { Some(rect) } else { None }).collect();
assert!(!fills.is_empty(), "page {}: no fill", i + 1);
for r in fills {
assert!(r.bottom() <= 36.0 + 720.0 + 0.01, "page {}: fill {r:?}", i + 1);
}
}
// … after other content on the page …
let form = layout_xml(&one_area_form(
r#"layout="tb""#,
&format!(r#"<draw name="head" w="4in" h="3in"><value><text>Head</text></value></draw><subform name="body">{fields}</subform>"#),
))
.unwrap();
assert_paginated(&form, 30, 3);
assert!(!widgets(&form.pages[0]).is_empty(), "the block starts on the page the heading is on");
// … and as the root itself (positioned is the default layout).
let form = layout_xml(&one_area_form("", &fields)).unwrap();
assert_paginated(&form, 30, 3);
}
#[test]
fn wrapped_and_fixed_height_blocks_taller_than_a_page_are_split_too() {
let fields: String = (0..60).map(|i| format!(r#"<field name="f{i}" w="3.5in" h="0.8in"><ui><textEdit/></ui></field>"#)).collect();
// Left-to-right wrapping: 30 lines of 0.8in.
let form = layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"<subform name="body" layout="lr-tb" w="7.5in">{fields}</subform>"#))).unwrap();
assert_paginated(&form, 60, 3);
// Top-to-bottom with a fixed height the content outgrows.
let form =
layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"<subform name="body" layout="tb" w="7.5in" h="9in">{fields}</subform>"#))).unwrap();
assert_paginated(&form, 60, 5);
}
#[test]
fn a_block_that_fits_a_page_is_still_moved_whole() {
let block = |n: usize| {
format!(r#"<subform name="b{n}" w="7in" h="6in"><field name="f{n}" x="0in" y="5in" w="4in" h="0.4in"><ui><textEdit/></ui></field></subform>"#)
};
let form = layout_xml(&one_area_form(r#"layout="tb""#, &format!("{}{}{}", block(0), block(1), block(2)))).unwrap();
assert_eq!(form.pages.len(), 3);
for p in &form.pages {
let w = widgets(p);
assert_eq!(w.len(), 1);
assert!((w[0].rect.y - (36.0 + 360.0)).abs() < 0.01, "{:?}", w[0].rect);
}
}
#[test]
fn a_field_taller_than_a_page_is_cut_through_without_looping() {
let body = r#"<field name="f0" w="4in" h="25in"><ui><textEdit/></ui></field><field name="f1" w="4in" h="0.4in"><ui><textEdit/></ui></field>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
let all: Vec<&Widget> = form.pages.iter().flat_map(widgets).collect();
assert_eq!(all.len(), 2);
assert!(form.pages.len() <= 4, "{} pages", form.pages.len());
}
/// A form built the way Designer builds a flowed one: everything in one left-to-right wrapped
/// body, sections of a heading over repeating rows of fields, and a text field that grows.
fn wrapped_form(data: &str) -> String {
let body = r#"<subform name="body" layout="lr-tb" w="7.5in">
<subform name="section" layout="lr-tb" w="7.5in" minH="0.5in">
<draw name="heading" w="7.5in" h="0.2in"><value><text>Entries</text></value></draw>
<subform name="row" layout="lr-tb" w="7.5in" minH="0.5in"><occur max="-1"/>
<field name="what" w="3.5in" h="1in"><ui><textEdit multiLine="1"/></ui></field>
<field name="when" w="0.5in" h="1in"><ui><textEdit/></ui></field>
<field name="why" w="3.5in" h="1in"><ui><textEdit multiLine="1"/></ui></field>
</subform>
</subform>
<field name="notes" w="7.5in" minH="1.5in"><ui><textEdit multiLine="1"/></ui></field>
<field name="after" w="7.5in" h="0.3in"><ui><textEdit/></ui></field>
</subform>"#;
let form = one_area_form(r#"layout="tb""#, body);
let packet =
format!("<xfa:datasets xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><xfa:data>{data}</xfa:data></xfa:datasets>\n</xdp:xdp>");
form.replace("</xdp:xdp>", &packet)
}
#[test]
fn repeating_rows_in_a_wrapped_container_get_the_instances_the_data_holds() {
let rows: String = (0..4).map(|i| format!("<row><what>what {i}</what><when>{i}</when><why>why {i}</why></row>")).collect();
let form = layout_xml(&wrapped_form(&format!("<form><body><section>{rows}</section><notes>n</notes></body></form>"))).unwrap();
let all: Vec<&Widget> = form.pages.iter().flat_map(widgets).collect();
let whats: Vec<(&str, Option<&str>, f64)> =
all.iter().filter(|w| w.som.ends_with(".what[0]")).map(|w| (w.som.as_str(), w.value.as_deref(), w.rect.y)).collect();
assert_eq!(whats.len(), 4, "{whats:?}");
for (i, (som, value, _)) in whats.iter().enumerate() {
assert_eq!(*som, format!("form[0].body[0].section[0].row[{i}].what[0]"));
assert_eq!(*value, Some(format!("what {i}").as_str()));
}
// One under another, the section growing with them: what follows comes after the last.
assert!(whats.windows(2).all(|p| (p[1].2 - p[0].2 - 72.0).abs() < 0.01), "{whats:?}");
let notes = all.iter().find(|w| w.name == "notes").unwrap();
assert!(notes.rect.y >= whats[3].2 + 72.0 - 0.01, "{:?} after {whats:?}", notes.rect);
// Without data a row is there once.
let form = layout_xml(&wrapped_form("<form/>")).unwrap();
assert_eq!(form.pages.iter().flat_map(widgets).filter(|w| w.name.starts_with("what")).count(), 1);
}
/// A multi-line field with a minimum height and no fixed one grows to hold its text, moving
/// what follows down; one with a fixed height keeps it.
#[test]
fn a_multi_line_field_without_a_height_grows_to_hold_its_text() {
let place = |data: &str| {
let form = layout_xml(&wrapped_form(data)).unwrap();
let on = |name: &str| {
form.pages.iter().enumerate().find_map(|(i, p)| widgets(p).into_iter().find(|w| w.name == name).map(|w| (i, w.rect))).unwrap()
};
(on("notes"), on("after"))
};
// Little text: the minimum height.
let ((_, notes), (_, after)) = place("<form><body><notes>Short.</notes></body></form>");
assert!((notes.h - 108.0).abs() < 0.01, "{notes:?}");
assert!((after.y - notes.bottom()).abs() < 0.01);
// Forty lines: the field holds them, and what follows moves down.
let long: String = (0..40).map(|i| format!("Line {i} of the notes.\n")).collect();
let ((notes_page, grown), (after_page, after)) = place(&format!("<form><body><notes>{long}</notes></body></form>"));
assert!(grown.h > 40.0 * 11.0 && grown.h < 720.0, "{grown:?}");
assert_eq!(notes_page, after_page);
assert!((after.y - grown.bottom()).abs() < 0.01, "{after:?} after {grown:?}");
// A fixed height stays what it is.
let fixed = wrapped_form(&format!("<form><body><notes>{long}</notes></body></form>"))
.replace(r#"minH="1.5in"><ui><textEdit multiLine"#, r#"h="1.5in"><ui><textEdit multiLine"#);
let form = layout_xml(&fixed).unwrap();
let notes = form.pages.iter().flat_map(widgets).find(|w| w.name == "notes").unwrap();
assert!((notes.rect.h - 108.0).abs() < 0.01, "{:?}", notes.rect);
}
/// The rounded boxes laid out on `page`, in order.
fn rounded(page: &Page) -> Vec<&crate::layout::Rounded> {
page.items.iter().filter_map(|i| if let Item::Rounded(r) = i { Some(r.as_ref()) } else { None }).collect()
}
/// A border or rectangle with rounded corners is one shape, filled and edged along its curves:
/// one corner applies to all four, a corner not given repeats the last one given, a radius is at
/// most half the box's shorter side, and inverted corners are kept. Hidden corners, and edges
/// that differ from each other, keep the square box.
#[test]
fn rounded_corners_make_a_border_one_rounded_shape() {
let draw = |name: &str, y: f64, border: &str| {
format!(r#"<draw name="{name}" x="0in" y="{y}in" w="2in" h="1in"><value><text>{name}</text></value>{border}</draw>"#)
};
let body = [
draw("round", 0.0, r#"<border><edge thickness="1pt"><color value="255,0,0"/></edge><corner radius="0.25in"/><fill><color value="230,230,230"/></fill></border>"#),
draw("mixed", 1.2, r#"<border><edge/><corner radius="0.1in"/><corner radius="0.2in" inverted="1"/></border>"#),
draw("huge", 2.4, r#"<border><edge/><corner radius="3in"/></border>"#),
draw("hiddenCorner", 3.6, r#"<border><edge/><corner radius="0.25in" presence="hidden"/></border>"#),
draw("unlikeEdges", 4.8, r#"<border><edge/><edge presence="hidden"/><corner radius="0.25in"/></border>"#),
draw("fillOnly", 6.0, r#"<border><edge presence="hidden"/><corner radius="0.25in"/><fill><color value="200,200,200"/></fill></border>"#),
r#"<draw name="shape" x="0in" y="7.2in" w="2in" h="1in"><value><rectangle><edge thickness="0.5pt"/><corner radius="5.08mm"/></rectangle></value></draw>"#.to_string(),
]
.concat();
let form = layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"<subform name="body" layout="position" w="7.5in" h="9in">{body}</subform>"#)))
.unwrap();
let shapes = rounded(&form.pages[0]);
let at = |y: f64| shapes.iter().copied().find(|r| (r.rect.y - 36.0 - y * 72.0).abs() < 0.01);
let round = at(0.0).expect("the rounded border is one shape");
assert_eq!((round.rect.w, round.rect.h, round.radii), (144.0, 72.0, [18.0; 4]));
assert_eq!((round.fill, round.edge), (Some([230.0 / 255.0; 3]), Some((1.0, [1.0, 0.0, 0.0], false))));
// Two corners alternate: the first is drawn top-left and bottom-right.
let mixed = at(1.2).expect("the box with two corners given");
assert_eq!((mixed.radii, mixed.inverted), ([7.2, 14.4, 7.2, 14.4], [false, true, false, true]));
assert_eq!(at(2.4).expect("the huge radius").radii, [36.0; 4], "at most half the shorter side");
assert!(at(3.6).is_none() && at(4.8).is_none(), "hidden corners and unlike edges keep a square box");
let fill_only = at(6.0).expect("a fill with hidden edges is rounded too");
assert_eq!((fill_only.fill.is_some(), fill_only.edge), (true, None));
let shape = at(7.2).expect("a rectangle drawn as a value");
assert!((shape.radii[0] - 5.08 * 72.0 / 25.4).abs() < 1e-9 && shape.edge.is_some());
// The square boxes are drawn as before: edges as lines.
let lines_at = |y: f64| {
form.pages[0]
.items
.iter()
.filter(|i| matches!(i, Item::Line { from, .. } if from.1 >= 36.0 + y * 72.0 - 1.0 && from.1 <= 36.0 + (y + 1.0) * 72.0 + 1.0))
.count()
};
assert_eq!((lines_at(3.6), lines_at(4.8)), (4, 2));
}
/// Corners not listed are drawn the way edges are, from the corner on the same side, as
/// readers draw them (XFA 3.3 p. 38 gives the order top-left, top-right, bottom-right,
/// bottom-left, and says the last corner listed is reused): one serves all four, two
/// alternate, three reuse the second for the bottom-left.
#[test]
fn corners_not_listed_follow_the_edge_pattern() {
let radii = |corners: &str| {
let body = format!(
r#"<subform name="body" layout="position" w="7.5in" h="9in"><draw name="d" x="0in" y="0in" w="2in" h="1in"><value><text>d</text></value><border><edge/>{corners}</border></draw></subform>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
rounded(&form.pages[0]).first().map(|r| r.radii)
};
let (round, square) = (r#"<corner radius="0.25in"/>"#, r#"<corner/>"#);
assert_eq!(radii(&format!("{round}{square}")), Some([18.0, 0.0, 18.0, 0.0]), "round top-left and bottom-right");
assert_eq!(radii(&format!("{square}{round}")), Some([0.0, 18.0, 0.0, 18.0]));
assert_eq!(
radii(r#"<corner radius="5pt"/><corner radius="10pt"/><corner radius="15pt"/>"#),
Some([5.0, 10.0, 15.0, 10.0]),
"the second serves the bottom-left"
);
assert_eq!(radii(round), Some([18.0; 4]));
for (listed, sides) in [(1, [0, 0, 0, 0]), (2, [0, 1, 0, 1]), (3, [0, 1, 2, 1]), (4, [0, 1, 2, 3])] {
assert_eq!(std::array::from_fn::<_, 4, _>(|i| crate::parse::drawn_side(listed, i)), sides.map(Some), "{listed}");
}
assert_eq!(crate::parse::drawn_side(0, 2), None);
}
/// A rounded box a page break cuts keeps its rounded corners on each page, square where it was
/// cut, and its edge stops there instead of closing across the cut.
#[test]
fn a_rounded_box_cut_by_a_page_break_keeps_its_corners_on_each_page() {
// A 12-inch box in a 10-inch content area: it is cut at the area's bottom.
let body = r#"<subform name="body" layout="tb" w="7.5in"><subform name="tall" layout="position" w="7.5in" h="12in"><border><edge/><corner radius="0.25in"/></border><draw name="note" x="0in" y="0in" w="2in" h="0.3in"><value><text>Note</text></value></draw></subform></subform>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
assert_eq!(form.pages.len(), 2);
let (first, last) = (rounded(&form.pages[0]), rounded(&form.pages[1]));
assert_eq!((first.len(), last.len()), (1, 1), "{first:?} {last:?}");
assert_eq!((first[0].radii, first[0].open_top, first[0].open_bottom), ([18.0, 18.0, 0.0, 0.0], false, true));
assert_eq!((last[0].radii, last[0].open_top, last[0].open_bottom), ([0.0, 0.0, 18.0, 18.0], true, false));
assert!((first[0].rect.h + last[0].rect.h - 12.0 * 72.0).abs() < 0.01, "the two parts make the whole box");
}
/// A rounded box is written as one path: filled along its curves, then edged half its width
/// inside, the curves as quarter circles. An inverted corner curves into the box, and the edge
/// of a box a page break cut doesn't close across the cut.
#[test]
fn rounded_boxes_are_written_as_curved_paths() {
use crate::layout::Rounded;
// A 2-by-1-inch box at the page's top left, on a page 792pt tall.
let shape = |inverted: [bool; 4], edge: bool, open: (bool, bool)| Rounded {
rect: Rect::new(36.0, 36.0, 144.0, 72.0),
radii: [18.0; 4],
inverted,
fill: Some([0.9, 0.9, 0.9]),
edge: edge.then_some((2.0, [1.0, 0.0, 0.0], false)),
open_top: open.0,
open_bottom: open.1,
};
let content = |r: Rounded| crate::pdf::rounded(&r, 792.0);
let ops = content(shape([false; 4], true, (false, false)));
// The fill: from the top-left corner's start, a quarter circle to (54, 36), closed.
assert!(ops.contains("0.9 0.9 0.9 rg 36 738 m 36 747.941 44.059 756 54 756 c "), "{ops}");
assert!(ops.contains(" h f\n"), "{ops}");
// The edge: 1pt inside, the corners 1pt tighter.
assert!(ops.contains("q 1 0 0 RG 2 w 37 738 m 37 747.389 44.611 755 54 755 c "), "{ops}");
assert!(ops.contains(" h S Q\n"), "{ops}");
// Inverted: the curve bends towards the box's inside.
let inv = content(shape([true; 4], false, (false, false)));
assert!(inv.contains("36 738 m 45.941 738 54 746.059 54 756 c "), "{inv}");
// Cut at the bottom: the edge runs from the bottom left round the top and back down, open.
let cut = content(Rounded { radii: [18.0, 18.0, 0.0, 0.0], ..shape([false; 4], true, (false, true)) });
let edge = cut.lines().find(|l| l.contains(" RG ")).unwrap_or_default();
assert!(edge.starts_with("q 1 0 0 RG 2 w 37 685 m 37 738 l ") && edge.ends_with(" 179 685 l S Q") && !edge.contains(" h "), "{edge}");
}
/// A flowed subform without a fixed height gets its border and fill round all it takes, margins
/// included, drawn under its content; a flowed table too. One a page break cuts between its
/// children gets a closed border round its part on each page, its bottom margin ending the first
/// part and its top margin starting the next, as another viewer draws it on a synthetic form. One
/// holding an item that doesn't fit on its page keeps no border, and the layout says so.
#[test]
fn a_flowed_subform_is_drawn_with_its_border_under_its_content() {
let field = |name: &str| format!(r#"<field name="{name}" w="3in" h="0.5in"><ui><textEdit/></ui></field>"#);
let boxed = |inner: &str| {
format!(
r#"<subform name="box" layout="tb" w="7.5in"><border><edge thickness="1pt"/><fill><color value="230,230,230"/></fill></border><margin topInset="0.1in" bottomInset="0.2in"/>{inner}</subform>"#
)
};
let lay = |body: &str| {
layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"<subform name="body" layout="tb" w="7.5in">{body}</subform>"#))).unwrap()
};
// Two half-inch fields between a tenth and a fifth of an inch of margin: 1.3in from the top.
let form = lay(&boxed(&(field("a") + &field("b"))));
let items = &form.pages[0].items;
let fill = items.iter().position(|i| matches!(i, Item::Fill { .. })).expect("the subform's fill");
let Some(Item::Fill { rect, .. }) = items.get(fill) else { panic!("item {fill} is the fill") };
assert!((rect.y - 36.0).abs() < 0.01 && (rect.h - 1.3 * 72.0).abs() < 0.01 && (rect.w - 540.0).abs() < 0.01, "{rect:?}");
assert_eq!(items.iter().filter(|i| matches!(i, Item::Line { .. })).count(), 4, "its four edges");
let first_widget = items.iter().position(|i| matches!(i, Item::Widget(_))).unwrap();
assert!(fill < first_widget, "the fill is under the fields");
assert!(form.warnings.is_empty(), "{:?}", form.warnings);
// A flowed table's border too.
let table = r#"<subform name="grid" layout="table" columnWidths="2in 2in" w="4in"><border><edge/></border><subform name="row" layout="row"><draw name="c1" h="0.4in"><value><text>One</text></value></draw><draw name="c2" h="0.4in"><value><text>Two</text></value></draw></subform></subform>"#;
let form = lay(table);
assert_eq!(form.pages[0].items.iter().filter(|i| matches!(i, Item::Line { .. })).count(), 4, "{:?}", form.pages[0].items);
// Thirty fields: 19 fit the first page after the top margin, 11 go to the second.
let many: String = (0..30).map(|i| field(&format!("f{i}"))).collect();
let form = lay(&boxed(&many));
assert_eq!(form.pages.len(), 2);
let fills = |page: usize| -> Vec<Rect> {
form.pages[page].items.iter().filter_map(|i| if let Item::Fill { rect, .. } = i { Some(*rect) } else { None }).collect()
};
let (first, second) = (fills(0), fills(1));
assert_eq!((first.len(), second.len()), (1, 1), "a part on each page");
// Page 1: from the top (36) past 0.1in of margin and 19 fields, then 0.2in of margin.
assert!((first[0].y - 36.0).abs() < 0.01 && (first[0].bottom() - (36.0 + 7.2 + 19.0 * 36.0 + 14.4)).abs() < 0.01, "{:?}", first[0]);
// Page 2: the top margin again, 11 fields, the bottom margin.
assert!((second[0].y - 36.0).abs() < 0.01 && (second[0].bottom() - (36.0 + 7.2 + 11.0 * 36.0 + 14.4)).abs() < 0.01, "{:?}", second[0]);
let lines = |page: usize| form.pages[page].items.iter().filter(|i| matches!(i, Item::Line { .. })).count();
assert_eq!((lines(0), lines(1)), (4, 4), "each part's border is closed");
let f19 = form.pages[1].items.iter().find_map(|i| if let Item::Widget(w) = i { (w.name == "f19").then_some(w.rect) } else { None }).unwrap();
assert!((f19.y - 43.2).abs() < 0.01, "the second part starts after the top margin: {}", f19.y);
assert!(form.warnings.is_empty(), "{:?}", form.warnings);
// A bottom margin that would run past the content area stops at its edge: 39 quarter-inch
// fields end at 738, and 0.4in more would reach 766.8, past 756.
let quarter: String = (0..39).map(|i| format!(r#"<field name="q{i}" w="3in" h="0.25in"><ui><textEdit/></ui></field>"#)).collect();
let low = format!(r#"<subform name="box" layout="tb" w="7.5in"><border><edge/><fill/></border><margin bottomInset="0.4in"/>{quarter}</subform>"#);
let form = lay(&low);
let edge = form.pages[0].items.iter().find_map(|i| if let Item::Fill { rect, .. } = i { Some(rect.bottom()) } else { None }).unwrap();
assert!((edge - 756.0).abs() < 0.01, "the box ends at the content area's bottom: {edge}");
// The margins come back without a border too.
let bare = format!(r#"<subform name="box" layout="tb" w="7.5in"><margin topInset="0.1in" bottomInset="0.2in"/>{many}</subform>"#);
let form = lay(&bare);
let f19 = form.pages[1].items.iter().find_map(|i| if let Item::Widget(w) = i { (w.name == "f19").then_some(w.rect) } else { None }).unwrap();
assert!((f19.y - 43.2).abs() < 0.01, "{}", f19.y);
// A text of its own longer than a page, cut across pages: no border, one warning.
let long = format!(
r#"<draw name="long" w="7in"><font typeface="Arial" size="10pt"/><value><text>{}</text></value></draw>"#,
"A line of the long text.\n".repeat(80)
);
let form = lay(&boxed(&(field("a") + &long)));
assert!(form.pages.len() >= 2, "the long text runs onto another page");
assert!(form.pages.iter().all(|p| !p.items.iter().any(|i| matches!(i, Item::Fill { .. }))), "no fill drawn");
assert_eq!(form.warnings.iter().filter(|w| w.contains("bordered section")).count(), 1, "{:?}", form.warnings);
// A field that fits a fresh page (720pt) but not after the 7.2pt top margin: the margin
// gives way, so the field ends at the content area's bottom, inside the second part.
let tall = r#"<field name="tall" w="3in" h="715pt"><ui><textEdit/></ui></field>"#;
let form = lay(&boxed(&(field("a") + tall)));
assert_eq!(form.pages.len(), 2);
let tall = form.pages[1].items.iter().find_map(|i| if let Item::Widget(w) = i { (w.name == "tall").then_some(w.rect) } else { None }).unwrap();
assert!(tall.bottom() <= 756.01, "the field stays in the content area: {tall:?}");
let part = form.pages[1].items.iter().find_map(|i| if let Item::Fill { rect, .. } = i { Some(*rect) } else { None }).expect("the second part");
assert!(part.y <= tall.y + 0.01 && part.bottom() >= tall.bottom() - 0.01, "the border holds the field: {part:?} {tall:?}");
assert!(form.warnings.is_empty(), "{:?}", form.warnings);
// A section that starts near a page's bottom, where its first field doesn't fit: the field
// moves to the next page whole, and the border starts there with it, none left behind.
let spacer = r#"<field name="spacer" w="3in" h="684pt"><ui><textEdit/></ui></field>"#;
let form = lay(&format!("{spacer}{}", boxed(&(field("a") + &field("b")))));
assert_eq!(form.pages.len(), 2);
let fills = |page: usize| -> Vec<Rect> {
form.pages[page].items.iter().filter_map(|i| if let Item::Fill { rect, .. } = i { Some(*rect) } else { None }).collect()
};
assert!(fills(0).is_empty(), "no border left behind on page 1: {:?}", fills(0));
let moved = fills(1);
assert!(moved.len() == 1 && (moved[0].y - 36.0).abs() < 0.01 && (moved[0].h - (7.2 + 2.0 * 36.0 + 14.4)).abs() < 0.01, "{moved:?}");
assert!(form.warnings.is_empty(), "{:?}", form.warnings);
// The same field first in the section, at the top of the page: after the section's own top
// margin it runs past the bottom, so the section has no border round it, and says so.
let form = lay(&boxed(r#"<field name="tall" w="3in" h="715pt"><ui><textEdit/></ui></field>"#));
assert!(form.pages.iter().all(|p| !p.items.iter().any(|i| matches!(i, Item::Fill { .. }))), "no fill drawn");
assert_eq!(form.warnings.iter().filter(|w| w.contains("bordered section")).count(), 1, "{:?}", form.warnings);
}
/// A flowed table a page break cuts between its rows gets a closed border round its part on
/// each page, as a flowed subform does: its margins repeat, and its overflow leader starts the
/// second part after the top margin.
#[test]
fn a_flowed_table_cut_between_its_rows_keeps_its_border_on_each_page() {
let row = |name: &str, text: &str| {
format!(
r#"<subform name="{name}" layout="row"><draw name="{name}a" h="0.3in"><value><text>{text}</text></value></draw><draw name="{name}b" h="0.3in"><value><text>-</text></value></draw></subform>"#
)
};
let rows: String = (0..40).map(|i| row(&format!("r{i}"), &format!("Row {i}"))).collect();
let table = format!(
r#"<subform name="grid" layout="table" columnWidths="2in 2in" w="4in"><border><edge/><fill><color value="230,230,230"/></fill></border><margin topInset="0.1in" bottomInset="0.2in"/><overflow leader="head"/>{}{rows}</subform>"#,
row("head", "Head")
);
let body = format!(r#"<subform name="body" layout="tb" w="7.5in">{table}</subform>"#);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
assert_eq!(form.pages.len(), 2);
let fills = |page: usize| -> Vec<Rect> {
form.pages[page].items.iter().filter_map(|i| if let Item::Fill { rect, .. } = i { Some(*rect) } else { None }).collect()
};
let lines = |page: usize| form.pages[page].items.iter().filter(|i| matches!(i, Item::Line { .. })).count();
let (first, second) = (fills(0), fills(1));
assert_eq!((first.len(), second.len()), (1, 1), "a part on each page");
assert_eq!((lines(0), lines(1)), (4, 4), "each part's border is closed");
// Page 1: 0.1in of margin, the leader and 32 rows of 0.3in fill the area to its bottom.
assert!((first[0].y - 36.0).abs() < 0.01 && (first[0].bottom() - 756.0).abs() < 0.01, "{:?}", first[0]);
// Page 2: the top margin again, the leader, the other 8 rows, the bottom margin.
assert!((second[0].y - 36.0).abs() < 0.01 && (second[0].bottom() - (36.0 + 7.2 + 9.0 * 21.6 + 14.4)).abs() < 0.01, "{:?}", second[0]);
let head = form.pages[1].items.iter().find_map(|i| if let Item::Text(t) = i { (t.text == "Head").then_some(t.baseline) } else { None });
assert!(head.is_some_and(|b| b > 43.2 && b < 64.8), "the leader starts the second part after its top margin: {head:?}");
assert!(form.warnings.is_empty(), "{:?}", form.warnings);
}
/// A flowed table's overflow leader and the row that moved are given room together on the new
/// page; a leader and row too tall for any page, and a first row taller than its page, cost the
/// table its border, with the warning, rather than a border round what runs off the page.
#[test]
fn a_tables_leader_and_oversized_rows_fit_its_border_or_lose_it() {
let row = |name: &str, h: &str| {
format!(r#"<subform name="{name}" layout="row"><draw name="{name}a" h="{h}"><value><text>{name}</text></value></draw></subform>"#)
};
let table = |rows: &str| {
format!(
r#"<subform name="body" layout="tb" w="7.5in"><subform name="grid" layout="table" columnWidths="3in" w="3in"><border><edge/><fill/></border><margin topInset="0.1in"/><overflow leader="head"/>{}{rows}</subform></subform>"#,
row("head", "0.3in")
)
};
let lay = |rows: &str| layout_xml(&one_area_form(r#"layout="tb""#, &table(rows))).unwrap();
let fills = |form: &Form, page: usize| -> Vec<Rect> {
form.pages[page].items.iter().filter_map(|i| if let Item::Fill { rect, .. } = i { Some(*rect) } else { None }).collect()
};
let small: String = (0..10).map(|i| row(&format!("r{i}"), "0.3in")).collect();
// A 695pt row after ten small ones moves; it and the 21.6pt leader leave 3.4pt of the 720pt
// page for the top margin, so the row ends at the content area's bottom, in the border.
let form = lay(&(small.clone() + &row("big", "695pt")));
assert_eq!(form.pages.len(), 2);
let part = fills(&form, 1);
assert!(part.len() == 1 && (part[0].y - 36.0).abs() < 0.01 && (part[0].bottom() - 756.0).abs() < 0.01, "{part:?}");
assert!(form.warnings.is_empty(), "{:?}", form.warnings);
// 710pt and the leader don't fit any page: no border, one warning.
let form = lay(&(small + &row("big", "710pt")));
assert!(form.pages.iter().enumerate().all(|(p, _)| fills(&form, p).is_empty()), "no fill drawn");
assert_eq!(form.warnings.iter().filter(|w| w.contains("bordered section")).count(), 1, "{:?}", form.warnings);
// A first row taller than the page: no border round it, one warning.
let form = lay(&row("tall", "800pt"));
assert!(fills(&form, 0).is_empty(), "{:?}", fills(&form, 0));
assert_eq!(form.warnings.iter().filter(|w| w.contains("bordered section")).count(), 1, "{:?}", form.warnings);
}
/// A child's own page break (breakBefore, breakAfter) breaks the flowed subform around it as a
/// break between children does: a closed part on each page, no warning.
#[test]
fn a_childs_page_break_keeps_the_border_around_it_on_each_page() {
let field = |name: &str| format!(r#"<field name="{name}" w="3in" h="0.5in"><ui><textEdit/></ui></field>"#);
let body = format!(
r#"<subform name="body" layout="tb" w="7.5in"><subform name="box" layout="tb" w="7.5in"><border><edge/><fill/></border><margin topInset="0.1in" bottomInset="0.2in"/>{}<subform name="s1" layout="tb"><breakBefore targetType="pageArea"/>{}</subform><subform name="s2" layout="tb"><breakAfter targetType="pageArea"/>{}</subform>{}</subform></subform>"#,
field("a"),
field("b"),
field("c"),
field("d")
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
assert_eq!(form.pages.len(), 3, "a, then b and c, then d");
for (page, fields) in [(0, 1.0), (1, 2.0), (2, 1.0)] {
let fills: Vec<Rect> =
form.pages[page].items.iter().filter_map(|i| if let Item::Fill { rect, .. } = i { Some(*rect) } else { None }).collect();
let lines = form.pages[page].items.iter().filter(|i| matches!(i, Item::Line { .. })).count();
assert_eq!((fills.len(), lines), (1, 4), "page {}: one closed part", page + 1);
// The top margin, its fields, the bottom margin.
assert!((fills[0].y - 36.0).abs() < 0.01 && (fills[0].h - (7.2 + fields * 36.0 + 14.4)).abs() < 0.01, "page {}: {:?}", page + 1, fills[0]);
}
assert!(form.warnings.is_empty(), "{:?}", form.warnings);
}
#[test]
fn a_page_break_keeps_a_fields_border_with_the_field() {
// 6in of heading, then a bordered 5in field: it doesn't fit the 10in area and moves to
// the next page whole, leaving no piece of its border behind.
let body = r#"<subform name="body" layout="lr-tb" w="7.5in">
<draw name="head" w="7.5in" h="6in"><value><text>Head</text></value></draw>
<field name="f0" w="7.5in" h="5in"><border><edge/><fill><color value="230,230,230"/></fill></border><ui><textEdit multiLine="1"/></ui></field>
<field name="f1" w="7.5in" h="0.4in"><ui><textEdit/></ui></field>
</subform>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
assert_paginated(&form, 2, 2);
let below_head = |it: &&Item| match it {
Item::Fill { rect, .. } => rect.bottom() > 36.0 + 432.0 + 1.0,
Item::Line { from, to, .. } => from.1.max(to.1) > 36.0 + 432.0 + 1.0,
_ => false,
};
assert_eq!(form.pages[0].items.iter().filter(below_head).count(), 0, "{:?}", form.pages[0].items);
assert!(
form.pages[1].items.iter().any(|it| matches!(it, Item::Fill { rect, .. } if (rect.y - 36.0).abs() < 0.01 && (rect.h - 360.0).abs() < 0.01))
);
}
#[test]
fn text_too_long_for_its_fixed_height_is_drawn_smaller_instead_of_over_what_follows() {
let words = "certification statement wording ".repeat(12);
let body = format!(
r#"<draw name="note" w="7.5in" h="0.3in"><font typeface="Arial" size="8pt"/><value><text>{words}</text></value></draw>
<draw name="short" w="7.5in" h="0.3in"><font typeface="Arial" size="8pt"/><value><text>Short</text></value></draw>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let spans: Vec<&crate::text::Span> = form.pages[0].items.iter().filter_map(|i| if let Item::Text(s) = i { Some(s) } else { None }).collect();
let (short, note): (Vec<_>, Vec<_>) = spans.into_iter().partition(|s| s.text == "Short");
// Three lines at 8pt need 27.6pt; the box is 21.6pt high.
assert!(note.iter().all(|s| s.face.size < 8.0 && s.face.size >= 5.6), "{:?}", note.iter().map(|s| s.face.size).collect::<Vec<_>>());
assert!(note.iter().all(|s| s.baseline <= 36.0 + 21.6 + 0.5), "{:?}", note.iter().map(|s| s.baseline).collect::<Vec<_>>());
assert!(note.iter().all(|s| s.x + s.face.width(&s.text) <= 36.0 + 540.0 + 0.5));
// Text that fits keeps its size.
assert!((short[0].face.size - 8.0).abs() < 1e-9);
}
#[test]
fn a_text_field_that_outgrows_a_page_continues_on_the_next_as_text() {
let long: String = (0..150).map(|i| format!("Line {i} of the notes.\n")).collect();
let form = layout_xml(&wrapped_form(&format!("<form><body><notes>{long}</notes><after>end</after></body></form>"))).unwrap();
assert!(form.pages.len() >= 3, "{} pages", form.pages.len());
assert!(form.warnings.iter().any(|w| w.starts_with("notes: its text is longer than a page")), "{:?}", form.warnings);
// Every line is there, in order, inside the content area of its page; no widget holds it.
let mut lines = Vec::new();
for (i, p) in form.pages.iter().enumerate() {
for it in &p.items {
if let Item::Text(s) = it
&& s.text.starts_with("Line ")
{
assert!(s.baseline > 36.0 && s.baseline <= 36.0 + 720.0 + 0.01, "page {}: {:?} at {}", i + 1, s.text, s.baseline);
lines.push(s.text.clone());
}
}
assert!(widgets(p).iter().all(|w| w.name != "notes"));
}
assert_eq!(lines, (0..150).map(|i| format!("Line {i} of the notes.")).collect::<Vec<_>>());
// What follows comes after the last line, on the last page.
let last = form.pages.last().unwrap();
let after = widgets(last).into_iter().find(|w| w.name == "after").unwrap();
let last_line = last.items.iter().filter_map(|it| if let Item::Text(s) = it { Some(s.baseline) } else { None }).fold(0.0, f64::max);
assert!(after.rect.y >= last_line - 0.01 && after.rect.bottom() <= 36.0 + 720.0 + 0.01, "{:?} after {last_line}", after.rect);
}
#[test]
fn the_form_packet_restores_the_presence_and_access_the_form_was_saved_with() {
// Three rows hidden in the template; a script showed the first two before the form was
// saved, and locked a field.
let row = |n: usize, presence: &str| {
format!(
r#"<subform name="row{n}" layout="lr-tb" w="7.5in"{presence}><field name="who" w="3in" h="0.4in"><ui><textEdit/></ui></field></subform>"#
)
};
let body = format!(
r#"<subform name="body" layout="lr-tb" w="7.5in">{}{}{}{}<subform name="rep" layout="lr-tb" w="7.5in"><occur max="-1"/><field name="x" w="3in" h="0.4in"><ui><textEdit/></ui></field></subform></subform>"#,
row(0, ""),
row(1, r#" presence="hidden""#),
row(2, r#" presence="hidden""#),
row(3, r#" presence="hidden""#)
);
let template = one_area_form(r#"layout="tb""#, &body);
let visible = |xdp: &str| -> Vec<String> { layout_xml(xdp).unwrap().pages.iter().flat_map(widgets).map(|w| w.som.clone()).collect() };
assert_eq!(visible(&template), ["form[0].body[0].row0[0].who[0]", "form[0].body[0].rep[0].x[0]"]);
let saved = r#"<form xmlns="http://www.xfa.org/schema/xfa-form/2.8/" checksum="x"><subform name="form">
<instanceManager name="_body"/>
<subform name="body">
<subform name="row0"><field name="who" access="readOnly"/></subform>
<subform name="row1" presence="visible"><field name="who" access="readOnly"><value override="1"/></field></subform>
<subform name="row2" presence="visible"/>
<subform name="row3" presence="hidden"/>
<subform name="rep"><field name="x"/></subform>
<subform name="rep" presence="hidden"><field name="x" access="readOnly"/></subform>
<subform name="nowhere" presence="hidden"/>
</subform>
<pageSet><pageArea name="page"/></pageSet>
</subform></form>
</xdp:xdp>"#;
let xdp = template.replace("</xdp:xdp>", saved);
assert_eq!(
visible(&xdp),
["form[0].body[0].row0[0].who[0]", "form[0].body[0].row1[0].who[0]", "form[0].body[0].row2[0].who[0]", "form[0].body[0].rep[0].x[0]"],
"a later instance of a repeating subform says nothing about the template's one"
);
let form = layout_xml(&xdp).unwrap();
let locked: Vec<bool> = form.pages.iter().flat_map(widgets).map(|w| w.read_only).collect();
assert_eq!(locked, [true, true, false, false]);
}
/// A subform without a height, flowed or positioned, is as tall as what it holds, whatever its
/// `minH`. XFA 3.3 p. 847 makes `minH` the minimum of a growable subform; this follows Adobe
/// Acrobat instead. IRCC's IMM 5257 (04-2022, visitor visa) ends its first page with section 10
/// (`MaritalStatus`), a positioned subform at `minH="58.274mm"` holding about 80pt, then an
/// office-use box: Acrobat draws the section as tall as its fields, the box after it on page 1
/// (5 pages); stretched to 165pt, the section pushed the box onto a page of its own.
#[test]
fn a_subform_is_as_tall_as_its_content_whatever_its_minimum_height() {
// A bar with a stale 3in `minH` holds one 0.2in line; the row after it follows directly.
let body = |bar: &str| {
format!(
r#"<subform name="body" layout="lr-tb" w="7.5in"><subform name="bar" {bar} w="7.5in" minH="3in"><draw w="7.5in" h="0.2in"><value><text>Attachments</text></value></draw></subform><field name="who" w="3in" h="0.4in"><ui><textEdit/></ui></field></subform>"#
)
};
let top = |bar: &str| {
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body(bar))).unwrap();
let w = widgets(&form.pages[0]);
w[0].rect.y
};
let flowed = top(r#"layout="lr-tb""#);
assert!((top(r#"layout="tb""#) - flowed).abs() < 0.01);
assert!((top("") - flowed).abs() < 0.01, "positioned: {} against {flowed}", top(""));
}
/// The cases around a positioned subform's `minH`: a `minH` below the content, content taller
/// than `minH`, a `minH` above the content, a fixed `h` (alone and with a `minH` below it), and
/// hidden children (which take no room). A table row, which no form we test gives a `minH`
/// without an `h`, keeps its `minH` as XFA 3.3 p. 847 (subform, `minH`) says.
#[test]
fn a_positioned_subform_takes_its_content_height_and_a_row_keeps_its_minimum() {
// The field after a positioned 7.5in-wide bar starts where the bar ends.
let after = |bar_attrs: &str, content: &str| {
let body = format!(
r#"<subform name="body" layout="lr-tb" w="7.5in"><subform name="bar" w="7.5in" {bar_attrs}>{content}</subform><field name="who" w="3in" h="0.4in"><ui><textEdit/></ui></field></subform>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
widgets(&form.pages[0])[0].rect.y
};
let line = |h: &str| format!(r#"<draw w="7.5in" h="{h}"><value><text>Line</text></value></draw>"#);
let bare = after("", &line("0.2in"));
let inch = 72.0;
// A `minH` below the content, and content taller than the `minH`: the content's height.
assert!((after(r#"minH="0.1in""#, &line("0.2in")) - bare).abs() < 0.01);
assert!((after(r#"minH="0.1in""#, &line("1in")) - after("", &line("1in"))).abs() < 0.01);
assert!(after("", &line("1in")) - bare > 0.7 * inch, "taller content pushes the field down");
// A `minH` above the content: still the content's height, not the 3in.
let above = after(r#"minH="3in""#, &line("0.2in"));
assert!((above - bare).abs() < 0.01, "{above} against {bare}");
assert!((after(r#"minH="3in""#, &line("1in")) - after("", &line("1in"))).abs() < 0.01);
// A fixed `h` is the height, whatever the content.
assert!((after(r#"h="2in""#, &line("0.2in")) - after(r#"h="2in""#, &line("1in"))).abs() < 0.01);
assert!(after(r#"h="2in""#, &line("0.2in")) - bare > 1.7 * inch, "h=2in, not the 0.2in content");
let fixed = after(r#"h="2in" minH="1in""#, &line("0.2in"));
assert!((fixed - after(r#"h="2in""#, &line("0.2in"))).abs() < 0.01, "a minH below h changes nothing: {fixed}");
// A hidden child takes no room.
let hidden = format!(r#"{}<draw w="7.5in" h="2in" presence="hidden"><value><text>Hidden</text></value></draw>"#, line("0.2in"));
assert!((after(r#"minH="3in""#, &hidden) - bare).abs() < 0.01, "{} against {bare}", after(r#"minH="3in""#, &hidden));
// A table row keeps its `minH`: one holding a 0.2in cell with `minH="3in"` is 3in tall.
let after_table = |row_min_h: &str| {
let body = format!(
r#"<subform name="body" layout="tb" w="7.5in"><subform name="grid" layout="table" columnWidths="2in"><subform name="row" layout="row" {row_min_h}><draw h="0.2in"><value><text>One</text></value></draw></subform></subform><field name="who" w="3in" h="0.4in"><ui><textEdit/></ui></field></subform>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
widgets(&form.pages[0])[0].rect.y
};
let grown = after_table(r#"minH="3in""#) - after_table("");
assert!((grown - 2.8 * inch).abs() < 0.01, "the row grew by {grown}pt");
}
#[test]
fn a_caption_beside_a_check_box_wraps_in_its_reserve() {
// A 7.5in check box whose right-hand caption reserves 6.5in: two lines of text, not one or
// two words to a line in the 1in the box keeps. The field after it follows directly.
let words = "Applicant does not authorize the office to permit a participating office access to the application as filed. ".repeat(2);
let body = format!(
r#"<subform name="body" layout="tb" w="7.5in"><field name="opt" w="7.5in" minH="0.3in"><ui><checkButton/></ui><caption placement="right" reserve="6.5in"><value><text>{words}</text></value></caption></field><field name="who" w="3in" h="0.4in"><ui><textEdit/></ui></field></subform>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let w = widgets(&form.pages[0]);
let gap = w[1].rect.y - w[0].rect.y;
assert!(gap < 72.0, "the check box took {gap}pt");
}
#[test]
fn the_form_packet_restores_a_caption_a_script_changed() {
let body = r#"<subform name="body" layout="tb" w="7.5in"><field name="bar" w="2in" h="0.3in"><ui><button/></ui><caption><value><text>Show Bar</text></value></caption></field></subform>"#;
let template = one_area_form(r#"layout="tb""#, body);
let caption = |xdp: &str| match &widgets(&layout_xml(xdp).unwrap().pages[0])[0].kind {
WidgetKind::Button { caption } => caption.clone(),
other => panic!("{other:?}"),
};
assert_eq!(caption(&template), "Show Bar");
let saved = r#"<form xmlns="http://www.xfa.org/schema/xfa-form/2.8/"><subform name="form"><subform name="body">
<field name="bar"><caption><value><text>Hide Bar</text></value></caption></field>
</subform></subform></form>
</xdp:xdp>"#;
assert_eq!(caption(&template.replace("</xdp:xdp>", saved)), "Hide Bar");
}
#[test]
fn a_text_field_without_a_border_of_its_own_has_no_box() {
let body = r#"<subform name="body" layout="tb" w="7.5in"><field name="plain" w="3in" h="0.4in"><ui><textEdit/></ui></field><field name="boxed" w="3in" h="0.4in"><ui><textEdit><border><edge/></border></textEdit></ui></field><field name="tick" w="3in" h="0.4in"><ui><checkButton/></ui></field></subform>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
let shapes: Vec<BorderShape> = widgets(&form.pages[0]).iter().map(|w| w.border.shape).collect();
assert_eq!(shapes, [BorderShape::None, BorderShape::Full, BorderShape::Full]);
}
/// One measured check box: its name, width, box size, check box children, field children, and
/// where its box was drawn (x and y in inches from the field's top left).
type CheckCase<'a> = (&'a str, &'a str, Option<&'a str>, String, String, f64, f64);
/// A check box field for the placement tests: `extra` holds its margin, paragraph and caption,
/// `ui` the check box's own children, and `size` its box size (none for the default 10pt).
fn placed_check(name: &str, x: f64, y: f64, w: &str, size: Option<&str>, ui: &str, extra: &str) -> String {
let size = size.map(|s| format!(r#" size="{s}""#)).unwrap_or_default();
format!(
r#"<field name="{name}" x="{x}in" y="{y}in" w="{w}" h="0.6in"><ui><checkButton{size}>{ui}</checkButton></ui><font typeface="Arial" size="9pt"/>{extra}<items><integer>1</integer><integer>0</integer></items></field>"#
)
}
/// Where a check box is drawn inside its field, measured in inches from the field's top left in
/// another viewer on synthetic probes: with no caption the box sits at the right of the content
/// area whatever the paragraph's alignment, beside a reserved caption the alignment places it,
/// a caption without a reserve takes all the box leaves, and the box's own margin doesn't move it.
#[test]
fn a_check_box_sits_where_its_margins_caption_and_alignment_put_it() {
let m = |a: &str| format!("<margin {a}/>");
let p = |a: &str| format!("<para {a}/>");
let cap = |a: &str, text: &str| format!(r#"<caption {a}><font typeface="Arial" size="9pt"/><value><text>{text}</text></value></caption>"#);
// (name, width, box size, check box children, field children, box x and y in inches)
let cases: Vec<CheckCase> = vec![
("none", "1.2in", Some("0.25in"), String::new(), String::new(), 0.95, 0.0),
("left_margin", "1.2in", Some("0.25in"), String::new(), m(r#"leftInset="0.3in""#), 0.95, 0.0),
("right_margin", "1.2in", Some("0.25in"), String::new(), m(r#"rightInset="0.3in""#), 0.65, 0.0),
("both_margins", "1.2in", Some("0.25in"), String::new(), m(r#"leftInset="0.1in" rightInset="0.4in""#), 0.55, 0.0),
("h_left", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="left""#), 0.95, 0.0),
("h_center", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="center""#), 0.95, 0.0),
("h_right", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="right""#), 0.95, 0.0),
("h_justify", "1.2in", Some("0.25in"), String::new(), p(r#"hAlign="justify""#), 0.95, 0.0),
("center_right_margin", "1.2in", Some("0.25in"), String::new(), m(r#"rightInset="0.3in""#) + &p(r#"hAlign="center""#), 0.65, 0.0),
("left_left_margin", "1.2in", Some("0.25in"), String::new(), m(r#"leftInset="0.3in""#) + &p(r#"hAlign="left""#), 0.95, 0.0),
("v_top_margin", "1.2in", Some("0.25in"), String::new(), m(r#"topInset="0.15in""#) + &p(r#"vAlign="top""#), 0.95, 0.15),
("v_middle_margin", "1.2in", Some("0.25in"), String::new(), m(r#"topInset="0.2in""#) + &p(r#"vAlign="middle""#), 0.95, 0.275),
("v_bottom_margin", "1.2in", Some("0.25in"), String::new(), m(r#"bottomInset="0.15in""#) + &p(r#"vAlign="bottom""#), 0.95, 0.2),
("v_bottom", "1.2in", Some("0.25in"), String::new(), p(r#"vAlign="bottom""#), 0.95, 0.35),
("cap_left_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left" reserve="0.5in""#, "Cap"), 0.5, 0.0),
("cap_right_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="right" reserve="0.5in""#, "Cap"), 0.0, 0.0),
(
"cap_left_reserve_center",
"1.5in",
Some("0.25in"),
String::new(),
cap(r#"placement="left" reserve="0.5in""#, "Cap") + &p(r#"hAlign="center""#),
0.875,
0.0,
),
(
"cap_left_reserve_right",
"1.5in",
Some("0.25in"),
String::new(),
cap(r#"placement="left" reserve="0.5in""#, "Cap") + &p(r#"hAlign="right""#),
1.25,
0.0,
),
(
"cap_left_reserve_middle",
"1.5in",
Some("0.25in"),
String::new(),
cap(r#"placement="left" reserve="0.5in""#, "Cap") + &p(r#"vAlign="middle""#),
0.5,
0.175,
),
(
"cap_right_reserve_center",
"1.5in",
Some("0.25in"),
String::new(),
cap(r#"placement="right" reserve="0.5in""#, "Cap") + &p(r#"hAlign="center""#),
0.375,
0.0,
),
("cap_top_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="top" reserve="0.25in""#, "Cap"), 0.0, 0.25),
("cap_bottom_reserve", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="bottom" reserve="0.25in""#, "Cap"), 0.0, 0.0),
(
"cap_hidden_reserve",
"1.5in",
Some("0.25in"),
String::new(),
cap(r#"placement="left" reserve="0.5in" presence="hidden""#, "Cap"),
1.25,
0.0,
),
("cap_empty_reserve", "1.5in", Some("0.25in"), String::new(), r#"<caption placement="left" reserve="0.5in"/>"#.to_string(), 0.5, 0.0),
("cap_left_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left""#, "Cap"), 1.25, 0.0),
("cap_left_auto_center", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left""#, "Cap") + &p(r#"hAlign="center""#), 1.25, 0.0),
("cap_right_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="right""#, "Cap"), 0.0, 0.0),
("cap_right_auto_middle", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="right""#, "Cap") + &p(r#"vAlign="middle""#), 0.0, 0.175),
("cap_top_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="top""#, "Cap"), 0.0, 0.35),
("cap_top_auto_center", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="top""#, "Cap") + &p(r#"hAlign="center""#), 0.625, 0.35),
("cap_bottom_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="bottom""#, "Cap"), 0.0, 0.0),
("cap_inline", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="inline""#, "Cap"), 1.25, 0.0),
("cap_hidden_auto", "1.5in", Some("0.25in"), String::new(), cap(r#"placement="left" presence="hidden""#, "Cap"), 1.25, 0.0),
("box_margin_left", "1.5in", Some("0.25in"), m(r#"leftInset="0.1in""#), String::new(), 1.25, 0.0),
(
"box_margin_all",
"1.5in",
Some("0.25in"),
m(r#"leftInset="0.1in" rightInset="0.1in" topInset="0.1in" bottomInset="0.1in""#),
String::new(),
1.25,
0.0,
),
("default_size", "1.2in", None, String::new(), String::new(), 1.2 - 10.0 / 72.0, 0.0),
("default_size_center", "1.2in", None, String::new(), p(r#"hAlign="center""#), 1.2 - 10.0 / 72.0, 0.0),
];
let fields: String = cases
.iter()
.enumerate()
.map(|(i, (name, w, size, ui, extra, _, _))| placed_check(name, (i % 4) as f64 * 1.8, (i / 4) as f64 * 0.8, w, *size, ui, extra))
.collect();
// The form in the measured case the probes started from (DD Form 2946's checklist boxes).
let cell = r#"<field name="cell" x="0in" y="8in" w="12.7mm" h="0.6in"><ui><checkButton size="4.9389mm"><border><edge/><fill/></border></checkButton></ui><margin leftInset="0mm" rightInset="3.556mm"/><para vAlign="middle"/><items><integer>1</integer><integer>0</integer></items></field>"#;
let body = format!(r#"<subform name="body" layout="position" w="7.5in" h="9in">{fields}{cell}</subform>"#);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let laid = widgets(&form.pages[0]);
let at = |name: &str| laid.iter().find(|w| w.name == name).map(|w| w.rect).unwrap_or_else(|| panic!("no widget {name}"));
// The content area starts half an inch in.
for (i, (name, _, size, _, _, x, y)) in cases.iter().enumerate() {
let r = at(name);
let (fx, fy) = (36.0 + (i % 4) as f64 * 1.8 * 72.0, 36.0 + (i / 4) as f64 * 0.8 * 72.0);
let s = if size.is_some() { 18.0 } else { 10.0 };
assert!((r.x - fx - x * 72.0).abs() < 0.01, "{name}: box x {} in, expected {x}", (r.x - fx) / 72.0);
assert!((r.y - fy - y * 72.0).abs() < 0.01, "{name}: box y {} in, expected {y}", (r.y - fy) / 72.0);
assert!((r.w - s).abs() < 0.01 && (r.h - s).abs() < 0.01, "{name}: box size {}x{}", r.w, r.h);
}
// Its box sits 4.2mm in, against its 3.556mm right margin, and in the middle of its height.
let r = at("cell");
let mm = 72.0 / 25.4;
assert!((r.x - 36.0 - (12.7 - 3.556 - 4.9389) * mm).abs() < 0.01, "cell box x {}", r.x - 36.0);
assert!((r.y - 36.0 - 8.0 * 72.0 - (0.6 * 72.0 - 4.9389 * mm) / 2.0).abs() < 0.01, "cell box y {}", r.y - 36.0 - 8.0 * 72.0);
}
/// Radio buttons in an exclusion group sit as check boxes do: at the right without a caption,
/// moved in by a right margin, and placed by the alignment or the caption beside a caption.
#[test]
fn a_radio_button_sits_where_a_check_box_would() {
let radio = |name: &str, x: f64, extra: &str| {
format!(
r#"<field name="{name}" x="{x}in" y="0in" w="1.5in" h="0.6in"><ui><checkButton size="0.25in" shape="round"/></ui><font typeface="Arial" size="9pt"/>{extra}<items><text>{name}</text></items></field>"#
)
};
let cap = |a: &str| format!(r#"<caption {a}><font typeface="Arial" size="9pt"/><value><text>Cap</text></value></caption>"#);
// (name, field children, box x and y in inches from the field's top left)
let cases = [
("plain", String::new(), 1.25, 0.0),
("right_margin", r#"<margin rightInset="0.3in"/>"#.to_string(), 0.95, 0.0),
("centered", r#"<para hAlign="center"/>"#.to_string(), 1.25, 0.0),
("cap_right_center", cap(r#"placement="right" reserve="0.5in""#) + r#"<para hAlign="center"/>"#, 0.375, 0.0),
("cap_left_auto", cap(r#"placement="left""#), 1.25, 0.0),
("cap_top_auto", cap(r#"placement="top""#), 0.0, 0.35),
];
let fields: String = cases.iter().enumerate().map(|(i, (name, extra, _, _))| radio(name, i as f64 * 1.6, extra)).collect();
let body = format!(
r#"<subform name="body" layout="position" w="7.5in" h="9in"><exclGroup name="group" x="0in" y="0in" w="9.6in" h="0.6in" layout="position">{fields}</exclGroup></subform>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let laid = widgets(&form.pages[0]);
for (i, (name, _, x, y)) in cases.iter().enumerate() {
let w = laid.iter().find(|w| w.name == *name).unwrap_or_else(|| panic!("no radio button {name}"));
assert!(matches!(w.kind, WidgetKind::Radio { .. }), "{name} is a radio button");
let fx = 36.0 + i as f64 * 1.6 * 72.0;
assert!((w.rect.x - fx - x * 72.0).abs() < 0.01, "{name}: box x {} in, expected {x}", (w.rect.x - fx) / 72.0);
assert!((w.rect.y - 36.0 - y * 72.0).abs() < 0.01, "{name}: box y {} in, expected {y}", (w.rect.y - 36.0) / 72.0);
}
}
/// A check box without a width is as wide as its box and caption, at least its minW, not the rest
/// of its group: two choices side by side in a positioned radio group keep their own boxes.
#[test]
fn a_radio_choice_without_a_width_is_as_wide_as_its_content() {
let choice = |name: &str, x: &str, item: &str| {
format!(
r#"<field name="{name}" x="{x}" y="0mm" h="5.906mm" minW="20.32mm"><ui><checkButton shape="round"/></ui><caption reserve="-5.08mm"><value><text>{name}</text></value><para hAlign="center"/></caption><font typeface="Arial" size="10pt"/><items><text>{item}</text></items></field>"#
)
};
let body = format!(
r#"<subform name="body" layout="position" w="7.5in" h="1in"><exclGroup name="pick" x="0mm" y="0mm" w="40.64mm">{}{}</exclGroup></subform>"#,
choice("Yes", "0mm", "Y"),
choice("No", "20.308mm", "N"),
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let laid = widgets(&form.pages[0]);
let x = |name: &str| laid.iter().find(|w| w.name == name).map(|w| w.rect.x - 36.0).unwrap_or_else(|| panic!("no radio button {name}"));
let mm = 72.0 / 25.4;
// A negative reserve (as Designer writes) sizes the caption to its text, so content is
// narrower than minW and each box sits at the right end of its own 20.32mm-wide choice.
assert!((x("Yes") - (20.32 * mm - 10.0)).abs() < 0.01, "Yes box at {} pt", x("Yes"));
assert!((x("No") - ((20.308 + 20.32) * mm - 10.0)).abs() < 0.01, "No box at {} pt", x("No"));
}
/// Without a width or minW, a check box is exactly its caption's reserve plus its box, whether
/// placed (its right-aligned box ends there) or flowed (two fit side by side in an lr-tb row).
#[test]
fn a_check_box_without_a_width_is_its_caption_and_box() {
let check = |name: &str, at: &str| {
format!(
r#"<field name="{name}" {at} h="0.25in"><ui><checkButton size="10pt"/></ui><caption reserve="0.5in"><value><text>{name}</text></value></caption><para hAlign="right"/><items><integer>1</integer><integer>0</integer></items></field>"#
)
};
let box_at = |body: String, name: &str| {
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
widgets(&form.pages[0]).iter().find(|w| w.name == name).map(|w| (w.rect.x - 36.0, w.rect.y - 36.0)).unwrap()
};
let placed = format!(r#"<subform name="body" layout="position" w="7.5in" h="1in">{}</subform>"#, check("placed", r#"x="0in" y="0in""#));
let (x, _) = box_at(placed, "placed");
assert!((x - 36.0).abs() < 0.01, "the box ends the 46pt field, after the 36pt caption: {x}");
let flowed = format!(r#"<subform name="body" layout="lr-tb" w="3in">{}{}</subform>"#, check("first", ""), check("second", ""));
let (x, y) = box_at(flowed, "second");
assert!((x - 82.0).abs() < 0.01 && y.abs() < 0.01, "the second check box follows the first on its row: ({x}, {y})");
}
/// A caption without a reserve leaves room for the box at the size it is drawn, a box larger than
/// its field shrinking to fit; and a field without a height is as tall as that caption drawn in
/// all the box leaves, not at some narrower width.
#[test]
fn a_check_box_caption_without_a_reserve_is_measured_as_it_is_drawn() {
let cap =
r#"<caption placement="left"><font typeface="Arial" size="9pt"/><value><text>Caption text running on one line</text></value></caption>"#;
let tall = r#"<field name="tall" x="0in" y="0in" w="1.5in" h="0.25in"><ui><checkButton size="0.75in"/></ui><font typeface="Arial" size="9pt"/>"#
.to_string()
+ cap
+ "<items><integer>1</integer><integer>0</integer></items></field>";
let form = layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"<subform name="body" layout="position" w="7.5in" h="1in">{tall}</subform>"#)))
.unwrap();
let r = widgets(&form.pages[0]).iter().find(|w| w.name == "tall").map(|w| w.rect).unwrap();
assert!((r.w - 18.0).abs() < 0.01, "the box shrinks to the field's height: {}", r.w);
assert!((r.x - 36.0 - 1.25 * 72.0).abs() < 0.01, "and still sits at the right: {} in", (r.x - 36.0) / 72.0);
let grows = r#"<field name="grows" w="3in"><ui><checkButton size="0.25in"/></ui><font typeface="Arial" size="9pt"/>"#.to_string()
+ cap
+ r#"<items><integer>1</integer><integer>0</integer></items></field><field name="next" w="3in" h="0.3in"><ui><textEdit/></ui></field>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, &format!(r#"<subform name="body" layout="tb" w="7.5in">{grows}</subform>"#))).unwrap();
let next = widgets(&form.pages[0]).iter().find(|w| w.name == "next").map(|w| w.rect).unwrap();
assert!((next.y - 36.0 - 18.0).abs() < 0.01, "a one-line caption beside the box keeps the field the box's height: {}", next.y - 36.0);
}
/// A caption without a reserve beside a check box takes all the room the box leaves, and starts
/// right after it; an inline caption has no text to run with and is not drawn.
#[test]
fn a_check_box_caption_without_a_reserve_takes_the_rest_of_the_field() {
let cap = |place: &str, text: &str| {
format!(r#"<caption placement="{place}"><font typeface="Arial" size="9pt"/><value><text>{text}</text></value></caption>"#)
};
let body = format!(
r#"<subform name="body" layout="position" w="7.5in" h="9in">{}{}{}{}</subform>"#,
placed_check("after", 0.0, 0.0, "1.5in", Some("0.25in"), "", &cap("right", "Right")),
placed_check("before", 2.0, 0.0, "1.5in", Some("0.25in"), "", &cap("left", "Left")),
placed_check("below", 4.0, 0.0, "1.5in", Some("0.25in"), "", &cap("bottom", "Below")),
placed_check("inline", 0.0, 1.0, "1.5in", Some("0.25in"), "", &cap("inline", "Inline")),
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let span = |t: &str| {
form.pages[0].items.iter().find_map(|i| match i {
Item::Text(s) if s.text == t => Some(s.clone()),
_ => None,
})
};
let right = span("Right").expect("the right caption is drawn");
assert!((right.x - 36.0 - 18.0).abs() < 0.01, "a right caption starts after the box: {}", right.x - 36.0);
let left = span("Left").expect("the left caption is drawn");
assert!((left.x - 36.0 - 2.0 * 72.0).abs() < 0.01, "a left caption starts at the field's left: {}", left.x - 36.0);
let below = span("Below").expect("the bottom caption is drawn");
assert!(below.baseline - 36.0 > 18.0, "a bottom caption is below the box: {}", below.baseline - 36.0);
assert!(span("Inline").is_none(), "an inline caption beside a check box is not drawn");
}
/// A caption reserve of zero sizes the caption to its content, as no reserve does: beside a check
/// box it takes the rest of the field, and before a text field it is as wide as its text.
#[test]
fn a_zero_caption_reserve_sizes_the_caption_as_none_does() {
let cap = |reserve: &str| {
format!(r#"<caption placement="right"{reserve}><font typeface="Arial" size="9pt"/><value><text>Right</text></value></caption>"#)
};
let text = |name: &str, y: &str, reserve: &str| {
format!(
r#"<field name="{name}" x="0in" y="{y}" w="3in" h="0.3in"><ui><textEdit/></ui><font typeface="Arial" size="9pt"/><caption placement="left"{reserve}><font typeface="Arial" size="9pt"/><value><text>Name</text></value></caption></field>"#
)
};
let body = format!(
r#"<subform name="body" layout="position" w="7.5in" h="9in">{}{}{}</subform>"#,
placed_check("zero", 0.0, 0.0, "1.5in", Some("0.25in"), "", &cap(r#" reserve="0""#)),
text("withZero", "1in", r#" reserve="0in""#),
text("without", "2in", ""),
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let right = form.pages[0].items.iter().find_map(|i| if let Item::Text(s) = i { (s.text == "Right").then_some(s.x) } else { None });
assert!(right.is_some_and(|x| (x - 36.0 - 18.0).abs() < 0.01), "the caption starts after the box: {right:?}");
let x_of = |name: &str| widgets(&form.pages[0]).iter().find(|w| w.name == name).map(|w| w.rect.x).unwrap();
assert!(x_of("withZero") > 36.0 + 1.0, "the caption takes its text's width: {}", x_of("withZero"));
assert!((x_of("withZero") - x_of("without")).abs() < 0.01, "as without a reserve: {} {}", x_of("withZero"), x_of("without"));
}
/// The terminal fields by full name, down the field tree.
fn full_names(doc: &Document) -> Vec<(String, Dict)> {
let root = doc.get(doc.root().unwrap());
let acro = doc.resolve(root.as_dict().unwrap().get(b"AcroForm").unwrap());
let mut todo: Vec<(Object, String)> =
doc.resolve(acro.as_dict().unwrap().get(b"Fields").unwrap()).as_array().unwrap().iter().map(|f| (f.clone(), String::new())).collect();
let mut out = Vec::new();
while let Some((f, prefix)) = todo.pop() {
let d = doc.resolve(&f).as_dict().unwrap().clone();
let t = d.get(b"T").map(|t| doc.resolve(t)).and_then(|t| t.as_string().map(|t| t.to_text()));
let name = match t {
Some(t) if prefix.is_empty() => t,
Some(t) => format!("{prefix}.{t}"),
None => prefix,
};
match d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()) {
Some(kids) if kids.iter().any(|k| doc.resolve(k).as_dict().is_some_and(|k| k.contains(b"T"))) => {
todo.extend(kids.into_iter().map(|k| (k, name.clone())));
}
_ => out.push((name, d)),
}
}
out
}
/// A laid-out signature field is named by its SOM path, under a generated field for each step
/// above it, as other viewers lay a dynamic form out again and find its signature by that name.
/// Boxes in one subform share those fields; a new layout replaces them rather than adding more;
/// taking the XFA out leaves them as ordinary fields.
#[test]
fn signature_fields_are_named_by_their_som_path() {
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">
<pageSet><pageArea name="page"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<subform name="body" layout="tb" w="7.5in">
<field name="name" w="3in" h="0.3in"><ui><textEdit/></ui></field>
<field name="sign" w="3in" h="1in"><ui><signature/></ui></field>
<field name="other" w="3in" h="1in"><ui><signature/></ui></field>
</subform>
<subform name="end" layout="tb" w="7.5in">
<field name="last" w="3in" h="1in"><ui><signature/></ui></field>
</subform>
</subform>
</template>
</xdp:xdp>
"##;
let mut doc = Document::open(Arc::new(shell(xdp))).unwrap();
let report = render_into(&mut doc).unwrap();
assert_eq!(report.fields, 4, "name and the three signature fields");
let doc = Document::open(Arc::new(write_incremental(&doc, &SaveOptions::default()).unwrap())).unwrap();
let check = |doc: &Document| {
let top: Vec<String> = pdfcraft_forms_free_fields(doc).into_iter().map(|(name, _)| name).collect();
assert_eq!(top.iter().filter(|n| *n == "form[0]").count(), 1, "one field for the root subform: {top:?}");
assert!(top.iter().any(|n| n == "name"), "other fields keep their names: {top:?}");
let named = full_names(doc);
for som in ["form[0].body[0].sign[0]", "form[0].body[0].other[0]", "form[0].end[0].last[0]"] {
let (_, d) = named.iter().find(|(name, _)| name == som).unwrap_or_else(|| panic!("{som} in {named:?}"));
assert_eq!(d.name(b"FT"), Some(b"Sig".as_slice()));
assert_eq!(fields_by_som(doc).get(som).map(String::as_str), Some(som), "the data finds it by its SOM path");
}
assert_eq!(named.len(), 4, "{named:?}");
};
check(&doc);
let body = |doc: &Document| {
let named = full_names(doc);
let parent = |som: &str| named.iter().find(|(name, _)| name == som).and_then(|(_, d)| d.get(b"Parent").and_then(Object::as_ref));
(parent("form[0].body[0].sign[0]"), parent("form[0].body[0].other[0]"))
};
let (a, b) = body(&doc);
assert!(a.is_some() && a == b, "the two boxes of one subform share its field");
// Laid out again: the same fields, not a second set.
let mut doc = doc;
let tpl = crate::script::template_of(&doc).unwrap();
rerender(&mut doc, &tpl).unwrap();
check(&doc);
// The XFA taken out: ordinary fields with the same names, without the private key.
strip(&mut doc).unwrap();
let named = full_names(&doc);
assert!(named.iter().any(|(name, _)| name == "form[0].end[0].last[0]"), "{named:?}");
let top = pdfcraft_forms_free_fields(&doc);
let node = top.iter().find(|(name, _)| name == "form[0]").map(|(_, d)| d.clone()).expect("the root subform's field");
assert!(!node.contains(NODE_KEY));
}
/// The terminal field named `full`, down the field tree.
fn field_ref(doc: &Document, full: &str) -> Option<pdfcraft_cos::ObjRef> {
let root = doc.get(doc.root()?);
let acro = doc.resolve(root.as_dict()?.get(b"AcroForm")?);
let mut todo: Vec<(pdfcraft_cos::ObjRef, String)> =
doc.resolve(acro.as_dict()?.get(b"Fields")?).as_array()?.iter().filter_map(Object::as_ref).map(|r| (r, String::new())).collect();
while let Some((r, prefix)) = todo.pop() {
let d = doc.get(r).as_dict()?.clone();
let t = d.get(b"T").map(|t| doc.resolve(t)).and_then(|t| t.as_string().map(|t| t.to_text())).unwrap_or_default();
let name = if prefix.is_empty() { t } else { format!("{prefix}.{t}") };
if name == full {
return Some(r);
}
let kids = d.get(b"Kids").map(|k| doc.resolve(k)).and_then(|k| k.as_array().cloned()).unwrap_or_default();
todo.extend(kids.iter().filter_map(Object::as_ref).map(|k| (k, name.clone())));
}
None
}
/// A box signed on a laid-out form stays signed when the form is laid out again (as after a
/// script adds a row): the new layout's field, named by the same SOM path, holds the same
/// signature and is locked, and the old field is gone from the AcroForm.
#[test]
fn a_signature_on_a_laid_out_box_survives_a_new_layout() {
let mut doc = Document::open(Arc::new(shell(&fields_template("")))).unwrap();
render_into(&mut doc).unwrap();
let som = "form[0].page1[0].sign[0]";
let old = field_ref(&doc, som).expect("the box");
// Signed as signing does it: a signature dictionary as the field's value, and a picture.
let mut sig = Dict::new();
sig.set(b"Type".to_vec(), Object::name("Sig"));
let sig = doc.add(Object::Dict(sig));
let picture = doc.add(Object::Stream(pdfcraft_cos::Stream::from_raw(Dict::new(), b"0 0 1 rg 0 0 10 10 re f".to_vec())));
doc.update_dict(old, |d| {
d.set(b"V".to_vec(), Object::Ref(sig));
let mut ap = Dict::new();
ap.set(b"N".to_vec(), Object::Ref(picture));
d.set(b"AP".to_vec(), Object::Dict(ap));
})
.unwrap();
let tpl = crate::script::template_of(&doc).unwrap();
rerender(&mut doc, &tpl).unwrap();
let new = field_ref(&doc, som).expect("still named by its SOM path");
assert_ne!(new, old, "a field of the new layout");
let d = doc.get(new).as_dict().unwrap().clone();
assert_eq!(d.get(b"V").and_then(Object::as_ref), Some(sig), "the same signature");
let shown = d.get(b"AP").map(|ap| doc.resolve(ap)).and_then(|ap| ap.as_dict().and_then(|ap| ap.get(b"N").and_then(Object::as_ref)));
assert_eq!(shown, Some(picture), "and the same picture");
assert!(matches!(&*doc.get(picture), Object::Stream(_)), "which is still in the file");
assert!(matches!(&*doc.get(sig), Object::Dict(_)), "as is the signature");
assert_eq!(d.int(b"Ff").unwrap_or(0) & 1, 1, "a signed box is not signed again");
let top = pdfcraft_forms_free_fields(&doc);
assert_eq!(top.iter().filter(|(name, _)| name == "form[0]").count(), 1, "the old fields are gone");
}
/// A box right in the form's root subform, signed and then laid out again, keeps its signature
/// and picture in the file: its field sits just under the one naming it, and the old fields that
/// give way to the new layout's (freed when this session made them) take nothing it still uses.
#[test]
fn a_signed_box_in_the_root_subform_keeps_its_picture_through_a_new_layout() {
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"><pageSet><pageArea name="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<field name="sign" w="3in" h="1in"><ui><signature/></ui></field>
</subform></template></xdp:xdp>"#;
let mut doc = Document::open(Arc::new(shell(xdp))).unwrap();
render_into(&mut doc).unwrap();
let som = "form[0].sign[0]";
let old = field_ref(&doc, som).expect("the box");
let sig = doc.add(Object::Dict(Dict::new()));
let picture = doc.add(Object::Stream(pdfcraft_cos::Stream::from_raw(Dict::new(), b"0 0 1 rg 0 0 10 10 re f".to_vec())));
doc.update_dict(old, |d| {
d.set(b"V".to_vec(), Object::Ref(sig));
let mut ap = Dict::new();
ap.set(b"N".to_vec(), Object::Ref(picture));
d.set(b"AP".to_vec(), Object::Dict(ap));
})
.unwrap();
let tpl = crate::script::template_of(&doc).unwrap();
rerender(&mut doc, &tpl).unwrap();
let new = field_ref(&doc, som).expect("still named by its SOM path");
let d = doc.get(new).as_dict().unwrap().clone();
let shown = d.get(b"AP").map(|ap| doc.resolve(ap)).and_then(|ap| ap.as_dict().and_then(|ap| ap.get(b"N").and_then(Object::as_ref)));
assert_eq!(shown, Some(picture));
assert!(matches!(&*doc.get(picture), Object::Stream(_)), "the picture is still in the file");
assert!(matches!(&*doc.get(sig), Object::Dict(_)), "and the signature");
}
/// A field of the same pass keeps a signature field named by its SOM path from repeating its
/// name, written before the box or after it: with a text field named `form[0]` (as a hostile
/// template may name one), the box keeps its own name and no two fields share one.
#[test]
fn a_signature_field_does_not_repeat_a_name_another_field_has() {
let text = r#"<field name="form[0]" w="3in" h="0.3in"><ui><textEdit/></ui></field>"#;
let sign = r#"<field name="sign" w="3in" h="1in"><ui><signature/></ui></field>"#;
for (first, second) in [(text, sign), (sign, text)] {
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">
<pageSet><pageArea name="page"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<subform name="body" layout="tb" w="7.5in">{first}{second}</subform>
</subform>
</template>
</xdp:xdp>
"##
);
let mut doc = Document::open(Arc::new(shell(&xdp))).unwrap();
render_into(&mut doc).unwrap();
let mut top: Vec<String> = pdfcraft_forms_free_fields(&doc).into_iter().map(|(name, _)| name).collect();
assert!(top.iter().any(|n| n == "sign"), "the box keeps its own name: {top:?}");
top.sort();
let len = top.len();
top.dedup();
assert_eq!(top.len(), len, "no name twice: {top:?}");
}
}
/// A caption without a font of its own is drawn in its field's font, not the font around the
/// field (XFA 3.3, "Formatting Text That Appears as Fixed or Variable Content", p. 43): text is
/// formatted by its containing element's font properties, inherited from an ancestor when it
/// has none. A caption font that names only some properties takes the rest from the field.
#[test]
fn a_caption_without_a_font_of_its_own_takes_its_fields() {
let field = |name: &str, caption_font: &str| {
format!(
r#"<field name="{name}" w="5in" h="0.4in"><ui><textEdit/></ui><font typeface="Arial" size="8pt"/><caption reserve="2in">{caption_font}<value><text>{name}:</text></value></caption></field>"#
)
};
let body = format!(
r#"<subform name="body" layout="tb" w="7.5in">{}{}{}</subform>"#,
field("plain", ""),
field("own", r#"<font typeface="Times New Roman" size="11pt"/>"#),
field("sized", r#"<font size="12pt"/>"#)
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let faces: Vec<(String, crate::text::Family, f64)> = form.pages[0]
.items
.iter()
.filter_map(|i| if let Item::Text(s) = i { Some((s.text.clone(), s.face.family, s.face.size)) } else { None })
.collect();
assert_eq!(
faces,
[
("plain:".to_string(), crate::text::Family::Helvetica, 8.0),
("own:".to_string(), crate::text::Family::Times, 11.0),
("sized:".to_string(), crate::text::Family::Helvetica, 12.0)
]
);
}
#[test]
fn a_button_caption_without_a_font_of_its_own_takes_its_fields() {
// An Arial 8pt button without a height: a caption naming no font is shown in Arial 8pt, not
// the 10pt Courier default, and the button is as tall as one 8pt line; one naming only a size
// keeps the field's typeface.
let button = |caption_font: &str| {
let items = positioned(&format!(
r#"<field name="go" x="1in" y="0" w="100pt"><ui><button/></ui><font typeface="Arial" size="8pt"/><caption>{caption_font}<value><text>Go</text></value></caption></field>"#
));
items.iter().find_map(|i| if let Item::Widget(w) = i { Some((w.face.family, w.face.size, w.rect.h)) } else { None }).expect("the button")
};
let (family, size, h) = button("");
assert_eq!((family, size), (crate::text::Family::Helvetica, 8.0));
assert!((h - text::line_height(8.0)).abs() < 0.05, "{h}");
let (family, size, h) = button(r#"<font size="12pt"/>"#);
assert_eq!((family, size), (crate::text::Family::Helvetica, 12.0));
assert!((h - text::line_height(12.0)).abs() < 0.05, "{h}");
}
/// A caption is measured as it is drawn: in its field's font (XFA 3.3, "Formatting Text That
/// Appears as Fixed or Variable Content", p. 43) and in the paragraph around the field, not the
/// field's own, which formats the field's value. A field paragraph's space above or line height
/// gives its caption no extra room.
#[test]
fn a_caption_is_measured_in_the_font_and_paragraph_it_is_drawn_in() {
let field = |name: &str, para: &str, caption: &str| {
format!(
r#"<field name="{name}" w="3in"><ui><textEdit/></ui><font typeface="Arial" size="14pt"/><para {para}/><caption {caption}><value><text>Cap</text></value></caption></field><field name="{name}_next" w="3in" h="0.3in"><ui><textEdit/></ui></field>"#
)
};
let body = format!(
r#"<subform name="body" layout="tb" w="7.5in">{}{}</subform>"#,
field("top", r#"spaceAbove="0.5in""#, r#"placement="top""#),
field("left", r#"lineHeight="0.75in""#, r#"placement="left" reserve="1in""#),
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let ws = widgets(&form.pages[0]);
let rect = |n: &str| ws.iter().find(|w| w.name == n).map(|w| w.rect).unwrap();
let line = crate::text::line_height(14.0);
let (top, top_next) = (rect("top"), rect("top_next"));
// Above the box, the caption takes one line of the field's 14pt font.
assert!((top.y - 36.0 - line).abs() < 0.01, "the top caption's room is one 14pt line: {}", top.y - 36.0);
assert!((top_next.y - top.bottom()).abs() < 0.01, "and the field ends where its box does: {} {}", top_next.y, top.bottom());
// Beside the box, a one-line caption leaves the field the box's height.
let (left, left_next) = (rect("left"), rect("left_next"));
assert!((left_next.y - left.y - (line + 4.0)).abs() < 0.01, "a one-line caption beside the box adds no height: {}", left_next.y - left.y);
}
/// The room a caption with no font and no reserve takes is worked out in its field's font,
/// resolved before the room is: beside the box, the caption text's width; above it, one line.
/// A 24pt field's caption takes four times the room of a 6pt one's, and neither takes the
/// room of the 10pt Courier default.
#[test]
fn a_caption_without_a_font_or_a_reserve_takes_room_in_its_fields_font() {
// A 5in field at x=1in in 24pt or 6pt Arial, its caption naming no font and no reserve.
let field = |size: f64, placement: &str| {
let items = positioned(&format!(
r#"<field name="f" x="1in" y="0" w="5in" h="1in"><ui><textEdit/></ui><font typeface="Arial" size="{size}pt"/><caption placement="{placement}"><value><text>Name:</text></value></caption></field>"#
));
let rect = items.iter().find_map(|i| if let Item::Widget(w) = i { Some(w.rect) } else { None }).expect("the field");
let cap = items.iter().find_map(|i| if let Item::Text(s) = i { Some((s.x, s.face.family, s.face.size)) } else { None }).expect("the caption");
(rect, cap)
};
let helvetica = |size: f64| text::Face {
family: crate::text::Family::Helvetica,
bold: false,
italic: false,
size,
color: [0.0; 3],
underline: false,
h_scale: 1.0,
};
let courier_room = text::Face { family: crate::text::Family::Courier, ..helvetica(10.0) }.width("Name:") + 2.0;
let mut rooms = Vec::new();
for size in [24.0, 6.0] {
let (rect, (cap_x, family, cap_size)) = field(size, "left");
// The box starts after the caption's room: its text's width in the field's font, plus 2pt.
let room = rect.x - cap_x;
let expected = helvetica(size).width("Name:") + 2.0;
assert!((room - expected).abs() < 0.05, "{size}pt: the caption takes {room}pt, not {expected}pt");
assert!((room - courier_room).abs() > 1.0, "{size}pt: not the default's {courier_room}pt");
// And it is drawn in that font, whole, in the room it was given.
assert_eq!((family, cap_size), (crate::text::Family::Helvetica, size), "drawn in the field's font");
rooms.push(room - 2.0);
// Above the box, the caption takes one line of the field's font.
// (The field's top is the box's, 0.5in down the page.)
let (top, _) = field(size, "top");
let above = top.y - 36.0;
assert!((above - text::line_height(size)).abs() < 0.05, "{size}pt: the top caption takes {above}pt");
}
assert!((rooms[0] / rooms[1] - 4.0).abs() < 0.01, "24pt against 6pt: {rooms:?}");
}
/// A caption font that names only a size takes the rest, its weight, style and family, from
/// its field's font (XFA 3.3, "Formatting Text That Appears as Fixed or Variable Content", p. 43).
#[test]
fn a_caption_font_naming_only_a_size_takes_the_fields_weight_style_and_family() {
let items = positioned(
r#"<field name="f" x="1in" y="0" w="5in" h="0.5in"><ui><textEdit/></ui><font typeface="Times New Roman" size="8pt" weight="bold" posture="italic"/><caption reserve="2in"><font size="12pt"/><value><text>Name:</text></value></caption></field>"#,
);
let face = items.iter().find_map(|i| if let Item::Text(s) = i { Some(s.face.clone()) } else { None }).expect("the caption");
assert_eq!((face.family, face.bold, face.italic, face.size), (crate::text::Family::Times, true, true, 12.0));
}
/// A caption font that sets only the weight keeps its field's posture: bold from the caption,
/// italic from the field, both on the caption (XFA 3.3, "Formatting Text That Appears as Fixed or
/// Variable Content", p. 43).
#[test]
fn a_caption_font_naming_only_a_weight_keeps_the_fields_posture() {
let items = positioned(
r#"<field name="f" x="1in" y="0" w="5in" h="0.5in"><ui><textEdit/></ui><font typeface="Arial" size="8pt" posture="italic"/><caption reserve="2in"><font weight="bold"/><value><text>Name:</text></value></caption></field>"#,
);
let face = items.iter().find_map(|i| if let Item::Text(s) = i { Some(s.face.clone()) } else { None }).expect("the caption");
assert_eq!((face.family, face.bold, face.italic, face.size), (crate::text::Family::Helvetica, true, true, 8.0));
}
/// A signature box the file already holds a signature for shows that signature, the file's own
/// objects, and is locked; the other box stays unsigned.
#[test]
fn a_signed_signature_box_shows_the_signature_the_file_holds() {
let mut doc = Document::open(Arc::new(crate::fixtures::signed_shell())).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 laid: Vec<_> = fields.iter().map(|f| doc.resolve(f)).filter(|f| f.as_dict().unwrap().contains(SOM_KEY)).collect();
// The file has a field named `form[0]` already: the unsigned box keeps its own name rather
// than repeat that one.
let (signed, unsigned) = (laid[0].as_dict().unwrap(), laid[1].as_dict().unwrap());
assert_eq!(unsigned.get(b"T").and_then(|t| t.as_string()).map(|t| t.to_text()).as_deref(), Some("other"));
// The signature dictionary and the picture are the file's own objects, not copies.
let value = doc.resolve(signed.get(b"V").unwrap());
assert_eq!(value.as_dict().unwrap().name(b"Type"), Some(&b"Sig"[..]));
assert!(signed.get(b"V").unwrap().as_ref().is_some());
let shown = doc.resolve(signed.get(b"AP").unwrap());
let picture = doc.resolve(shown.as_dict().unwrap().get(b"N").unwrap());
assert!(matches!(&*picture, Object::Stream(s) if s.dict.name(b"Subtype") == Some(&b"Form"[..])));
assert_eq!(signed.int(b"Ff").unwrap_or(0) & 1, 1, "a signed box is not signed again");
assert!(!unsigned.contains(b"V") && !unsigned.contains(b"AP"));
}
#[test]
fn a_carriage_return_and_line_feed_are_one_line_break() {
let lines = |t: &str| crate::text::plain(t).paragraphs.len();
assert_eq!(lines("one\r\ntwo\r\nthree"), 3);
assert_eq!(lines("one\ntwo\rthree"), 3);
assert_eq!(lines("one\r\n\r\ntwo"), 3, "an empty line stays");
// As the data holds it: character references, which the XML parser leaves alone.
let form = layout_xml(&wrapped_form("<form><body><notes>one&#xD;&#xA;two&#xD;&#xA;three</notes></body></form>")).unwrap();
let crlf = form.pages.iter().flat_map(widgets).find(|w| w.name == "notes").unwrap().rect.h;
let form = layout_xml(&wrapped_form("<form><body><notes>one&#xA;two&#xA;three</notes></body></form>")).unwrap();
let lf = form.pages.iter().flat_map(widgets).find(|w| w.name == "notes").unwrap().rect.h;
assert!((crlf - lf).abs() < 0.01);
}
#[test]
fn data_exports_as_datasets_xml_or_an_xdp_and_imports_from_any_of_them() {
use crate::data::{export_data, import_data};
let data = "<form><page1><country>JP</country><langs>English\nSpanish</langs></page1></form>";
let mut doc = Document::open(Arc::new(shell(&fields_template(data)))).unwrap();
render_into(&mut doc).unwrap();
// XML: the data alone, rooted at the form's root data node, as Acrobat's XML export is.
let xml = export_data(&doc, false, "fields.pdf").unwrap();
assert!(xml.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<form"), "{xml}");
assert!(xml.contains("<country>JP</country>") && xml.contains("<langs>English\nSpanish</langs>"), "{xml}");
assert!(xml.trim_end().ends_with("</form>"), "{xml}");
assert_eq!(crate::parse_data_file(&xml, Some("form")).unwrap().len(), 1, "the export is importable");
// XDP: the datasets inside an xdp envelope with a reference to the PDF.
let xdp = export_data(&doc, true, "my \"form\".pdf").unwrap();
assert!(xdp.contains("<xdp:xdp xmlns:xdp=\"http://ns.adobe.com/xdp/\">") && xdp.contains("</xdp:xdp>"), "{xdp}");
assert!(xdp.contains("<pdf href=\"my &quot;form&quot;.pdf\" xmlns=\"http://ns.adobe.com/xdp/pdf/\"/>"), "{xdp}");
assert_eq!(parse_datasets(&xdp).unwrap().text_at(&som_to_path("form[0].page1[0].country[0]")), Some("JP"));
// A form without a datasets packet exports empty data.
let bare = Document::open(Arc::new(shell(&fields_template("")))).unwrap();
let xml = export_data(&bare, false, "x.pdf").unwrap();
assert!(xml.contains("<xfa:data></xfa:data>") || xml.contains("<xfa:data/>"), "{xml}");
// A datasets packet alone (no template) still exports its data; no XFA at all is an error.
let static_doc = Document::open(Arc::new(static_shell("<form1><page1><name>Ada</name></page1></form1>"))).unwrap();
assert!(export_data(&static_doc, false, "s.pdf").unwrap().contains("<name>Ada</name>"));
assert!(export_data(&static_doc, true, "s.pdf").unwrap().contains("<xfa:datasets"));
// An XFA entry without a template or datasets exports empty data rather than failing.
let plain = Document::open(Arc::new(shell("<xdp:xdp xmlns:xdp=\"http://ns.adobe.com/xdp/\"></xdp:xdp>"))).unwrap();
assert!(export_data(&plain, false, "p.pdf").unwrap().contains("<xfa:data"));
// Import: each shape of file replaces the data; what no field binds to in the datasets
// (a data description) stays.
let with_desc = fields_template(data).replace(
"<xfa:data>",
"<dd:dataDescription xmlns:dd=\"http://ns.adobe.com/data-description/\" dd:name=\"form\"><form/></dd:dataDescription><xfa:data>",
);
let shapes = [
format!(
"<?xml version=\"1.0\"?>\n<xdp:xdp xmlns:xdp=\"http://ns.adobe.com/xdp/\"><xfa:datasets xmlns:xfa=\"{XFA_NS}\"><xfa:data><form><page1><country>CA</country></page1></form></xfa:data></xfa:datasets></xdp:xdp>"
),
format!("<xfa:datasets xmlns:xfa=\"{XFA_NS}\"><xfa:data><form><page1><country>CA</country></page1></form></xfa:data></xfa:datasets>"),
format!("\u{feff}<xfa:data xmlns:xfa=\"{XFA_NS}\"><form><page1><country>CA</country></page1></form></xfa:data>"),
"<form><page1><country>CA</country></page1></form>".to_string(),
];
for file in &shapes {
let mut doc = Document::open(Arc::new(shell(&with_desc))).unwrap();
render_into(&mut doc).unwrap();
let r = import_data(&mut doc, file, Some("form"), None).unwrap();
assert_eq!(r.nodes, 3, "{file}");
let d = crate::data_of(&doc).unwrap();
assert_eq!(d.text_at(&som_to_path("form[0].page1[0].country[0]")), Some("CA"), "{file}");
assert_eq!(d.text_at(&som_to_path("form[0].page1[0].langs[0]")), None, "the old data is gone: {file}");
let xdp = export_data(&doc, true, "x.pdf").unwrap();
assert!(xdp.contains("dataDescription"), "kept: {xdp}");
assert!(!export_data(&doc, false, "x.pdf").unwrap().contains("dataDescription"), "the XML export is the data alone");
// Laid out again, the form shows the imported value.
let (t, _) = parse(&with_desc).unwrap();
rerender(&mut doc, &t).unwrap();
let fields = pdfcraft_forms_free_fields(&doc);
let c = &fields.iter().find(|(n, _)| n == "country").unwrap().1;
assert_eq!(c.get(b"V").and_then(|v| v.as_string()).map(|s| s.to_text()).as_deref(), Some("CA"), "{file}");
}
// Not XFA data: refused, the document untouched.
let mut doc = Document::open(Arc::new(shell(&fields_template(data)))).unwrap();
render_into(&mut doc).unwrap();
for bad in [
"<xfdf xmlns=\"http://ns.adobe.com/xfdf/\"><fields/></xfdf>",
"<fields><field name=\"a\"><value>1</value></field></fields>",
"not xml at all",
"<a><b></a>",
] {
assert!(import_data(&mut doc, bad, Some("form"), None).is_err(), "{bad}");
}
assert_eq!(crate::data_of(&doc).unwrap().text_at(&som_to_path("form[0].page1[0].country[0]")), Some("JP"));
// Empty data: the data element is emptied, not removed.
let r = import_data(&mut doc, &format!("<xfa:data xmlns:xfa=\"{XFA_NS}\"/>"), Some("form"), None).unwrap();
assert_eq!(r.nodes, 0);
assert!(crate::data_of(&doc).is_some());
assert_eq!(crate::data_of(&doc).unwrap().children.len(), 0);
// Hostile: a file over the size cap, and one with more nodes than the parser allows.
assert!(import_data(&mut doc, &"x".repeat(17 << 20), None, None).is_err());
let many = format!("<form>{}</form>", "<a/>".repeat(1_100_000));
assert!(import_data(&mut doc, &many, None, None).is_err());
// A self-closing data element opens up for an import.
let empty = fields_template("")
.replace("</template>", "</template><xfa:datasets xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><xfa:data/></xfa:datasets>");
let mut doc = Document::open(Arc::new(shell(&empty))).unwrap();
render_into(&mut doc).unwrap();
import_data(&mut doc, "<form><page1><country>FR</country></page1></form>", Some("form"), None).unwrap();
assert_eq!(crate::data_of(&doc).unwrap().text_at(&som_to_path("form[0].page1[0].country[0]")), Some("FR"));
}
const XFA_NS: &str = "http://www.xfa.org/schema/xfa-data/1.0/";
#[test]
fn a_picture_chosen_for_an_image_field_is_kept_in_the_data_with_its_content_type() {
use crate::data::write_data_image;
let mut doc = Document::open(Arc::new(shell(&fields_template("")))).unwrap();
render_into(&mut doc).unwrap();
let path = som_to_path("form[0].page1[0].photo[0]");
// No data node yet: it is made.
let r = write_data_image(&mut doc, &path, "image/gif", TINY_GIF, None).unwrap();
assert!(r.written, "{:?}", r.warnings);
let xdp = crate::read_packets(&doc).unwrap().unwrap().xdp;
assert!(xdp.contains("<photo xfa:contentType=\"image/gif\">R0lGODlh"), "{xdp}");
// Written again: replaced, not duplicated; a hostile content type is cleaned.
let r = write_data_image(&mut doc, &path, "image/png\"><evil/><x a=\"", &tiny_png(), None).unwrap();
assert!(r.written);
let xdp = crate::read_packets(&doc).unwrap().unwrap().xdp;
assert_eq!(xdp.matches("<photo ").count(), 1, "{xdp}");
assert!(xdp.contains("<photo xfa:contentType=\"image/pngevil/xa\">iVBORw0KGgo"), "{xdp}");
assert!(!xdp.contains("<evil/>"));
// The form shows it: laid out again, the page's picture is the PNG from the data.
let (t, _) = parse(&fields_template("")).unwrap();
rerender(&mut doc, &t).unwrap();
let d = crate::data_of(&doc).unwrap();
assert!(d.text_at(&path).unwrap().starts_with("iVBORw0KGgo"));
// Too big is refused before anything is written.
assert!(write_data_image(&mut doc, &path, "image/png", &vec![0u8; (8 << 20) + 1], None).is_err());
assert!(write_data_image(&mut doc, &Vec::new(), "image/png", TINY_GIF, None).is_err());
// The image field is a push button marked as one, with no action and nothing drawn.
let bytes = write_incremental(&doc, &SaveOptions::default()).unwrap();
let doc = Document::open(Arc::new(bytes)).unwrap();
let fields = pdfcraft_forms_free_fields(&doc);
let photo = &fields.iter().find(|(n, _)| n == "photo").unwrap().1;
assert_eq!(photo.name(b"FT"), Some(b"Btn".as_slice()));
assert_eq!(photo.int(b"Ff"), Some(1 << 16));
assert_eq!(photo.get(b"PCXfaImage"), Some(&Object::Bool(true)));
assert!(!photo.contains(b"A") && !photo.contains(b"MK"));
}
#[test]
fn imported_data_is_written_with_the_packets_own_prefix_and_never_leaves_it_unreadable() {
use crate::data::{export_data, import_data, write_data_image};
// A file binding the data namespace to another prefix, with an attribute in it.
let file = format!(
"<x:datasets xmlns:x=\"{XFA_NS}\"><x:data><form x:dataNode=\"dataGroup\"><page1><country>CA</country></page1></form></x:data></x:datasets>"
);
let mut doc = Document::open(Arc::new(shell(&fields_template("<form><page1><country>JP</country></page1></form>")))).unwrap();
render_into(&mut doc).unwrap();
import_data(&mut doc, &file, Some("form"), None).unwrap();
let xdp = crate::read_packets(&doc).unwrap().unwrap().xdp;
assert!(xdp.contains("<form xfa:dataNode=\"dataGroup\">"), "{xdp}");
assert_eq!(crate::data_of(&doc).unwrap().text_at(&som_to_path("form[0].page1[0].country[0]")), Some("CA"));
// An xsi:nil declared on an envelope the file's data element doesn't carry.
let file = "<xdp:xdp xmlns:xdp=\"http://ns.adobe.com/xdp/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><xfa:datasets xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><xfa:data><form><page1><country xsi:nil=\"true\"/><pin>1</pin></page1></form></xfa:data></xfa:datasets></xdp:xdp>";
import_data(&mut doc, file, Some("form"), None).unwrap();
let xdp = crate::read_packets(&doc).unwrap().unwrap().xdp;
assert!(xdp.contains("xmlns:n0=\"http://www.w3.org/2001/XMLSchema-instance\" n0:nil=\"true\""), "{xdp}");
assert!(crate::data_of(&doc).is_some(), "the packet still parses");
// Our own export, from a packet using another prefix, imports back.
let other = fields_template("<form><page1><pin>7</pin></page1></form>")
.replace("xfa:datasets", "xd:datasets")
.replace("xfa:data>", "xd:data>")
.replace("xmlns:xfa=", "xmlns:xd=");
let mut doc2 = Document::open(Arc::new(shell(&other))).unwrap();
render_into(&mut doc2).unwrap();
let exported = export_data(&doc2, true, "o.pdf").unwrap();
import_data(&mut doc, &exported, Some("form"), None).unwrap();
assert_eq!(crate::data_of(&doc).unwrap().text_at(&som_to_path("form[0].page1[0].pin[0]")), Some("7"));
// A picture into that other-prefix packet uses its prefix.
let path = som_to_path("form[0].page1[0].photo[0]");
write_data_image(&mut doc2, &path, "image/gif", TINY_GIF, None).unwrap();
let xdp = crate::read_packets(&doc2).unwrap().unwrap().xdp;
assert!(xdp.contains("<photo xd:contentType=\"image/gif\">"), "{xdp}");
assert!(crate::data_of(&doc2).is_some());
// A picture where the data node is a group is refused, the group kept.
let grouped = fields_template("<form><page1><photo><note>keep me</note></photo></page1></form>");
let mut doc3 = Document::open(Arc::new(shell(&grouped))).unwrap();
render_into(&mut doc3).unwrap();
let r = write_data_image(&mut doc3, &path, "image/gif", TINY_GIF, None).unwrap();
assert!(!r.written && r.warnings.iter().any(|w| w.contains("structured")), "{r:?}");
assert!(crate::read_packets(&doc3).unwrap().unwrap().xdp.contains("<note>keep me</note>"));
// A field name XML can't hold is written under the same cleaned name the values use.
let odd = fields_template("").replace("name=\"photo\"", "name=\"Foto_Straße\"");
let mut doc4 = Document::open(Arc::new(shell(&odd))).unwrap();
render_into(&mut doc4).unwrap();
let r = write_data_image(&mut doc4, &som_to_path("form[0].page1[0].Foto_Straße[0]"), "image/gif", TINY_GIF, None).unwrap();
assert!(r.written, "{r:?}");
let xdp = crate::read_packets(&doc4).unwrap().unwrap().xdp;
assert_eq!(xdp.matches("<Foto_Stra_e").count(), 1, "{xdp}");
assert!(xdp.contains("<Foto_Stra_e xfa:contentType=\"image/gif\">R0lG"), "{xdp}");
// What is not this form's data is refused: an SVG, an XDP without datasets, an XDP whose
// config has a <data> element before the datasets, a data document with another root.
let mut doc = Document::open(Arc::new(shell(&fields_template("<form><page1><country>JP</country></page1></form>")))).unwrap();
render_into(&mut doc).unwrap();
for bad in [
"<svg xmlns=\"http://www.w3.org/2000/svg\"><rect/></svg>".to_string(),
"<xdp:xdp xmlns:xdp=\"http://ns.adobe.com/xdp/\"><template/></xdp:xdp>".to_string(),
"<other><page1><country>CA</country></page1></other>".to_string(),
format!("<x:datasets xmlns:x=\"{XFA_NS}\"><x:data><form><page1><country>CA</country></page1></form></x:data></x:datasets>")
.replace("x:data", "x:nodata"),
] {
assert!(import_data(&mut doc, &bad, Some("form"), None).is_err(), "{bad}");
}
let config_first = format!(
"<xdp:xdp xmlns:xdp=\"http://ns.adobe.com/xdp/\"><config xmlns=\"http://www.xfa.org/schema/xci/3.0/\"><present><data>junk</data></present></config><xfa:datasets xmlns:xfa=\"{XFA_NS}\"><xfa:data><form><page1><country>CA</country></page1></form></xfa:data></xfa:datasets></xdp:xdp>"
);
import_data(&mut doc, &config_first, Some("form"), None).unwrap();
assert_eq!(crate::data_of(&doc).unwrap().text_at(&som_to_path("form[0].page1[0].country[0]")), Some("CA"));
// Deep nesting is refused before it is parsed; a data path deeper than the data limit too.
let deep = format!("{}x{}", "<a>".repeat(20_000), "</a>".repeat(20_000));
assert!(import_data(&mut doc, &deep, None, None).is_err());
let deepish = format!("<form>{}x{}</form>", "<a>".repeat(100), "</a>".repeat(100));
assert!(import_data(&mut doc, &deepish, Some("form"), None).is_err());
assert_eq!(crate::data_of(&doc).unwrap().text_at(&som_to_path("form[0].page1[0].country[0]")), Some("CA"), "untouched");
// The data holds more rows than are laid out: said, not hidden.
let n = crate::layout::MAX_INSTANCES + 10;
let rows: String = (0..n).map(|i| format!("<row><item>r{i}</item><amount>1</amount></row>")).collect();
let many = scripted_template().replace(
"</template>",
&format!(
"</template><xfa:datasets xmlns:xfa=\"{XFA_NS}\"><xfa:data><form><page1><table>{rows}</table></page1></form></xfa:data></xfa:datasets>"
),
);
let form = layout_xml(&many).unwrap();
assert!(form.warnings.iter().any(|w| w.contains(&format!("{n} rows")) && w.contains(&format!("first {}", n - 10))), "{:?}", form.warnings);
}
#[test]
fn an_anchor_type_places_the_named_point_of_the_box_at_its_x_and_y() {
// The page label of IRCC IMM 5532E: x is the centre of the box, so its right edge sits
// 10.795mm right of x, inside the page, not 21.59mm.
let xml = 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="1.5in" w="7.5in" h="8in"/><medium short="8.5in" long="11in"/>
<draw anchorType="topCenter" name="PageOf" x="197.485mm" y="13.97mm" w="21.59mm" h="3.81mm"><value><text>PAGE 1 OF 8</text></value><font size="7pt" typeface="Arial"/><para hAlign="right"/></draw>
<draw anchorType="bottomRight" name="foot" x="8in" y="10.5in" w="1in" h="0.25in"><value><text>Footer</text></value><font size="8pt" typeface="Arial"/></draw>
<field anchorType="topRight" name="ref" x="8in" y="1in" w="2in" h="0.3in"><ui><textEdit/></ui></field>
</pageArea></pageSet>
<draw name="body" w="7.5in" h="0.3in"><value><text>Body</text></value></draw>
</subform>
</template>
</xdp:xdp>
"##;
let form = layout_xml(xml).unwrap();
let page = &form.pages[0];
let span = |t: &str| {
page.items
.iter()
.find_map(|i| {
if let Item::Text(s) = i
&& s.text == t
{
Some(s.clone())
} else {
None
}
})
.unwrap()
};
let label = span("PAGE 1 OF 8");
let right = (197.485 + 21.59 / 2.0) * 72.0 / 25.4;
assert!(
(label.x + label.face.width(&label.text) - right).abs() < 0.5,
"label ends at {}, box at {right}",
label.x + label.face.width(&label.text)
);
let foot = span("Footer");
assert!((foot.x - 7.0 * 72.0).abs() < 0.01, "footer at x {}", foot.x);
assert!(foot.baseline > 10.25 * 72.0 && foot.baseline < 10.5 * 72.0, "footer baseline {}", foot.baseline);
let field = widgets(page).into_iter().find(|w| w.name == "ref").unwrap();
assert!((field.rect.x - 6.0 * 72.0).abs() < 0.01 && (field.rect.y - 72.0).abs() < 0.01, "{:?}", field.rect);
}
#[test]
fn laying_a_form_out_takes_off_the_usage_rights_it_voids() {
use crate::fixtures::usage_rights_shell;
let xdp = fields_template("<form><page1><country>JP</country></page1></form>");
// What `/Perms` holds once the layout is saved and the file read again.
let laid_out = |bytes: Vec<u8>| {
let mut doc = Document::open(Arc::new(bytes)).unwrap();
let report = render_into(&mut doc).unwrap();
let doc = Document::open(Arc::new(write_incremental(&doc, &SaveOptions::default()).unwrap())).unwrap();
let catalog = doc.get(doc.root().unwrap()).as_dict().cloned().unwrap();
let indirect = catalog.get(b"Perms").and_then(Object::as_ref).is_some();
let perms = catalog.get(b"Perms").map(|p| doc.resolve(p)).and_then(|p| p.as_dict().cloned());
let said = report.warnings.iter().any(|w| w.contains("usage rights"));
(perms, indirect, said, report.warnings)
};
// Usage rights alone: `/Perms` goes, and the user is told.
let (perms, _, said, warnings) = laid_out(usage_rights_shell(&xdp, "", false));
assert!(perms.is_none(), "{perms:?}");
assert!(said, "{warnings:?}");
// Beside a certification, in an object of its own: only the usage rights go, and the
// object is rewritten where it is.
let (perms, indirect, said, warnings) = laid_out(usage_rights_shell(&xdp, "/DocMDP 6 0 R", true));
let perms = perms.expect("the certification stays");
assert!(perms.contains(b"DocMDP") && !perms.contains(b"UR3"), "{perms:?}");
assert!(indirect, "/Perms is still its own object");
assert!(said, "{warnings:?}");
// A form without usage rights says nothing about them.
let (perms, _, said, warnings) = laid_out(shell(&xdp));
assert!(perms.is_none() && !said, "{perms:?} {warnings:?}");
}
#[test]
fn stripping_takes_the_xfa_out_and_leaves_an_ordinary_document() {
assert_stripping_leaves_ordinary_document();
assert_stripping_handles_unbound_data_and_shared_field_tree();
}
fn assert_stripping_leaves_ordinary_document() {
use crate::pdf::strip;
let mut doc = Document::open(Arc::new(shell(&fields_template("<form><page1><country>JP</country></page1></form>")))).unwrap();
render_into(&mut doc).unwrap();
assert!(crate::read_packets(&doc).unwrap().is_some());
// Reader usage rights on the catalog go too (changing the form voids them).
let root = doc.root().unwrap();
let mut ur = pdfcraft_cos::Dict::new();
ur.set(b"UR3".to_vec(), Object::Dict(pdfcraft_cos::Dict::new()));
doc.update_dict(root, |d| d.set(b"Perms".to_vec(), Object::Dict(ur))).unwrap();
let r = strip(&mut doc).unwrap();
assert!(doc.full_save_required());
assert_eq!(r.packets, vec!["template".to_string(), "datasets".to_string()]);
assert_eq!(r.unbound_data, Some(0));
assert_eq!((r.script_buttons, r.image_fields), (0, 1), "{r:?}");
assert!(r.usage_rights);
assert!(r.field_keys >= 7, "{r:?}");
assert!(
r.notes().iter().any(|n| n.contains("template, datasets")) && r.notes().iter().any(|n| n.contains("extended features")),
"{:?}",
r.notes()
);
let bytes = write_incremental(&doc, &SaveOptions::default()).unwrap();
let doc = Document::open(Arc::new(bytes)).unwrap();
assert!(crate::read_packets(&doc).unwrap().is_none(), "no XFA entry");
assert!(!is_dynamic(&doc));
assert!(crate::existing_layout(&doc).is_none(), "the layout mark is gone");
let root = doc.get(doc.root().unwrap());
let catalog = root.as_dict().unwrap();
assert!(!catalog.contains(b"NeedsRendering") && !catalog.contains(b"Perms"));
let acro = doc.resolve(catalog.get(b"AcroForm").unwrap());
let acro = acro.as_dict().unwrap();
assert!(!acro.contains(b"XFA") && !acro.contains(b"PCXfaLayout") && !acro.contains(b"PCXfaOverrides"));
// The fields stay, with their values, and without the private keys.
let fields = pdfcraft_forms_free_fields(&doc);
assert_eq!(fields.len(), 7);
let country = &fields.iter().find(|(n, _)| n == "country").unwrap().1;
assert_eq!(country.get(b"V").and_then(|v| v.as_string()).map(|s| s.to_text()).as_deref(), Some("JP"));
for (name, d) in &fields {
for k in [b"PCSom".as_slice(), b"PCXfaClick", b"PCXfaImage", b"PCItems"] {
assert!(!d.contains(k), "{name} still has {}", String::from_utf8_lossy(k));
}
}
// The pages are untouched.
let pages = doc.resolve(catalog.get(b"Pages").unwrap());
assert_eq!(pages.as_dict().unwrap().int(b"Count"), Some(1));
// Twice is nothing: a document without XFA is left as it is.
let mut doc = doc;
let r = strip(&mut doc).unwrap();
assert_eq!(r, crate::Stripped::default());
assert!(!doc.is_modified());
}
fn assert_stripping_handles_unbound_data_and_shared_field_tree() {
use crate::pdf::strip;
// Data no field holds is counted; a form whose click buttons ran scripts too; the shape
// check needs no packet decoded and tells a never-laid-out dynamic form from one to strip.
let mut doc = Document::open(Arc::new(shell(&scripted_template().replace("</template>", "</template><xfa:datasets xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><xfa:data><form><page1><qty>3</qty><extra>kept nowhere</extra><more2>x</more2></page1></form></xfa:data></xfa:datasets>")))).unwrap();
let before = crate::xfa_shape(&doc).unwrap();
assert_eq!(before, crate::XfaShape { needs_rendering: true, has_fields: false, laid_out: false });
assert!(!before.strippable(), "nothing laid out yet: stripping would leave the placeholder page");
render_into(&mut doc).unwrap();
assert!(crate::xfa_shape(&doc).unwrap().strippable());
let r = strip(&mut doc).unwrap();
assert_eq!(r.unbound_data, Some(2), "{r:?}");
assert_eq!(r.script_buttons, 4, "addRow, removeRow, hello, legacy: {r:?}");
assert!(crate::xfa_shape(&doc).is_none());
// A field tree whose dictionaries share one Kids array (every kid listing every other) is
// walked once per dictionary, not once per listing.
let mut doc = Document::open(Arc::new(shell(&fields_template("")))).unwrap();
render_into(&mut doc).unwrap();
let root = doc.root().unwrap();
let acro_ref = doc.get(root).as_dict().unwrap().get(b"AcroForm").and_then(Object::as_ref);
let fields: Vec<Object> = (0..2000).map(|_| Object::Ref(doc.add(Object::Dict(pdfcraft_cos::Dict::new())))).collect();
let kids = doc.add(Object::Array(fields.clone()));
for f in &fields {
if let Some(r) = f.as_ref() {
doc.update_dict(r, |d| {
d.set(b"Kids".to_vec(), Object::Ref(kids));
d.set(b"PCSom".to_vec(), Object::String(pdfcraft_cos::PdfString::text("x")));
})
.unwrap();
}
}
let update = |d: &mut pdfcraft_cos::Dict| d.set(b"Fields".to_vec(), Object::Array(fields.clone()));
match acro_ref {
Some(r) => doc.update_dict(r, update).unwrap(),
None => doc
.update_dict(root, |c| {
let mut a = c.get(b"AcroForm").and_then(|a| a.as_dict().cloned()).unwrap_or_default();
update(&mut a);
c.set(b"AcroForm".to_vec(), Object::Dict(a));
})
.unwrap(),
}
let started = std::time::Instant::now();
let r = strip(&mut doc).unwrap();
assert_eq!(r.field_keys, 2000);
assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
}
#[test]
fn strip_marks_document_as_requiring_full_save() {
use crate::pdf::strip;
let mut doc = Document::open(Arc::new(shell(&fields_template("<form><page1><country>JP</country></page1></form>")))).unwrap();
render_into(&mut doc).unwrap();
assert!(!doc.full_save_required());
strip(&mut doc).unwrap();
assert!(doc.full_save_required(), "stripping XFA packets must require a full save to prevent data exposure in incremental saves");
}
#[test]
fn som_indices_count_earlier_same_named_siblings() {
let draw = |name: Option<&str>| {
Node::Draw(Box::new(Draw { common: Common { name: name.map(str::to_string), ..Default::default() }, ..Default::default() }))
};
let children = [draw(Some("a")), draw(Some("b")), draw(Some("a")), draw(None), draw(Some("a")), draw(Some("b"))];
let sibs = SomIndices::of(&children);
assert_eq!((0..=children.len()).map(|i| sibs.at(i)).collect::<Vec<_>>(), [0, 0, 1, 0, 2, 1, 0]);
}
/// A TIFF is drawn as viewers show it, turned by its Orientation tag: a 2 × 1 picture (red,
/// blue) tagged 6 (turn 90° clockwise) is 1 × 2, red above blue, in layout and in the PDF.
#[test]
fn a_tiff_picture_is_turned_by_its_orientation_tag() {
let strip: &[u8] = &[255, 0, 0, 0, 0, 255];
let (bps_at, strip_at) = (8 + 2 + 10 * 12 + 4, 8 + 2 + 10 * 12 + 4 + 6);
let mut b = b"II*\0".to_vec();
b.extend_from_slice(&8u32.to_le_bytes());
b.extend_from_slice(&10u16.to_le_bytes());
for (tag, ty, count, value) in [
(256u16, 3u16, 1u32, 2u32),
(257, 3, 1, 1),
(258, 3, 3, bps_at as u32),
(259, 3, 1, 1),
(262, 3, 1, 2),
(273, 4, 1, strip_at as u32),
(274, 3, 1, 6),
(277, 3, 1, 3),
(278, 3, 1, 1),
(279, 4, 1, strip.len() as u32),
] {
b.extend_from_slice(&tag.to_le_bytes());
b.extend_from_slice(&ty.to_le_bytes());
b.extend_from_slice(&count.to_le_bytes());
b.extend_from_slice(&value.to_le_bytes());
}
b.extend_from_slice(&0u32.to_le_bytes());
for _ in 0..3 {
b.extend_from_slice(&8u16.to_le_bytes());
}
b.extend_from_slice(strip);
let d = crate::image::decode(&b).unwrap();
assert_eq!(crate::image::size(&b), Some((1, 2)), "layout size");
assert_eq!((d.width, d.height), (1, 2), "decoded size");
assert_eq!(d.samples, vec![255, 0, 0, 0, 0, 255]);
}
/// A draw `w` points wide holding `text` in Arial 10 pt, aligned `h_align`.
fn one_draw(text: &str, w: f64, h_align: &str) -> String {
format!(
r##"<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="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<draw name="label" w="{w}pt" h="0.5in"><value><text>{text}</text></value><font typeface="Arial" size="10pt"/><para hAlign="{h_align}"/></draw>
</subform>
</template></xdp:xdp>"##
)
}
/// The text spans of the only page, with their baselines.
fn draw_spans(xdp: &str) -> Vec<text::Span> {
layout_xml(xdp).unwrap().pages[0].items.iter().filter_map(|i| if let Item::Text(s) = i { Some(s.clone()) } else { None }).collect()
}
/// A label that fits its box but is written with trailing spaces stays on one line and measures
/// as tall as without them; text wider than the box still wraps.
#[test]
fn a_space_at_the_end_of_a_line_does_not_count_when_fitting_it() {
// The box is just wide enough for "a. DATE"; the label is written "a. DATE " (as forms
// often are). The trailing space is never drawn, so the label stays on one line.
let w = pdfcraft_fonts::helvetica_width("a. DATE", 10.0) + 0.01;
let spans = draw_spans(&one_draw("a. DATE ", w, "left"));
let baselines: std::collections::BTreeSet<i64> = spans.iter().map(|s| (s.baseline * 100.0).round() as i64).collect();
assert_eq!(baselines.len(), 1, "{spans:?}");
// Several spaces after it don't count either.
let spans = draw_spans(&one_draw("a. DATE ", w, "left"));
let baselines: std::collections::BTreeSet<i64> = spans.iter().map(|s| (s.baseline * 100.0).round() as i64).collect();
assert_eq!(baselines.len(), 1, "{spans:?}");
// Nor do they add a blank line: the text measures as tall as without them.
let face = text::Face::of(&Font { typeface: "Arial".into(), size: 10.0, ..Font::default() });
let height = |t: &str| text::measure_height(&text::plain(t), w, &Para::default(), &face, &|_, _| String::new());
assert_eq!(height("a. DATE "), height("a. DATE"));
// Text that is wider than the box still wraps.
let spans = draw_spans(&one_draw("a. DATES ", w, "left"));
let baselines: std::collections::BTreeSet<i64> = spans.iter().map(|s| (s.baseline * 100.0).round() as i64).collect();
assert_eq!(baselines.len(), 2, "{spans:?}");
}
/// Centered and right-aligned text is placed by its drawn width, whatever spaces follow it.
#[test]
fn trailing_spaces_do_not_shift_centered_or_right_aligned_text() {
let w = 200.0;
let ink = pdfcraft_fonts::helvetica_width("TITLE", 10.0);
let left_edge = |align: &str, text: &str| draw_spans(&one_draw(text, w, align)).first().map(|s| s.x).unwrap();
// The draw's left edge is the content area's (0.5in); centered and right-aligned text is
// placed by its drawn width, whatever spaces follow it.
assert!((left_edge("center", "TITLE ") - (36.0 + (w - ink) / 2.0)).abs() < 1e-6);
assert!((left_edge("right", "TITLE ") - (36.0 + w - ink)).abs() < 1e-6);
}
/// `ready` is two events: `ref="$layout"` is layout:ready (`layoutReady`), anything else stays
/// form:ready (`ready`), in the template and in the live form; page numbering is recognized.
/// A field's page-number role comes from its layout:ready scripts, also when a form:ready script
/// comes first; a field whose layout:ready script only reads the count gets none.
#[test]
fn page_roles_come_from_layout_ready_scripts() {
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">
<pageSet><pageArea name="p"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/>
<field name="no" id="no" w="1in" h="0.3in"><ui><textEdit/></ui>
<event activity="ready" ref="$form"><script contentType="application/x-javascript">this.access = "readOnly";</script></event>
<event activity="ready" ref="$layout"><script contentType="application/x-javascript">this.rawValue = xfa.layout.page(this);</script></event>
</field>
<field name="reads" id="reads" w="1in" h="0.3in"><ui><textEdit/></ui>
<event activity="ready" ref="$layout"><script contentType="application/x-javascript">var n = xfa.layout.pageCount(); this.rawValue = "pages: " + n;</script></event>
</field>
</pageArea></pageSet>
<field name="body" w="1in" h="0.3in"><ui><textEdit/></ui></field>
</subform></template></xdp:xdp>"##;
let (tpl, _) = parse(xdp).unwrap();
assert_eq!(tpl.page_roles, vec![("no".to_string(), PageRole::Number)]);
}
/// A `layout:ready` script is an activity of its own (`layoutReady`), told apart from `form:ready`
/// (`ready`), in the template and in the live form's events.
#[test]
fn a_layout_ready_event_is_told_apart_from_form_ready() {
let (tpl, _) = parse(&crate::fixtures::layout_ready_template()).unwrap();
assert_eq!(tpl.root.scripts.iter().map(|s| s.activity.as_str()).collect::<Vec<_>>(), ["layoutReady"]);
let Node::Subform(page) = &tpl.root.children[0] else { panic!() };
let activity = |name: &str| match page.children.iter().find(|n| n.common().name.as_deref() == Some(name)) {
Some(Node::Field(f)) => f.scripts.iter().map(|s| s.activity.clone()).collect::<Vec<_>>(),
_ => panic!("no field {name}"),
};
assert_eq!(activity("stamp"), ["layoutReady"]);
assert_eq!(activity("note"), ["ready"], "form:ready keeps its name");
// The live form's events carry the same names.
let live = form_tree(&tpl, None, &Overrides::default());
assert!(live.events.iter().any(|e| e.som == "form[0]" && e.activity == "layoutReady"), "{:?}", live.events);
}
/// A script numbers its own field's page when it gives that field a layout page call's result
/// (`page`, `absPage`, `pageCount`): read from its code, not a comment or a string, by whole
/// names, over several lines, and in bounded time for a hostile script. Page numbering is what
/// the layout does itself.
#[test]
fn a_script_that_gives_its_field_a_page_call_numbers_it() {
let js = |s: &str| crate::numbers_pages(s, false);
let formcalc = |s: &str| crate::numbers_pages(s, true);
assert!(js("this.rawValue = xfa.layout.page(this);"));
assert!(js("this.rawValue = xfa.layout.pageCount();"));
assert!(!js("this.rawValue = \"laid out\";"));
// Only the code counts: a mention in a comment or a string is not a page number.
assert!(!js("// xfa.layout.pageCount() was here\nthis.rawValue = \"ready\";"));
assert!(!js("/* xfa.layout.page(this) */ this.rawValue = 'see pageCount';"));
assert!(!js("this.rawValue = \"it's \\\"pageCount\\\"\";"));
assert!(js("var s = 'pageCount'; this.rawValue = xfa.layout.pageCount();"), "a string before the call");
assert!(formcalc("$ = xfa.layout.pageCount()"));
assert!(!formcalc("; xfa.layout.pageCount()\n$ = \"pageCount \"\" here\""));
assert!(formcalc("$ = \"a;b\" ; not a comment's end\n$ = xfa.layout.page($)"), "a ; inside a string isn't a comment");
// Only a script that gives its own field the page call's result numbers that field.
assert!(!js("other.rawValue = xfa.layout.pageCount(); this.rawValue = 'x';"), "it numbers another field");
assert!(!js("var n = xfa.layout.pageCount(); this.rawValue = 'pages: ' + n;"), "it only reads the count");
assert!(!js("if (this.rawValue == xfa.layout.page(this)) { }"), "a comparison, not an assignment");
assert!(formcalc("$.rawValue = xfa.layout.page($)"));
// The calls are matched as whole names, spaces allowed before the parenthesis.
assert!(!js("var pageCounter = 1; this.rawValue = pageCounter;"));
assert!(!js("this.rawValue = mylayout.page(this);"));
assert!(js("this.rawValue = xfa.layout.page (this);"));
assert!(js("this.rawValue = xfa . layout . absPage(this);"));
// An assignment over several lines is read whole; the next statement is not part of it.
assert!(js("this.rawValue =\n xfa.layout.page(this);"));
assert!(js("this.rawValue = 'Page ' +\n xfa.layout.page(this)"));
assert!(!js("this.rawValue = 'x'\nother.rawValue = xfa.layout.page(this)"), "the next line is another statement");
assert!(js("if (true) { this.rawValue = xfa.layout.page(this) }"));
assert!(!js("that.this.rawValue = xfa.layout.page(this);"), "not the script's own field");
assert!(formcalc("$ =\n xfa.layout.page($)"));
assert!(!formcalc("$record.x = xfa.layout.page($)"), "not the field");
// A hostile script (a bracket left open, then a name repeated many times) is read in bounded
// time: each expression stops at its length cap, and only so many places are looked at.
let hostile = "$ = (\n".repeat(200_000);
let started = std::time::Instant::now();
assert!(!formcalc(&hostile));
assert!(started.elapsed() < std::time::Duration::from_secs(2), "took {:?}", started.elapsed());
}
/// `typed_date` rewrites a date typed by another of a field's edit-picture patterns in the first
/// one, and leaves alone a date the first pattern reads, text no pattern reads, a field with one
/// pattern and a field that isn't a date.
#[test]
fn a_date_typed_by_another_of_its_edit_pictures_patterns_is_written_in_the_first() {
let (tpl, _) = crate::parse(&crate::fixtures::date_alternatives_template()).unwrap();
let typed = |som: &str, text: &str| crate::typed_date(&tpl, som, text);
let leave = "form[0].leave[0]";
assert_eq!(typed(leave, "261018").as_deref(), Some("20261018"), "by yymmdd");
assert_eq!(typed(leave, "2026118").as_deref(), Some("20261108"), "by yyyymd");
assert_eq!(typed(leave, "26 10 18").as_deref(), Some("20261018"), "by yy mm dd");
assert_eq!(typed(leave, "20261018"), None, "the first pattern reads it: it stays as typed");
assert_eq!(typed(leave, "not a date"), None);
assert_eq!(typed(leave, "2618"), None, "no pattern has room for four digits");
assert_eq!(typed("form[0].born[0]", "181026"), None, "one pattern: nothing else to try");
assert_eq!(typed("form[0].name[0]", "261018"), None, "not a date field");
}
/// Only date clauses are other ways to type a date, and a date is rewritten only when the first
/// pattern keeps it: a later `text{…}` clause is no date pattern, a year a two-digit first
/// pattern can't hold leaves the text as typed instead of becoming another date, and a pattern
/// whose date the first can't keep gives way to a later one whose date it can.
#[test]
fn a_typed_date_is_rewritten_only_by_date_clauses_into_a_first_pattern_that_keeps_it() {
let (tpl, _) = crate::parse(&crate::fixtures::date_alternatives_template()).unwrap();
let typed = |som: &str, text: &str| crate::typed_date(&tpl, som, text);
assert_eq!(typed("form[0].code[0]", "261018"), None, "text{{YYMMDD}} is not a date alternative");
let short = "form[0].short[0]";
assert_eq!(typed(short, "20261018").as_deref(), Some("261018"), "a year the first pattern keeps");
assert_eq!(typed(short, "19011018"), None, "1901 as 01 would read back as 2001");
assert_eq!(typed(short, "19451018").as_deref(), Some("451018"), "45 reads back as 1945");
assert_eq!(typed(short, "20301018"), None, "2030 as 30 would read back as 1930");
// DDMMYYYY reads 20011203 as 1203-01-20, which YYMMDD can't keep; YYYYMMDD reads 2001-12-03.
assert_eq!(typed("form[0].pick[0]", "20011203").as_deref(), Some("011203"), "the next pattern that the first keeps");
}
/// A word longer than its line is broken by character in work linear in its length.
#[test]
fn a_long_word_breaks_in_linear_work() {
let face = text::Face::of(&Font { typeface: "Arial".into(), size: 1.0, ..Font::default() });
let word = "i".repeat(20_000);
text::MEASURED.with(|m| m.set(0));
let b = text::layout(&text::plain(&word), Rect::new(0.0, 0.0, 1000.0, 0.0), &Para::default(), &face, &|_, _| String::new());
let measured = text::MEASURED.with(|m| m.get());
assert!(b.spans.len() > 2, "{} lines", b.spans.len());
assert_eq!(b.spans.iter().map(|s| s.text.len()).sum::<usize>(), 20_000);
assert!(measured < 200_000, "{measured} bytes measured for a 20000-byte word");
}
/// Rich text that embeds one long field value many times lays out a bounded amount of it.
#[test]
fn embedded_field_values_expand_to_a_bounded_amount_of_text() {
let face = text::Face::of(&Font { typeface: "Arial".into(), size: 10.0, ..Font::default() });
let value = "word ".repeat(3_300);
let run = Run { embed: Some("f".into()), ..Run::default() };
let rich = RichText { paragraphs: vec![Paragraph { runs: vec![run; 100], h_align: None }] };
let b = text::layout(&rich, Rect::new(0.0, 0.0, 500.0, 0.0), &Para::default(), &face, &|_, _| value.clone());
let kept: usize = b.spans.iter().map(|s| s.text.len()).sum();
assert!(kept > 0);
assert!(kept <= text::MAX_EMBEDDED, "{kept} bytes of embedded text laid out");
assert!(text::natural_width(&rich, &Para::default(), &face, &|_, _| value.clone()) <= face.width(&value) * 70.0);
}
/// Once the embedded-text budget is nearly spent, a long value embedded again is copied out only
/// as far as the budget reaches, not whole each time.
#[test]
fn embedded_values_are_copied_out_only_as_far_as_the_budget() {
let first: String = "xxxxxxx ".repeat(text::MAX_EMBEDDED / 8 + 1).chars().take(text::MAX_EMBEDDED - 1).collect();
let second = "\u{e9}".repeat(100_000);
let span = |id: &str| format!(r##"<span xfa:embed="#{id}" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"/>"##);
let spans = format!("{}{}", span("a"), span("b").repeat(200));
let tpl = format!(
r#"<template><subform layout="tb">
<field id="a" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><value><text>{first}</text></value></field>
<field id="b" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><value><text>{second}</text></value></field>
<draw w="7in" h="9in"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>{spans}</p></body></exData></value></draw>
</subform></template>"#
);
crate::layout::EMBED_COPIED.with(|c| c.set(0));
// The draw budget counts embedded values too (1 MiB in tests), so it may stop the draw
// before its last pass; either way no more than this is copied out.
match layout_xml(&tpl) {
Ok(_) | Err(XfaError::TooLarge(_)) => {}
Err(e) => panic!("{e:?}"),
}
let copied = crate::layout::EMBED_COPIED.with(|c| c.get());
// The draw is measured at most seven times before it is laid out once.
assert!(copied <= 8 * text::MAX_EMBEDDED as u64 + 8 * 4 * 201, "{copied} bytes of embedded values copied");
}
/// Repeated subforms each carry their own copy of a long script: the live form holds a bounded
/// amount of script text and says it left the rest out.
#[test]
fn repeated_script_events_hold_a_bounded_amount_of_script() {
let script = format!("var a = 1; //{}", "x".repeat(32 * 1024));
let xml = 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 name="outer" layout="tb"><occur min="1" max="-1" initial="50"/>
<subform name="inner" layout="tb"><occur min="1" max="-1" initial="50"/>
<field name="f" w="1in" h="0.3in"><ui><textEdit/></ui>
<event activity="initialize"><script contentType="application/x-javascript">{script}</script></event></field>
</subform>
</subform>
</subform>
</template></xdp:xdp>"##
);
let (tpl, _) = parse(&xml).unwrap();
let live = form_tree(&tpl, None, &Overrides::default());
assert!(!live.events.is_empty());
let held: usize = live.events.iter().map(|e| e.script.len()).sum();
assert!(held <= crate::script::MAX_EVENT_SCRIPT_BYTES, "{held} bytes of script held by {} events", live.events.len());
assert!(live.truncated, "{held} bytes, {} events", live.events.len());
}
/// Rows added one at a time (each op asking for one more instance) queue each instance node
/// once, and removals in between don't let the queue grow without bound.
#[test]
fn added_instances_are_queued_once_each() {
use crate::data::{DataOp, ENSURED, write_data_ops};
let mut doc = Document::open(Arc::new(shell(&scripted_template()))).unwrap();
render_into(&mut doc).unwrap();
let table = som_to_path("form[0].page1[0].table[0]");
let ops: Vec<DataOp> = (1..=1000).map(|count| DataOp::Instances { parent: table.clone(), name: "row".into(), count }).collect();
ENSURED.with(|n| n.set(0));
let r = write_data_ops(&mut doc, &ops, None).unwrap();
assert!(r.written, "{r:?}");
assert_eq!(crate::data_of(&doc).unwrap().count(&table, "row"), 1000);
let queued = ENSURED.with(|n| n.get());
assert!(queued <= 2_000, "{queued} instance nodes queued for 1000 rows");
// Removals split the ops into separate passes; together they stay within the budget.
let ops: Vec<DataOp> = (0..300)
.flat_map(|_| {
[
DataOp::Instances { parent: table.clone(), name: "row".into(), count: 1000 },
DataOp::Remove(som_to_path("form[0].page1[0].table[0].row[999]")),
]
})
.collect();
ENSURED.with(|n| n.set(0));
let r = write_data_ops(&mut doc, &ops, None).unwrap();
let queued = ENSURED.with(|n| n.get());
assert!(queued <= 200_000, "{queued} instance nodes queued");
assert!(r.warnings.iter().any(|w| w.contains("instances")), "{r:?}");
}
/// A namespace declared once and inherited by many imported elements is not copied into each
/// past the import's byte budget.
#[test]
fn an_inherited_namespace_does_not_multiply_an_import() {
use crate::data::parse_data_file;
let uri = format!("urn:{}", "n".repeat(70_000));
let xml = format!("<form1 xmlns:p=\"{uri}\">{}</form1>", "<p:a/>".repeat(1_000));
fn ns_bytes(nodes: &[crate::data::ImportNode]) -> usize {
nodes.iter().map(|n| n.ns.as_ref().map_or(0, String::len) + ns_bytes(&n.children)).sum()
}
match parse_data_file(&xml, None) {
Ok(nodes) => assert!(ns_bytes(&nodes) <= crate::data::MAX_IMPORT_BYTES, "{} bytes of namespaces copied", ns_bytes(&nodes)),
Err(e) => assert!(matches!(e, XfaError::TooLarge(_)), "{e:?}"),
}
}
/// A long data name with a high index is not copied into every sibling created before it.
#[test]
fn long_names_repeated_by_an_index_are_capped() {
let doc = Document::open(Arc::new(static_shell("<form1/>"))).unwrap();
let fields = vec![FieldDatum {
obj: pdfcraft_cos::ObjRef::new(1000, 0),
name: format!("form1[0].{}[9999]", "n".repeat(2_000)),
data: FieldData::Text("v".into()),
}];
let data = build_data(&doc, &fields);
assert!(data.len() < 2_000_000, "{} bytes of data built", data.len());
}
/// Forms with an `enter` or `exit` script, in the body, a radio group or a page master, have
/// something to run when the focus moves; forms with other scripts only, or blank ones, don't.
#[test]
fn focus_scripts_are_found_wherever_the_template_has_them() {
let has = |xml: &str| has_focus_scripts(&parse(xml).unwrap().0);
assert!(has(&crate::fixtures::focus_template()));
let clicks =
crate::fixtures::focus_template().replace(r#"activity="enter""#, r#"activity="click""#).replace(r#"activity="exit""#, r#"activity="click""#);
assert!(!has(&clicks), "click scripts only");
let large = r#"<items><text>L</text></items><event activity="#;
assert!(has(&clicks.replace(&format!(r#"{large}"click""#), &format!(r#"{large}"enter""#))), "a radio button's enter script");
assert!(!has(&template(2)), "click and ready scripts only");
let print = crate::fixtures::repeated_print_button_template();
assert!(!has(&print));
assert!(has(&print.replace(r#"activity="click""#, r#"activity="exit""#)), "a page master's exit script");
assert!(
!has(&print
.replace(r#"activity="click""#, r#"activity="exit""#)
.replace("xfa.host.print(1, \"0\", (xfa.host.numPages -1).toString(), 0, 0, 0, 0, 0);", " ")),
"a blank script"
);
}
/// #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);
}
/// #3944: clearing XFA password values removes values typed into `<passwordEdit/>` fields from the
/// datasets packet (including across repeating subforms), restores a field's template default
/// `<value><text>…</text></value>` when it has one, and replaces the datasets stream in place so
/// the typed password is not left in an unreferenced stream in the overlay.
#[test]
fn clear_password_values_removes_typed_passwords_from_datasets_in_place() {
let xdp = r#"<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="front"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<subform name="page1" layout="tb">
<field name="user" w="2in" h="0.3in"><ui><textEdit/></ui></field>
<field name="pin" w="2in" h="0.3in"><ui><passwordEdit/></ui></field>
<field name="preset" w="2in" h="0.3in"><ui><passwordEdit/></ui><value><text>0000</text></value></field>
<subform name="row" layout="lr-tb"><occur min="1" max="-1"/>
<field name="secret" w="2in" h="0.3in"><ui><passwordEdit/></ui></field>
</subform>
</subform>
</subform>
</template>
<xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<xfa:data><form><page1><user>Ada</user><pin>hunter2</pin><preset>9999</preset><row><secret>first</secret></row><row><secret>second</secret></row></page1></form></xfa:data>
</xfa:datasets>
</xdp:xdp>"#;
let mut doc = Document::open(Arc::new(shell(xdp))).unwrap();
render_into(&mut doc).unwrap();
assert!(has_password_values(&doc));
let cleared = clear_password_values(&mut doc).unwrap();
assert_eq!(cleared, 4);
assert!(!has_password_values(&doc), "only default and non-password values remain");
assert_eq!(clear_password_values(&mut doc).unwrap(), 0);
let packets = read_packets(&doc).unwrap().unwrap();
assert!(packets.xdp.contains("<user>Ada</user>"), "non-password fields stay: {}", packets.xdp);
assert!(packets.xdp.contains("<preset>0000</preset>"), "template default restored: {}", packets.xdp);
for secret in ["hunter2", "9999", "first", "second"] {
assert!(!packets.xdp.contains(secret), "{secret} still in datasets: {}", packets.xdp);
}
let written = write_incremental(&doc, &SaveOptions::default()).unwrap();
let reopened = Document::open(Arc::new(written)).unwrap();
for num in reopened.object_numbers() {
if let Object::Stream(st) = &*reopened.get(pdfcraft_cos::ObjRef::new(num, 0)) {
let decoded = st.decoded().unwrap_or_default();
let text = String::from_utf8_lossy(&decoded);
for secret in ["hunter2", "9999", "first", "second"] {
assert!(!text.contains(secret), "object {num} still holds {secret}: {text}");
}
}
}
}
/// #3944: a static XFA form whose AcroForm field sets the Password flag (`/Ff 8192`) also has its
/// typed value cleared from the datasets packet.
#[test]
fn clear_password_values_clears_static_xfa_password_fields() {
let pdf = String::from_utf8(static_shell("<form1><page1><name>hunter2</name></page1></form1>"))
.unwrap()
.replace("/T (name[0])", "/T (name[0]) /Ff 8192");
let mut doc = Document::open(Arc::new(pdf.into_bytes())).unwrap();
assert!(has_password_values(&doc));
assert_eq!(clear_password_values(&mut doc).unwrap(), 1);
assert!(!has_password_values(&doc));
let packets = read_packets(&doc).unwrap().unwrap();
assert!(!packets.xdp.contains("hunter2"), "{}", packets.xdp);
}
/// The data a radio group writes for its selected on state compares every button's state before
/// any `/PCOn`: with states `/0` `/1` and `/PCOn` items `1` `2`, the state `1` is the second
/// button, whose item is `2` (it used to match the first button's `/PCOn` `1` and write `1`).
/// A selection that is only an item still finds its button.
#[test]
fn a_radio_state_is_matched_before_any_pcon_item() {
let doc = Document::open(Arc::new(crate::fixtures::static_radio_shell_with_pcon("<form1/>", ["1", "2"]))).unwrap();
let group = FieldDatum { obj: pdfcraft_cos::ObjRef::new(8, 0), name: "form1[0].page1[0].lang[0]".into(), data: FieldData::None };
let write = |sel: &str| crate::data::radio_dataset_value(&doc, &group, &Some(sel.to_string()));
assert_eq!(write("0"), "1");
assert_eq!(write("1"), "2");
// `2` is no state: it is the second button's item.
assert_eq!(write("2"), "2");
// Neither: written as given; nothing selected: empty.
assert_eq!(write("9"), "9");
assert_eq!(crate::data::radio_dataset_value(&doc, &group, &None), "");
}
/// A radio group's value is an on-state name as the AcroForm reads it: `#` and bytes that are
/// not UTF-8 (a Shift-JIS state) written `#XX`. Saving and opening spell the buttons' states the
/// same way, so a state `/A#23B` (the bytes `A#B`) or `/#82#CD` still finds its button and its
/// `/Opt` item, both ways. Read lossily, neither state matched: saving wrote the state's text as
/// the item, and opening returned a state no button has.
#[test]
fn radio_states_with_hash_or_non_utf8_bytes_find_their_buttons() {
let pdf = String::from_utf8(crate::fixtures::static_radio_shell("<form1/>"))
.unwrap()
.replace("/N << /0 ", "/N << /A#23B ")
.replace("/N << /1 ", "/N << /#82#CD ");
let doc = Document::open(Arc::new(pdf.into_bytes())).unwrap();
let group = FieldDatum { obj: pdfcraft_cos::ObjRef::new(8, 0), name: "form1[0].page1[0].lang[0]".into(), data: FieldData::None };
let write = |sel: &str| crate::data::radio_dataset_value(&doc, &group, &Some(sel.to_string()));
assert_eq!(write("A#23B"), "1", "the first button writes its /Opt item");
assert_eq!(write("#82#CD"), "2", "the second button writes its /Opt item");
assert_eq!(crate::data::radio_state_for_item(&doc, &group, "1").as_deref(), Some("A#23B"));
assert_eq!(crate::data::radio_state_for_item(&doc, &group, "2").as_deref(), Some("#82#CD"));
// The spelling is the forms crate's `name_text`.
for (bytes, text) in [(&b"Yes"[..], "Yes"), ("はい".as_bytes(), "はい"), (b"A#1", "A#231"), (b"\x82\xcd", "#82#CD"), (b"\xff#\x00", "#FF#23#00")]
{
assert_eq!(crate::data::name_text(bytes), text, "{bytes:?}");
}
}
/// #5153 review: a row outside a table keeps its `minH`, as a table row does (XFA 3.3 p. 847):
/// one holding a 0.2in cell with `minH="3in"` is 3in tall, in a top-to-bottom and in a
/// left-to-right parent, and the field after it starts 2.8in lower than after a row without one.
#[test]
fn a_row_outside_a_table_keeps_its_minimum_height() {
let inch = 72.0;
for parent in ["tb", "lr-tb"] {
let after = |row_min_h: &str| {
let body = format!(
r#"<subform name="body" layout="{parent}" w="7.5in"><subform name="row" layout="row" w="7.5in" {row_min_h}><draw w="2in" h="0.2in"><value><text>One</text></value></draw></subform><field name="who" w="3in" h="0.4in"><ui><textEdit/></ui></field></subform>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
widgets(&form.pages[0])[0].rect.y
};
let grown = after(r#"minH="3in""#) - after("");
assert!((grown - 2.8 * inch).abs() < 0.01, "{parent}: the row grew by {grown}pt");
}
}
/// What a script sets on page-master content (a field hidden on the second page made from a
/// page area) is applied to that page's copy only, when the form is laid out again: the other
/// pages keep the field.
#[test]
fn a_script_hiding_master_content_on_one_page_hides_it_there_only() {
let section = |n: u32| {
format!(
r#"<subform name="s{n}" layout="tb"><breakBefore targetType="pageArea" startNew="1"/><field name="f{n}" w="2in" h="0.3in"><ui><textEdit/></ui></field></subform>"#
)
};
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">
<pageSet>
<pageArea name="Body"><contentArea x="0.5in" y="0.5in" w="7.5in" h="2in"/><medium short="8.5in" long="11in"/>
<field name="pageNo" x="7in" y="10in" w="1in" h="0.3in"><ui><textEdit/></ui></field>
</pageArea>
</pageSet>
{}{}{}
</subform>
</template>
</xdp:xdp>
"##,
section(1),
section(2),
section(3)
);
let (tpl, _) = crate::parse(&xdp).unwrap();
let mut ov = Overrides::default();
ov.presence.insert("Body[1].pageNo[0]".into(), "hidden".into());
let laid = apply_overrides(&tpl, &ov);
let form = crate::layout::layout_with_overrides(&laid, None, &ov).unwrap();
let has: Vec<bool> = form.pages.iter().map(|p| widgets(p).iter().any(|w| w.som.contains("pageNo"))).collect();
assert_eq!(has, [true, false, true], "hidden on the second page only");
}
/// Hidden master widgets still count their page area, and removed pages leave no
/// stale count when a page set has several page areas (wireless89, #5368).
#[test]
fn page_area_uses_follow_hidden_masters_and_shrink_with_multiple_areas() {
let xml = fixtures::repeated_print_button_template()
.replace(
"<pageSet><pageArea name=\"master\"><occur max=\"-1\"/>",
r#"<pageSet><pageArea name="Cover"><occur max="1"/><contentArea w="540pt" h="648pt"/><medium short="612pt" long="792pt"/>
<field name="hidden" presence="hidden"><ui><textEdit/></ui></field></pageArea><pageArea name="master"><occur max="-1"/>"#,
)
.replace("<occur max=\"-1\"/>", "<occur min=\"0\" max=\"-1\"/>")
.replace("name=\"PrintButton1\"", "name=\"PrintButton1\" presence=\"hidden\"");
let (tpl, _) = parse(&xml).unwrap();
let mut doc = Document::open(Arc::new(shell(&xml))).unwrap();
render_into(&mut doc).unwrap();
let uses = page_area_uses(&doc, &tpl);
assert_eq!(uses.get("Cover"), Some(&1));
assert_eq!(uses.get("master"), Some(&2));
let mut ov = Overrides::default();
ov.presence.insert("form[0].page3[0]".into(), "hidden".into());
set_overrides(&mut doc, &ov).unwrap();
rerender(&mut doc, &tpl).unwrap();
assert_eq!(page_area_uses(&doc, &tpl).get("master"), Some(&1));
ov.presence.insert("form[0].page2[0]".into(), "hidden".into());
set_overrides(&mut doc, &ov).unwrap();
rerender(&mut doc, &tpl).unwrap();
let uses = page_area_uses(&doc, &tpl);
assert_eq!(uses.get("Cover"), Some(&1));
assert!(!uses.contains_key("master"), "removed pages leave no stale occurrence metadata: {uses:?}");
}
/// A `subformSet` is transparent to layout (XFA 3.3 p. 357): in a positioned subform its members
/// sit at their own positions, side by side as a public stamp-duty form's two columns do, not one
/// under the other; in a flowed one they still go one under another.
#[test]
fn a_subform_set_in_a_positioned_subform_places_its_members_where_they_are() {
let xml = |layout: &str| {
format!(
r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
<pageSet><pageArea name="p"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<subform name="box" w="7in" {layout}>
<subformSet name="cols">
<subform name="left" w="3in" h="2in"><draw name="a" x="0in" y="0.5in" w="2in" h="0.3in"><value><text>left</text></value></draw></subform>
<subform name="right" w="3in" h="2in"><draw name="b" x="4in" y="0.5in" w="2in" h="0.3in"><value><text>right</text></value></draw></subform>
</subformSet>
</subform>
</subform></template>"#
)
};
let baseline = |layout: &str, text: &str| {
let form = crate::layout::layout(&crate::parse(&xml(layout)).unwrap().0, None).unwrap();
form.pages[0].items.iter().find_map(|i| if let Item::Text(s) = i { (s.text == text).then_some(s.baseline) } else { None }).unwrap()
};
assert!((baseline(r#"h="3in""#, "left") - baseline(r#"h="3in""#, "right")).abs() < 0.01, "positioned: side by side");
assert!(baseline(r#"layout="tb""#, "right") - baseline(r#"layout="tb""#, "left") > 140.0, "flowed: one under the other");
}
/// In a flowing (`lr-tb`) subform a `subformSet`'s members go on among their parent's other
/// children (XFA 3.3 p. 357): beside a 1in field in a 2in row, the first 0.6in member takes the
/// rest of that line and the second wraps, rather than the set moving to the next line whole.
/// The members keep the set in their SOM paths.
#[test]
fn a_subform_set_in_an_lr_tb_subform_flows_its_members_with_their_siblings() {
let body = r#"<subform name="row" layout="lr-tb" w="2in">
<field name="a" w="1in" h="0.3in"><ui><textEdit/></ui></field>
<subformSet name="grp" relation="ordered">
<subform name="m1" w="0.6in" h="0.3in"><field name="x" w="0.6in" h="0.3in"><ui><textEdit/></ui></field></subform>
<subform name="m2" w="0.6in" h="0.3in"><field name="y" w="0.6in" h="0.3in"><ui><textEdit/></ui></field></subform>
</subformSet>
</subform>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
let w = widgets(&form.pages[0]);
let at = |name: &str| w.iter().find(|w| w.name == name).map(|w| (w.som.clone(), w.rect.x, w.rect.y)).unwrap();
let (_, ax, ay) = at("a");
let (xsom, xx, xy) = at("x");
let (ysom, yx, yy) = at("y");
assert!((xy - ay).abs() < 0.5 && (xx - (ax + 72.0)).abs() < 0.5, "the first member goes on beside a: a at ({ax}, {ay}), x at ({xx}, {xy})");
assert!(yy > ay + 1.0 && (yx - ax).abs() < 0.5, "the second wraps to the next line: y at ({yx}, {yy})");
assert!(xsom.ends_with("row[0].grp[0].m1[0].x[0]") && ysom.ends_with("row[0].grp[0].m2[0].y[0]"), "{xsom} {ysom}");
}
/// In a table, and in one of its rows, a `subformSet`'s members still go one under another: the
/// set lays them out top to bottom there rather than taking the table's or the row's layout.
#[test]
fn a_subform_set_in_a_table_or_a_row_puts_its_members_one_under_another() {
let set = |name: &str| {
format!(
r#"<subformSet name="grp">
<subform name="m1" w="2in" h="0.3in"><field name="{name}1" w="2in" h="0.3in"><ui><textEdit/></ui></field></subform>
<subform name="m2" w="2in" h="0.3in"><field name="{name}2" w="2in" h="0.3in"><ui><textEdit/></ui></field></subform>
</subformSet>"#
)
};
let body = format!(
r#"<subform name="t" layout="table" columnWidths="2in 2in">
{}
<subform name="r" layout="row"><field name="c" w="2in" h="0.3in"><ui><textEdit/></ui></field>{}</subform>
</subform>"#,
set("s"),
set("q")
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let w = widgets(&form.pages[0]);
let at = |name: &str| w.iter().find(|w| w.name == name).map(|w| (w.rect.x, w.rect.y)).unwrap();
for (first, second) in [("s1", "s2"), ("q1", "q2")] {
let ((x1, y1), (x2, y2)) = (at(first), at(second));
assert!((x1 - x2).abs() < 0.5 && y2 > y1 + 20.0, "{second} under {first}: ({x1}, {y1}) then ({x2}, {y2})");
}
}
/// The SOM path and place of each widget of the template's field `name`, in layout order, found
/// by its SOM path (a repeated field's PDF name is made up: `x_2`).
fn widgets_named(form: &Form, name: &str) -> Vec<(String, f64, f64)> {
let tail = format!(".{name}[0]");
widgets(&form.pages[0]).iter().filter(|w| w.som.ends_with(&tail)).map(|w| (w.som.clone(), w.rect.x, w.rect.y)).collect()
}
/// #5369 review: a `subformSet` inside a `subformSet` is transparent too: in an `lr-tb` row the
/// inner set's member goes on beside the field before the outer set, the outer set's own member
/// wraps, and the field after the sets follows it. Each member keeps both sets in its SOM path.
#[test]
fn nested_subform_sets_in_an_lr_tb_subform_flow_their_members_with_their_siblings() {
let body = r#"<subform name="row" layout="lr-tb" w="2in">
<field name="a" w="1in" h="0.3in"><ui><textEdit/></ui></field>
<subformSet name="outer">
<subformSet name="inner">
<subform name="m1" w="0.6in" h="0.3in"><field name="x" w="0.6in" h="0.3in"><ui><textEdit/></ui></field></subform>
</subformSet>
<subform name="m2" w="0.6in" h="0.3in"><field name="y" w="0.6in" h="0.3in"><ui><textEdit/></ui></field></subform>
</subformSet>
<field name="b" w="0.6in" h="0.3in"><ui><textEdit/></ui></field>
</subform>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
let at = |name: &str| widgets_named(&form, name).into_iter().next().unwrap();
let ((_, ax, ay), (xsom, xx, xy), (ysom, yx, yy), (_, bx, by)) = (at("a"), at("x"), at("y"), at("b"));
assert!((xy - ay).abs() < 0.5 && (xx - (ax + 72.0)).abs() < 0.5, "x goes on beside a: a ({ax}, {ay}), x ({xx}, {xy})");
assert!(yy > ay + 1.0 && (yx - ax).abs() < 0.5, "y wraps: ({yx}, {yy})");
assert!((by - yy).abs() < 0.5 && (bx - (yx + 43.2)).abs() < 0.5, "b follows y: ({bx}, {by})");
assert!(xsom.ends_with("row[0].outer[0].inner[0].m1[0].x[0]") && ysom.ends_with("row[0].outer[0].m2[0].y[0]"), "{xsom} {ysom}");
}
/// #5369 review: in a positioned subform, the members of a `subformSet` nested in another sit at
/// their own positions, side by side, as the members of one set do.
#[test]
fn nested_subform_sets_in_a_positioned_subform_place_their_members_where_they_are() {
let body = r#"<subform name="box" w="7in" h="3in">
<subformSet name="outer">
<subformSet name="inner">
<subform name="l" x="0in" y="0.5in" w="3in" h="1in"><field name="p" w="1in" h="0.3in"><ui><textEdit/></ui></field></subform>
</subformSet>
<subform name="r" x="4in" y="0.5in" w="3in" h="1in"><field name="q" w="1in" h="0.3in"><ui><textEdit/></ui></field></subform>
</subformSet>
</subform>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
let at = |name: &str| widgets_named(&form, name).into_iter().next().unwrap();
let ((psom, px, py), (_, qx, qy)) = (at("p"), at("q"));
assert!((py - qy).abs() < 0.5 && (qx - px - 288.0).abs() < 0.5, "side by side, 4in apart: p ({px}, {py}), q ({qx}, {qy})");
assert!(psom.ends_with("box[0].outer[0].inner[0].l[0].p[0]"), "{psom}");
}
/// #5369 review: an empty `subformSet`, and one holding only an empty one, takes no room: in an
/// `lr-tb` row the field after it goes on beside the field before it, and in a positioned or a
/// `tb` subform the layout goes on as if it weren't there.
#[test]
fn an_empty_subform_set_takes_no_room() {
for (attrs, after_a) in [(r#"layout="lr-tb" w="2in""#, (72.0, 0.0)), (r#"w="7in" h="2in""#, (0.0, 0.0)), (r#"layout="tb" w="7in""#, (0.0, 21.6))]
{
let body = format!(
r#"<subform name="row" {attrs}>
<field name="a" w="1in" h="0.3in"><ui><textEdit/></ui></field>
<subformSet name="none"/>
<subformSet name="outer"><subformSet name="inner"/></subformSet>
<field name="b" w="0.6in" h="0.3in"><ui><textEdit/></ui></field>
</subform>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let at = |name: &str| widgets_named(&form, name).into_iter().next().unwrap();
let ((_, ax, ay), (_, bx, by)) = (at("a"), at("b"));
assert!((bx - ax - after_a.0).abs() < 0.5 && (by - ay - after_a.1).abs() < 0.5, "{attrs}: a ({ax}, {ay}), b ({bx}, {by})");
}
}
/// #5369 review: a repeating member of a `subformSet` flows instance by instance among its
/// parent's other children in an `lr-tb` row, as a repeating child of the row would: the first
/// instance beside the field before the set, the others wrapping, each with its own index.
#[test]
fn a_repeating_member_of_a_subform_set_flows_instance_by_instance() {
let body = r#"<subform name="row" layout="lr-tb" w="2in">
<field name="a" w="1in" h="0.3in"><ui><textEdit/></ui></field>
<subformSet name="grp">
<subform name="m" w="0.6in" h="0.3in"><occur initial="3" max="5"/><field name="x" w="0.6in" h="0.3in"><ui><textEdit/></ui></field></subform>
</subformSet>
</subform>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
let (_, ax, ay) = widgets_named(&form, "a").into_iter().next().unwrap();
let x = widgets_named(&form, "x");
assert_eq!(x.len(), 3, "{x:?}");
let places: Vec<(f64, f64)> = x.iter().map(|(_, px, py)| (px - ax, py - ay)).collect();
for ((got_x, got_y), (want_x, want_y)) in places.iter().zip([(72.0, 0.0), (0.0, 21.6), (43.2, 21.6)]) {
assert!((got_x - want_x).abs() < 0.5 && (got_y - want_y).abs() < 0.5, "{places:?}");
}
for (i, (som, _, _)) in x.iter().enumerate() {
assert!(som.ends_with(&format!("row[0].grp[0].m[{i}].x[0]")), "{som}");
}
}
/// #5369 review: a repeating `subformSet` lays its members out once per instance, each instance
/// flowing on from the last in an `lr-tb` row, and each member taking its set's instance index.
#[test]
fn a_repeating_subform_set_flows_each_instance_of_its_members() {
let body = r#"<subform name="row" layout="lr-tb" w="2in">
<field name="a" w="1in" h="0.3in"><ui><textEdit/></ui></field>
<subformSet name="grp"><occur initial="2" max="3"/>
<subform name="m" w="0.6in" h="0.3in"><field name="x" w="0.6in" h="0.3in"><ui><textEdit/></ui></field></subform>
</subformSet>
</subform>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
let (_, ax, ay) = widgets_named(&form, "a").into_iter().next().unwrap();
let x = widgets_named(&form, "x");
assert_eq!(x.len(), 2, "{x:?}");
let places: Vec<(f64, f64)> = x.iter().map(|(_, px, py)| (px - ax, py - ay)).collect();
for ((got_x, got_y), (want_x, want_y)) in places.iter().zip([(72.0, 0.0), (0.0, 21.6)]) {
assert!((got_x - want_x).abs() < 0.5 && (got_y - want_y).abs() < 0.5, "{places:?}");
}
for (i, (som, _, _)) in x.iter().enumerate() {
assert!(som.ends_with(&format!("row[0].grp[{i}].m[0].x[0]")), "{som}");
}
}
/// A flowed subform in a table cell is as tall as its content even when it gives a height, as
/// other viewers lay out a public form's per-child section (a `tb` subform with `h="186mm"` in a
/// row); a positioned cell, and a flowed subform outside a table, keep their heights.
#[test]
fn a_flowed_subform_in_a_table_cell_is_as_tall_as_its_content() {
let after_y = |cell: &str| {
let body = format!(
r#"<subform name="t" layout="table" columnWidths="5in"><subform name="r" layout="row">{cell}</subform></subform>
<field name="after" w="2in" h="0.3in"><ui><textEdit/></ui></field>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
widgets(&form.pages[0]).iter().find(|w| w.name == "after").map(|w| w.rect.y).unwrap()
};
let fields = r#"<field name="a" w="2in" h="0.3in"><ui><textEdit/></ui></field><field name="b" w="2in" h="0.3in"><ui><textEdit/></ui></field>"#;
// The table starts at 0.5in (36pt); its content is two 0.3in fields (43.2pt).
let flowed = after_y(&format!(r#"<subform name="c" layout="tb" w="5in" h="5in">{fields}</subform>"#));
assert!((flowed - (36.0 + 43.2)).abs() < 0.5, "flowed cell: the next object at {flowed}");
let positioned = after_y(r#"<subform name="c" w="5in" h="5in"><field name="a" w="2in" h="0.3in"><ui><textEdit/></ui></field></subform>"#);
assert!((positioned - (36.0 + 360.0)).abs() < 0.5, "positioned cell keeps h: {positioned}");
let outside = {
let body = format!(
r#"<subform name="c" layout="tb" w="5in" h="5in">{fields}</subform><field name="after" w="2in" h="0.3in"><ui><textEdit/></ui></field>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
widgets(&form.pages[0]).iter().find(|w| w.name == "after").map(|w| w.rect.y).unwrap()
};
assert!((outside - (36.0 + 360.0)).abs() < 0.5, "a flowed subform outside a table keeps h: {outside}");
// Measured at the column's width, where it is drawn, not its own: in a 1in column, two 0.8in
// fields of a 5in-wide lr-tb cell go on two lines (43.2pt), not one.
let narrow = {
let two =
r#"<field name="a" w="0.8in" h="0.3in"><ui><textEdit/></ui></field><field name="b" w="0.8in" h="0.3in"><ui><textEdit/></ui></field>"#;
let body = format!(
r#"<subform name="t" layout="table" columnWidths="1in"><subform name="r" layout="row"><subform name="c" layout="lr-tb" w="5in" h="5in">{two}</subform></subform></subform>
<field name="after" w="2in" h="0.3in"><ui><textEdit/></ui></field>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
widgets(&form.pages[0]).iter().find(|w| w.name == "after").map(|w| w.rect.y).unwrap()
};
assert!((narrow - (36.0 + 43.2)).abs() < 0.5, "measured at the column's width: the next object at {narrow}");
}
/// The page and top of the field `after` once `body` is laid out in a top-to-bottom root whose
/// content area starts 0.5in (36pt) down the page.
fn page_and_y_of_after(body: &str) -> (usize, f64) {
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
form.pages
.iter()
.enumerate()
.find_map(|(i, p)| widgets(p).iter().find(|w| w.som.ends_with(".after[0]") || w.name == "after").map(|w| (i, w.rect.y)))
.unwrap()
}
/// A 2in by 0.3in text field.
fn text_field(name: &str) -> String {
format!(r#"<field name="{name}" w="2in" h="0.3in"><ui><textEdit/></ui></field>"#)
}
/// `cell` as the only cell of a one-row table with `columns`, followed by the field `after`.
fn table_then_after(columns: &str, cell: &str) -> String {
format!(
r#"<subform name="t" layout="table" columnWidths="{columns}"><subform name="r" layout="row">{cell}</subform></subform>{}"#,
text_field("after")
)
}
/// #5370 review: moving the measurement of a node with no height into `content_height` leaves
/// each kind of node as tall as its content: a draw, a field, an exclusion group, an area and a
/// subform of every layout, each followed by a field that starts where it ends.
#[test]
fn every_kind_of_node_without_a_height_is_as_tall_as_its_content() {
let after = |node: &str| {
let (page, y) = page_and_y_of_after(&format!("{node}{}", text_field("after")));
assert_eq!(page, 0, "{node}");
y - 36.0
};
let two = format!("{}{}", text_field("a"), text_field("b"));
// Containers of 0.3in fields: their heights are exact.
let area = after(r#"<area name="box" x="0in" y="0in"><field name="a" x="0in" y="1in" w="2in" h="0.3in"><ui><textEdit/></ui></field></area>"#);
assert!((area - 93.6).abs() < 0.5, "area: {area}");
let positioned = after(r#"<subform name="s" w="5in"><field name="a" x="0in" y="1in" w="2in" h="0.3in"><ui><textEdit/></ui></field></subform>"#);
assert!((positioned - 93.6).abs() < 0.5, "positioned subform: {positioned}");
let tb = after(&format!(r#"<subform name="s" layout="tb" w="5in">{two}</subform>"#));
assert!((tb - 43.2).abs() < 0.5, "tb subform: {tb}");
let lr_tb = after(&format!(r#"<subform name="s" layout="lr-tb" w="3in">{two}</subform>"#));
assert!((lr_tb - 43.2).abs() < 0.5, "lr-tb subform, one field a line: {lr_tb}");
let rl_tb = after(&format!(r#"<subform name="s" layout="rl-tb" w="5in">{two}</subform>"#));
assert!((rl_tb - 21.6).abs() < 0.5, "rl-tb subform, both fields on a line: {rl_tb}");
let table =
after(&format!(r#"<subform name="s" layout="table" columnWidths="2.5in 2.5in"><subform name="r" layout="row">{two}</subform></subform>"#));
assert!((table - 21.6).abs() < 0.5, "table subform: {table}");
let group = after(
r#"<exclGroup name="g" w="2in"><field name="a" x="0in" y="0in" w="2in" h="0.3in"><ui><checkButton/></ui></field><field name="b" x="0in" y="0.5in" w="2in" h="0.3in"><ui><checkButton/></ui></field></exclGroup>"#,
);
assert!((group - 57.6).abs() < 0.5, "exclusion group: {group}");
let margins = after(&format!(r#"<subform name="s" layout="tb" w="5in"><margin topInset="0.1in" bottomInset="0.2in"/>{two}</subform>"#));
assert!((margins - (43.2 + 21.6)).abs() < 0.5, "tb subform with margins: {margins}");
// A field and a draw are as tall as a line of their text: more than its 10pt size, and one
// line, not two.
let field = after(r#"<field name="a" w="2in"><ui><textEdit/></ui><font size="10pt"/></field>"#);
assert!(field > 10.0 && field < 20.0, "field: {field}");
let draw = after(r#"<draw name="d" w="2in"><value><text>One line</text></value><font size="10pt"/></draw>"#);
assert!(draw > 10.0 && draw < 20.0, "draw: {draw}");
}
/// #5370 review: a flowed subform in a table cell grows to its content when the height it gives
/// is too small or zero, its margins count, a `maxH` still caps it, and a cell that spans two
/// columns is measured at both columns' width.
#[test]
fn a_flowed_cell_grows_past_a_small_height_and_keeps_margins_and_max_height() {
let after = |cell: &str| {
let (page, y) = page_and_y_of_after(&table_then_after("5in", cell));
assert_eq!(page, 0, "{cell}");
y - 36.0
};
let two = format!("{}{}", text_field("a"), text_field("b"));
let small = after(&format!(r#"<subform name="c" layout="tb" w="5in" h="0.2in">{two}</subform>"#));
assert!((small - 43.2).abs() < 0.5, "a 0.2in cell holding 0.6in: {small}");
let zero = after(&format!(r#"<subform name="c" layout="tb" w="5in" h="0in">{two}</subform>"#));
assert!((zero - 43.2).abs() < 0.5, "a zero-height cell: {zero}");
let margins = after(&format!(r#"<subform name="c" layout="tb" w="5in" h="5in"><margin topInset="0.1in" bottomInset="0.1in"/>{two}</subform>"#));
assert!((margins - 57.6).abs() < 0.5, "content and margins: {margins}");
let three = format!("{two}{}", text_field("x"));
let capped = after(&format!(r#"<subform name="c" layout="tb" w="5in" h="0.2in" maxH="0.5in">{three}</subform>"#));
assert!((capped - 36.0).abs() < 0.5, "maxH caps the content height: {capped}");
let table = after(&format!(
r#"<subform name="c" layout="table" w="5in" h="5in" columnWidths="2.5in 2.5in"><subform name="r2" layout="row">{two}</subform></subform>"#
));
assert!((table - 21.6).abs() < 0.5, "a table-layout cell: {table}");
// Two 1in columns; a 1in-wide lr-tb cell spanning both fits two 0.8in fields on one line.
let spanned = {
let two_narrow =
r#"<field name="a" w="0.8in" h="0.3in"><ui><textEdit/></ui></field><field name="b" w="0.8in" h="0.3in"><ui><textEdit/></ui></field>"#;
let (_, y) = page_and_y_of_after(&table_then_after(
"1in 1in",
&format!(r#"<subform name="c" layout="lr-tb" w="1in" h="5in" colSpan="2">{two_narrow}</subform>"#),
));
y - 36.0
};
assert!((spanned - 21.6).abs() < 0.5, "measured across both spanned columns: {spanned}");
}
/// #5370 review: only a flowed subform in a cell gives up its height. A field, an exclusion
/// group and a positioned or row subform in a cell keep theirs, and the row is as tall as its
/// tallest cell.
#[test]
fn other_cells_keep_their_heights_and_the_row_takes_the_tallest() {
let after = |cells: &str| page_and_y_of_after(&table_then_after("2.5in 2.5in", cells)).1 - 36.0;
let field = after(r#"<field name="f" w="2in" h="2in"><ui><textEdit/></ui></field>"#);
assert!((field - 144.0).abs() < 0.5, "a field cell: {field}");
let group =
after(r#"<exclGroup name="g" w="2in" h="2in"><field name="a" x="0in" y="0in" w="2in" h="0.3in"><ui><checkButton/></ui></field></exclGroup>"#);
assert!((group - 144.0).abs() < 0.5, "an exclusion group cell: {group}");
let positioned = after(&format!(r#"<subform name="c" w="2in" h="2in">{}</subform>"#, text_field("a")));
assert!((positioned - 144.0).abs() < 0.5, "a positioned cell: {positioned}");
let row = after(&format!(r#"<subform name="c" layout="row" w="2in" h="2in">{}</subform>"#, text_field("a")));
assert!((row - 144.0).abs() < 0.5, "a row-layout cell: {row}");
// A flowed cell beside a 2in field: the field is the taller.
let beside = after(&format!(
r#"<field name="f" w="2in" h="2in"><ui><textEdit/></ui></field><subform name="c" layout="tb" w="2in" h="5in">{}</subform>"#,
text_field("a")
));
assert!((beside - 144.0).abs() < 0.5, "the taller cell sets the row: {beside}");
}
/// #5370 review: an empty flowed cell is as tall as nothing, so its row is as tall as its other
/// cell; a flowed cell inside a flowed cell of a nested table gives up its height too.
#[test]
fn an_empty_flowed_cell_and_a_nested_one_are_as_tall_as_their_content() {
let after = |cells: &str| page_and_y_of_after(&table_then_after("2.5in 2.5in", cells)).1 - 36.0;
let empty = after(&format!(r#"{}<subform name="c" layout="tb" w="2in" h="5in"></subform>"#, text_field("f")));
assert!((empty - 21.6).abs() < 0.5, "an empty flowed cell: {empty}");
let alone = after(r#"<subform name="c" layout="tb" w="2in" h="5in"><margin topInset="2pt" bottomInset="3pt"/></subform>"#);
assert!((alone - 5.0).abs() < 0.5, "an empty flowed cell is as tall as its margins: {alone}");
let two = format!("{}{}", text_field("a"), text_field("b"));
let nested = after(&format!(
r#"<subform name="c" layout="tb" w="2.5in" h="5in"><subform name="t2" layout="table" columnWidths="2.5in"><subform name="r2" layout="row"><subform name="c2" layout="tb" w="2.5in" h="5in">{two}</subform></subform></subform></subform>"#
));
assert!((nested - 43.2).abs() < 0.5, "a nested table's flowed cell: {nested}");
}
/// #5370 review: a flowed cell holding a repeating subform counts each instance, and a repeating
/// row of such cells takes each row's content height. The repeated fields are found by SOM path,
/// since their PDF names are made up.
#[test]
fn repeating_content_and_repeating_rows_of_flowed_cells_take_their_content_height() {
let line = format!(r#"<subform name="line" layout="tb"><occur initial="3" max="-1"/>{}</subform>"#, text_field("v"));
let (_, y) = page_and_y_of_after(&table_then_after("5in", &format!(r#"<subform name="c" layout="tb" w="5in" h="5in">{line}</subform>"#)));
assert!((y - 36.0 - 64.8).abs() < 0.5, "three 0.3in instances: {}", y - 36.0);
let form = layout_xml(&one_area_form(
r#"layout="tb""#,
&format!(
r#"<subform name="t" layout="table" columnWidths="5in"><subform name="r" layout="row"><occur initial="2" max="-1"/><subform name="c" layout="tb" w="5in" h="5in">{}{}</subform></subform></subform>{}"#,
text_field("a"),
text_field("b"),
text_field("after")
),
))
.unwrap();
let ws = widgets(&form.pages[0]);
let top = |som: &str| {
ws.iter()
.find(|w| w.som.ends_with(som))
.map(|w| w.rect.y)
.unwrap_or_else(|| panic!("no {som} in {:?}", ws.iter().map(|w| &w.som).collect::<Vec<_>>()))
};
assert!((top("r[1].c[0].a[0]") - top("r[0].c[0].a[0]") - 43.2).abs() < 0.5, "the second row starts 0.6in below the first");
assert!((top("after[0]") - 36.0 - 86.4).abs() < 0.5, "two rows of 0.6in: {}", top("after[0]") - 36.0);
}
/// #5370 review: a flowed cell giving a height taller than the page no longer pushes what follows
/// it to another page; huge margins in a narrow column and flowed cells nested deeper than the
/// template reader follows are laid out without panicking.
#[test]
fn a_flowed_cell_taller_than_the_page_huge_margins_and_deep_nesting_stay_bounded() {
let two = format!("{}{}", text_field("a"), text_field("b"));
let (page, y) = page_and_y_of_after(&table_then_after("5in", &format!(r#"<subform name="c" layout="tb" w="5in" h="20in">{two}</subform>"#)));
assert_eq!(page, 0, "the next object stays on the first page");
assert!((y - 36.0 - 43.2).abs() < 0.5, "{}", y - 36.0);
let (_, y) = page_and_y_of_after(&table_then_after(
"1in",
&format!(r#"<subform name="c" layout="tb" w="1in" h="5in"><margin leftInset="10in" rightInset="10in" topInset="0.1in"/>{two}</subform>"#),
));
assert!(y.is_finite() && (y - 36.0 - 50.4).abs() < 0.5, "margins wider than the column: {}", y - 36.0);
// Flowed cells nested 200 tables deep are cut off where the template is, not followed.
let open = r#"<subform layout="table" columnWidths="1in"><subform layout="row"><subform layout="tb" w="1in" h="1in">"#;
let deep = format!("{}{}{}", open.repeat(200), text_field("a"), "</subform></subform></subform>".repeat(200));
assert!(layout_xml(&one_area_form(r#"layout="tb""#, &deep)).is_ok());
}
/// A picture the template links (`href`) is drawn from the `XFAImages` name tree the PDF keeps
/// it in (XFA 3.3 pp. 257–258), through the tree's `Kids`. A link the file holds nothing for
/// stays out, as before, and is never looked for outside the file.
#[test]
fn a_linked_picture_is_drawn_from_the_pdfs_xfa_images() {
let mut doc = Document::open(Arc::new(crate::fixtures::linked_image_shell())).unwrap();
let mut tpl = crate::script::template_of(&doc).unwrap();
let mut pictures = Vec::new();
let mut walk = |nodes: &[Node]| {
for n in nodes {
if let Node::Subform(s) = n {
for c in &s.children {
if let Node::Draw(d) = c
&& let Value::Image { data, href, .. } = &d.value
{
pictures.push((href.clone(), data.len()));
}
}
}
}
};
walk(&tpl.root.children);
assert_eq!(pictures, vec![(Some(r".\logo.png".into()), crate::fixtures::tiny_png().len()), (Some(r".\missing.png".into()), 0)]);
assert!(crate::linked_images::resolve(&mut tpl, &doc).is_empty(), "nothing to say of a link the file doesn't hold");
let report = render_into(&mut doc).unwrap();
let doc = Document::open(Arc::new(write_incremental(&doc, &SaveOptions::default()).unwrap())).unwrap();
let images = doc
.object_numbers()
.into_iter()
.filter(
|n| matches!(&*doc.get(pdfcraft_cos::ObjRef { num: *n, generation: 0 }), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image")),
)
.count();
assert_eq!(images, 2, "the linked PNG and its soft mask");
assert_eq!(report.warnings.iter().filter(|w| w.contains("not a JPEG, PNG")).count(), 1, "only the missing one: {:?}", report.warnings);
}
/// A hostile `XFAImages` tree neither hangs nor panics: `Kids` that lead back to themselves, a
/// name that isn't a string, and a name for something that isn't a stream. The picture is then
/// left out, as a link the file holds nothing for.
#[test]
fn a_hostile_xfa_images_tree_is_walked_once_and_gives_nothing() {
for (root, kid) in [
(&b"<< /Kids [6 0 R 7 0 R] >>"[..], &b"<< /Kids [6 0 R 7 0 R] /Names [42 8 0 R] >>"[..]),
(&b"<< /Names [(.\\logo.png) 7 0 R] >>"[..], &b"<< /Kids [6 0 R] >>"[..]),
(&b"<< /Kids 7 0 R >>"[..], &b"[6 0 R]"[..]),
] {
let mut doc = Document::open(Arc::new(crate::fixtures::linked_image_shell_with(root, kid))).unwrap();
let mut tpl = crate::script::template_of(&doc).unwrap();
assert!(crate::linked_images::resolve(&mut tpl, &doc).is_empty());
let report = render_into(&mut doc).unwrap();
assert!(report.warnings.iter().any(|w| w.contains("not a JPEG, PNG")), "{:?}", report.warnings);
let images = doc.object_numbers().into_iter().filter(|n| matches!(&*doc.get(pdfcraft_cos::ObjRef { num: *n, generation: 0 }), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image"))).count();
assert_eq!(images, 0, "no picture drawn");
}
}
/// The picture data a draw named `name` ends up with, in the template's first subform.
fn linked_picture(tpl: &crate::model::Template, name: &str) -> Option<Vec<u8>> {
tpl.root.children.iter().find_map(|n| match n {
Node::Subform(s) => s.children.iter().find_map(|c| match c {
Node::Draw(d) if d.common.name.as_deref() == Some(name) => match &d.value {
Value::Image { data, .. } => Some(data.clone()),
_ => None,
},
_ => None,
}),
_ => None,
})
}
/// #5393 review: a `Names` array that repeats one name counts every pair it holds, not only the
/// names kept: the walk stops at its limit however often the name repeats, so the name listed
/// after twenty thousand repeats is never reached.
#[test]
fn a_repeated_xfa_images_name_counts_against_the_walk() {
let kid = format!(r"<< /Names [{}(.\\logo.png) 8 0 R] >>", r"(.\\dup.png) 8 0 R ".repeat(20_000));
let doc = Document::open(Arc::new(crate::fixtures::linked_image_shell_with(b"<< /Kids [7 0 R] >>", kid.as_bytes()))).unwrap();
let mut tpl = crate::script::template_of(&doc).unwrap();
crate::linked_images::resolve(&mut tpl, &doc);
assert_eq!(linked_picture(&tpl, "logo"), Some(Vec::new()), "past the limit the logo's name isn't reached");
}
/// The last node the walk reaches, the 4,096th, still gives its names: the node limit stops
/// the walk from going on, not the node it has just come to.
#[test]
fn the_last_xfa_images_node_the_walk_reaches_gives_its_names() {
// The root, 4,094 empty kids, and the kid holding the logo: 4,096 nodes in all.
let root = format!("<< /Kids [{}7 0 R] >>", "<< >> ".repeat(4_094));
let doc = Document::open(Arc::new(crate::fixtures::linked_image_shell_with(root.as_bytes(), br"<< /Names [(.\\logo.png) 8 0 R] >>"))).unwrap();
let mut tpl = crate::script::template_of(&doc).unwrap();
crate::linked_images::resolve(&mut tpl, &doc);
assert_eq!(linked_picture(&tpl, "logo"), Some(crate::fixtures::tiny_png()), "the 4,096th node's name is read");
}
/// #5393 review: a name longer than any link is left before it is turned into text; the names
/// beside it are still read.
#[test]
fn an_over_long_xfa_images_name_is_left() {
let long = "L".repeat(5_000);
let kid = format!(r"<< /Names [({long}) 8 0 R (.\\logo.png) 8 0 R] >>");
let doc = Document::open(Arc::new(crate::fixtures::linked_image_shell_with(b"<< /Kids [7 0 R] >>", kid.as_bytes()))).unwrap();
let xml = format!(
r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
<pageSet><pageArea name="p"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<subform name="page1" layout="tb">
<draw name="long" w="1in" h="1in"><value><image contentType="image/png" href="{long}"/></value></draw>
<draw name="logo" w="1in" h="1in"><value><image contentType="image/png" href=".\logo.png"/></value></draw>
</subform></subform></template>"#
);
let (mut tpl, _) = crate::parse(&xml).unwrap();
crate::linked_images::resolve(&mut tpl, &doc);
assert_eq!(linked_picture(&tpl, "long"), Some(Vec::new()), "the over-long name isn't kept");
assert_eq!(linked_picture(&tpl, "logo"), Some(crate::fixtures::tiny_png()), "the name beside it is");
}
/// #5393 review: a name the tree holds whose stream isn't a picture is taken as it is, and
/// drawing it draws nothing and warns, as a picture the template holds that isn't one does.
#[test]
fn a_linked_stream_that_is_not_a_picture_draws_nothing_and_warns() {
let mut doc = Document::open(Arc::new(crate::fixtures::linked_image_shell_holding(
b"<< /Kids [7 0 R] >>",
br"<< /Names [(.\\logo.png) 8 0 R] >>",
b"this is not a picture",
)))
.unwrap();
// The stream is found and taken as the logo's data.
let mut tpl = crate::script::template_of(&doc).unwrap();
assert!(crate::linked_images::resolve(&mut tpl, &doc).is_empty());
assert_eq!(linked_picture(&tpl, "logo"), Some(b"this is not a picture".to_vec()));
let report = render_into(&mut doc).unwrap();
// One warning for the logo and the missing picture alike (warnings are said once).
assert!(report.warnings.iter().any(|w| w.contains("not a JPEG, PNG")), "{:?}", report.warnings);
let images = doc
.object_numbers()
.into_iter()
.filter(
|n| matches!(&*doc.get(pdfcraft_cos::ObjRef { num: *n, generation: 0 }), Object::Stream(s) if s.dict.name(b"Subtype") == Some(b"Image")),
)
.count();
assert_eq!(images, 0, "no picture drawn");
}
/// #5393 review: a picture larger than the limit (small in tests) is left out with a warning,
/// not read whole.
#[test]
fn an_over_large_linked_picture_is_left_with_a_warning() {
let doc = Document::open(Arc::new(crate::fixtures::linked_image_shell_holding(
b"<< /Kids [7 0 R] >>",
br"<< /Names [(.\\logo.png) 8 0 R] >>",
&[7u8; 600],
)))
.unwrap();
let mut tpl = crate::script::template_of(&doc).unwrap();
let warnings = crate::linked_images::resolve(&mut tpl, &doc);
assert!(warnings.iter().any(|w| w.contains("could not be read")), "{warnings:?}");
assert_eq!(linked_picture(&tpl, "logo"), Some(Vec::new()));
}
/// An over-deep branch of the `XFAImages` tree is left on its own: the walk goes on to the
/// branches beside it, and the picture one of them holds is found.
#[test]
fn an_over_deep_xfa_images_branch_does_not_stop_the_walk() {
let mut deep = String::from("<< /Names [(x) 8 0 R] >>");
for _ in 0..40 {
deep = format!("<< /Kids [{deep}] >>");
}
// The deep branch is listed first, so it is walked first.
let root = format!("<< /Kids [{deep} 7 0 R] >>");
let doc = Document::open(Arc::new(crate::fixtures::linked_image_shell_with(root.as_bytes(), br"<< /Names [(.\\logo.png) 8 0 R] >>"))).unwrap();
let tpl = crate::script::template_of(&doc).unwrap();
let logo = tpl.root.children.iter().find_map(|n| match n {
Node::Subform(s) => s.children.iter().find_map(|c| match c {
Node::Draw(d) if d.common.name.as_deref() == Some("logo") => Some(d.value.clone()),
_ => None,
}),
_ => None,
});
assert!(matches!(logo, Some(Value::Image { data, .. }) if !data.is_empty()), "the logo is found beside the deep branch");
}
/// A `Kids` array far longer than the nodes walked is walked in order, up to the limit, and not
/// held whole: the picture its first kid names is found, however many kids follow.
#[test]
fn a_wide_xfa_images_kids_array_is_walked_in_order_within_the_limit() {
let root = format!("<< /Kids [7 0 R {}] >>", "<< >> ".repeat(10_000));
let doc = Document::open(Arc::new(crate::fixtures::linked_image_shell_with(root.as_bytes(), br"<< /Names [(.\\logo.png) 8 0 R] >>"))).unwrap();
let tpl = crate::script::template_of(&doc).unwrap();
let logo = tpl.root.children.iter().find_map(|n| match n {
Node::Subform(s) => s.children.iter().find_map(|c| match c {
Node::Draw(d) if d.common.name.as_deref() == Some("logo") => Some(d.value.clone()),
_ => None,
}),
_ => None,
});
assert!(matches!(logo, Some(Value::Image { data, .. }) if !data.is_empty()), "the first kid's logo is found");
}
/// A picture used in many places is held once per place, so every place counts against the
/// pictures' total (small in tests): past it the rest are left out, with a warning.
#[test]
fn a_linked_picture_used_in_many_places_counts_each_place() {
let doc = Document::open(Arc::new(crate::fixtures::linked_image_shell())).unwrap();
let draws: String = (0..30)
.map(|i| format!(r#"<draw name="d{i}" w="1in" h="1in"><value><image contentType="image/png" href=".\logo.png"/></value></draw>"#))
.collect();
let xml = format!(
r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
<pageSet><pageArea name="p"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
{draws}</subform></template>"#
);
let (mut tpl, _) = crate::parse(&xml).unwrap();
let warnings = crate::linked_images::resolve(&mut tpl, &doc);
let filled =
tpl.root.children.iter().filter(|n| matches!(n, Node::Draw(d) if matches!(&d.value, Value::Image { data, .. } if !data.is_empty()))).count();
let one = crate::fixtures::tiny_png().len();
assert_eq!(filled, (1 << 10) / one, "as many places as the total holds");
assert!(warnings.iter().any(|w| w.contains("too much memory")), "{warnings:?}");
}
/// Pictures read from the file and kept for reuse count against the total too (small in tests):
/// a tree with many names, each read once, holds no more than the total, however many names
/// there are; past it a name is neither read nor kept.
#[test]
fn pictures_kept_for_reuse_stay_under_the_total_whatever_the_number_of_names() {
let names: String = (0..30).map(|i| format!("(n{i}) 8 0 R ")).collect();
let kid = format!("<< /Names [{names}] >>");
let doc = Document::open(Arc::new(crate::fixtures::linked_image_shell_with(b"<< /Kids [7 0 R] >>", kid.as_bytes()))).unwrap();
let draws: String =
(0..30).map(|i| format!(r#"<draw name="d{i}" w="1in" h="1in"><value><image contentType="image/png" href="n{i}"/></value></draw>"#)).collect();
let xml = format!(
r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
<pageSet><pageArea name="p"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
{draws}</subform></template>"#
);
let (mut tpl, _) = crate::parse(&xml).unwrap();
let (warnings, kept) = crate::linked_images::resolve_keeping(&mut tpl, &doc);
assert!(kept <= 1 << 10, "kept {kept} bytes");
assert!(warnings.iter().any(|w| w.contains("too much memory")), "{warnings:?}");
}
/// The pages of `form[0].last[0].f[0]` and of the field `after` that follows `last`, when `last`
/// holds `before` ahead of `f` and `after` behind it. A breakAfter acts after its subform, so the
/// page of `after` shows whether it broke.
fn pages_around_break(before: &str, after: &str) -> (Option<usize>, Option<usize>) {
let xml = format!(
r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
<pageSet><pageArea name="p"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<field name="first" w="2in" h="0.3in"/><subform name="last" layout="tb">{before}<field name="f" w="2in" h="0.3in"/>{after}</subform><field name="after" w="2in" h="0.3in"/>
</subform></template>"#
);
let t = crate::parse(&xml).unwrap().0;
let form = crate::layout::layout(&t, None).unwrap();
let page_of = |som: &str| form.pages.iter().position(|p| widgets(p).iter().any(|w| w.som == som));
(page_of("form[0].last[0].f[0]"), page_of("form[0].after[0]"))
}
/// A `<breakBefore/>` without a targetType breaks nothing: its default is `auto`, layout goes on
/// in the current container (XFA 3.3 p. 638), as a public form's last section expects. Written
/// out as `auto` it breaks nothing either. One to a page area, or a content area, still starts a
/// new page; so does a `breakAfter` to one.
#[test]
fn a_break_before_without_a_target_type_does_not_start_a_page() {
let page_before = |brk: &str| pages_around_break(brk, "").0;
assert_eq!(page_before("<breakBefore/>"), Some(0), "auto: no break");
assert_eq!(page_before(r#"<breakBefore targetType="auto"/>"#), Some(0));
assert_eq!(page_before(r#"<breakBefore targetType="pageArea"/>"#), Some(1));
assert_eq!(page_before(r#"<breakBefore targetType="contentArea"/>"#), Some(1));
let page_after = |brk: &str| pages_around_break("", brk).1;
assert_eq!(page_after("<breakAfter/>"), Some(0), "auto: no break");
assert_eq!(page_after(r#"<breakAfter targetType="auto"/>"#), Some(0));
assert_eq!(page_after(r#"<breakAfter targetType="pageArea"/>"#), Some(1));
assert_eq!(page_after(r#"<breakAfter targetType="contentArea"/>"#), Some(1));
}
/// targetType is one of `auto`, `contentArea` and `pageArea` (XFA 3.3 pp. 636-638). An empty or
/// unknown value, in either direction, names neither a page nor a content area, so it breaks
/// nothing; the names are case-sensitive.
#[test]
fn a_break_with_an_empty_or_unknown_target_type_does_not_start_a_page() {
for value in ["", " ", "page", "pagearea", "PageArea", "next"] {
let before = format!(r#"<breakBefore targetType="{value}"/>"#);
assert_eq!(pages_around_break(&before, "").0, Some(0), "breakBefore targetType={value:?}");
let after = format!(r#"<breakAfter targetType="{value}"/>"#);
assert_eq!(pages_around_break("", &after).1, Some(0), "breakAfter targetType={value:?}");
}
}
/// The deprecated `<break before="...">` form (XFA 3.3 pp. 633-634): `auto`, its default, forces
/// no transition; `pageArea` and `contentArea` start a new page; an empty or unknown value breaks
/// nothing.
#[test]
fn the_deprecated_break_before_form_breaks_only_to_a_page_or_content_area() {
let page = |brk: &str| pages_around_break(brk, "").0;
assert_eq!(page("<break/>"), Some(0), "auto: no break");
assert_eq!(page(r#"<break before="auto"/>"#), Some(0));
assert_eq!(page(r#"<break before=""/>"#), Some(0));
assert_eq!(page(r#"<break before="next"/>"#), Some(0));
assert_eq!(page(r#"<break before="pageArea"/>"#), Some(1));
assert_eq!(page(r#"<break before="contentArea"/>"#), Some(1));
}
/// Review on #5010: the text the reader returns is held to what `parse` accepts. A packet within
/// the 64 MB byte limit that isn't valid UTF-8 grows as each bad byte becomes a three-byte
/// replacement character: 33 MiB of them come to 99 MiB of text, past the limit, and are refused
/// as too large rather than handed to `parse`, which would refuse them only later.
#[test]
fn packets_whose_text_grows_past_the_template_limit_are_refused() {
let mut doc = Document::open(Arc::new(shell("<template><subform/></template>"))).unwrap();
let mut bytes = b"<template>".to_vec();
bytes.resize(bytes.len() + (33 << 20), 0xFF);
assert!(bytes.len() <= crate::packets::MAX_XDP, "the packet is within the byte limit");
let packet = pdfcraft_cos::ObjRef::new(5, 0);
doc.set(packet, Object::Stream(pdfcraft_cos::Stream::flate(Dict::new(), &bytes)));
match read_packets(&doc) {
Err(XfaError::TooLarge(m)) => assert!(m.contains("bytes of text"), "{m}"),
other => panic!("{:?}", other.map(|p| p.map(|p| p.xdp.len()))),
}
// As one stream rather than an array of named parts too.
let root = doc.root().unwrap();
doc.update_dict(root, |c| {
let mut acro = c.get(b"AcroForm").and_then(Object::as_dict).cloned().unwrap();
acro.set(b"XFA".to_vec(), Object::Ref(packet));
c.set(b"AcroForm".to_vec(), Object::Dict(acro));
})
.unwrap();
assert!(matches!(read_packets(&doc), Err(XfaError::TooLarge(_))));
}
#[test]
fn fields_by_som_reads_a_field_listed_many_times_once() {
// A field lists itself twice and its one widget twice: walked once per path to it, that is
// 2^64 visits at the depth limit.
let mut doc = Document::new_empty();
let widget = Object::Ref(som_field(&mut doc, "name", Some("form1[0].name[0]"), None));
let parent = doc.add(Object::Null);
let kids = Object::Array(vec![Object::Ref(parent), widget.clone(), Object::Ref(parent), widget]);
doc.set(parent, field_named("form1", None, Some(kids)));
let by_som = fields_by_som_of(doc, vec![Object::Ref(parent)]);
assert_eq!(by_som.len(), 1, "{by_som:?}");
assert_eq!(by_som.get("form1[0].name[0]").map(String::as_str), Some("form1.name"));
}
#[test]
fn fields_by_som_reads_a_field_listed_under_many_generations_once() {
// `Document::get` finds a field by object number alone, so `5 0 R` and `5 1 R` are one field.
// The AcroForm lists one under 2,000 generations: read again for each, its 1,000 kids would
// spend the walk's 2^20 steps before the field listed after it.
let mut doc = Document::new_empty();
let leaf = som_field(&mut doc, "leaf", None, None);
let a = som_field(&mut doc, "a", None, Some(Object::Array(vec![Object::Ref(leaf); 1_000])));
let b = som_field(&mut doc, "b", Some("form1[0].b[0]"), None);
let mut fields: Vec<Object> = (0..2_000).map(|g| Object::Ref(pdfcraft_cos::ObjRef::new(a.num, g))).collect();
fields.push(Object::Ref(b));
let by_som = fields_by_som_of(doc, fields);
assert_eq!(by_som.get("form1[0].b[0]").map(String::as_str), Some("b"), "{by_som:?}");
}
#[test]
fn fields_by_som_counts_kids_that_are_not_references() {
// 2,000 fields share one `/Kids` array of 1,000 nulls. Skipped uncounted, the nulls would
// cost nothing against the walk's 2^20 steps, however many fields share however long an
// array. Counted, they spend the steps here, and the walk stops before the last field.
let mut doc = Document::new_empty();
let nulls = doc.add(Object::Array(vec![Object::Null; 1_000]));
let first = som_field(&mut doc, "first", Some("form1[0].first[0]"), None);
let last = som_field(&mut doc, "last", Some("form1[0].last[0]"), None);
let mut fields = vec![Object::Ref(first)];
fields.extend((0..2_000).map(|i| Object::Ref(som_field(&mut doc, &format!("f{i}"), None, Some(Object::Ref(nulls))))));
fields.push(Object::Ref(last));
let by_som = fields_by_som_of(doc, fields);
assert!(by_som.contains_key("form1[0].first[0]"), "{by_som:?}");
assert!(!by_som.contains_key("form1[0].last[0]"), "{by_som:?}");
}
#[test]
fn fields_by_som_reads_a_field_again_when_it_is_reached_shallower() {
// Field `s` is listed at the bottom of a chain 64 deep, which is walked first, and again
// under `b`. Reached first where its kids are past the depth limit, it is read again under
// `b`, and the field under it is found by its SOM path.
let mut doc = Document::new_empty();
let leaf = som_field(&mut doc, "leaf", Some("form1[0].leaf[0]"), None);
let shared = som_field(&mut doc, "s", None, Some(Object::Array(vec![Object::Ref(leaf)])));
let mut deep = shared;
for i in (0..64).rev() {
deep = som_field(&mut doc, &format!("d{i}"), None, Some(Object::Array(vec![Object::Ref(deep)])));
}
let b = som_field(&mut doc, "b", None, Some(Object::Array(vec![Object::Ref(shared)])));
let by_som = fields_by_som_of(doc, vec![Object::Ref(deep), Object::Ref(b)]);
assert_eq!(by_som.get("form1[0].leaf[0]").map(String::as_str), Some("b.s.leaf"), "{by_som:?}");
}
/// An AcroForm field named `t`, with SOM path `som` and `kids` when given.
fn field_named(t: &str, som: Option<&str>, kids: Option<Object>) -> Object {
let s = |t: &str| Object::String(pdfcraft_cos::PdfString::literal(t));
let mut d = Dict::new();
d.set(b"T".to_vec(), s(t));
if let Some(som) = som {
d.set(crate::pdf::SOM_KEY.to_vec(), s(som));
}
if let Some(kids) = kids {
d.set(b"Kids".to_vec(), kids);
}
Object::Dict(d)
}
/// [`field_named`], added to `doc`.
fn som_field(doc: &mut Document, t: &str, som: Option<&str>, kids: Option<Object>) -> pdfcraft_cos::ObjRef {
doc.add(field_named(t, som, kids))
}
/// [`fields_by_som`] of `doc`, its catalog's AcroForm listing `fields`.
fn fields_by_som_of(mut doc: Document, fields: Vec<Object>) -> std::collections::HashMap<String, String> {
let mut acro = Dict::new();
acro.set(b"Fields".to_vec(), Object::Array(fields));
let mut cat = Dict::new();
cat.set(b"Type".to_vec(), Object::Name(b"Catalog".to_vec()));
cat.set(b"AcroForm".to_vec(), Object::Dict(acro));
let cat = doc.add(Object::Dict(cat));
doc.trailer_mut().set(b"Root".to_vec(), Object::Ref(cat));
fields_by_som(&doc)
}
/// An empty multi-line field with a minimum height and no height (a growable table cell, as a
/// public form's activity list has) starts at its minimum, not three lines; text it can't hold
/// grows it; one without a minimum stays three lines tall.
#[test]
fn an_empty_multiline_field_with_a_minimum_height_starts_there() {
let xml = |cell: &str| {
format!(
r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
<pageSet><pageArea name="p"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<field name="a" w="2in" {cell}><ui><textEdit multiLine="1"/></ui><margin topInset="0.508mm" bottomInset="0.508mm"/></field>
</subform></template>"#
)
};
let height = |cell: &str, value: Option<&str>| {
let t = crate::parse(&xml(cell)).unwrap().0;
let data = value.map(|v| {
parse_datasets(&format!(
"<xfa:datasets xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><xfa:data><form><a>{v}</a></form></xfa:data></xfa:datasets>"
))
.unwrap()
});
let form = crate::layout::layout(&t, data.as_ref()).unwrap();
widgets(&form.pages[0]).first().map(|w| w.rect.h + 2.0 * 0.508 * 72.0 / 25.4).unwrap()
};
assert!((height(r#"minH="7.62mm""#, None) - 21.6).abs() < 0.01, "{}", height(r#"minH="7.62mm""#, None));
assert!(height(r#"minH="7.62mm""#, Some(&"word ".repeat(80))) > 40.0, "text grows it");
assert!(height("", None) > 38.0, "three lines without a minimum: {}", height("", None));
}
/// A growable `lr-tb` subform that doesn't fit what is left of the page is split there (XFA 3.3
/// p. 1520), its first rows on this page and the rest on the next, as a public evaluation form's
/// sections are; one with a height, a positioned one, still moves whole.
#[test]
fn a_growable_lr_tb_subform_is_split_at_the_page_break() {
let xml = |attrs: &str| {
let rows: String = (0..6).map(|i| format!(r#"<field name="f{i}" w="7in" h="1in"/>"#)).collect();
format!(
r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
<pageSet><pageArea name="p"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<field name="tall" w="7in" h="6in"/><subform name="s" w="7.5in" {attrs}>{rows}</subform>
</subform></template>"#
)
};
let pages_of = |attrs: &str| {
let t = crate::parse(&xml(attrs)).unwrap().0;
let form = crate::layout::layout(&t, None).unwrap();
(0..6)
.map(|i| form.pages.iter().position(|p| widgets(p).iter().any(|w| w.som == format!("form[0].s[0].f{i}[0]"))).unwrap_or(9))
.collect::<Vec<_>>()
};
assert_eq!(pages_of(r#"layout="lr-tb""#), [0, 0, 0, 0, 1, 1], "split at the break");
assert_eq!(pages_of(r#"layout="lr-tb" h="6in""#), [1, 1, 1, 1, 1, 1], "a fixed height moves whole");
}
/// Where a row group lands against a page break, for each case the splitting rule tells apart:
/// a growable `lr-tb`/`rl-tb` one that fits what is left stays whole on this page, one that
/// doesn't is split at the break, and one taller than a whole page goes on over pages; one with
/// a height, and a positioned one, move whole to the next page when they fit there.
#[test]
fn a_row_group_against_a_page_break_splits_only_when_growable_and_flowing() {
// A 6in field, then the group of `n` 1in rows (7in wide, one to a line) in a 10in area.
let pages_of = |attrs: &str, n: usize, positioned: bool| {
let rows: String = (0..n)
.map(|i| {
if positioned {
format!(r#"<field name="f{i}" y="{i}in" w="7in" h="1in"/>"#)
} else {
format!(r#"<field name="f{i}" w="7in" h="1in"/>"#)
}
})
.collect();
let xml = format!(
r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
<pageSet><pageArea name="p"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<field name="tall" w="7in" h="6in"/><subform name="s" w="7.5in" {attrs}>{rows}</subform>
</subform></template>"#
);
let t = crate::parse(&xml).unwrap().0;
let form = crate::layout::layout(&t, None).unwrap();
(0..n)
.map(|i| form.pages.iter().position(|p| widgets(p).iter().any(|w| w.som == format!("form[0].s[0].f{i}[0]"))).unwrap_or(99))
.collect::<Vec<_>>()
};
// Fits the 4in left: stays on this page, whole.
assert_eq!(pages_of(r#"layout="lr-tb""#, 3, false), [0, 0, 0], "a group that fits stays");
// Taller than a page (14in): starts here, 4 rows, then 10 on the next page.
let mut over = vec![0; 4];
over.extend([1; 10]);
assert_eq!(pages_of(r#"layout="lr-tb""#, 14, false), over, "a group taller than a page goes on over pages");
// Right-to-left rows split at the break as left-to-right ones do.
assert_eq!(pages_of(r#"layout="rl-tb""#, 6, false), [0, 0, 0, 0, 1, 1], "rl-tb splits at the break");
// A height, or a positioned layout: moved whole when it fits the next page.
assert_eq!(pages_of(r#"layout="lr-tb" h="6in""#, 6, false), [1; 6], "a fixed height moves whole");
assert_eq!(pages_of("", 6, true), [1; 6], "a positioned group moves whole");
}
/// The rows of a table whose cells are empty multi-line fields with a minimum height and no
/// height start at that minimum (XFA 3.3 p. 731), so a table taller than a page puts as many of
/// them on it as that height allows, and the rest on the next; cells with a height keep it.
#[test]
fn table_rows_of_minimum_height_cells_fill_the_page_at_that_height() {
let pages = |cell: &str, n: usize| {
let rows: String = (0..n)
.map(|i| format!(r#"<subform name="r{i}" layout="row"><field name="c" {cell}><ui><textEdit multiLine="1"/></ui></field><field name="d" {cell}><ui><textEdit multiLine="1"/></ui></field></subform>"#))
.collect();
let xml = format!(
r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form" layout="tb">
<pageSet><pageArea name="p"><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea></pageSet>
<subform name="t" layout="table" columnWidths="2in 2in" w="4in">{rows}</subform>
</subform></template>"#
);
let t = crate::parse(&xml).unwrap().0;
let form = crate::layout::layout(&t, None).unwrap();
let per_page: Vec<usize> = form.pages.iter().map(|p| widgets(p).iter().filter(|w| w.som.ends_with(".c[0]")).count()).collect();
// Every cell of every row, on every page: a shorter `d` cell, or a shorter row further
// down, leaves the counts above as they are.
let heights: Vec<f64> =
form.pages.iter().flat_map(|p| widgets(p)).filter(|w| w.som.ends_with(".c[0]") || w.som.ends_with(".d[0]")).map(|w| w.rect.h).collect();
(per_page, heights)
};
// 0.4in (28.8pt) rows: 25 to a 10in page. At three lines (38.5pt), 18 would fit.
let (per_page, h) = pages(r#"minH="0.4in""#, 30);
assert_eq!(per_page, [25, 5], "row heights {h:?}");
assert!(h.len() == 60 && h.iter().all(|c| (c - 28.8).abs() < 0.01), "every cell starts at its minimum: {h:?}");
// A table that fits keeps all its rows on the page, each at the minimum.
let (per_page, h) = pages(r#"minH="0.4in""#, 10);
assert_eq!(per_page, [10]);
assert!(h.len() == 20 && h.iter().all(|c| (c - 28.8).abs() < 0.01), "every cell starts at its minimum: {h:?}");
// Cells with a height: 0.5in rows, 20 to a page.
assert_eq!(pages(r#"h="0.5in""#, 30).0, [20, 10]);
}
/// An unnamed growable multi-line field grows to hold its text as a named one does, with a
/// minimum height or without. A nameless field takes no part in data binding (XFA 3.3 p. 194),
/// so the text it shows, and the layout measures, is the template's.
#[test]
fn an_unnamed_growable_field_grows_to_hold_its_text() {
let lay = |name: &str, min_h: &str| {
let body = format!(
r#"<subform name="s" layout="tb" w="7.5in"><field {name} w="2in" {min_h}><ui><textEdit multiLine="1"/></ui><value><text>{}</text></value></field><field name="after" w="2in" h="0.3in"/></subform>"#,
"word ".repeat(80)
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let ws = widgets(&form.pages[0]);
let field = ws.iter().find(|w| w.name != "after").map(|w| w.rect.h).unwrap();
let after = ws.iter().find(|w| w.name == "after").map(|w| w.rect.y).unwrap();
(field, after)
};
for min_h in ["", r#"minH="0.3in""#] {
let named = lay(r#"name="a""#, min_h);
assert!(named.0 > 100.0, "the named field grows: {named:?}");
let unnamed = lay("", min_h);
assert!(
(unnamed.0 - named.0).abs() < 0.01 && (unnamed.1 - named.1).abs() < 0.01,
"{min_h}: unnamed {unnamed:?}, named {named:?} (field height, next field's top)"
);
}
}
/// A growable `lr-tb` subform split at a page break inside a bordered, filled `tb` section breaks
/// that section with it, as a break between the section's children does: a closed part on each
/// page, its bottom margin ending the first and its top margin starting the second, no warning.
#[test]
fn a_split_lr_tb_subform_keeps_the_border_of_the_section_round_it() {
let rows: String = (0..6).map(|i| format!(r#"<field name="f{i}" w="7in" h="1in"/>"#)).collect();
let body = format!(
r#"<subform name="box" layout="tb" w="7.5in"><border><edge/><fill><color value="230,230,230"/></fill></border><margin topInset="0.1in" bottomInset="0.2in"/><field name="tall" w="7in" h="6in"/><subform name="s" layout="lr-tb" w="7.5in">{rows}</subform></subform>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let rows_on: Vec<usize> =
(0..6).map(|i| form.pages.iter().position(|p| widgets(p).iter().any(|w| w.name == format!("f{i}"))).unwrap_or(9)).collect();
// After 0.1in of margin and the 6in field, three 1in rows fit the 10in area.
assert_eq!(rows_on, [0, 0, 0, 1, 1, 1]);
let fills = |page: usize| -> Vec<Rect> {
form.pages[page].items.iter().filter_map(|i| if let Item::Fill { rect, .. } = i { Some(*rect) } else { None }).collect()
};
let lines = |page: usize| form.pages[page].items.iter().filter(|i| matches!(i, Item::Line { .. })).count();
let (first, second) = (fills(0), fills(1));
assert_eq!((first.len(), second.len()), (1, 1), "a part on each page: {:?}", form.warnings);
assert_eq!((lines(0), lines(1)), (4, 4), "each part's border is closed");
// Page 1: the top margin, the field, three rows, the bottom margin.
assert!((first[0].y - 36.0).abs() < 0.01 && (first[0].bottom() - (36.0 + 7.2 + 432.0 + 216.0 + 14.4)).abs() < 0.01, "{:?}", first[0]);
// Page 2: the top margin again, the other three rows, the bottom margin.
assert!((second[0].y - 36.0).abs() < 0.01 && (second[0].bottom() - (36.0 + 7.2 + 216.0 + 14.4)).abs() < 0.01, "{:?}", second[0]);
let f3 = widgets(&form.pages[1]).into_iter().find(|w| w.name == "f3").map(|w| w.rect).unwrap();
assert!((f3.y - 43.2).abs() < 0.01, "the second part starts after the top margin: {f3:?}");
assert!(form.warnings.is_empty(), "{:?}", form.warnings);
}
/// Two PDF fields never share a name: a made-up `_2`, `_3` name skips one the template gives
/// another field. Whichever comes first in layout order, the field the template names `Cell4_2`
/// keeps that name and the second `Cell4` takes the next free one. Before, the second `Cell4`
/// became `Cell4_2` as well, so a script writing by that name hit the wrong cell.
#[test]
fn a_made_up_field_name_never_takes_one_the_template_uses() {
for rows in [["Cell4", "Cell4_2", "Cell4"], ["Cell4", "Cell4", "Cell4_2"]] {
let body: String = rows
.iter()
.enumerate()
.map(|(i, name)| {
format!(r#"<subform name="row{i}" layout="tb"><field name="{name}" w="2in" h="0.3in"><ui><textEdit/></ui></field></subform>"#)
})
.collect();
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let all = widgets(&form.pages[0]);
let names: Vec<&str> = all.iter().map(|w| w.name.as_str()).collect();
let mut unique = names.clone();
unique.sort_unstable();
unique.dedup();
assert_eq!(unique.len(), names.len(), "{rows:?}: {names:?}");
let template_named = rows.iter().position(|n| *n == "Cell4_2").unwrap();
let som = format!("form[0].row{template_named}[0].Cell4_2[0]");
let got = all.iter().find(|w| w.som == som).map(|w| w.name.as_str());
assert_eq!(got, Some("Cell4_2"), "{rows:?}: the template's own name is kept ({names:?})");
}
}
/// #5225 review: a member of an exclusion group keeps the name the template gives it, whatever
/// is drawn before it: a repeated field drawn first doesn't take it as its made-up name.
#[test]
fn a_made_up_field_name_never_takes_an_exclusion_group_members_name() {
let field = |name: &str| format!(r#"<field name="{name}" w="2in" h="0.3in"><ui><textEdit/></ui></field>"#);
let group = r#"<exclGroup name="Choice" layout="tb"><field name="Cell4_2" w="1in" h="0.3in"><ui><checkButton shape="round"/></ui><items><text>A</text></items></field><field name="Other" w="1in" h="0.3in"><ui><checkButton shape="round"/></ui><items><text>B</text></items></field></exclGroup>"#;
// The repeated field first, then the group; and the other way round.
for body in [format!("{}{}{group}", field("Cell4"), field("Cell4")), format!("{group}{}{}", field("Cell4"), field("Cell4"))] {
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let all = widgets(&form.pages[0]);
let shown: Vec<(String, String)> = all.iter().map(|w| (w.som.clone(), w.name.clone())).collect();
let member = all.iter().find(|w| w.som.ends_with(".Choice[0].Cell4_2[0]")).map(|w| w.name.as_str());
assert_eq!(member, Some("Cell4_2"), "the member keeps its name: {shown:?}");
let mut names: Vec<&str> = all.iter().map(|w| w.name.as_str()).collect();
names.sort_unstable();
names.dedup();
assert_eq!(names.len(), all.len(), "no two widgets share a name: {shown:?}");
}
}
/// #5225 review: a form whose fields don't repeat keeps every template name as it is, a name
/// that looks like a made-up one (`Total_2`) included, in every subform. Reserving the template's
/// names must not push a field off its own.
#[test]
fn a_form_without_repeats_keeps_every_template_name() {
let names = ["Name", "Total", "Total_2", "Date"];
let body: String = names
.iter()
.enumerate()
.map(|(i, name)| {
format!(r#"<subform name="part{i}" layout="tb"><field name="{name}" w="2in" h="0.3in"><ui><textEdit/></ui></field></subform>"#)
})
.collect();
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let got: Vec<String> = widgets(&form.pages[0]).iter().map(|w| w.name.clone()).collect();
assert_eq!(got, names, "the template's names, unchanged");
}
/// An unnamed field's made-up name (`field`) doesn't take the name a later field has in the
/// template: the field the template names `field` keeps it, and the unnamed one before it takes
/// the next free name.
#[test]
fn an_unnamed_field_never_takes_a_name_the_template_uses() {
let body = r#"<field w="2in" h="0.3in"><ui><textEdit/></ui></field>
<field name="field" w="2in" h="0.3in"><ui><textEdit/></ui></field>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
let all = widgets(&form.pages[0]);
// In layout order: the unnamed field, then the one the template names `field`.
let names: Vec<&str> = all.iter().map(|w| w.name.as_str()).collect();
assert_eq!(names.get(1), Some(&"field"), "{names:?}");
assert_ne!(names.first(), Some(&"field"), "{names:?}");
}
/// A form with `draws` in a subform placed by position, on a letter page whose content area is a
/// quarter inch in, with `master` on the page itself.
fn form_of_draws(master: &str, draws: &str) -> String {
format!(
r#"<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="p">{master}<contentArea x="0.25in" y="0.25in" w="8in" h="10.5in"/><medium stock="letter" short="8.5in" long="11in"/></pageArea></pageSet><subform name="s" w="8in" h="2.5in">{draws}</subform></subform></template></xdp:xdp>"#
)
}
/// A line from the top-left to the bottom-right of a box 0.7in × 0.4in, as #5561's form draws.
fn line_draw(x: &str, y: &str, rotate: &str) -> String {
format!(r#"<draw x="{x}" y="{y}" w="0.7in" h="0.4in" {rotate}><value><line><edge thickness="2.5pt"/></line></value></draw>"#)
}
/// `xdp` laid out into its document, and that document's first page.
fn written(xdp: &str) -> (Document, Dict) {
let mut doc = Document::open(Arc::new(shell(xdp))).unwrap();
render_into(&mut doc).unwrap();
let root = doc.get(doc.root().unwrap());
let pages = doc.get(root.as_dict().unwrap().reference(b"Pages").unwrap());
let kids = pages.as_dict().unwrap().get(b"Kids").map(|k| doc.resolve(k)).unwrap();
let page = doc.get(kids.as_array().unwrap()[0].as_ref().unwrap());
let page = page.as_dict().unwrap().clone();
(doc, page)
}
fn page_content(doc: &Document, page: &Dict) -> String {
let contents = doc.get(page.reference(b"Contents").unwrap());
let Object::Stream(s) = &*contents else { panic!("not a stream") };
String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
}
/// The ends of each line `content` strokes, on the page: through the matrices around it.
fn stroked_lines(content: &str) -> Vec<[(f64, f64); 2]> {
let (mut stack, mut matrix) = (Vec::new(), [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
let (mut numbers, mut from, mut lines): (Vec<f64>, _, _) = (Vec::new(), (0.0, 0.0), Vec::new());
for token in content.split_whitespace() {
let at = |m: [f64; 6], x: f64, y: f64| (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]);
let last = |numbers: &[f64]| (numbers[numbers.len() - 2], numbers[numbers.len() - 1]);
match token {
"q" => stack.push(matrix),
"Q" => matrix = stack.pop().unwrap(),
"cm" => {
let n: [f64; 6] = numbers[numbers.len() - 6..].try_into().unwrap();
let m = matrix;
matrix = [
n[0] * m[0] + n[1] * m[2],
n[0] * m[1] + n[1] * m[3],
n[2] * m[0] + n[3] * m[2],
n[2] * m[1] + n[3] * m[3],
n[4] * m[0] + n[5] * m[2] + m[4],
n[4] * m[1] + n[5] * m[3] + m[5],
];
}
"m" => {
let (x, y) = last(&numbers);
from = at(matrix, x, y);
}
"l" => {
let (x, y) = last(&numbers);
lines.push([from, at(matrix, x, y)]);
}
_ => {}
}
match token.parse() {
Ok(v) => numbers.push(v),
Err(_) => numbers.clear(),
}
}
lines
}
fn turned(page: &Page) -> Vec<&crate::layout::Turned> {
page.items.iter().filter_map(|i| if let Item::Turned(t) = i { Some(t.as_ref()) } else { None }).collect()
}
/// A draw turns counter-clockwise about its anchor. The figures are where Acrobat put these lines
/// on the page it flattened for #5561's form: from the anchor by (+50.4, -28.8) unturned, and by
/// (+28.8, +50.4), (-50.4, +28.8) and (-28.8, -50.4) at 90, 180 and 270 degrees.
#[test]
fn a_draw_turns_counter_clockwise_about_its_anchor() {
let draws = [
line_draw("1in", "0.95in", ""),
line_draw("3in", "0.95in", r#"rotate="90""#),
line_draw("5in", "0.95in", r#"rotate="180""#),
line_draw("7in", "0.95in", r#"rotate="270""#),
]
.concat();
let (doc, page) = written(&form_of_draws("", &draws));
let lines = stroked_lines(&page_content(&doc, &page));
assert_eq!(lines.len(), 4, "{lines:?}");
let top = 792.0 - 18.0 - 0.95 * 72.0;
let acrobat = [((90.0, top), (50.4, -28.8)), ((234.0, top), (28.8, 50.4)), ((378.0, top), (-50.4, 28.8)), ((522.0, top), (-28.8, -50.4))];
for ([from, to], (anchor, by)) in lines.iter().zip(acrobat) {
assert!((from.0 - anchor.0).abs() < 0.01 && (from.1 - anchor.1).abs() < 0.01, "{from:?} for {anchor:?}");
let moved = (to.0 - from.0, to.1 - from.1);
assert!((moved.0 - by.0).abs() < 0.01 && (moved.1 - by.1).abs() < 0.01, "{moved:?} for {by:?}");
}
}
/// A turned draw that only prints is written in the print-only group inside its turn: the marked
/// content and the turn's `q`/`Q` nest, never cross, and the draw still turns as one shown everywhere.
#[test]
fn a_turned_print_only_draw_nests_its_group_inside_the_turn() {
let draws = [
line_draw("1in", "0.95in", r#"presence="invisible" relevant="+print""#),
line_draw("3in", "0.95in", r#"rotate="90" presence="invisible" relevant="+print""#),
line_draw("5in", "0.95in", ""),
]
.concat();
let (doc, page) = written(&form_of_draws("", &draws));
let content = page_content(&doc, &page);
let mut open = Vec::new();
let mut turned_groups = 0;
for token in content.split_whitespace() {
match token {
"q" | "BDC" => {
if token == "BDC" && open.contains(&"cm") {
turned_groups += 1;
}
open.push(token);
}
"cm" if open.last() == Some(&"q") => open.push("cm"),
"Q" => {
if open.last() == Some(&"cm") {
open.pop();
}
assert_eq!(open.pop(), Some("q"), "a Q closes a q: {content}");
}
"EMC" => assert_eq!(open.pop(), Some("BDC"), "an EMC closes a BDC: {content}"),
_ => {}
}
}
assert!(open.is_empty(), "{content}");
assert_eq!(turned_groups, 1, "the turned draw is in a group of its own inside the turn: {content}");
let lines = stroked_lines(&content);
assert_eq!(lines.len(), 3, "{lines:?}");
let top = 792.0 - 18.0 - 0.95 * 72.0;
let [from, to] = lines[1];
assert!((from.0 - 234.0).abs() < 0.01 && (from.1 - top).abs() < 0.01, "{from:?}");
assert!((to.0 - from.0 - 28.8).abs() < 0.01 && (to.1 - from.1 - 50.4).abs() < 0.01, "{to:?}");
}
/// The anchor is the point it turns about, whichever corner that is: a box anchored at its bottom
/// right stands up and to the left of it, not where a top-left anchor would turn it.
#[test]
fn a_draw_turns_about_the_anchor_it_names() {
let draw = r#"<draw x="3in" y="1in" w="0.7in" h="0.4in" anchorType="bottomRight" rotate="90"><value><line><edge thickness="1pt"/></line></value></draw>"#;
let (doc, page) = written(&form_of_draws("", draw));
let lines = stroked_lines(&page_content(&doc, &page));
let anchor = (18.0 + 216.0, 792.0 - 18.0 - 72.0);
// Its bottom right is 0.7in right and 0.4in down of its top left, here turned to 0.7in up and
// 0.4in right: so the top left is that far back from the anchor, and the line ends on it.
let [from, to] = lines[0];
assert!((to.0 - anchor.0).abs() < 0.01 && (to.1 - anchor.1).abs() < 0.01, "{to:?} for {anchor:?}");
assert!((from.0 - (anchor.0 - 28.8)).abs() < 0.01 && (from.1 - (anchor.1 - 50.4)).abs() < 0.01, "{from:?}");
}
/// Each of the nine anchors stays where it is, and the box goes round it at each turn. What is
/// asked for comes from the box's corners here, not from layout: from the anchor, y up, the line
/// runs from the top left to the bottom right, and a quarter turn takes (x, y) to (-y, x).
#[test]
fn a_draw_turns_about_each_of_the_nine_anchors() {
let (w, h) = (50.4, 28.8);
let anchor = (18.0 + 216.0, 792.0 - 18.0 - 72.0);
for (name, down) in [("top", 0.0), ("middle", 0.5), ("bottom", 1.0)] {
for (side, across) in [("Left", 0.0), ("Center", 0.5), ("Right", 1.0)] {
for quarters in 0..4 {
let rotate = quarters * 90;
let draw = format!(
r#"<draw x="3in" y="1in" w="0.7in" h="0.4in" anchorType="{name}{side}" rotate="{rotate}"><value><line><edge thickness="1pt"/></line></value></draw>"#
);
let (doc, page) = written(&form_of_draws("", &draw));
let lines = stroked_lines(&page_content(&doc, &page));
assert_eq!(lines.len(), 1, "{name}{side} at {rotate}: {lines:?}");
let (left, top) = (-across * w, down * h);
for (got, corner) in lines[0].iter().zip([(left, top), (left + w, top - h)]) {
let turned = (0..quarters).fold(corner, |(x, y), _| (-y, x));
let want = (anchor.0 + turned.0, anchor.1 + turned.1);
assert!((got.0 - want.0).abs() < 0.01 && (got.1 - want.1).abs() < 0.01, "{name}{side} at {rotate}: {got:?} for {want:?}");
}
}
}
}
}
/// A draw that stands past the edge of the page once turned stays where it turned to: nothing moves
/// it back or cuts it, as for an upright one. From the page's top left corner of the content area
/// it goes off to the left and above the page, and from its right side, off to the right.
#[test]
fn a_turned_draw_stands_past_the_edge_of_the_page() {
for (x, rotate, anchor, by) in [("0in", "180", 18.0, (-50.4, 28.8)), ("8in", "90", 594.0, (28.8, 50.4))] {
let draw = line_draw(x, "0in", &format!(r#"rotate="{rotate}""#));
let (doc, page) = written(&form_of_draws("", &draw));
let content = page_content(&doc, &page);
assert!(!content.split_whitespace().any(|t| t == "W" || t == "W*"), "{rotate}: nothing clips it: {content}");
let lines = stroked_lines(&content);
assert_eq!(lines.len(), 1, "{rotate}: {lines:?}");
let [from, to] = lines[0];
assert!((from.0 - anchor).abs() < 0.01 && (from.1 - 774.0).abs() < 0.01, "{rotate}: {from:?}");
assert!((to.0 - (anchor + by.0)).abs() < 0.01 && (to.1 - (774.0 + by.1)).abs() < 0.01, "{rotate}: {to:?}");
assert!(to.0 < 0.0 || to.0 > 612.0, "{rotate}: it does stand past the edge, at {to:?}");
}
}
/// Everything a draw shows turns with it, under one matrix: its text, its picture and its border,
/// rounded or not, each written as if it stood upright.
#[test]
fn text_pictures_and_borders_turn_with_their_draw() {
let picture = format!(
r#"<draw x="1in" y="1in" w="1in" h="1in" rotate="90"><value><image contentType="image/png">{}</image></value></draw>"#,
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, tiny_png())
);
for (draw, shows) in [
(r#"<draw x="1in" y="1in" w="2in" h="0.5in" rotate="90"><value><text>upright</text></value></draw>"#.to_string(), "(upright) Tj"),
(picture, " Do "),
(r#"<draw x="1in" y="1in" w="2in" h="0.5in" rotate="90"><value><rectangle><edge thickness="1pt"/></rectangle></value></draw>"#.to_string(), " l S"),
(
r#"<draw x="1in" y="1in" w="2in" h="0.5in" rotate="90"><value><rectangle><edge thickness="1pt"/><corner radius="5pt"/></rectangle></value></draw>"#.to_string(),
" c",
),
(r#"<draw x="1in" y="1in" w="2in" h="0.5in" rotate="90"><border><fill><color value="255,0,0"/></fill></border><value><text>x</text></value></draw>"#.to_string(), " re f"),
] {
let (doc, page) = written(&form_of_draws("", &draw));
let content = page_content(&doc, &page);
let open = content.find("0 1 -1 0 ").unwrap_or_else(|| panic!("no matrix for {draw}: {content}"));
let close = open + content[open..].find("\nQ\n").unwrap_or_else(|| panic!("no end for {draw}: {content}"));
assert!(content[open..close].contains(shows), "{shows} outside the matrix: {content}");
}
}
/// `rotate` as a multiple of 90 degrees, with a unit or not, past a full turn or below none;
/// anything else leaves the draw as it stands.
#[test]
fn rotate_reads_as_quarter_turns() {
let quarters = |rotate: &str| {
let form = layout_xml(&form_of_draws("", &line_draw("1in", "1in", &format!(r#"rotate="{rotate}""#)))).unwrap();
turned(&form.pages[0]).first().map_or(0, |t| t.quarters)
};
for (rotate, want) in [("90", 1), ("180", 2), ("270", 3), ("0", 0), ("360", 0), ("450", 1), ("-90", 3), ("90deg", 1), (" 90 ", 1), ("90.0", 1)] {
assert_eq!(quarters(rotate), want, "{rotate}");
}
for rotate in ["45", "89.5", "135", "225", "abc", "", "deg", "NaN", "inf", "-inf"] {
assert_eq!(quarters(rotate), 0, "{rotate}");
}
// Far past what a turn can be told apart at, or just under none: in range whatever it reads as.
for rotate in ["1e300", "-1e-300"] {
assert!(quarters(rotate) < 4, "{rotate}");
}
}
/// A turned draw is one item: a page break moves it whole, what it holds moving with the point it
/// turns about, and doesn't cut it, and the draws around it stay where they belong.
#[test]
fn a_page_break_moves_a_turned_draw_whole() {
let draws = format!(
r#"<draw x="6in" y="10.4in" w="1in" h="0.5in"><border><edge thickness="1pt"/></border><value><text>across</text></value></draw><draw x="1in" y="1in" w="2in" h="0.5in"><value><text>first</text></value></draw>{}{}<draw x="1in" y="13in" w="2in" h="0.5in"><value><text>last</text></value></draw>"#,
[
line_draw("3in", "12in", r#"rotate="90""#),
r#"<draw x="5in" y="12in" w="2in" h="0.5in" rotate="90"><border><edge thickness="1pt"/></border><value><text>sideways</text></value></draw>"#.to_string(),
]
.concat(),
(2..8).map(|y| line_draw("1in", &format!("{y}in"), "")).collect::<String>()
);
let xdp = form_of_draws("", &draws).replace(r#"h="2.5in""#, r#"h="14in""#);
let form = layout_xml(&xdp).unwrap();
assert!(form.pages.len() >= 2, "{}", form.pages.len());
assert_eq!(texts(&form.pages[0]), ["first"]);
// Written after the turned draws, these lines still belong at the top of the block: what the
// break knew of the draw's many items mustn't carry over to those that now stand in their places.
let lines = form.pages[0].items.iter().filter(|i| matches!(i, Item::Line { .. })).count();
assert_eq!(lines, 6, "{:?}", form.pages[0].items);
assert_eq!(turned(&form.pages[0]).len(), 0);
let moved = turned(&form.pages[1]);
assert_eq!(moved.len(), 2, "{:?}", form.pages[1].items);
let Item::Line { from, .. } = &moved[0].items[0] else { panic!("not a line") };
assert_eq!(*from, moved[0].about, "the line moved with the point it turns about");
// Turned 90 degrees, a box 0.7in wide stands 0.7in up from its anchor, on a second page.
assert!(moved[0].about.1 < 792.0, "{:?}", moved[0].about);
assert!((moved[0].extent.1 - moved[0].about.1).abs() < 0.01, "{:?}", moved[0]);
assert!((moved[0].about.1 - moved[0].extent.0 - 50.4).abs() < 0.01, "{:?}", moved[0]);
let moved_text = texts(&form.pages[1]);
assert!(moved_text.contains(&"last".to_string()) && moved_text.contains(&"across".to_string()), "{moved_text:?}");
}
/// What a page break goes by is the box as it stands once turned, whichever way, about whichever
/// corner: from a top-left anchor, it stands up, up or down of it; from a bottom-right one, the
/// box starts behind the anchor and the same turns take it the other way.
#[test]
fn a_turned_draw_knows_where_it_stands() {
let box_at = |anchor: &str, rotate: u32| {
let draw = format!(
r#"<draw x="3in" y="1in" w="0.7in" h="0.4in" {anchor} rotate="{rotate}"><value><line><edge thickness="1pt"/></line></value></draw>"#
);
let form = layout_xml(&form_of_draws("", &draw)).unwrap();
let held = turned(&form.pages[0]);
let t = held.first().expect("turned");
(t.extent.0 - t.about.1, t.extent.1 - t.about.1)
};
let close = |got: (f64, f64), want: (f64, f64)| (got.0 - want.0).abs() < 0.01 && (got.1 - want.1).abs() < 0.01;
for (rotate, want) in [(90, (-50.4, 0.0)), (180, (-28.8, 0.0)), (270, (0.0, 50.4))] {
assert!(close(box_at("", rotate), want), "{rotate}: {:?}", box_at("", rotate));
}
for (rotate, want) in [(90, (0.0, 50.4)), (180, (0.0, 28.8)), (270, (-50.4, 0.0))] {
let got = box_at(r#"anchorType="bottomRight""#, rotate);
assert!(close(got, want), "{rotate}: {got:?}");
}
}
/// The page count is filled in inside a turned draw too, as it comes last, when every page is known.
#[test]
fn the_page_count_reaches_a_turned_draw() {
let master = r##"<draw x="7in" y="10in" w="1in" h="0.2in" rotate="90"><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p>of <span xfa:embed="#pageCount" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/"/></p></body></exData></value></draw><field name="pageCount" id="pageCount" presence="hidden" w="1in" h="0.2in"><ui><textEdit/></ui><event activity="ready" ref="$layout"><script contentType="application/x-javascript">this.rawValue = xfa.layout.pageCount();</script></event></field>"##;
let form = layout_xml(&form_of_draws(master, &line_draw("1in", "1in", ""))).unwrap();
let held = turned(&form.pages[0]);
assert_eq!(held.len(), 1, "{:?}", form.pages[0].items);
let text: Vec<&str> = held[0].items.iter().filter_map(|i| if let Item::Text(s) = i { Some(s.text.as_str()) } else { None }).collect();
assert_eq!(text.concat().trim(), "of 1", "{text:?}");
}
/// A link in turned text is clicked where the text is drawn, whichever way it turned: the box it
/// has unturned, turned about the draw's anchor.
#[test]
fn a_link_turns_with_its_text() {
let rect_at = |rotate: &str| {
let draw = format!(
r#"<draw x="1in" y="3in" w="2in" h="0.5in" {rotate}><value><exData contentType="text/html"><body xmlns="http://www.w3.org/1999/xhtml"><p><a href="https://example.com/a">a link in turned text</a></p></body></exData></value></draw>"#
);
let (doc, page) = written(&form_of_draws("", &draw));
let annots = page.get(b"Annots").map(|a| doc.resolve(a)).expect("the link");
let annot = doc.get(annots.as_array().unwrap()[0].as_ref().unwrap());
let rect: Vec<f64> = annot.as_dict().unwrap().get(b"Rect").unwrap().as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
rect
};
let upright = rect_at("");
let (ax, ay) = (18.0 + 72.0, 792.0 - 18.0 - 216.0);
let (left, bottom, right, top) = (upright[0] - ax, upright[1] - ay, upright[2] - ax, upright[3] - ay);
assert!(left >= -0.01 && top <= 0.01 && right - left > 3.0 * (top - bottom), "it stands right and down of its anchor: {upright:?}");
for (rotate, want) in [
("90", [ax - top, ay + left, ax - bottom, ay + right]),
("180", [ax - right, ay - top, ax - left, ay - bottom]),
("270", [ax + bottom, ay - right, ax + top, ay - left]),
] {
let got = rect_at(&format!(r#"rotate="{rotate}""#));
assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 0.01), "{rotate}: {got:?} for {want:?}");
}
}
/// Only a draw placed by position turns: a field, and a draw in a flow, stand as they did.
#[test]
fn only_positioned_draws_turn() {
let field = r#"<field name="f" x="1in" y="1in" w="2in" h="0.5in" rotate="90"><ui><textEdit/></ui></field>"#;
let form = layout_xml(&form_of_draws("", field)).unwrap();
assert!(turned(&form.pages[0]).is_empty());
assert_eq!(widgets(&form.pages[0]).len(), 1);
let flowed = form_of_draws("", &line_draw("1in", "1in", r#"rotate="90""#))
.replace(r#"<subform name="s" w="8in" h="2.5in">"#, r#"<subform name="s" w="8in" layout="tb">"#);
let form = layout_xml(&flowed).unwrap();
assert!(turned(&form.pages[0]).is_empty(), "{:?}", form.pages[0].items);
assert!(form.pages[0].items.iter().any(|i| matches!(i, Item::Line { .. })), "it is still drawn");
// A draw that shows nothing has nothing to turn.
let form = layout_xml(&form_of_draws("", &line_draw("1in", "1in", r#"rotate="90" presence="invisible""#))).unwrap();
assert!(form.pages[0].items.is_empty(), "{:?}", form.pages[0].items);
}
/// A block carried over to a content area further across takes a turned draw with it, point and
/// items both.
#[test]
fn a_turned_draw_moves_across_with_its_content_area() {
let xdp = form_of_draws("", &line_draw("1in", "6in", r#"rotate="90""#))
.replace(
r#"<contentArea x="0.25in" y="0.25in" w="8in" h="10.5in"/>"#,
r#"<contentArea x="0.25in" y="0.25in" w="3in" h="5in"/><contentArea x="4in" y="0.25in" w="3in" h="5in"/>"#,
)
.replace(r#"h="2.5in""#, r#"h="7in""#);
let form = layout_xml(&xdp).unwrap();
let moved = form.pages.iter().flat_map(turned).next().expect("turned");
let Item::Line { from, .. } = &moved.items[0] else { panic!("not a line") };
assert_eq!(*from, moved.about);
assert!((moved.about.0 - (4.0 + 1.0) * 72.0).abs() < 0.01, "{:?}", moved.about);
}
/// A positioned subform with no height grows to hold what it holds as it stands, so what comes next
/// neither runs through a turned draw nor leaves the room its upright box would have had.
#[test]
fn a_container_grows_to_a_turned_draw_as_it_stands() {
let next = r#"</subform><subform name="next" w="8in" h="1in"><draw x="0in" y="0in" w="2in" h="0.5in"><value><text>next</text></value></draw></subform></subform></template>"#;
let baseline = |rotate: &str| {
let xdp = form_of_draws("", &line_draw("1in", "1in", rotate)).replace(r#" h="2.5in""#, "").replace("</subform></subform></template>", next);
let form = layout_xml(&xdp).unwrap();
assert_eq!(form.pages.len(), 1);
form.pages[0].items.iter().find_map(|i| if let Item::Text(s) = i { Some(s.baseline) } else { None }).expect("the next block")
};
// Upright the box ends 0.4in below the anchor, and the next block starts there.
let upright = baseline("");
for (rotate, bottom) in [("90", 0.0), ("180", 0.0), ("270", 50.4)] {
let got = baseline(&format!(r#"rotate="{rotate}""#)) - (upright - 28.8);
assert!((got - bottom).abs() < 0.01, "{rotate}: the next block starts {got} below the anchor, not {bottom}");
}
}
/// A subform with no width is as wide as what it holds as it stands, whichever way that turned,
/// so a neighbour in a row doesn't stand off from it or over it.
#[test]
fn a_container_is_as_wide_as_a_turned_draw_stands() {
let row = |rotate: &str| {
let xdp = form_of_draws(
"",
&format!(
r#"<subform name="turned">{}</subform><subform name="beside" w="1in" h="1in"><draw x="0in" y="0in" w="1in" h="0.5in"><value><text>beside</text></value></draw></subform>"#,
line_draw("1in", "1in", rotate)
),
)
.replace(r#"<subform name="s" w="8in" h="2.5in">"#, r#"<subform name="s" w="8in" h="2.5in" layout="lr-tb">"#);
let form = layout_xml(&xdp).unwrap();
form.pages[0].items.iter().find_map(|i| if let Item::Text(s) = i { Some(s.x) } else { None }).expect("the neighbour")
};
let upright = row("");
// Upright it ends 0.7in right of the anchor; turned, 0.4in right, at the anchor, and at it again.
for (rotate, right) in [("90", 28.8), ("180", 0.0), ("270", 0.0)] {
let got = row(&format!(r#"rotate="{rotate}""#)) - (upright - 50.4);
assert!((got - right).abs() < 0.01, "{rotate}: the neighbour stands {got} right of the anchor, not {right}");
}
// From a bottom-right anchor the box starts behind it, and the same turns take it the other way.
for (rotate, right) in [("90", 0.0), ("180", 50.4), ("270", 28.8)] {
let got = row(&format!(r#"anchorType="bottomRight" rotate="{rotate}""#)) - (upright - 50.4);
assert!((got - right).abs() < 0.01, "{rotate}: the neighbour stands {got} right of the anchor, not {right}");
}
}
/// A page break splits an empty multi-line field that grows with its text (XFA 3.3 pp. 291–292:
/// text splits between lines, and a field's `keep intact` is `none`): it starts where it is, its
/// widget runs to the bottom of the content area, and the rest of its box, closed on every side,
/// goes on at the top of the next. Kept intact, holding a value or on one line, the field moves
/// to the next content area whole, as before.
#[test]
fn an_empty_growing_field_is_split_by_a_page_break() {
let form = |field_extra: &str, multi: &str| {
let body = format!(
r#"<draw name="filler" w="7.5in" h="8in"><value><text>above</text></value></draw>
<field name="notes" w="7.5in" minH="3in">{field_extra}
<ui><textEdit {multi}><border><edge/></border></textEdit></ui>
<caption reserve="0.5in" placement="top"><value><text>Notes</text></value></caption>
</field>"#
);
layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap()
};
let notes = |page: &Page| widgets(page).into_iter().find(|w| w.name == "notes").map(|w| w.rect);
// The content area runs from 36 to 756; the field starts at 36 + 576 = 612 and is 216 tall.
let split = form("", r#"multiLine="1""#);
assert_eq!(split.pages.len(), 2);
let first = notes(&split.pages[0]).expect("the widget starts on the first page");
assert!((first.y - 648.0).abs() < 0.5 && (first.bottom() - 756.0).abs() < 0.5, "down to the bottom of the area: {first:?}");
assert!(notes(&split.pages[1]).is_none(), "one widget");
let edges: Vec<((f64, f64), (f64, f64))> =
split.pages[1].items.iter().filter_map(|i| if let Item::Line { from, to, .. } = i { Some((*from, *to)) } else { None }).collect();
assert_eq!(edges.len(), 4, "the rest of the box, closed: {edges:?}");
let (top, bottom) = edges.iter().flat_map(|(a, b)| [a.1, b.1]).fold((f64::INFINITY, 0.0_f64), |(t, b), y| (t.min(y), b.max(y)));
assert!((top - 36.0).abs() < 1.0 && (bottom - 108.0).abs() < 1.0, "at the top of the next area, 72 tall: {top}..{bottom}");
for (extra, multi, why) in [
(r#"<keep intact="contentArea"/>"#, r#"multiLine="1""#, "kept intact"),
(r#"<value><text>typed</text></value>"#, r#"multiLine="1""#, "holding a value"),
("", "", "on one line"),
] {
let whole = form(extra, multi);
assert_eq!(whole.pages.len(), 2, "{why}");
assert!(notes(&whole.pages[0]).is_none(), "{why}: nothing of it on the first page");
let moved = notes(&whole.pages[1]).unwrap_or_else(|| panic!("{why}: the field is on the second page"));
assert!((moved.y - 72.0).abs() < 0.5, "{why}: whole, under its caption at the top: {moved:?}");
}
}
/// A field split by a page break has its own border drawn round each piece (a border's default
/// `break="close"`, XFA 3.3 pp. 629–630): an edge at the bottom of the first page and one at the
/// top of the next. One whose widget would have no room above the break for a line of its text
/// moves to the next page whole, its caption and border with it.
#[test]
fn a_split_field_closes_its_border_on_each_piece_and_a_sliver_moves_whole() {
let form = |filler: &str| {
let body = format!(
r#"<draw name="filler" w="7.5in" h="{filler}"><value><text>above</text></value></draw>
<field name="notes" w="7.5in" minH="3in">
<border><edge/></border>
<ui><textEdit multiLine="1"><border><edge presence="hidden"/></border></textEdit></ui>
<caption reserve="0.5in" placement="top"><value><text>Notes</text></value></caption>
</field>"#
);
layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap()
};
// Level lines across the field (its border's top and bottom) on `page`, top to bottom.
let levels = |page: &Page| -> Vec<f64> {
let mut ys: Vec<f64> = page
.items
.iter()
.filter_map(|i| match i {
Item::Line { from, to, .. } if (from.1 - to.1).abs() < 0.01 && (to.0 - from.0).abs() > 500.0 => Some(from.1),
_ => None,
})
.collect();
ys.sort_by(f64::total_cmp);
ys
};
// The field starts at 612, with 144 left in the area (down to 756).
let split = form("8in");
assert_eq!(split.pages.len(), 2);
let (first, next) = (levels(&split.pages[0]), levels(&split.pages[1]));
let near = |got: &[f64], want: &[f64]| got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1.0);
assert!(near(&first, &[612.0, 756.0]), "first piece closed, once: {first:?}");
assert!(near(&next, &[36.0, 108.0]), "next piece closed, once: {next:?}");
// 9.9in of filler leaves 0.1in above the break, under the widget's 0.5in caption: no room.
let sliver = form("9.9in");
assert_eq!(sliver.pages.len(), 2);
assert!(levels(&sliver.pages[0]).is_empty(), "nothing of the field left on the first page: {:?}", levels(&sliver.pages[0]));
assert!(!texts(&sliver.pages[0]).iter().any(|t| t == "Notes"), "its caption moves with it");
let whole = levels(&sliver.pages[1]);
assert!(whole.iter().any(|y| (y - 36.0).abs() < 1.0) && whole.iter().any(|y| (y - 252.0).abs() < 1.0), "whole on the next page: {whole:?}");
}
/// A field split inside a bordered section breaks the section with it, as a field moving on whole
/// does: the section's border closes on the first page under its bottom margin, which the field
/// leaves free, and opens again on the next, where the rest of the field sits under its top margin.
#[test]
fn a_field_split_inside_a_bordered_section_keeps_the_section_border_on_each_page() {
let body = r#"<subform name="sec" layout="tb" w="7.5in">
<margin topInset="0.25in" bottomInset="0.25in"/>
<border><edge/></border>
<draw name="filler" w="7.5in" h="8in"><value><text>above</text></value></draw>
<field name="notes" w="7in" minH="3in">
<border><edge/></border>
<ui><textEdit multiLine="1"/></ui>
<caption reserve="0.5in" placement="top"><value><text>Notes</text></value></caption>
</field>
</subform>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
assert_eq!(form.pages.len(), 2);
// Level lines `width` long on `page`, top to bottom: the section's are 540 long, the field's 504.
let levels = |page: &Page, width: f64| -> Vec<f64> {
let mut ys: Vec<f64> = page
.items
.iter()
.filter_map(|i| match i {
Item::Line { from, to, .. } if (from.1 - to.1).abs() < 0.01 && ((to.0 - from.0).abs() - width).abs() < 1.0 => Some(from.1),
_ => None,
})
.collect();
ys.sort_by(f64::total_cmp);
ys
};
let near = |got: &[f64], want: &[f64]| got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1.0);
// The section opens at 36 and its filler ends at 36 + 18 + 576 = 630, where the field starts.
let (sec, field) = (levels(&form.pages[0], 540.0), levels(&form.pages[0], 504.0));
assert!(near(&sec, &[36.0, 756.0]), "the section closed at the bottom of the area: {sec:?}");
assert!(near(&field, &[630.0, 738.0]), "the field's first piece ends above the section's bottom margin: {field:?}");
// 216 - 108 = 108 of the field are left, under the section's top margin.
let (sec, field) = (levels(&form.pages[1], 540.0), levels(&form.pages[1], 504.0));
assert!(near(&sec, &[36.0, 180.0]), "the section opened again round the rest: {sec:?}");
assert!(near(&field, &[54.0, 162.0]), "the rest of the field under the section's top margin: {field:?}");
}
/// A field with no room above the break for a line of its widget is placed exactly as one that
/// can't split: inside a bordered section with a top margin that goes on to the next page, it
/// sits where a field kept intact does, under the section's margin there.
#[test]
fn a_sliver_field_moves_on_as_a_field_kept_intact_does() {
let form = |keep: &str| {
let body = format!(
r#"<subform name="sec" layout="tb" w="7.5in">
<margin topInset="0.25in" bottomInset="0.25in"/>
<border><edge/></border>
<draw name="filler" w="7.5in" h="9.3in"><value><text>above</text></value></draw>
<field name="notes" w="7.5in" minH="3in">{keep}
<border><edge/></border>
<ui><textEdit multiLine="1"/></ui>
<caption reserve="0.5in" placement="top"><value><text>Notes</text></value></caption>
</field>
</subform>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let at = form.pages.iter().enumerate().find_map(|(i, p)| widgets(p).into_iter().find(|w| w.name == "notes").map(|w| (i, w.rect)));
(form.pages.len(), at)
};
let (pages, at) = form("");
assert_eq!((pages, at), form(r#"<keep intact="contentArea"/>"#), "the sliver field and one kept intact");
assert_eq!(at.map(|(page, _)| page), Some(1), "on the second page");
}
/// #5525 review: a field laid out again to move on whole (no room above the break for a line)
/// counts its items once against `MAX_ITEMS`, as a field kept intact does: what the first try
/// drew is taken off the page, and its count with it.
#[test]
fn a_field_laid_out_again_counts_its_items_once() {
let laid_out = |keep: &str| {
let body = format!(
r#"<subform name="sec" layout="tb" w="7.5in">
<draw name="filler" w="7.5in" h="9.9in"><value><text>above</text></value></draw>
<field name="notes" w="7.5in" minH="3in">{keep}
<border><edge/></border>
<ui><textEdit multiLine="1"/></ui>
<caption reserve="0.5in" placement="top"><value><text>Notes</text></value></caption>
</field>
</subform>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
let on_pages: usize = form.pages.iter().map(|p| p.items.len()).sum();
(form.pages.len(), on_pages, crate::layout::LAID_OUT_ITEMS.with(std::cell::Cell::get))
};
let (pages, on_pages, counted) = laid_out("");
assert_eq!(pages, 2, "the field moves on to page 2");
assert_eq!((pages, on_pages, counted), laid_out(r#"<keep intact="contentArea"/>"#), "laid out again, as kept intact");
}
/// #5525 review: the level lines about `len` long on `page` (a border's top and bottom edges),
/// top to bottom.
fn level_lines(page: &Page, len: f64) -> Vec<f64> {
let mut ys: Vec<f64> = page
.items
.iter()
.filter_map(|i| match i {
Item::Line { from, to, .. } if (from.1 - to.1).abs() < 0.01 && ((to.0 - from.0).abs() - len).abs() < 1.0 => Some(from.1),
_ => None,
})
.collect();
ys.sort_by(f64::total_cmp);
ys
}
/// #5525 review: whether `got` holds the values of `want`, each within a point.
fn near_all(got: &[f64], want: &[f64]) -> bool {
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1.0)
}
/// #5525 review: the pages (by index) holding the widget at SOM path `som`, with its box on each.
/// A repeated field's PDF name is made up, so the widget is found by its SOM path.
fn widget_pieces(form: &Form, som: &str) -> Vec<(usize, Rect)> {
form.pages.iter().enumerate().flat_map(|(i, p)| widgets(p).into_iter().filter(|w| w.som == som).map(move |w| (i, w.rect))).collect()
}
/// #5525 review: the baseline of the first text span `text` on `page`.
fn baseline_of(page: &Page, text: &str) -> Option<f64> {
page.items.iter().find_map(|i| match i {
Item::Text(s) if s.text == text => Some(s.baseline),
_ => None,
})
}
/// #5525 review: an empty growing field `name` with its own border all round and no widget
/// border, `min_h` tall, `extra` inside it.
fn bordered_notes(name: &str, min_h: &str, extra: &str) -> String {
format!(
r#"<field name="{name}" w="7.5in" minH="{min_h}">{extra}
<border><edge/></border>
<ui><textEdit multiLine="1"><border><edge presence="hidden"/></border></textEdit></ui>
</field>"#
)
}
/// #5525 review: a field split over two pages. With 144 points left on the first page, a 216
/// point field runs to the bottom of it and its other 72 points go on at the top of the next,
/// its border closed round each piece; what follows the field starts under that rest, not
/// under a whole field moved to the next page.
#[test]
fn a_field_split_over_two_pages_has_what_follows_start_under_its_rest() {
let body = format!(
r#"<draw name="filler" w="7.5in" h="8in"><value><text>above</text></value></draw>
{}
<draw name="after" w="7.5in" h="0.5in"><value><text>after</text></value></draw>"#,
bordered_notes("notes", "3in", "")
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
assert_eq!(form.pages.len(), 2);
let pieces = widget_pieces(&form, "form[0].notes[0]");
assert!(
matches!(pieces.as_slice(), [(0, r)] if (r.y - 612.0).abs() < 0.5 && (r.bottom() - 756.0).abs() < 0.5),
"one widget, on the first page: {pieces:?}"
);
let (first, next) = (level_lines(&form.pages[0], 540.0), level_lines(&form.pages[1], 540.0));
assert!(near_all(&first, &[612.0, 756.0]), "first piece, closed: {first:?}");
assert!(near_all(&next, &[36.0, 108.0]), "the other 72 points, closed: {next:?}");
let after = baseline_of(&form.pages[1], "after").expect("what follows is on the second page");
assert!(after > 108.0 && after < 144.0, "under the rest of the field: {after}");
}
/// #5525 review: a field split over three pages. A 936 point field with 144 points left on the
/// first page fills that, the whole of the second page's content area, and 72 points of the
/// third; its border is closed round each of the three pieces, and what follows starts under
/// the last.
#[test]
fn a_field_split_over_three_pages_closes_its_border_round_every_piece() {
let body = format!(
r#"<draw name="filler" w="7.5in" h="8in"><value><text>above</text></value></draw>
{}
<draw name="after" w="7.5in" h="0.5in"><value><text>after</text></value></draw>"#,
bordered_notes("notes", "13in", "")
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
assert_eq!(form.pages.len(), 3);
let pieces = widget_pieces(&form, "form[0].notes[0]");
assert!(
matches!(pieces.as_slice(), [(0, r)] if (r.y - 612.0).abs() < 0.5 && (r.bottom() - 756.0).abs() < 0.5),
"one widget, on the first page: {pieces:?}"
);
let levels: Vec<Vec<f64>> = form.pages.iter().map(|p| level_lines(p, 540.0)).collect();
assert!(near_all(&levels[0], &[612.0, 756.0]), "first piece: {levels:?}");
assert!(near_all(&levels[1], &[36.0, 756.0]), "a whole content area: {levels:?}");
assert!(near_all(&levels[2], &[36.0, 108.0]), "the last 72 points: {levels:?}");
let after = baseline_of(&form.pages[2], "after").expect("what follows is on the third page");
assert!(after > 108.0 && after < 144.0, "under the last piece: {after}");
}
/// #5525 review: a field taller than a page that starts at the top of one (the page break is
/// right above it) splits at the bottom of that content area rather than running off the page:
/// 864 points become 720 here and 144 on the next page.
#[test]
fn a_field_taller_than_a_page_starting_at_its_top_splits_at_its_bottom() {
let form = layout_xml(&one_area_form(r#"layout="tb""#, &bordered_notes("notes", "12in", ""))).unwrap();
assert_eq!(form.pages.len(), 2);
let pieces = widget_pieces(&form, "form[0].notes[0]");
assert!(
matches!(pieces.as_slice(), [(0, r)] if (r.y - 36.0).abs() < 0.5 && (r.bottom() - 756.0).abs() < 0.5),
"the widget fills the first content area, no more: {pieces:?}"
);
assert!(near_all(&level_lines(&form.pages[0], 540.0), &[36.0, 756.0]), "{:?}", level_lines(&form.pages[0], 540.0));
assert!(near_all(&level_lines(&form.pages[1], 540.0), &[36.0, 180.0]), "{:?}", level_lines(&form.pages[1], 540.0));
}
/// #5525 review: a field that starts exactly at a page break (what is above it fills the content
/// area) has no room at all on that page: it moves to the next page whole, its border with it,
/// and nothing of it is left behind.
#[test]
fn a_field_starting_exactly_at_a_page_break_moves_on_whole() {
let body = format!(
r#"<draw name="filler" w="7.5in" h="10in"><value><text>above</text></value></draw>
{}"#,
bordered_notes("notes", "3in", "")
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
assert_eq!(form.pages.len(), 2);
assert!(level_lines(&form.pages[0], 540.0).is_empty(), "no border left behind: {:?}", level_lines(&form.pages[0], 540.0));
let pieces = widget_pieces(&form, "form[0].notes[0]");
assert!(
matches!(pieces.as_slice(), [(1, r)] if (r.y - 36.0).abs() < 0.5 && (r.bottom() - 252.0).abs() < 0.5),
"whole at the top of the next page: {pieces:?}"
);
assert!(near_all(&level_lines(&form.pages[1], 540.0), &[36.0, 252.0]), "{:?}", level_lines(&form.pages[1], 540.0));
}
/// #5525 review: the room a field needs above a page break to split there is one line of its
/// text (10 point Courier, 12 points). With exactly 12 points left the field splits, its widget
/// on the last 12 points of the page; with 11 it has no room and moves to the next page whole.
#[test]
fn a_field_splits_with_one_line_of_room_and_moves_on_whole_with_less() {
let form = |filler: &str| {
let body = format!(
r#"<draw name="filler" w="7.5in" h="{filler}"><value><text>above</text></value></draw>
{}"#,
bordered_notes("notes", "3in", "")
);
layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap()
};
let line = form("708pt");
let pieces = widget_pieces(&line, "form[0].notes[0]");
assert!(
matches!(pieces.as_slice(), [(0, r)] if (r.y - 744.0).abs() < 0.5 && (r.bottom() - 756.0).abs() < 0.5),
"one line on the first page: {pieces:?}"
);
assert!(near_all(&level_lines(&line.pages[1], 540.0), &[36.0, 240.0]), "the other 204 points: {:?}", level_lines(&line.pages[1], 540.0));
let less = form("709pt");
let pieces = widget_pieces(&less, "form[0].notes[0]");
assert!(matches!(pieces.as_slice(), [(1, r)] if (r.y - 36.0).abs() < 0.5 && (r.h - 216.0).abs() < 0.5), "whole on the next page: {pieces:?}");
assert!(level_lines(&less.pages[0], 540.0).is_empty(), "nothing of it left on the first page");
}
/// #5525 review: two such fields in a row are split by their own page breaks, and the second
/// starts from nothing of the first: the first (216 points) splits over pages one and two, the
/// second (792 points) starts under the first's rest and splits over pages two and three, and
/// each page holds only the borders of its own pieces. A second field that fits after a split
/// one is drawn whole, once.
#[test]
fn two_fields_in_a_row_are_each_split_by_their_own_page_break() {
let form = |second: &str| {
let body = format!(
r#"<draw name="filler" w="7.5in" h="8in"><value><text>above</text></value></draw>
{}
{}"#,
bordered_notes("a", "3in", ""),
bordered_notes("b", second, "")
);
layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap()
};
let both = form("11in");
assert_eq!(both.pages.len(), 3);
let a = widget_pieces(&both, "form[0].a[0]");
let b = widget_pieces(&both, "form[0].b[0]");
assert!(matches!(a.as_slice(), [(0, r)] if (r.y - 612.0).abs() < 0.5 && (r.bottom() - 756.0).abs() < 0.5), "a: {a:?}");
assert!(matches!(b.as_slice(), [(1, r)] if (r.y - 108.0).abs() < 0.5 && (r.bottom() - 756.0).abs() < 0.5), "b: {b:?}");
let levels: Vec<Vec<f64>> = both.pages.iter().map(|p| level_lines(p, 540.0)).collect();
assert!(near_all(&levels[0], &[612.0, 756.0]), "a's first piece: {levels:?}");
assert!(near_all(&levels[1], &[36.0, 108.0, 108.0, 756.0]), "a's rest and b's first piece: {levels:?}");
assert!(near_all(&levels[2], &[36.0, 180.0]), "b's other 144 points: {levels:?}");
let fits = form("1in");
assert_eq!(fits.pages.len(), 2);
let b = widget_pieces(&fits, "form[0].b[0]");
assert!(matches!(b.as_slice(), [(1, r)] if (r.y - 108.0).abs() < 0.5 && (r.h - 72.0).abs() < 0.5), "b whole: {b:?}");
let levels = level_lines(&fits.pages[1], 540.0);
assert!(near_all(&levels, &[36.0, 108.0, 108.0, 180.0]), "a's rest, and b once: {levels:?}");
}
/// #5525 review: the field of the second instance of a repeated subform splits like any other,
/// found by its SOM path (its PDF name is made up), while the first instance's field, which
/// fits, stays whole.
#[test]
fn a_field_in_a_repeated_subform_splits_in_the_instance_that_reaches_the_break() {
let body = format!(
r#"<draw name="filler" w="7.5in" h="6in"><value><text>above</text></value></draw>
<subform name="row" layout="tb" w="7.5in"><occur min="2" initial="2"/>
{}
</subform>"#,
bordered_notes("notes", "3in", "")
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
assert_eq!(form.pages.len(), 2);
let first = widget_pieces(&form, "form[0].row[0].notes[0]");
let second = widget_pieces(&form, "form[0].row[1].notes[0]");
assert!(matches!(first.as_slice(), [(0, r)] if (r.y - 468.0).abs() < 0.5 && (r.h - 216.0).abs() < 0.5), "first whole: {first:?}");
assert!(matches!(second.as_slice(), [(0, r)] if (r.y - 684.0).abs() < 0.5 && (r.bottom() - 756.0).abs() < 0.5), "second split: {second:?}");
let (page0, page1) = (level_lines(&form.pages[0], 540.0), level_lines(&form.pages[1], 540.0));
assert!(near_all(&page0, &[468.0, 684.0, 684.0, 756.0]), "{page0:?}");
assert!(near_all(&page1, &[36.0, 180.0]), "{page1:?}");
}
/// #5525 review: a field split inside two nested sections, each with a quarter-inch bottom and
/// top margin, leaves both bottom margins free under its first piece (it ends 36 points above
/// the bottom of the content area) and goes on under both top margins on the next page.
#[test]
fn a_field_split_inside_nested_sections_leaves_room_for_both_margins() {
let body = r#"<subform name="outer" layout="tb" w="7.5in">
<margin topInset="0.25in" bottomInset="0.25in"/>
<subform name="inner" layout="tb" w="7.5in">
<margin topInset="0.25in" bottomInset="0.25in"/>
<draw name="filler" w="7.5in" h="8in"><value><text>above</text></value></draw>
<field name="notes" w="7in" minH="3in">
<border><edge/></border>
<ui><textEdit multiLine="1"><border><edge presence="hidden"/></border></textEdit></ui>
</field>
</subform>
</subform>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
assert_eq!(form.pages.len(), 2);
// The filler starts under both top margins, at 72, so the field starts at 648.
let (first, next) = (level_lines(&form.pages[0], 504.0), level_lines(&form.pages[1], 504.0));
assert!(near_all(&first, &[648.0, 720.0]), "first piece ends above both bottom margins: {first:?}");
assert!(near_all(&next, &[72.0, 216.0]), "the other 144 points under both top margins: {next:?}");
}
/// #5525 review: `<keep intact>` decides whether a page break may split the field (XFA 3.3
/// p. 292): `contentArea` and `pageArea` keep it whole, moving it to the next page, while
/// `none` and a value XFA doesn't define leave a field's default, `none`, and it splits.
#[test]
fn keep_intact_values_decide_whether_the_field_splits() {
let at = |keep: &str| {
let body = format!(
r#"<draw name="filler" w="7.5in" h="8in"><value><text>above</text></value></draw>
{}"#,
bordered_notes("notes", "3in", &format!(r#"<keep intact="{keep}"/>"#))
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
widget_pieces(&form, "form[0].notes[0]")
};
for keep in ["contentArea", "pageArea"] {
let pieces = at(keep);
assert!(matches!(pieces.as_slice(), [(1, r)] if (r.y - 36.0).abs() < 0.5 && (r.h - 216.0).abs() < 0.5), "{keep}: whole: {pieces:?}");
}
for keep in ["none", "sideways", ""] {
let pieces = at(keep);
assert!(
matches!(pieces.as_slice(), [(0, r)] if (r.y - 612.0).abs() < 0.5 && (r.bottom() - 756.0).abs() < 0.5),
"{keep:?}: split: {pieces:?}"
);
}
}
/// #5525 review: extreme and malformed sizes. A 1000 inch empty field splits over exactly 100
/// pages, its widget on the first only and its border closed on each; a `minH` past the largest
/// length a measurement may have (100,000 points) splits over 139 pages; fields that would need
/// more pages than a form may have (500) are refused with an error rather than a panic or a
/// hang; and a negative, NaN or non-numeric `minH`, or a content area too short for a line,
/// lays out without panicking.
#[test]
fn a_split_field_survives_huge_and_malformed_sizes() {
let huge = layout_xml(&one_area_form(r#"layout="tb""#, &bordered_notes("notes", "1000in", ""))).unwrap();
assert_eq!(huge.pages.len(), 100);
assert!(matches!(widget_pieces(&huge, "form[0].notes[0]").as_slice(), [(0, _)]), "one widget, on the first page");
for (i, p) in huge.pages.iter().enumerate() {
assert!(near_all(&level_lines(p, 540.0), &[36.0, 756.0]), "page {i}: {:?}", level_lines(p, 540.0));
}
let capped = layout_xml(&one_area_form(r#"layout="tb""#, &bordered_notes("notes", "100000in", ""))).unwrap();
assert_eq!(capped.pages.len(), 139, "100,000 points over 720 point content areas");
let four: String = (0..4).map(|i| bordered_notes(&format!("n{i}"), "100000in", "")).collect();
let too_many = layout_xml(&one_area_form(r#"layout="tb""#, &four));
assert!(matches!(too_many, Err(XfaError::TooLarge(_))), "{:?}", too_many.map(|f| f.pages.len()));
for min_h in ["-3in", "NaNin", "abc", "0"] {
let form = layout_xml(&one_area_form(r#"layout="tb""#, &bordered_notes("notes", min_h, ""))).unwrap();
assert!(!form.pages.is_empty(), "{min_h}");
}
let tiny = one_area_form(r#"layout="tb""#, &bordered_notes("notes", "3in", "")).replace(r#"h="10in""#, r#"h="0.5pt""#);
let _ = layout_xml(&tiny);
}
/// #5525 review: the widget's own border (the text edit's) of a field split over three pages is
/// closed round every piece below the widget, not only the first: the middle page gets a box
/// from the top of its content area to the bottom, and the last page one round the last 72
/// points, each with its top and bottom edge.
#[test]
fn a_widget_border_split_over_three_pages_is_closed_round_every_piece() {
let body = r#"<draw name="filler" w="7.5in" h="8in"><value><text>above</text></value></draw>
<field name="notes" w="7.5in" minH="13in"><ui><textEdit multiLine="1"><border><edge/></border></textEdit></ui></field>"#;
let form = layout_xml(&one_area_form(r#"layout="tb""#, body)).unwrap();
assert_eq!(form.pages.len(), 3);
// The edges are half a point wide, drawn a quarter of a point inside the box.
let (middle, last) = (level_lines(&form.pages[1], 539.5), level_lines(&form.pages[2], 539.5));
assert!(near_all(&middle, &[36.25, 755.75]), "the middle piece, closed at the bottom of the page: {middle:?}");
assert!(near_all(&last, &[36.25, 107.75]), "the last piece, closed at its top: {last:?}");
}
/// #5525 review: a bordered section round an empty field split over three pages keeps its
/// border on every page, even when what is left of the field draws nothing there (no widget
/// border or fill): the middle page and the last still hold a part of the section. With or
/// without the field's own border, the section is closed on page one under its bottom margin,
/// runs the whole content area on page two, and closes under the field's last 144 points on
/// page three.
#[test]
fn a_bordered_section_round_a_field_split_over_three_pages_is_closed_on_every_page() {
for field_border in ["", "<border><edge/></border>"] {
let body = format!(
r#"<subform name="sec" layout="tb" w="7.5in">
<margin topInset="0.25in" bottomInset="0.25in"/>
<border><edge/></border>
<draw name="filler" w="7.5in" h="8in"><value><text>above</text></value></draw>
<field name="notes" w="7in" minH="13in">{field_border}
<ui><textEdit multiLine="1"><border><edge presence="hidden"/></border></textEdit></ui>
</field>
</subform>"#
);
let form = layout_xml(&one_area_form(r#"layout="tb""#, &body)).unwrap();
assert_eq!(form.pages.len(), 3, "{field_border:?}");
let sec: Vec<Vec<f64>> = form.pages.iter().map(|p| level_lines(p, 540.0)).collect();
// The field starts at 36 + 18 + 576 = 630 and is 936 tall: 108 on page one (down to
// 738), 684 on page two (54 to 738), and the last 144 on page three (54 to 198).
assert!(near_all(&sec[0], &[36.0, 756.0]), "{field_border:?}: page one: {sec:?}");
assert!(near_all(&sec[1], &[36.0, 756.0]), "{field_border:?}: page two, a whole content area: {sec:?}");
assert!(near_all(&sec[2], &[36.0, 216.0]), "{field_border:?}: page three, under the field's last piece: {sec:?}");
if !field_border.is_empty() {
let field: Vec<Vec<f64>> = form.pages.iter().map(|p| level_lines(p, 504.0)).collect();
assert!(near_all(&field[0], &[630.0, 738.0]), "{field:?}");
assert!(near_all(&field[1], &[54.0, 738.0]), "{field:?}");
assert!(near_all(&field[2], &[54.0, 198.0]), "{field:?}");
}
}
}
/// #5525 review: a field split into content areas of different sizes keeps moving down even
/// where the margins of the sections round it leave no room. The first page area (used once) has
/// a 720 point content area; the next has one only 36 points tall, under a section's 72 point
/// bottom margin (or with its 72 point top margin taking the whole of it). The field still goes on
/// 36 points a page, from the top of each small area, instead of breaking to new pages until the
/// form has too many; the section, which can't hold it there, is drawn without its border, and
/// the layout says so.
#[test]
fn a_field_split_into_areas_smaller_than_its_sections_margins_still_moves_on() {
let form = |margin: &str, border: &str| {
let xml = 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="first"><occur max="1"/><contentArea x="0.5in" y="0.5in" w="7.5in" h="10in"/><medium short="8.5in" long="11in"/></pageArea>
<pageArea name="rest"><contentArea x="0.5in" y="0.5in" w="7.5in" h="0.5in"/><medium short="8.5in" long="11in"/></pageArea>
</pageSet>
<subform name="sec" layout="tb" w="7.5in">
<margin {margin}/>{border}
<draw name="filler" w="7.5in" h="8in"><value><text>above</text></value></draw>
{}
</subform>
</subform>
</template>
</xdp:xdp>
"##,
bordered_notes("notes", "3in", "")
);
layout_xml(&xml)
};
// Under a 72 point bottom margin the field starts at 612 and its first piece ends at 684; under
// a 72 point top margin it starts at 684 and its first piece ends at 756. Either way 144 points
// are left, four small areas' worth.
for (margin, first) in [(r#"bottomInset="1in""#, [612.0, 684.0]), (r#"topInset="1in""#, [684.0, 756.0])] {
let laid_out = form(margin, "");
let pages = match &laid_out {
Ok(f) => &f.pages,
Err(e) => panic!("{margin}: {e:?}"),
};
assert_eq!(pages.len(), 5, "{margin}");
let levels: Vec<Vec<f64>> = pages.iter().map(|p| level_lines(p, 540.0)).collect();
assert!(near_all(&levels[0], &first), "{margin}: first piece: {levels:?}");
for (i, l) in levels.iter().enumerate().skip(1) {
assert!(near_all(l, &[36.0, 72.0]), "{margin}: page {i}, the whole small area: {levels:?}");
}
let bordered = form(margin, "<border><edge/></border>").unwrap_or_else(|e| panic!("{margin}: bordered: {e:?}"));
assert_eq!(bordered.pages.len(), 5, "{margin}: bordered");
assert!(bordered.warnings.iter().any(|w| w.contains("without its border")), "{margin}: {:?}", bordered.warnings);
}
}
/// A template for the reset defaults: a choice list showing `Label` and saving `code`, with
/// `Label` its default, and an exclusion group whose second button is on by default.
fn reset_defaults_template() -> Template {
let xml = r#"<template xmlns="http://www.xfa.org/schema/xfa-template/3.3/"><subform name="form"><subform name="page1">
<field name="kind"><ui><choiceList/></ui><items><text>Label</text><text>Other</text></items><items save="1"><text>code</text><text>other</text></items><value><text>Label</text></value></field>
<exclGroup name="pick"><field name="a"><ui><checkButton/></ui><items><text>A</text></items></field><field name="b"><ui><checkButton/></ui><items><text>B</text></items><value><text>B</text></value></field></exclGroup>
<exclGroup name="none"><field name="a"><ui><checkButton/></ui><items><text>A</text></items></field></exclGroup>
<field name="go"><ui><button/></ui></field>
</subform></subform></template>"#;
crate::parse::parse(xml).unwrap().0
}
/// A reset gives a choice list the default it saves (the item value), not the text it shows,
/// as the live form reads it.
#[test]
fn a_choice_list_resets_to_its_saved_default() {
let tpl = reset_defaults_template();
assert_eq!(reset_default(&tpl, "form[0].page1[0].kind[0]").as_deref(), Some("code"));
}
/// An exclusion group resets to the on value of the button that is on by default, or to
/// nothing; its buttons, and push buttons, restore no value of their own.
#[test]
fn an_exclusion_group_resets_to_its_default_button() {
let tpl = reset_defaults_template();
assert_eq!(reset_default(&tpl, "form[0].page1[0].pick[0]").as_deref(), Some("B"));
assert_eq!(reset_default(&tpl, "form[0].page1[0].none[0]").as_deref(), Some(""));
assert_eq!(reset_default(&tpl, "form[0].page1[0].pick[0].b[0]"), None);
assert_eq!(reset_default(&tpl, "form[0].page1[0].go[0]"), None);
assert_eq!(reset_default(&tpl, "form[0].page1[0]"), None);
assert_eq!(reset_default(&tpl, "form[0].page1[0].missing[0]"), None);
}
/// A reset writes a multi-select list's default picks as `value` elements, in the packet and in
/// the copy scripts read, as any value write does; other structured content (rich text) is left
/// as it is, with a warning.
#[test]
fn a_reset_replaces_structured_multi_select_picks() {
let xdp = template_with_data(1, "<form><tags><value>a</value><value>b</value></tags><body><p>rich</p></body></form>");
let path = som_to_path("form[0].tags[0]");
let value_at = |doc: &Document| data_of(doc).and_then(|d| d.value_at(&path)).unwrap_or_default();
let mut doc = Document::open(Arc::new(shell(&xdp))).unwrap();
write_data_ops(
&mut doc,
&[DataOp::Value {
path: path.clone(),
text: "c
d&e"
.into(),
}],
None,
)
.unwrap();
assert_eq!(
value_at(&doc),
"c
d&e"
);
let packets = read_packets(&doc).unwrap().unwrap();
assert!(packets.xdp.contains("<value>c</value><value>d&amp;e</value></tags>"), "{}", packets.xdp);
let mut copy = data_of(&Document::open(Arc::new(shell(&xdp))).unwrap()).unwrap();
copy.apply(&DataOp::Value {
path: path.clone(),
text: "c
d&e"
.into(),
});
assert_eq!(
copy.value_at(&path).as_deref(),
Some(
"c
d&e"
)
);
let body = som_to_path("form[0].body[0]");
let r = write_data_ops(&mut doc, &[DataOp::Value { path: body.clone(), text: String::new() }], None).unwrap();
assert!(!r.warnings.is_empty());
assert_eq!(data_of(&doc).unwrap().get(&body).map(|n| n.children.len()), Some(1));
copy.apply(&DataOp::Value { path: body.clone(), text: String::new() });
assert_eq!(copy.get(&body).map(|n| n.children.len()), Some(1));
}
/// Only a template that is a packet of the XDP is the form's: one inside imported data (a
/// dataset holding XML that looks like a template) is not read, and neither are its scripts.
#[test]
fn a_template_inside_the_data_is_not_the_form() {
let nested = "<xdp:xdp xmlns:xdp=\"http://ns.adobe.com/xdp/\"><xfa:datasets xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"><xfa:data><template xmlns=\"http://www.xfa.org/schema/xfa-template/3.3/\"><subform name=\"evil\"><event activity=\"initialize\"><script>xfa.host.messageBox(1)</script></event></subform></template></xfa:data></xfa:datasets></xdp:xdp>";
assert!(parse(nested).is_err(), "no template packet");
let real = "<xdp:xdp xmlns:xdp=\"http://ns.adobe.com/xdp/\"><template xmlns=\"http://www.xfa.org/schema/xfa-template/3.3/\"><subform name=\"form1\"/></template></xdp:xdp>";
assert_eq!(parse(real).unwrap().0.root.common.name.as_deref(), Some("form1"));
}
/// A multi-select choice list is bound to a data group of `value` elements, one per pick, and its
/// value is theirs joined by newlines (XFA 3.3 p. 198). New picks replace the group's `value`
/// elements, values off the list included, as Acrobat discards them (p. 199): the group was left
/// as it was, so the old picks came back on reading, in the datasets and in the scripts' data.
#[test]
fn a_multi_select_lists_data_group_takes_its_new_picks() {
let shell =
crate::fixtures::static_shell("<form1><page1><grains><value>rye</value><value>barley</value><value>wheat</value></grains></page1></form1>");
let mut doc = Document::open(Arc::new(shell)).unwrap();
let path = som_to_path("form1[0].page1[0].grains[0]");
assert!(write_data_value(&mut doc, &path, "wheat\nmillet & oats").unwrap().written);
let data = crate::script::data_of(&doc).unwrap();
assert_eq!(data.value_at(&path).as_deref(), Some("wheat\nmillet & oats"));
assert_eq!(data.count(&path, "value"), 2, "one value element per pick");
assert!(!write_data_value(&mut doc, &path, "wheat\nmillet & oats").unwrap().written, "the same picks change nothing");
assert!(write_data_value(&mut doc, &path, "").unwrap().written);
assert_eq!(crate::script::data_of(&doc).unwrap().value_at(&path).as_deref(), Some(""), "nothing picked");
// Emptied, the group is marked as one (XFA 3.3 p. 150), so it is still written as picks.
let xdp = crate::read_packets(&doc).unwrap().unwrap().xdp;
assert!(xdp.contains("<grains xfa:dataNode=\"dataGroup\"></grains>"), "{xdp}");
assert!(
write_data_value(
&mut doc,
&path,
"rye
millet"
)
.unwrap()
.written
);
assert_eq!(crate::script::data_of(&doc).unwrap().count(&path, "value"), 2, "picks again, not text");
// A pick split or led by a comment is read whole: the same pick is no change, and clearing
// a pick that reads as empty through its first segment alone still clears it.
let commented =
crate::fixtures::static_shell("<form1><page1><grains><value><!-- a -->rye</value><value>whe<!-- b -->at</value></grains></page1></form1>");
let mut doc = Document::open(Arc::new(commented)).unwrap();
assert!(
!write_data_value(
&mut doc,
&path,
"rye
wheat"
)
.unwrap()
.written,
"the same picks, read past the comments"
);
assert_eq!(
crate::script::data_of(&doc).unwrap().value_at(&path).as_deref(),
Some(
"rye
wheat"
),
"and read back without them"
);
assert!(write_data_value(&mut doc, &path, "").unwrap().written, "cleared");
assert_eq!(crate::script::data_of(&doc).unwrap().count(&path, "value"), 0);
// Where `xfa` names another namespace and `pcxfa` is taken too, the marker's prefix is a free
// one, declared on the group, so no attribute in scope changes meaning.
let shadowed = crate::fixtures::static_shell(
"<form1><page1><grains xmlns:xfa=\"urn:other\" xmlns:pcxfa=\"urn:taken\" pcxfa:note=\"x\"><value>rye</value></grains></page1></form1>",
);
let mut doc = Document::open(Arc::new(shadowed)).unwrap();
assert!(write_data_value(&mut doc, &path, "").unwrap().written);
let xdp = crate::read_packets(&doc).unwrap().unwrap().xdp;
assert!(xdp.contains("xmlns:pcxfa1=\"http://www.xfa.org/schema/xfa-data/1.0/\" pcxfa1:dataNode=\"dataGroup\""), "{xdp}");
assert!(xdp.contains("xmlns:pcxfa=\"urn:taken\" pcxfa:note=\"x\""), "the taken prefix keeps its namespace: {xdp}");
// With every candidate prefix taken, no marker can be written: the group keeps its pick
// and the skip is reported, rather than emptied into what would load as a data value.
let taken: String = (0..16).map(|i| if i == 0 { " xmlns:pcxfa=\"urn:t\"".to_string() } else { format!(" xmlns:pcxfa{i}=\"urn:t\"") }).collect();
let crowded =
crate::fixtures::static_shell(&format!("<form1><page1><grains xmlns:xfa=\"urn:other\"{taken}><value>rye</value></grains></page1></form1>"));
let mut doc = Document::open(Arc::new(crowded)).unwrap();
let r = write_data_value(&mut doc, &path, "").unwrap();
assert!(!r.written && r.warnings.iter().any(|w| w.contains("structured content")), "{:?}", r.warnings);
assert_eq!(crate::script::data_of(&doc).unwrap().value_at(&path).as_deref(), Some("rye"));
// One `value` whose text holds a line break is one pick, not the two it would join to.
let one = crate::fixtures::static_shell(
"<form1><page1><grains><value>one
two</value></grains></page1></form1>",
);
let mut doc = Document::open(Arc::new(one)).unwrap();
assert!(
write_data_value(
&mut doc, &path, "one
two"
)
.unwrap()
.written,
"two picks replace the one"
);
assert_eq!(crate::script::data_of(&doc).unwrap().count(&path, "value"), 2);
// The in-memory data, which scripts read before the packet is written, follows the same rule.
let mut tree = crate::script::data_of(
&Document::open(Arc::new(crate::fixtures::static_shell("<form1><page1><grains><value>rye</value></grains></page1></form1>"))).unwrap(),
)
.unwrap();
tree.apply(&DataOp::Value { path: path.clone(), text: "millet\nwheat".into() });
assert_eq!(tree.value_at(&path).as_deref(), Some("millet\nwheat"));
// Emptied in memory, the group still takes picks, not text.
tree.apply(&DataOp::Value { path: path.clone(), text: String::new() });
assert_eq!((tree.count(&path, "value"), tree.value_at(&path).as_deref()), (0, Some("")));
tree.apply(&DataOp::Value { path: path.clone(), text: "rye\nmillet".into() });
assert_eq!((tree.count(&path, "value"), tree.text_at(&path)), (2, Some("")), "picks again, not text");
assert_eq!(tree.value_at(&path).as_deref(), Some("rye\nmillet"));
let tree_of = |data: &str| crate::script::data_of(&Document::open(Arc::new(crate::fixtures::static_shell(data))).unwrap()).unwrap();
// A group read emptied, as the packet writer marks it, takes picks the same way.
let mut tree = tree_of("<form1><page1><grains xfa:dataNode=\"dataGroup\"/></page1></form1>");
tree.apply(&DataOp::Value { path: path.clone(), text: "rye\nmillet".into() });
assert_eq!(tree.count(&path, "value"), 2);
// A node holding anything but `value` leaves is not a list's picks: it is left as it was,
// as the packet writer leaves it (and reports the skip).
for structured in [
"<form1><page1><grains><value>rye</value><note>x</note></grains></page1></form1>",
"<form1><page1><grains><value><b>rye</b></value></grains></page1></form1>",
] {
let mut tree = tree_of(structured);
let before = tree.clone();
tree.apply(&DataOp::Value { path: path.clone(), text: "millet".into() });
assert_eq!(tree, before, "{structured}");
}
}