diff --git a/crates/automation/src/a11y/form_tools.rs b/crates/automation/src/a11y/form_tools.rs index 7ff433af63..10cc9d2078 100644 --- a/crates/automation/src/a11y/form_tools.rs +++ b/crates/automation/src/a11y/form_tools.rs @@ -19,6 +19,11 @@ fn request_json(r: &pdfcraft_engine::js::Request) -> Value { R::OpenDoc(path) => json!({ "open_doc": path }), R::OpenAttachment { name, open } => json!({ "attachment": name, "open": open }), R::ShowPanel(p) => json!({ "panel": p.id() }), + // Applied by the engine with the script's field changes; listed only if one is left over. + R::SpawnTemplate { name, page, rename, overlay } => { + json!({ "spawn_template": name, "page": page.saturating_add(1), "rename": rename, "overlay": overlay }) + } + R::SetTemplateHidden { name, hidden } => json!({ "template": name, "hidden": hidden }), } } diff --git a/crates/automation/src/dispatch.rs b/crates/automation/src/dispatch.rs index 6439a12d1d..212664a37a 100644 --- a/crates/automation/src/dispatch.rs +++ b/crates/automation/src/dispatch.rs @@ -315,6 +315,22 @@ impl Automation { let at = self.opt_position(&a, "at")?; self.apply(&a, Edit::DuplicatePages { pages, at })? } + "page_templates" => { + let templates: Vec = self.doc(&a)?.templates().into_iter().map(|t| json!({ "name": t.name, "hidden": t.hidden })).collect(); + json!({ "templates": templates }) + } + "page_template_spawn" => { + let at = self.opt_position(&a, "at")?.unwrap_or(self.doc(&a)?.info.pages.len()); + let edit = Edit::SpawnTemplate { name: a.str("name")?.into(), at, rename: a.opt_bool("rename")?.unwrap_or(true) }; + self.apply(&a, edit)? + } + "page_template_set_hidden" => self.apply( + &a, + Edit::SetTemplateHidden { + name: a.str("name")?.into(), + hidden: a.opt_bool("hidden")?.ok_or_else(|| ToolError::InvalidArgs("hidden is required".into()))?, + }, + )?, "page_set_box" => self.page_set_box(&a)?, "page_transition_set" => self.page_transition_set(&a)?, "doc_create" => self.doc_create(&a)?, diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs index 481ded19b9..a5b6d99617 100644 --- a/crates/automation/src/tools.rs +++ b/crates/automation/src/tools.rs @@ -1184,6 +1184,13 @@ pub fn tools() -> Vec { t("page_duplicate", "Duplicate pages", "Insert copies of pages so the first copy becomes page `at`, or after the last of them when `at` is left out (fonts and images are shared, not copied). Undoable.") .cmd("page.duplicate") .with(schema(json!({ "doc": doc(), "pages": pages("to duplicate"), "at": { "type": "integer", "minimum": 1 } }), &["doc", "pages"])), + t("page_templates", "List page templates", "The document's page templates (ISO 32000-2 §7.7.4: the name dictionary's /Templates, pages kept out of the document, then /Pages, named visible pages): each name, and whether it is hidden. A form's JavaScript adds pages from them (Template.spawn) or shows them (Template.hidden = false).") + .ro() + .with(schema(json!({ "doc": doc() }), &["doc"])), + t("page_template_spawn", "Add a page from a template", "Insert a copy of page template `name` so it becomes page `at` (default: after the last page), as JavaScript's Template.spawn does. With rename (the default, as in Acrobat) the copy's fields are its own, named P..; with rename false they are more widgets of the template's fields and share their values. Undoable.") + .with(schema(json!({ "doc": doc(), "name": { "type": "string" }, "at": { "type": "integer", "minimum": 1 }, "rename": { "type": "boolean" } }), &["doc", "name"])), + t("page_template_set_hidden", "Show or hide a page template", "Show page template `name` (hidden false: its own page goes at the end of the document, with its fields) or hide it again (hidden true: the page leaves the document and is kept as a template), as JavaScript's Template.hidden does. Undoable.") + .with(schema(json!({ "doc": doc(), "name": { "type": "string" }, "hidden": { "type": "boolean" } }), &["doc", "name", "hidden"])), t( "page_transition_set", "Set page transitions", diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs index 2e828f2643..c8caff969f 100644 --- a/crates/automation/tests/it/main.rs +++ b/crates/automation/tests/it/main.rs @@ -20,6 +20,7 @@ mod model_render; mod office; mod optimize_content_boundaries; mod page_actions; +mod page_templates; mod portfolio_info; mod redact_after_stray_q_form; mod redact_text_after_q; diff --git a/crates/automation/tests/it/page_templates.rs b/crates/automation/tests/it/page_templates.rs new file mode 100644 index 0000000000..f8206fbd32 --- /dev/null +++ b/crates/automation/tests/it/page_templates.rs @@ -0,0 +1,95 @@ +//! Page templates through the tools (#1429): list them, add a page from one, show or hide one. + +use std::path::PathBuf; + +use pdfcraft_automation::{Automation, Content, ToolError}; +use serde_json::{Value, json}; + +/// One visible page and a hidden template `More` holding the text field `Extra`. +fn form() -> Vec { + let bodies = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /Templates 6 0 R >> /AcroForm << /Fields [7 0 R] /DA (/Helv 0 Tf 0 g) >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>", + "<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /Font << /F1 9 0 R >> >> >>", + "<< /Length 40 >>\nstream\nBT /F1 12 Tf 20 20 Td (Visible) Tj ET\nendstream", + "<< /Type /Template /Contents 8 0 R /Resources << /Font << /F1 9 0 R >> >> /Annots [7 0 R] >>", + "<< /Names [(More) 5 0 R] >>", + "<< /FT /Tx /T (Extra) /Subtype /Widget /Rect [20 100 180 120] /P 5 0 R >>", + "<< /Length 41 >>\nstream\nBT /F1 12 Tf 20 20 Td (Template) Tj ET\nendstream", + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, b) in bodies.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{b}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", bodies.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", bodies.len() + 1).as_bytes()); + out +} + +fn setup(test: &str) -> (PathBuf, Automation) { + let dir = std::env::temp_dir().join(format!("pdfcraft-page-templates-{test}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("form.pdf"), form()).unwrap(); + let a = Automation::new().with_root(&dir).unwrap(); + (dir, a) +} + +fn ok(a: &mut Automation, tool: &str, args: Value) -> Value { + match a.call(tool, &args).unwrap_or_else(|e| panic!("{tool}: {e:?}")).remove(0) { + Content::Json(v) => v, + other => panic!("{tool}: expected JSON: {other:?}"), + } +} + +fn field_names(a: &mut Automation, doc: u64) -> Vec { + let fields = ok(a, "form_fields", json!({ "doc": doc })); + let mut names: Vec = fields["fields"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap().to_string()).collect(); + names.sort(); + names +} + +#[test] +fn templates_are_listed_spawned_shown_and_hidden_through_tools() { + let (dir, mut a) = setup("tools"); + let doc = ok(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap(); + assert_eq!(ok(&mut a, "page_templates", json!({ "doc": doc })), json!({ "templates": [{ "name": "More", "hidden": true }] })); + + // Without `at`, after the last page; renamed unless asked otherwise. + let spawned = ok(&mut a, "page_template_spawn", json!({ "doc": doc, "name": "More" })); + assert_eq!(spawned["pages"], 2, "{spawned}"); + assert_eq!(field_names(&mut a, doc), ["Extra", "P1.More.Extra"]); + ok(&mut a, "page_template_spawn", json!({ "doc": doc, "name": "More", "at": 1, "rename": false })); + assert_eq!(field_names(&mut a, doc), ["Extra", "P1.More.Extra"], "an unrenamed copy shares Extra"); + + let shown = ok(&mut a, "page_template_set_hidden", json!({ "doc": doc, "name": "More", "hidden": false })); + assert_eq!(shown["pages"], 4, "{shown}"); + assert_eq!(ok(&mut a, "page_templates", json!({ "doc": doc })), json!({ "templates": [{ "name": "More", "hidden": false }] })); + let hidden = ok(&mut a, "page_template_set_hidden", json!({ "doc": doc, "name": "More", "hidden": true })); + assert_eq!(hidden["pages"], 3, "{hidden}"); + + assert!(matches!(a.call("page_template_spawn", &json!({ "doc": doc, "name": "Nope" })), Err(ToolError::Failed(_)))); + assert!(matches!(a.call("page_template_spawn", &json!({ "doc": doc, "name": "More", "at": 0 })), Err(ToolError::InvalidArgs(_)))); + assert!(matches!(a.call("page_template_set_hidden", &json!({ "doc": doc, "name": "More" })), Err(ToolError::InvalidArgs(_)))); + let _ = std::fs::remove_dir_all(dir); +} + +/// `js_run` applies a script's spawn with its other changes, and reports nothing left over. +#[test] +fn a_script_run_through_the_tools_adds_the_page() { + let (dir, mut a) = setup("js"); + let doc = ok(&mut a, "doc_open", json!({ "path": "form.pdf" }))["doc"].as_u64().unwrap(); + let out = ok(&mut a, "js_run", json!({ "doc": doc, "script": "getTemplate('More').spawn(1, false, false);" })); + assert_eq!(out["error"], Value::Null, "{out}"); + assert_eq!(out["requests"], json!([]), "{out}"); + let info = ok(&mut a, "doc_info", json!({ "doc": doc })); + assert_eq!(info["pages"].as_array().map(Vec::len), Some(2), "{info}"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/document.rs b/crates/engine/src/document.rs index 644ca4d54e..98a7e45009 100644 --- a/crates/engine/src/document.rs +++ b/crates/engine/src/document.rs @@ -754,6 +754,11 @@ impl Document { self.editor.as_ref().map(|e| pdfcraft_organize::custom_info(&e.cos)).unwrap_or_default() } + /// The page templates as they are now: the hidden ones, then the named visible pages (#1429). + pub fn templates(&self) -> Vec { + self.editor.as_ref().map(|e| pdfcraft_organize::templates(&e.cos)).unwrap_or_default() + } + /// The name shown on the tab and window: the document title when the document asks for it /// (Initial View ▸ Show: Document Title) and has a real one, else the file name. pub fn display_name(&self) -> String { diff --git a/crates/engine/src/edit.rs b/crates/engine/src/edit.rs index 80c51658e4..bd65f1fa5f 100644 --- a/crates/engine/src/edit.rs +++ b/crates/engine/src/edit.rs @@ -45,6 +45,20 @@ pub enum Edit { pages: Vec, at: Option, }, + /// A copy of page template `name` inserted at `at` (clamped to the end), as JavaScript's + /// `Template.spawn` adds it (#1429). `rename` puts the copy's fields under `P.`; + /// without it they are more widgets of the template's fields. + SpawnTemplate { + name: String, + at: usize, + rename: bool, + }, + /// Show page template `name` at the end of the document, or take its page out of the + /// document again (JavaScript's `Template.hidden`). + SetTemplateHidden { + name: String, + hidden: bool, + }, /// Replace Pages: the content of `pages` is replaced by `src_pages` of another PDF; the /// pages' links, comments and bookmarks stay. ReplacePages { diff --git a/crates/engine/src/edit/labels.rs b/crates/engine/src/edit/labels.rs index 93045146ae..829afea516 100644 --- a/crates/engine/src/edit/labels.rs +++ b/crates/engine/src/edit/labels.rs @@ -15,6 +15,9 @@ pub const EDIT_LABELS: &[&str] = &[ "Insert blank page", "Duplicate page", "Duplicate pages", + "Add a page from template {name}", + "Show template {name}", + "Hide template {name}", "Replace page", "Replace pages", "Crop page", @@ -188,6 +191,9 @@ impl Edit { Edit::ReversePages { .. } => Label::of("Reverse pages"), Edit::InsertBlankPage { .. } => Label::of("Insert blank page"), Edit::DuplicatePages { pages, .. } => plural("Duplicate page", "Duplicate pages", pages.len()), + Edit::SpawnTemplate { name, .. } => Label::with("Add a page from template {name}", name.as_str()), + Edit::SetTemplateHidden { name, hidden: false } => Label::with("Show template {name}", name.as_str()), + Edit::SetTemplateHidden { name, hidden: true } => Label::with("Hide template {name}", name.as_str()), Edit::ReplacePages { pages, .. } => plural("Replace page", "Replace pages", pages.len()), Edit::SetPageBox { pages, which: PageBox::Crop, .. } => plural("Crop page", "Crop pages", pages.len()), Edit::SetPageBox { .. } => Label::of("Set page boxes"), diff --git a/crates/engine/src/edit/run.rs b/crates/engine/src/edit/run.rs index a6603d91e3..cda9d4d77a 100644 --- a/crates/engine/src/edit/run.rs +++ b/crates/engine/src/edit/run.rs @@ -15,6 +15,8 @@ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Re | Edit::ReversePages { .. } | Edit::InsertBlankPage { .. } | Edit::DuplicatePages { .. } + | Edit::SpawnTemplate { .. } + | Edit::SetTemplateHidden { .. } | Edit::ReplacePages { .. } | Edit::SetPageBox { .. } | Edit::SetTransition { .. } @@ -546,6 +548,10 @@ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut E } pdfcraft_organize::duplicate_pages(doc, pages, *at)? } + Edit::SpawnTemplate { name, at, rename } => { + pdfcraft_organize::spawn_template(doc, name, *at, *rename)?; + } + Edit::SetTemplateHidden { name, hidden } => pdfcraft_organize::set_template_hidden(doc, name, *hidden)?, Edit::ReplacePages { pages, name, bytes, src_pages } => { let src = crate::sources::open_source_into(name, bytes, doc)?; pdfcraft_organize::replace_pages(doc, pages, &src, src_pages)?; diff --git a/crates/engine/src/js.rs b/crates/engine/src/js.rs index 301f9ce25e..6772e9828d 100644 --- a/crates/engine/src/js.rs +++ b/crates/engine/src/js.rs @@ -11,6 +11,17 @@ pub use pdfcraft_js::{Limits, Message, MessageButtons, MessageIcon, Outcome, Pan use crate::{DocId, Edit, EditError, Session}; +/// At most this many pages a script adds or shows from templates in one run: each one copies +/// the document, so a script looping over `spawn` must not hold the app on a large file (#1429). +const MAX_TEMPLATE_PAGES: usize = 100; + +/// Whether a script run for `target` may add or show pages from templates (#1429): only a push +/// button's may, as for field scripts (`JsOutput`), and a document-level script with no target; +/// a target naming another field is refused that (CodeRabbit on #5332). +fn may_change_pages(target: Option<&str>, fields: &[pdfcraft_forms::Field]) -> bool { + target.is_none_or(|t| fields.iter().any(|f| f.name == t && f.kind == pdfcraft_forms::FieldKind::PushButton)) +} + /// Reset writeback does two full passes (preview and commit); reject amplification before either. const MAX_SCRIPT_RESETS: usize = pdfcraft_js::MAX_RESET_CALLS; const MAX_SCRIPT_RESET_SELECTORS: usize = 4096; @@ -172,6 +183,9 @@ impl JsOutput { Request::OpenAttachment { name, .. } => { notes.push(format!("A field script asked to open the attached file {name}; only a button may open an attached file")) } + Request::SpawnTemplate { .. } | Request::SetTemplateHidden { .. } => { + self.console.push("A field script asked to add or show a page from a template; only a button may change the pages".into()) + } Request::OpenDoc(path) => notes.push(format!( "A field script asked to open the document {path}; only a button, a link or the console may open another document" )), @@ -557,6 +571,8 @@ impl JsRunner { c.set((g + 1, p)); }); let pages = pdfcraft_model::pages(cos); + // The page templates a script can show or add a page from (#1429). + let templates = pdfcraft_organize::templates(cos).into_iter().map(|t| (t.name, t.hidden)).collect(); let doc = pdfcraft_js::DocInfo { file_name: file_name.to_string(), num_pages: pages.len(), @@ -565,6 +581,7 @@ impl JsRunner { page_boxes: pdfcraft_organize::page_boxes(cos).unwrap_or_default(), page_rotations: pages.iter().map(|page| page.rotation(cos)).collect(), xfa, + templates, zoom: 100.0, runtime_highlight: highlight, icon_epoch: 0, @@ -1220,7 +1237,7 @@ impl Session { answers, ); let discard = o.execution_refused && !o.realm_untouched; - let result = self.apply_script_outcome(id, &states, o, opening); + let result = self.apply_script_outcome(id, &states, o, opening, may_change_pages(target, &fields)); if discard || result.is_err() { self.invalidate_javascript(id); } @@ -1234,6 +1251,7 @@ impl Session { states: &[pdfcraft_js::FieldState], mut o: Outcome, opening: bool, + may_change_pages: bool, ) -> Result { if o.execution_refused { o.changed.clear(); @@ -1269,6 +1287,32 @@ impl Session { let editor = doc.editor.as_ref().ok_or_else(|| EditError::ReadOnly(doc.read_only_reason.clone().unwrap_or_default()))?; Some(editor.cos.clone()) }; + // Pages from templates go in the same undo step, after the field changes (#1429). Only a + // push button may change the pages, as for field scripts (`JsOutput`); a target that + // names another field is refused that (CodeRabbit on #5332, [`may_change_pages`]). + let button = may_change_pages; + let mut pages = Vec::new(); + let (mut over, mut overlaid, mut not_button) = (false, None, false); + for r in std::mem::take(&mut o.requests) { + match r { + Request::SpawnTemplate { .. } | Request::SetTemplateHidden { .. } if !button => not_button = true, + Request::SpawnTemplate { .. } | Request::SetTemplateHidden { .. } if pages.len() >= MAX_TEMPLATE_PAGES => over = true, + Request::SpawnTemplate { overlay: true, name, .. } => overlaid = overlaid.or(Some(name)), + Request::SpawnTemplate { name, page, rename, overlay: false } => pages.push(Edit::SpawnTemplate { name, at: page, rename }), + Request::SetTemplateHidden { name, hidden } => pages.push(Edit::SetTemplateHidden { name, hidden }), + r => o.requests.push(r), + } + } + // Said once, however many overlays the script asked for. + if let Some(name) = overlaid { + o.console.push(format!("Laying template {name} over an existing page isn't supported yet; ask for a new page (bOverlay false)")); + } + if not_button { + o.console.push("A field script asked to add or show a page from a template; only a button may change the pages".into()); + } + if over { + o.console.push(format!("A script may add or show at most {MAX_TEMPLATE_PAGES} pages from templates at a time; the rest were left out")); + } // The calculations the script's changes set off read the field highlight it asked for. if let Some(on) = last_highlight(&o.requests) { self.field_highlight = on; @@ -1301,6 +1345,7 @@ impl Session { if !changes.is_empty() { edits.push(Edit::ApplyScriptChanges { changes }); } + edits.extend(pages); if !edits.is_empty() { self.apply(id, Edit::Batch { label: "Run JavaScript".into(), edits })?; } @@ -1729,7 +1774,8 @@ impl Session { drop_failed_link_effects(&mut o); self.keep_read_only_link_requests(id, &states, &mut o); let discard = o.execution_refused && !o.realm_untouched; - let result = self.apply_script_outcome(id, &states, o, false); + // A link's script has the document as its target, as a document script does. + let result = self.apply_script_outcome(id, &states, o, false, may_change_pages(None, &[])); if discard || result.is_err() { self.invalidate_javascript(id); } @@ -1764,6 +1810,8 @@ pub struct PendingScript { generation: u64, runtime: Runtime, states: std::sync::Arc>, + /// Whether the script may add or show pages from templates ([`may_change_pages`]). + may_change_pages: bool, pub receiver: std::sync::mpsc::Receiver, } #[cfg(not(target_arch = "wasm32"))] @@ -1810,7 +1858,8 @@ impl Session { }; let receiver = doc.js_runtime.lock().map_err(|_| EditError::Invalid("script runtime unavailable".into()))?.start(job).map_err(EditError::Invalid)?; - Ok(PendingScript { id, link: false, generation: doc.generation, runtime: doc.js_runtime.clone(), states, receiver }) + let may_change_pages = may_change_pages(target, &fields); + Ok(PendingScript { id, link: false, generation: doc.generation, runtime: doc.js_runtime.clone(), states, may_change_pages, receiver }) } /// Start link `index` on page `page` as [`Session::run_link_javascript`] runs it, without /// blocking on its prompts; [`Session::finish_javascript`] commits nothing if it failed. @@ -1819,7 +1868,9 @@ impl Session { let doc = self.get(id).ok_or(EditError::NoDocument)?; let receiver = doc.js_runtime.lock().map_err(|_| EditError::Invalid("script runtime unavailable".into()))?.start(job).map_err(EditError::Invalid)?; - Ok(PendingScript { id, link: true, generation: doc.generation, runtime: doc.js_runtime.clone(), states, receiver }) + // A link's script has the document as its target, as a document script does. + let may_change_pages = may_change_pages(None, &[]); + Ok(PendingScript { id, link: true, generation: doc.generation, runtime: doc.js_runtime.clone(), states, may_change_pages, receiver }) } /// Discard only the captured runtime, preserving a newer realm created by an intervening edit. pub fn discard_javascript(&mut self, p: &PendingScript) { @@ -1854,7 +1905,7 @@ impl Session { self.keep_read_only_link_requests(p.id, &p.states, &mut out); } let discard = out.execution_refused && !out.realm_untouched; - let result = self.apply_script_outcome(p.id, &p.states, out, false); + let result = self.apply_script_outcome(p.id, &p.states, out, false, p.may_change_pages); if discard || result.is_err() { self.invalidate_javascript(p.id); } diff --git a/crates/engine/src/live_scripts.rs b/crates/engine/src/live_scripts.rs index b69f7d85d2..e35cf9c7ce 100644 --- a/crates/engine/src/live_scripts.rs +++ b/crates/engine/src/live_scripts.rs @@ -280,7 +280,9 @@ impl Session { let generation = self.get(id).map(Document::edit_generation); let layers = |s: &Session| s.get(id).map(|d| d.info.layers.iter().map(|l| l.visible).collect::>()); let layers_before = layers(self); - match self.apply_script_outcome(id, &states, o, false) { + // Page actions and timers run while the document is read: they add or show no template + // pages (#1429), which would change the document as the reader moves through it. + match self.apply_script_outcome(id, &states, o, false, false) { Ok(o) => { run.output.absorb(&o); // Only now: a script whose edits are refused shows nothing it did either. diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index c4cf560b9e..a94c5914d2 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -10,6 +10,7 @@ mod form_rotation; mod marked_content_isolation; mod ocr_edit; mod office_export_images; +mod page_templates; mod private_image_resize; mod private_text_glyphs; mod xfa_repeat; diff --git a/crates/engine/tests/it/page_templates.rs b/crates/engine/tests/it/page_templates.rs new file mode 100644 index 0000000000..a28d8543b7 --- /dev/null +++ b/crates/engine/tests/it/page_templates.rs @@ -0,0 +1,133 @@ +//! Page templates through the session (#1429): a button's script shows a template or adds a page +//! from one as one undo step with its other changes; a field's own scripts may not. + +use std::sync::Arc; + +use pdfcraft_engine::{DocId, Edit, FieldValue, Session}; + +/// One visible page with a text field `Name` (whose validate script tries to show the template), +/// and a hidden template `More` holding the text field `Extra`. +fn form() -> Vec { + let bodies = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /Templates 6 0 R >> /AcroForm << /Fields [7 0 R 10 0 R] /DA (/Helv 0 Tf 0 g) >> >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>", + "<< /Type /Page /Parent 2 0 R /Contents 4 0 R /Resources << /Font << /F1 9 0 R >> >> /Annots [10 0 R] >>", + "<< /Length 40 >>\nstream\nBT /F1 12 Tf 20 20 Td (Visible) Tj ET\nendstream", + "<< /Type /Template /Contents 8 0 R /Resources << /Font << /F1 9 0 R >> >> /Annots [7 0 R] >>", + "<< /Names [(More) 5 0 R] >>", + "<< /FT /Tx /T (Extra) /Subtype /Widget /Rect [20 100 180 120] /P 5 0 R >>", + "<< /Length 41 >>\nstream\nBT /F1 12 Tf 20 20 Td (Template) Tj ET\nendstream", + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + "<< /FT /Tx /T (Name) /Subtype /Widget /Rect [20 200 180 220] /P 3 0 R /AA << /V << /S /JavaScript /JS (getTemplate('More').hidden = false;) >> >> >>", + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, b) in bodies.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{b}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", bodies.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", bodies.len() + 1).as_bytes()); + out +} + +fn open() -> (Session, DocId) { + let mut s = Session::new(); + let id = s.open("form.pdf", None, Arc::new(form()), None).expect("opens"); + (s, id) +} + +fn pages(s: &Session, id: DocId) -> usize { + s.get(id).unwrap().info.pages.len() +} + +fn fields(s: &Session, id: DocId) -> Vec { + let mut names: Vec = s.get(id).unwrap().form.iter().map(|f| f.name.clone()).collect(); + names.sort(); + names +} + +#[test] +fn a_script_shows_a_template_as_one_undo_step() { + let (mut s, id) = open(); + let names: Vec<(String, bool)> = s.get(id).unwrap().templates().into_iter().map(|t| (t.name, t.hidden)).collect(); + assert_eq!(names, [("More".to_string(), true)]); + let o = s.run_javascript(id, "console.println(this.templates.length); getTemplate('More').hidden = false;", None).unwrap(); + assert_eq!((o.error, o.console), (None, vec!["1".to_string()])); + assert_eq!(pages(&s, id), 2, "the template's page is shown"); + assert!(!s.get(id).unwrap().templates()[0].hidden); + assert_eq!(s.get(id).unwrap().can_undo(), Some("Run JavaScript")); + s.undo(id).unwrap(); + assert_eq!(pages(&s, id), 1, "one undo takes it out again"); +} + +#[test] +fn a_script_adds_pages_from_a_template_renamed_or_shared() { + let (mut s, id) = open(); + let o = s.run_javascript(id, "this.spawnPageFromTemplate('More', 1, false, false); getTemplate('More').spawn(2, true, false);", None).unwrap(); + assert_eq!(o.error, None); + assert_eq!(pages(&s, id), 3); + assert_eq!(fields(&s, id), ["Extra", "Name", "P2.More.Extra"], "the renamed copy has a field of its own; the other shares Extra"); + // Saved and opened again, the pages and fields are still there. + let bytes = s.save_bytes(id).unwrap(); + let mut again = Session::new(); + let reopened = again.open("again.pdf", None, bytes, None).unwrap(); + assert_eq!(pages(&again, reopened), 3); + assert_eq!(fields(&again, reopened), ["Extra", "Name", "P2.More.Extra"]); +} + +/// Laying a template over a page isn't done yet: the script is told on the console, and the +/// pages stay as they were. +#[test] +fn an_overlaid_spawn_is_noted_and_changes_nothing() { + let (mut s, id) = open(); + let o = s.run_javascript(id, "getTemplate('More').spawn();", None).unwrap(); + assert_eq!(pages(&s, id), 1); + assert!(o.console.iter().any(|l| l.contains("More") && l.contains("bOverlay")), "{:?}", o.console); + assert!(o.requests.is_empty(), "nothing is left for the viewer: {:?}", o.requests); +} + +/// A field's own scripts run unasked, so they may not change the pages; they are told so. +#[test] +fn a_field_script_may_not_change_the_pages() { + let (mut s, id) = open(); + s.apply(id, Edit::SetFieldValue { name: "Name".into(), value: FieldValue::Text("Ada".into()) }).unwrap(); + assert_eq!(pages(&s, id), 1); + let out = s.take_js_output(id); + assert!(out.console.iter().any(|l| l.contains("only a button may change the pages")), "{:?}", out.console); +} + +/// A script looping over `spawn` adds at most 100 pages in one run, says so once, and doesn't +/// hold the app: each page copies the document. +#[test] +fn a_spawning_loop_stops_at_its_page_budget() { + let (mut s, id) = open(); + let o = s + .run_javascript(id, "for (var i = 0; i < 150; i++) getTemplate('More').spawn(this.numPages, false, false); for (var j = 0; j < 50; j++) getTemplate('More').spawn();", None) + .unwrap(); + assert_eq!(pages(&s, id), 101, "the visible page and 100 copies"); + let budget = o.console.iter().filter(|l| l.contains("at most 100 pages")).count(); + let overlays = o.console.iter().filter(|l| l.contains("bOverlay")).count(); + assert_eq!((budget, overlays), (1, 0), "said once; the overlays came after the budget was spent: {:?}", o.console); + assert_eq!(fields(&s, id), ["Extra", "Name"], "every unrenamed copy shares Extra"); +} + +/// Run as another field's script (`js_run`'s `field`), a script may not change the pages +/// either: only a push button may (CodeRabbit on #5332). A name no field has is no button. +#[test] +fn a_script_run_for_a_field_that_is_no_button_may_not_change_the_pages() { + let (mut s, id) = open(); + for target in ["Name", "Nope"] { + let o = + s.run_javascript(id, "getTemplate('More').hidden = false; this.spawnPageFromTemplate('More', 1, false, false);", Some(target)).unwrap(); + assert_eq!(pages(&s, id), 1, "{target}"); + let said = o.console.iter().filter(|l| l.contains("only a button may change the pages")).count(); + assert_eq!(said, 1, "{target}: said once: {:?}", o.console); + assert!(o.requests.is_empty(), "{target}: nothing is left for the viewer: {:?}", o.requests); + } + assert_eq!(s.get(id).unwrap().can_undo(), None, "nothing was changed"); +} diff --git a/crates/js/src/document.rs b/crates/js/src/document.rs index cccf89a7a2..3e754761c8 100644 --- a/crates/js/src/document.rs +++ b/crates/js/src/document.rs @@ -488,3 +488,94 @@ pub(crate) fn page_num_set(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> h.request(Request::GoToPage(p)); Ok(JsValue::undefined()) } + +// ── page templates (#1429) ────────────────────────────────────────────────────────────────── + +/// A Template object (`this.getTemplate(name)`): its `name`, whether it is `hidden` (setting it +/// shows or hides the template's page), and `spawn` to add a page from it. +pub(crate) fn template_object(ctx: &mut Context, name: &str) -> JsObject { + let n = JsString::from(name); + fn get_name(_: &JsValue, _: &[JsValue], name: &JsString, _c: &mut Context) -> JsResult { + Ok(JsValue::from(name.clone())) + } + fn get_hidden(_: &JsValue, _: &[JsValue], name: &JsString, c: &mut Context) -> JsResult { + let name = name.to_std_string_escaped(); + let hidden = host(c)?.borrow().doc.templates.iter().find(|(n, _)| *n == name).is_some_and(|(_, h)| *h); + Ok(JsValue::from(hidden)) + } + fn set_hidden(_: &JsValue, args: &[JsValue], name: &JsString, c: &mut Context) -> JsResult { + let hidden = arg(args, 0).to_boolean(); + let name = name.to_std_string_escaped(); + let mut h = host(c)?.borrow_mut(); + // The script reads back what it set. + if let Some(t) = h.doc.templates.iter_mut().find(|(n, _)| *n == name) { + t.1 = hidden; + } + h.request(Request::SetTemplateHidden { name, hidden }); + Ok(JsValue::undefined()) + } + fn spawn(_: &JsValue, args: &[JsValue], name: &JsString, c: &mut Context) -> JsResult { + let request = spawn_request(name.to_std_string_escaped(), args, 0, c)?; + host(c)?.borrow_mut().request(request); + Ok(JsValue::null()) + } + let rw = Attribute::CONFIGURABLE | Attribute::ENUMERABLE; + let get_name = function(ctx, NativeFunction::from_copy_closure_with_captures(get_name, n.clone())); + let get_hidden = function(ctx, NativeFunction::from_copy_closure_with_captures(get_hidden, n.clone())); + let set_hidden = function(ctx, NativeFunction::from_copy_closure_with_captures(set_hidden, n.clone())); + let spawn = NativeFunction::from_copy_closure_with_captures(spawn, n); + ObjectInitializer::new(ctx) + .accessor(js_string!("name"), Some(get_name), None, rw) + .accessor(js_string!("hidden"), Some(get_hidden), Some(set_hidden), rw) + .function(spawn, js_string!("spawn"), 4) + .build() +} + +/// The request for a page from template `name`, from `spawn`'s arguments starting at `first`: +/// `(nPage, bRename, bOverlay)` or one object holding them. As in Acrobat, the page is 0 unless +/// given, and the fields are renamed and the page laid over unless asked otherwise. +fn spawn_request(name: String, args: &[JsValue], first: usize, ctx: &mut Context) -> JsResult { + let given = arg(args, first); + let named = given.as_object().filter(|o| !o.is_array()); + let mut value = |key: &str, index: usize| -> JsResult { + match &named { + Some(o) => o.get(JsString::from(key), ctx), + None => Ok(arg(args, first.saturating_add(index))), + } + }; + let (page, rename, overlay) = (value("nPage", 0)?, value("bRename", 1)?, value("bOverlay", 2)?); + let page = if page.is_undefined() { 0.0 } else { page.to_number(ctx)? }; + // NaN, negative and huge numbers land on the first page and past the last, where the + // document clamps them. + let page = if page.is_finite() { + page.max(0.0).min(usize::MAX as f64) as usize + } else if page > 0.0 { + usize::MAX + } else { + 0 + }; + let flag = |v: &JsValue| if v.is_undefined() { true } else { v.to_boolean() }; + Ok(Request::SpawnTemplate { name, page, rename: flag(&rename), overlay: flag(&overlay) }) +} + +/// `this.getTemplate(cName)`: the Template object, or `null` when there is none of that name. +pub(crate) fn get_template(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult { + let name = text(&arg(args, 0), ctx)?; + let exists = host(ctx)?.borrow().doc.templates.iter().any(|(n, _)| *n == name); + Ok(if exists { template_object(ctx, &name).into() } else { JsValue::null() }) +} + +/// `this.spawnPageFromTemplate(cTemplate, nPage, bRename, bOverlay)`: the older way to spawn. +pub(crate) fn spawn_page_from_template(_: &JsValue, args: &[JsValue], ctx: &mut Context) -> JsResult { + // `({ cTemplate, nPage, bRename, bOverlay })` names its arguments, the template included. + let (name, first) = match arg(args, 0).as_object().filter(|o| !o.is_array()) { + Some(o) => (text(&o.get(js_string!("cTemplate"), ctx)?, ctx)?, 0), + None => (text(&arg(args, 0), ctx)?, 1), + }; + if !host(ctx)?.borrow().doc.templates.iter().any(|(n, _)| *n == name) { + return Err(error(format!("there is no template named {name}"))); + } + let request = spawn_request(name, args, first, ctx)?; + host(ctx)?.borrow_mut().request(request); + Ok(JsValue::null()) +} diff --git a/crates/js/src/globals.rs b/crates/js/src/globals.rs index 22f3bb7799..07e5c5d22a 100644 --- a/crates/js/src/globals.rs +++ b/crates/js/src/globals.rs @@ -1,4 +1,7 @@ -use super::document::{get_field, get_nth_field_name, noop, num_fields, page_num_get, page_num_set, print, reset_form, submit_form}; +use super::document::{ + get_field, get_nth_field_name, get_template, noop, num_fields, page_num_get, page_num_set, print, reset_form, spawn_page_from_template, + submit_form, template_object, +}; use super::format::{printd, printf, printx, scand}; use super::host::{arg, error, function, host, s, strings, text, text_line}; use super::model::{DISPLAY_HIDDEN, DISPLAY_NO_PRINT, DISPLAY_NO_VIEW, DISPLAY_VISIBLE, Event, Panel, Request}; @@ -527,7 +530,7 @@ fn document_info_get(_: &JsValue, _: &[JsValue], ctx: &mut Context) -> JsResult< /// Install the host API once; live document properties continue reading each job's snapshot. pub(crate) fn install(ctx: &mut Context) -> JsResult<()> { - let globals: [(&str, usize, NativeFunction); 13] = [ + let globals: [(&str, usize, NativeFunction); 15] = [ ("getField", 1, NativeFunction::from_fn_ptr(get_field)), ("getNthFieldName", 1, NativeFunction::from_fn_ptr(get_nth_field_name)), ("resetForm", 1, NativeFunction::from_fn_ptr(reset_form)), @@ -539,6 +542,8 @@ pub(crate) fn install(ctx: &mut Context) -> JsResult<()> { ("AFSimple_Calculate", 2, NativeFunction::from_fn_ptr(af_simple_calculate)), ("syncAnnotScan", 0, NativeFunction::from_fn_ptr(noop)), ("dirty", 0, NativeFunction::from_fn_ptr(noop)), + ("getTemplate", 1, NativeFunction::from_fn_ptr(get_template)), + ("spawnPageFromTemplate", 5, NativeFunction::from_fn_ptr(spawn_page_from_template)), ("exportDataObject", 4, NativeFunction::from_fn_ptr(export_data_object)), ("getOCGs", 1, NativeFunction::from_fn_ptr(crate::ocg::get_ocgs)), ]; @@ -578,6 +583,11 @@ pub(crate) fn install(ctx: &mut Context) -> JsResult<()> { let getter = function(ctx, NativeFunction::from_fn_ptr(getter)); global.define_property_or_throw(JsString::from(name), PropertyDescriptor::builder().get(getter).configurable(true), ctx)?; } + // `this.templates`: every page template, as Template objects (#1429). + let names: Vec = host(ctx)?.borrow().doc.templates.iter().map(|(n, _)| n.clone()).collect(); + let templates: Vec = names.iter().map(|n| template_object(ctx, n).into()).collect(); + let templates = JsArray::from_iter(templates, ctx); + ctx.register_global_property(js_string!("templates"), templates, rw)?; // XFA forms check both before they run: every document sees the XFA version, and only an // XFA form sees `xfa_installed`. ctx.register_global_property(js_string!("xfa_version"), JsValue::from(XFA_VERSION), rw)?; diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index f4da3d7a31..6e41a514d5 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -83,14 +83,16 @@ impl Host { Request::Submit(u) => Request::Submit(xfa::clip(u)), Request::Focus(n) => Request::Focus(xfa::clip(n)), Request::OpenDoc(p) => Request::OpenDoc(xfa::clip(p)), + // Template names are looked up exactly, so they are never clipped: a cut name could + // name another template. Their whole length is charged below. Request::FocusField { name, object_id } => Request::FocusField { name: xfa::clip(name), object_id }, other => other, }; let bytes = match &r { Request::Reset(names) => names.iter().fold(0usize, |n, s| n.saturating_add(s.len()).saturating_add(std::mem::size_of::())), Request::LaunchUrl(u) | Request::Submit(u) | Request::Focus(u) | Request::OpenDoc(u) => u.len(), + Request::SpawnTemplate { name, .. } | Request::SetTemplateHidden { name, .. } | Request::OpenAttachment { name, .. } => name.len(), Request::FocusField { name, .. } => name.len(), - Request::OpenAttachment { name, .. } => name.len(), _ => 0, }; let kept = self.room(bytes); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index c5e0d6b391..6d9f3f2829 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -8,7 +8,9 @@ //! - `event`: `value`, `change`, `willCommit`, `rc`, `name`, `type`, `target`, `targetName`. //! - the document (`this`, also the global object): `getField`, `numFields`, //! `getNthFieldName`, `numPages`, `pageNum`, `documentFileName`, `info`, `resetForm`, -//! `calculateNow`, `getPageBox`, `print`, `submitForm`, `mailDoc`, `exportDataObject`. +//! `calculateNow`, `getPageBox`, `print`, `submitForm`, `mailDoc`, `exportDataObject`, `templates`, +//! `getTemplate`, `spawnPageFromTemplate`. +//! - Template objects: `name`, `hidden` (setting it shows or hides the template's page), `spawn`. //! - Field objects: `name`, `type`, `value`, `valueAsString`, `defaultValue`, `readonly`, //! `required`, `display`, `hidden`, `numItems`, `getItemAt`, `currentValueIndices`, //! `isBoxChecked`, `checkThisBox`, `exportValues`, `charLimit`, `textColor`, `fillColor`, diff --git a/crates/js/src/model.rs b/crates/js/src/model.rs index 0b2744ec0b..43587067be 100644 --- a/crates/js/src/model.rs +++ b/crates/js/src/model.rs @@ -185,6 +185,8 @@ pub struct DocInfo { pub page_rotations: Vec, /// The document has an XFA form, so scripts see `xfa_installed`. pub xfa: bool, + /// The page templates, with whether each is hidden (`this.templates`, #1429). + pub templates: Vec<(String, bool)>, pub zoom: f64, pub runtime_highlight: bool, /// The document's layers (optional content groups), for `getOCGs`, in the viewer's order. @@ -330,6 +332,19 @@ pub enum Request { }, /// `app.execMenuItem("ShowHide…")`: show the side panel, or hide it when it is showing. ShowPanel(Panel), + /// `template.spawn(nPage, bRename, bOverlay)` or `this.spawnPageFromTemplate(…)`: a page from + /// template `name` at `page` (0-based), with its fields renamed or not, or laid over `page`. + SpawnTemplate { + name: String, + page: usize, + rename: bool, + overlay: bool, + }, + /// `template.hidden = hidden`. + SetTemplateHidden { + name: String, + hidden: bool, + }, } /// A side panel a script can show or hide (`app.execMenuItem("ShowHideFileAttachment")`, …). diff --git a/crates/js/src/tests.rs b/crates/js/src/tests.rs index 0c876688bd..2a1d6935a0 100644 --- a/crates/js/src/tests.rs +++ b/crates/js/src/tests.rs @@ -2676,6 +2676,83 @@ fn a_plain_form_sees_the_xfa_version_but_not_installed() { assert_eq!(o.alerts, [Message::plain("old viewer")]); } +/// A document with a hidden template `More` and a visible named page `Cover` (#1429). +fn templated() -> DocInfo { + DocInfo { templates: vec![("More".into(), true), ("Cover".into(), false)], ..doc() } +} + +fn run_templated(script: &str) -> Outcome { + run(script, &Event::field("Mouse Up", "agree", ""), &templated(), &fields(), &[], Limits::default()) +} + +#[test] +fn templates_are_listed_and_found_by_name() { + let o = run_templated( + "var t = this.getTemplate('More'); \ + console.println(this.templates.length + ' ' + this.templates[1].name + ' ' + t.name + ' ' + t.hidden + ' ' + this.getTemplate('Cover').hidden + ' ' + this.getTemplate('Nope'));", + ); + assert_eq!(o.error, None); + assert_eq!(o.console, ["2 Cover More true false null"]); +} + +#[test] +fn spawn_asks_for_a_page_from_the_template() { + let o = run_templated("getTemplate('More').spawn(2, false, false);"); + assert_eq!(o.requests, [Request::SpawnTemplate { name: "More".into(), page: 2, rename: false, overlay: false }]); + // As in Acrobat: page 0, renamed and laid over unless asked otherwise. + let o = run_templated("getTemplate('More').spawn();"); + assert_eq!(o.requests, [Request::SpawnTemplate { name: "More".into(), page: 0, rename: true, overlay: true }]); + // The arguments by name. + let o = run_templated("getTemplate('More').spawn({ nPage: 1, bOverlay: false });"); + assert_eq!(o.requests, [Request::SpawnTemplate { name: "More".into(), page: 1, rename: true, overlay: false }]); +} + +#[test] +fn spawn_page_from_template_takes_its_arguments_both_ways() { + let o = run_templated("this.spawnPageFromTemplate('More', 3, false, false);"); + assert_eq!(o.requests, [Request::SpawnTemplate { name: "More".into(), page: 3, rename: false, overlay: false }]); + let o = run_templated("this.spawnPageFromTemplate({ cTemplate: 'More', nPage: 1, bRename: false, bOverlay: false });"); + assert_eq!(o.requests, [Request::SpawnTemplate { name: "More".into(), page: 1, rename: false, overlay: false }]); + let o = run_templated("this.spawnPageFromTemplate('Nope', 1);"); + assert!(o.error.as_deref().is_some_and(|e| e.contains("Nope")), "{o:?}"); + assert!(o.requests.is_empty()); +} + +#[test] +fn hiding_and_showing_a_template_is_asked_for_and_read_back() { + let o = run_templated("var t = getTemplate('More'); t.hidden = false; console.println(t.hidden);"); + assert_eq!(o.requests, [Request::SetTemplateHidden { name: "More".into(), hidden: false }]); + assert_eq!(o.console, ["false"]); +} + +/// Page numbers that aren't one land on the first page or past the last, where the document +/// clamps them. +#[test] +fn spawn_pages_that_are_not_numbers_are_clamped() { + for (arg, page) in [("NaN", 0), ("-5", 0), ("Infinity", usize::MAX), ("-Infinity", 0), ("1e300", usize::MAX), ("'2'", 2)] { + let o = run_templated(&format!("getTemplate('More').spawn({arg}, true, false);")); + assert_eq!(o.requests, [Request::SpawnTemplate { name: "More".into(), page, rename: true, overlay: false }], "{arg}"); + } +} + +/// A template name longer than a console line is asked for whole, never clipped: a cut name +/// could name another template. +#[test] +fn long_template_names_are_asked_for_whole() { + let long = "T".repeat(5000); + let doc = DocInfo { templates: vec![(long.clone(), true)], ..doc() }; + let script = "var t = this.templates[0]; t.spawn(0, false, false); t.hidden = false;"; + let o = run(script, &Event::field("Mouse Up", "agree", ""), &doc, &fields(), &[], Limits::default()); + assert_eq!(o.error, None); + assert_eq!( + o.requests, + [ + Request::SpawnTemplate { name: long.clone(), page: 0, rename: false, overlay: false }, + Request::SetTemplateHidden { name: long, hidden: false }, + ] + ); +} + /// Arrays assigned to several fields are held to one run-wide budget, and replacing a field's /// array frees its charge. #[test] diff --git a/crates/organize/src/import.rs b/crates/organize/src/import.rs index 3d4791c83d..f6991308af 100644 --- a/crates/organize/src/import.rs +++ b/crates/organize/src/import.rs @@ -41,6 +41,7 @@ pub(crate) use copy::{Copier, copy_object}; use copy::{MAX_COPY_DEPTH, SKIP_ON_PAGE}; use fields::{add_kid, field_and_widget, register_fields, resolve_field_conflicts, split_own_field}; pub use fields::{combine_field_conflicts, field_name_conflicts}; +pub(crate) use fields::{listed_fields, share_fields_with_originals}; /// How colliding fully-qualified field names are resolved when pages are imported. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] diff --git a/crates/organize/src/import/fields.rs b/crates/organize/src/import/fields.rs index daeaecd3f6..94b2e39020 100644 --- a/crates/organize/src/import/fields.rs +++ b/crates/organize/src/import/fields.rs @@ -224,6 +224,26 @@ pub(super) fn add_kid(dst: &mut Document, field: ObjRef, kid: ObjRef) -> Result< Ok(()) } +/// Take `kid` out of field `field`'s `/Kids` (direct or held in an array object of its own). +fn remove_kid(dst: &mut Document, field: ObjRef, kid: ObjRef) -> Result<(), OrganizeError> { + match dst.get(field).as_dict().and_then(|f| f.get(b"Kids").cloned()) { + // Only an array is rewritten: `/Kids` pointing at anything else (a font, in a hostile + // file) is left as it is rather than overwritten. + Some(Object::Ref(list)) => { + if let Some(mut kids) = dst.get(list).as_array().cloned() { + kids.retain(|k| k.as_ref() != Some(kid)); + dst.set(list, Object::Array(kids)); + } + } + Some(Object::Array(mut kids)) => { + kids.retain(|k| k.as_ref() != Some(kid)); + dst.update_dict(field, |f| f.set(b"Kids".to_vec(), Object::Array(kids)))?; + } + _ => {} + } + Ok(()) +} + /// PdfCraft patch (#1810): split a widget that doubles as its own field into a parent field /// holding the field keys (name, value, flags…) and a widget child holding the annotation keys /// (rectangle, appearance, page). The parent takes the widget's place among the top-level fields; @@ -305,6 +325,218 @@ pub(super) fn register_fields(dst: &mut Document, fields: &[ObjRef]) -> Result<( Ok(()) } +/// At most this many field nodes are read when matching copied widgets to their originals. +const MAX_FIELD_NODES: usize = 100_000; + +/// Make the widgets on `page`, copied from a page of the same document, more widgets of the +/// fields they were copied from, so that each field stays one field, with one value shown on +/// every page (#1429: a page template spawned without renaming). A copied field is matched to +/// the field of the same fully-qualified name under the top-level fields the form listed before +/// the copy (`before`); the copies of the matched fields leave the form. +pub(crate) fn share_fields_with_originals(dst: &mut Document, page: ObjRef, before: &HashSet) -> Result<(), OrganizeError> { + let catalog = dst.root().ok_or(OrganizeError::NoPageTree)?; + let form_ref = dst.get(catalog).as_dict().and_then(|c| c.reference(b"AcroForm")); + let form = dst.get(catalog).as_dict().and_then(|c| c.get(b"AcroForm").cloned()).map(|f| dst.resolve(&f).as_ref().clone()); + let mut list: Vec = form + .as_ref() + .and_then(Object::as_dict) + .and_then(|f| f.get(b"Fields")) + .map(|l| dst.resolve(l).as_ref().clone()) + .and_then(|l| l.as_array().cloned()) + .unwrap_or_default(); + // The fields that were there before the copy, by fully-qualified name. + let mut originals: HashMap = HashMap::new(); + let mut seen = HashSet::new(); + let mut pending: Vec<(ObjRef, String, u8)> = + list.iter().filter_map(Object::as_ref).filter(|r| before.contains(r)).map(|r| (r, String::new(), 0)).collect(); + while let Some((node, prefix, depth)) = pending.pop() { + if depth > 32 || seen.len() >= MAX_FIELD_NODES || !seen.insert(node) { + continue; + } + let Some(d) = dst.get(node).as_dict().cloned() else { continue }; + let name = match d.get(b"T").and_then(|t| dst.resolve(t).as_string().map(|s| s.to_text())) { + Some(t) => qualified_optional(&prefix, &t), + None => prefix.clone(), + }; + if d.contains(b"T") { + originals.entry(name.clone()).or_insert(node); + } + for kid in d.get(b"Kids").map(|k| dst.resolve(k).as_ref().clone()).and_then(|k| k.as_array().cloned()).unwrap_or_default() { + if let Some(kid) = kid.as_ref() { + pending.push((kid, name.clone(), depth.saturating_add(1))); + } + } + } + let annots = dst.get(page).as_dict().and_then(|d| d.get(b"Annots").cloned()).map(|a| dst.resolve(&a).as_ref().clone()); + let widgets: Vec = annots + .as_ref() + .and_then(Object::as_array) + .into_iter() + .flatten() + .filter_map(Object::as_ref) + .filter(|w| dst.get(*w).as_dict().is_some_and(|d| d.name(b"Subtype") == Some(b"Widget"))) + .collect(); + let (mut shared, mut kept): (HashSet, HashSet) = (HashSet::new(), HashSet::new()); + for widget in widgets { + let Some(d) = dst.get(widget).as_dict().cloned() else { continue }; + // The copied field holding the widget: the widget itself when it is its own field. + let field = if d.contains(b"T") { Some(widget) } else { d.reference(b"Parent") }; + let Some((name, top)) = field.and_then(|f| name_and_top(dst, f)) else { continue }; + let Some(&original) = originals.get(&name) else { + kept.insert(top); + continue; + }; + // An original that is its own widget becomes a field with that widget as its child. + let original = if dst.get(original).as_dict().is_some_and(|o| o.name(b"Subtype") == Some(b"Widget")) { + let mut slot = [original]; + split_own_field(dst, &mut slot, original); + let [parent] = slot; + replace_kid(dst, &mut list, original, parent)?; + originals.insert(name, parent); + parent + } else { + original + }; + // The copied field it leaves no longer lists it, so no widget has two parents. + if let Some(former) = d.reference(b"Parent") { + remove_kid(dst, former, widget)?; + } + let (_, mut child) = if d.contains(b"T") { field_and_widget(dst, &d) } else { (Dict::new(), d) }; + child.set(b"Parent".to_vec(), Object::Ref(original)); + dst.set(widget, Object::Dict(child)); + add_kid(dst, original, widget)?; + shared.insert(top); + } + list.retain(|f| f.as_ref().is_none_or(|r| !shared.contains(&r) || kept.contains(&r))); + match (form_ref, form) { + (Some(r), _) => dst.update_dict(r, |f| f.set(b"Fields".to_vec(), Object::Array(list)))?, + (None, Some(_)) => dst.update_dict(catalog, |c| { + if let Some(Object::Dict(f)) = c.get(b"AcroForm").cloned() { + let mut f = f; + f.set(b"Fields".to_vec(), Object::Array(list)); + c.set(b"AcroForm".to_vec(), Object::Dict(f)); + } + })?, + (None, None) => {} + } + Ok(()) +} + +/// The fully-qualified name of field `node` and its top-level field, climbing `/Parent` at most +/// 32 levels and never through a node twice. +fn name_and_top(doc: &Document, node: ObjRef) -> Option<(String, ObjRef)> { + let mut parts = Vec::new(); + let mut seen = HashSet::new(); + let mut at = node; + for _ in 0..32 { + if !seen.insert(at) { + return None; + } + let d = doc.get(at).as_dict()?.clone(); + if let Some(t) = d.get(b"T").and_then(|t| doc.resolve(t).as_string().map(|s| s.to_text())) { + parts.push(t); + } + match d.reference(b"Parent") { + Some(parent) => at = parent, + None => { + parts.reverse(); + return Some((parts.join("."), at)); + } + } + } + None +} + +/// Put `new` where `old` was: among its parent field's `/Kids`, or among the form's top-level +/// `fields` when it has no parent. +fn replace_kid(dst: &mut Document, fields: &mut [Object], old: ObjRef, new: ObjRef) -> Result<(), OrganizeError> { + let swap = |kids: &mut Vec| { + for k in kids.iter_mut() { + if k.as_ref() == Some(old) { + *k = Object::Ref(new); + } + } + }; + match dst.get(new).as_dict().and_then(|d| d.reference(b"Parent")) { + Some(parent) => match dst.get(parent).as_dict().and_then(|p| p.get(b"Kids").cloned()) { + Some(Object::Ref(list)) => { + let mut kids = dst.get(list).as_array().cloned().unwrap_or_default(); + swap(&mut kids); + dst.set(list, Object::Array(kids)); + } + _ => dst.update_dict(parent, |p| { + let mut kids = p.get(b"Kids").and_then(|k| k.as_array()).cloned().unwrap_or_default(); + swap(&mut kids); + p.set(b"Kids".to_vec(), Object::Array(kids)); + })?, + }, + None => { + for f in fields.iter_mut() { + if f.as_ref() == Some(old) { + *f = Object::Ref(new); + } + } + } + } + Ok(()) +} + +/// The top-level fields `doc`'s form lists now, before an import adds its own. +pub(crate) fn listed_fields(doc: &Document) -> HashSet { + doc.root() + .and_then(|r| doc.get(r).as_dict().cloned()) + .and_then(|c| c.get(b"AcroForm").map(|f| doc.resolve(f).as_ref().clone())) + .and_then(|f| f.as_dict().and_then(|f| f.get(b"Fields")).map(|l| doc.resolve(l).as_ref().clone())) + .and_then(|l| l.as_array().cloned()) + .unwrap_or_default() + .iter() + .filter_map(Object::as_ref) + .collect() +} + +#[cfg(test)] +mod template_tests { + use std::sync::Arc; + + use super::*; + + fn doc(bodies: &[&str]) -> Document { + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, b) in bodies.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n{b}\nendobj\n", i + 1).as_bytes()); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", bodies.len() + 1).as_bytes()); + for o in offsets { + out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", bodies.len() + 1).as_bytes()); + Document::open(Arc::new(out)).expect("opens") + } + + /// `/Kids` held in an array object of its own loses the kid; `/Kids` pointing at something + /// that isn't an array (here a font) is never overwritten. + #[test] + fn removing_a_kid_rewrites_only_an_array() { + let mut d = doc(&[ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [] /Count 0 >>", + "<< /T (G) /Kids 4 0 R >>", + "[6 0 R 7 0 R]", + "<< /T (H) /Kids 8 0 R >>", + "<< /T (a) /Parent 3 0 R >>", + "<< /T (b) /Parent 3 0 R >>", + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + ]); + remove_kid(&mut d, ObjRef::new(3, 0), ObjRef::new(6, 0)).unwrap(); + assert_eq!(d.get(ObjRef::new(4, 0)).as_array().cloned(), Some(vec![Object::Ref(ObjRef::new(7, 0))])); + remove_kid(&mut d, ObjRef::new(5, 0), ObjRef::new(6, 0)).unwrap(); + assert_eq!(d.get(ObjRef::new(8, 0)).as_dict().and_then(|f| f.name(b"Type")), Some(&b"Font"[..]), "the font is untouched"); + } +} + #[cfg(test)] mod tests { use std::sync::Arc; diff --git a/crates/organize/src/lib.rs b/crates/organize/src/lib.rs index aa498b76a2..cf0947d375 100644 --- a/crates/organize/src/lib.rs +++ b/crates/organize/src/lib.rs @@ -23,6 +23,7 @@ mod outline; mod outline_io; mod pdfx; mod prune; +mod templates; mod transition; pub mod view; mod xmp; @@ -42,6 +43,7 @@ pub use outline::{ move_bookmark, rename_bookmark, set_bookmark_color, set_bookmark_open, set_bookmark_page, set_bookmark_style, top_level_bookmarks, }; pub use outline_io::{MAX_IMPORT_BOOKMARKS, OutlineNode, OutlineTree, import_outline, outline_tree, unmapped, view_arity}; +pub use templates::{Template, set_template_hidden, spawn_template, templates}; pub use transition::{TRANSITION_DIRECTIONS, TRANSITION_STYLES, Transition, TransitionSpec, set_transition}; pub use view::{InitialView, displays_doc_title, initial_view, set_initial_view}; diff --git a/crates/organize/src/templates.rs b/crates/organize/src/templates.rs new file mode 100644 index 0000000000..8314aaebca --- /dev/null +++ b/crates/organize/src/templates.rs @@ -0,0 +1,261 @@ +//! Page templates (#1429): the name dictionary's `/Templates` tree names pages kept out of the +//! page tree, and its `/Pages` tree names visible pages (ISO 32000-2 §7.7.4, Table 32). Forms +//! show more pages from them through JavaScript: `Template.spawn` adds a copy of a template's +//! page, and `Template.hidden = false` moves the template's own page into the document. + +use std::collections::HashSet; + +use pdfcraft_cos::{Dict, Document, ObjRef, Object, PdfString}; + +use crate::{INHERITABLE, OrganizeError, page_count, rebuild, walk}; + +/// At most this many names are read from one tree: a form has a handful of templates. +const MAX_NAMES: usize = 4096; + +/// Field levels followed up from a widget to its top-level field. +const MAX_FIELD_DEPTH: usize = 32; + +/// A named page a form can add or show. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Template { + pub name: String, + /// Kept out of the page tree (`/Templates`); a visible named page (`/Pages`) is not hidden. + pub hidden: bool, +} + +/// The document's templates: the hidden ones (`/Templates`), then the named visible pages +/// (`/Pages`), each in its tree's order. +pub fn templates(doc: &Document) -> Vec