diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a245b41f84..84d071083e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -8081,6 +8081,26 @@ fn exporting_office_keeps_dotted_leader_entries_as_paragraphs() { assert!(positions.windows(2).all(|pair| pair[0] < pair[1]), "reading order: {html}"); } +/// A field whose layout:ready script only reads the page count keeps the value its script gives +/// it: only a field the script gives the page call's result is numbered by the layout. +#[test] +fn a_field_that_only_reads_the_page_count_keeps_its_scripts_value() { + let xdp = r##" + + + +"##; + let mut s = Session::new(); + let id = s.open("reads.pdf", None, Arc::new(pdfcraft_xfa::fixtures::shell(xdp)), None).expect("opens"); + let value = s.get(id).unwrap().form.iter().find(|f| f.name == "reads").map(|f| f.value.clone()).unwrap_or_default(); + assert_eq!(value, vec!["pages: 1".to_string()]); +} + /// layout:ready scripts run once on opening: the root's turns field highlighting on (only when it /// is off), a field's sets a value and a later script reads the new highlight, while page /// numbering is left to the layout. form:ready is another event, and runs too. diff --git a/crates/xfa/src/parse.rs b/crates/xfa/src/parse.rs index 796c9827c8..35c756bd4f 100644 --- a/crates/xfa/src/parse.rs +++ b/crates/xfa/src/parse.rs @@ -682,13 +682,60 @@ fn parse_node(c: XmlNode, warnings: &mut Vec, depth: usize) -> Option bool { + own_page_role(script, formcalc).is_some() +} + +/// The page-number role a `layout:ready` script gives its own field ([`numbers_pages`]): the page +/// count when what it assigns calls `pageCount()`, else the page number. +fn own_page_role(script: &str, formcalc: bool) -> Option { let code = code_of(script, formcalc); - code.contains("pageCount") || code.contains("layout.page(") || code.contains("layout.absPage(") + let own = own_assignments(&code, formcalc); + if own.iter().any(|rhs| calls_layout(rhs, "pageCount")) { + Some(PageRole::Count) + } else if own.iter().any(|rhs| calls_layout(rhs, "page") || calls_layout(rhs, "absPage")) { + Some(PageRole::Number) + } else { + None + } +} + +/// What the statements of `code` assign to the script's own field: the text after `=` of each +/// `this.rawValue = …` (in FormCalc also `$.rawValue = …` and `$ = …`). Statements end at a line +/// break, and in JavaScript at `;` too. +fn own_assignments(code: &str, formcalc: bool) -> Vec<&str> { + let targets: &[&str] = if formcalc { &["this.rawValue", "$.rawValue", "$"] } else { &["this.rawValue"] }; + code.split(|c| c == '\n' || (!formcalc && c == ';')) + .filter_map(|statement| { + let statement = statement.trim(); + targets.iter().find_map(|t| { + let rhs = statement.strip_prefix(t)?.trim_start().strip_prefix('=')?; + (!rhs.starts_with('=')).then_some(rhs) + }) + }) + .collect() +} + +/// Whether `code` calls `layout.(…)`: the method's whole name after `layout.` (spaces +/// allowed around the dot), then `(` after any spaces. +fn calls_layout(code: &str, method: &str) -> bool { + let ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$'; + code.match_indices(method).any(|(i, _)| { + let before = code.get(..i).unwrap_or_default().trim_end(); + let after = code.get(i + method.len()..).unwrap_or_default(); + !after.chars().next().is_some_and(ident) + && after.trim_start().starts_with('(') + && before + .strip_suffix('.') + .map(str::trim_end) + .and_then(|b| b.strip_suffix("layout")) + .is_some_and(|rest| !rest.chars().next_back().is_some_and(ident)) + }) } /// `script` with its comments and string literals blanked out: `//` and `/* */` comments and @@ -739,14 +786,8 @@ fn code_of(script: &str, formcalc: bool) -> String { /// Which page-number role a field with a layout:ready script plays, if any. fn page_role(f: &Field) -> Option { - let script = f.scripts.iter().find(|s| s.activity == "ready" || s.activity == "layoutReady")?; - if !numbers_pages(&script.text, script.formcalc) { - None - } else if code_of(&script.text, script.formcalc).contains("pageCount") { - Some(PageRole::Count) - } else { - Some(PageRole::Number) - } + // Any of its layout:ready scripts, past a form:ready one. + f.scripts.iter().filter(|s| s.activity == "layoutReady").find_map(|s| own_page_role(&s.text, s.formcalc)) } fn collect_page_roles(nodes: &[Node], out: &mut Vec<(String, PageRole)>, depth: usize) { diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs index d79b5a3e37..5ddd409df8 100644 --- a/crates/xfa/src/tests.rs +++ b/crates/xfa/src/tests.rs @@ -3537,6 +3537,27 @@ fn trailing_spaces_do_not_shift_centered_or_right_aligned_text() { /// `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##" +"##; + let (tpl, _) = parse(xdp).unwrap(); + assert_eq!(tpl.page_roles, vec![("no".to_string(), PageRole::Number)]); +} + #[test] fn a_layout_ready_event_is_told_apart_from_form_ready() { let (tpl, _) = parse(&crate::fixtures::layout_ready_template()).unwrap(); @@ -3565,6 +3586,16 @@ fn a_layout_ready_event_is_told_apart_from_form_ready() { 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);")); } /// `typed_date` rewrites a date typed by another of a field's edit-picture patterns in the first