mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-11-18 23:13:03 +00:00
M12: forms show and add pages from page templates (#1429)
## What this changes Part of #1429. The form in that report keeps pages it shows on demand as **page templates**: the name dictionary's `/Templates` tree names pages kept out of the page tree, and `/Pages` names visible ones (ISO 32000-2 §7.7.4). Until now their fields were listed as unplaced, and the form's JavaScript could not reach them, so buttons that add a page or show a section did nothing. - **organize**: `templates`, `spawn_template` and `set_template_hidden`. - A spawned page is a copy of the template page. - With renaming, its fields become fields of their own under `P<page>.<template>.<name>`. - Without renaming, its widgets join the template's fields and share their values. A template field that is its own widget is split into field + widget first. - Hiding a template takes its page out of the tree, keeps what it inherited (MediaBox, Resources, …) and refuses to hide the last page. - **js**: `this.templates`, `getTemplate(name)`, `Template.name`, `Template.hidden` (setting it shows or hides the page), `Template.spawn(nPage, bRename, bOverlay)` and `spawnPageFromTemplate`, with positional or named arguments and the documented defaults (0 / true / true). Non-number pages are clamped. - **engine**: new `Edit::SpawnTemplate` and `Edit::SetTemplateHidden`. - Both are checked against the assemble permission and applied in the same undo step as the script's field changes. - Only a button's or the console's script may change the pages. A field's own scripts (format, keystroke, validate, calculate) are told so on the console. - At most 100 template pages per script run, because each spawn copies the document. A loop that asks for more stops there with one console note. - **automation**: `page_templates` (read-only), `page_template_spawn` and `page_template_set_hidden`. - Undo labels translated in all 34 catalogues. Not in this PR: - `bOverlay` true (laying a template over an existing page). The script is told so on the console once and nothing changes. - `createTemplate` / `removeTemplate`. - An Organize-panel UI for templates. - `numPages` is not updated inside the running script. - Mouse Up actions on radio buttons and checkboxes (the other half of #1429) are in the open #2546. ## How you verified it - [x] `cargo fmt --check` - [x] clippy with `-D warnings` on the crates I changed (organize, js, engine, automation, ui-egui) - [x] tests pass on the crates I changed | Crate | Result | |---|---| | organize | 188 passed | | js | 97 passed | | engine lib | 382 passed | | engine it | 21 passed | | automation | 45 + 282 passed | | ui-egui i18n | 65 passed | - [x] `cargo xtask layers`, `cargo xtask assets` and `cargo xtask parity` **Tests.** - organize has 9 unit tests: listing, renamed and shared spawns, appending past the end, show/hide, the last page and unknown names refused, hostile template trees, repeated unrenamed copies, and inherited attributes kept when hiding. - js has 5 tests: listing, `spawn` defaults, both argument forms, `hidden` read back, and clamping. - engine has 5 integration tests: one undo step, renamed and shared spawns surviving save + reopen, overlay noted, field scripts refused, and the 100-page budget. - automation has 2 tool tests. Each behaviour was seen failing by reverting it: - no renaming - no field sharing - no MediaBox fallback - hidden page dropping inherited attributes - no budget - field scripts allowed to spawn - requests not applied - wrong default flags Under a loaded machine `tests::xfa_model::a_slow_engine_start_does_not_count_against_the_script` (an existing timing test) failed once and passes on its own. It is not touched here. ## Never-crash - [x] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests, unless it is provably infallible with a comment saying why - [x] No indexing or slicing with input-derived positions; checked or saturating arithmetic; allocations sized by input are capped; recursion is bounded - Name trees are capped at 4096 names. - Field walks are capped at 32 levels and 100 000 nodes, with seen-sets. - Spawns are capped at 100 per script run. - Template names are clipped and charged to the script's output budget. - [x] No `unsafe` - [x] Any crash this fixes has a small synthetic regression test (no crash fixed; the hostile-tree test covers cyclic and malformed `/Templates`) ## Provenance - [x] No asset from an Adobe product, and no Adobe icon recreated, traced or imitated - [x] No font files committed here - [x] No GPL/AGPL code copied in - [x] Behaviour comes from the specification or black-box observation, **not** from reading another implementation's source. The sources are ISO 32000-2 §7.7.4 and §12.7.6 and the public Acrobat JavaScript API reference for `Template`/`spawnPageFromTemplate`. - [x] Every new asset has an `ATTRIBUTION.toml` entry and `cargo xtask assets` passes (no new assets) ## Security - [x] `--root` confinement still holds on every path, including ones reached by nested tool dispatch (the new tools take a document id, no paths) - [x] MCP and the UI control channel stay opt-in, loopback-only and token-authenticated - [x] No new outbound network access ## Parity and reach - [x] `parity/acrobat-features.toml` updated: `organize.page-templates` is now `partial`, with notes on what is still missing - [x] Reachable headlessly through an `automation` tool (`page_templates`, `page_template_spawn`, `page_template_set_hidden`, and `js_run` for scripts) - [x] Docs updated if this changes a documented behaviour (crate doc comments) ## Anything a reviewer should look at first - `share_fields_with_originals` in `crates/organize/src/import/fields.rs`: how an unrenamed copy's widgets are reparented onto the template's fields. When a template field is its own widget, it is split into a field with two widget kids. - The 100-page budget per script run in `crates/engine/src/js.rs`. Each spawn copies the document, so a `for` loop over `spawn` in a hostile form is bounded there.
This commit is contained in:
@@ -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 }),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Value> = 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)?,
|
||||
|
||||
@@ -1184,6 +1184,13 @@ pub fn tools() -> Vec<ToolDef> {
|
||||
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<at-1>.<name>.<field>; 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",
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<u8> {
|
||||
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<String> {
|
||||
let fields = ok(a, "form_fields", json!({ "doc": doc }));
|
||||
let mut names: Vec<String> = 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);
|
||||
}
|
||||
@@ -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<pdfcraft_organize::Template> {
|
||||
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 {
|
||||
|
||||
@@ -45,6 +45,20 @@ pub enum Edit {
|
||||
pages: Vec<usize>,
|
||||
at: Option<usize>,
|
||||
},
|
||||
/// 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<at>.<name>`;
|
||||
/// 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 {
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
+56
-5
@@ -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<Outcome, EditError> {
|
||||
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<Vec<pdfcraft_js::FieldState>>,
|
||||
/// Whether the script may add or show pages from templates ([`may_change_pages`]).
|
||||
may_change_pages: bool,
|
||||
pub receiver: std::sync::mpsc::Receiver<pdfcraft_js::interaction::InteractiveEvent>,
|
||||
}
|
||||
#[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);
|
||||
}
|
||||
|
||||
@@ -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::<Vec<_>>());
|
||||
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.
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<u8> {
|
||||
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<String> {
|
||||
let mut names: Vec<String> = 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");
|
||||
}
|
||||
@@ -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<JsValue> {
|
||||
Ok(JsValue::from(name.clone()))
|
||||
}
|
||||
fn get_hidden(_: &JsValue, _: &[JsValue], name: &JsString, c: &mut Context) -> JsResult<JsValue> {
|
||||
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<JsValue> {
|
||||
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<JsValue> {
|
||||
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<Request> {
|
||||
let given = arg(args, first);
|
||||
let named = given.as_object().filter(|o| !o.is_array());
|
||||
let mut value = |key: &str, index: usize| -> JsResult<JsValue> {
|
||||
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<JsValue> {
|
||||
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<JsValue> {
|
||||
// `({ 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())
|
||||
}
|
||||
|
||||
@@ -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<String> = host(ctx)?.borrow().doc.templates.iter().map(|(n, _)| n.clone()).collect();
|
||||
let templates: Vec<JsValue> = 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)?;
|
||||
|
||||
@@ -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::<String>())),
|
||||
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);
|
||||
|
||||
@@ -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`,
|
||||
|
||||
@@ -185,6 +185,8 @@ pub struct DocInfo {
|
||||
pub page_rotations: Vec<i64>,
|
||||
/// 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")`, …).
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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<ObjRef>) -> 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<Object> = 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<String, ObjRef> = 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<ObjRef> = 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<ObjRef>, HashSet<ObjRef>) = (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<Object>| {
|
||||
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<ObjRef> {
|
||||
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;
|
||||
|
||||
@@ -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};
|
||||
|
||||
|
||||
@@ -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<Template> {
|
||||
let named = |tree: &[u8], hidden: bool| {
|
||||
entries(doc, tree).into_iter().filter(|(_, v)| v.as_ref().is_some()).map(move |(k, _)| Template { name: text(&k), hidden })
|
||||
};
|
||||
named(b"Templates", true).chain(named(b"Pages", false)).collect()
|
||||
}
|
||||
|
||||
/// Add a copy of template `name`'s page as page `at` (0-based, clamped to the end), as
|
||||
/// JavaScript's `Template.spawn(at, rename, false)` does. With `rename`, the copy's fields are
|
||||
/// put under `P<at>.<name>`, so they are fields of their own; without it, they are more widgets
|
||||
/// of the template's fields and share their values. Returns where the page went.
|
||||
pub fn spawn_template(doc: &mut Document, name: &str, at: usize, rename: bool) -> Result<usize, OrganizeError> {
|
||||
let page = template_page(doc, name)?;
|
||||
let at = at.min(page_count(doc)?);
|
||||
// The copy is made from a version of the document whose page tree ends with the template's
|
||||
// page, so the page importer copies it as any page: its content, resources and widgets,
|
||||
// with their fields registered in the form.
|
||||
let mut src = doc.clone();
|
||||
let mut order = walk(&src)?;
|
||||
let index = match order.iter().position(|(r, _)| *r == page) {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
src.update_dict(page, |d| d.set(b"Type".to_vec(), Object::name("Page")))?;
|
||||
order.push((page, fallback_attributes(&order)));
|
||||
rebuild(&mut src, &order)?;
|
||||
order.len().saturating_sub(1)
|
||||
}
|
||||
};
|
||||
if rename {
|
||||
rename_fields(&mut src, page, &format!("P{at}"), name)?;
|
||||
}
|
||||
let before = crate::import::listed_fields(doc);
|
||||
// Renamed copies are fields of their own: a second copy spawned at the same page, whose
|
||||
// `P<at>` is taken, gets the first free `P<at>-1`… rather than a name the form already has.
|
||||
let conflicts = if rename { crate::import::FieldConflicts::Rename } else { crate::import::FieldConflicts::Merge };
|
||||
let copied = crate::import::import_pages_with(doc, &src, &[index], at, conflicts)?.pages;
|
||||
if !rename && let Some(©) = copied.first() {
|
||||
crate::import::share_fields_with_originals(doc, copy, &before)?;
|
||||
}
|
||||
Ok(at)
|
||||
}
|
||||
|
||||
/// Show (`hidden` false) or hide template `name`, as JavaScript's `Template.hidden` does. A
|
||||
/// shown template's page goes at the end of the document and is named in `/Pages`; a hidden
|
||||
/// one leaves the page tree, page and all, and is named in `/Templates` again. Showing a
|
||||
/// visible page, or hiding a hidden one, changes nothing.
|
||||
pub fn set_template_hidden(doc: &mut Document, name: &str, hidden: bool) -> Result<(), OrganizeError> {
|
||||
let (from, to): (&[u8], &[u8]) = if hidden { (b"Pages", b"Templates") } else { (b"Templates", b"Pages") };
|
||||
// Rewritten from every entry, not the listing's first [`MAX_NAMES`], so no name is lost.
|
||||
let mut source = all_entries(doc, from);
|
||||
let Some(k) = source.iter().position(|(key, _)| text(key) == name) else {
|
||||
return if all_entries(doc, to).iter().any(|(key, _)| text(key) == name) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(OrganizeError::Invalid(format!("the document has no template named {name}")))
|
||||
};
|
||||
};
|
||||
let (key, value) = source.remove(k);
|
||||
let page = value.as_ref().ok_or_else(|| OrganizeError::Invalid(format!("template {name} is not a page")))?;
|
||||
let mut order = walk(doc)?;
|
||||
if hidden {
|
||||
let Some(at) = order.iter().position(|(r, _)| *r == page) else {
|
||||
return Err(OrganizeError::Invalid(format!("template {name} is not a page of the document")));
|
||||
};
|
||||
if order.len() == 1 {
|
||||
return Err(OrganizeError::WouldRemoveAllPages);
|
||||
}
|
||||
// Out of the tree, the page no longer inherits: it keeps what it showed with.
|
||||
let (_, inherited) = order.remove(at);
|
||||
doc.update_dict(page, |d| {
|
||||
for k in INHERITABLE {
|
||||
if !d.contains(k)
|
||||
&& let Some(v) = inherited.get(k)
|
||||
{
|
||||
d.set(k.to_vec(), v.clone());
|
||||
}
|
||||
}
|
||||
d.remove(b"Parent");
|
||||
d.set(b"Type".to_vec(), Object::name("Template"));
|
||||
})?;
|
||||
} else {
|
||||
if order.iter().any(|(r, _)| *r == page) {
|
||||
return Err(OrganizeError::Invalid(format!("template {name} is already a page of the document")));
|
||||
}
|
||||
doc.update_dict(page, |d| d.set(b"Type".to_vec(), Object::name("Page")))?;
|
||||
let attributes = fallback_attributes(&order);
|
||||
order.push((page, attributes));
|
||||
}
|
||||
rebuild(doc, &order)?;
|
||||
let mut target = all_entries(doc, to);
|
||||
target.push((key, value));
|
||||
write_tree(doc, from, source)?;
|
||||
write_tree(doc, to, target)
|
||||
}
|
||||
|
||||
/// The page template `name` names, hidden or visible.
|
||||
fn template_page(doc: &Document, name: &str) -> Result<ObjRef, OrganizeError> {
|
||||
[&b"Templates"[..], b"Pages"]
|
||||
.iter()
|
||||
.flat_map(|tree| entries(doc, tree))
|
||||
.find(|(key, _)| text(key) == name)
|
||||
.and_then(|(_, v)| v.as_ref())
|
||||
.filter(|r| doc.get(*r).as_dict().is_some())
|
||||
.ok_or_else(|| OrganizeError::Invalid(format!("the document has no template named {name}")))
|
||||
}
|
||||
|
||||
/// What a page added to the tree inherits when it has no attributes of its own: those of the
|
||||
/// first page, so a template written without a media box still has one.
|
||||
fn fallback_attributes(order: &[(ObjRef, Dict)]) -> Dict {
|
||||
order.first().map(|(_, inherited)| inherited.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Put the fields of the widgets on `page` under a new field `outer`, holding one named
|
||||
/// `inner`: JavaScript's renaming of a spawned page's fields (`P1.Name.Field`).
|
||||
fn rename_fields(doc: &mut Document, page: ObjRef, outer: &str, inner: &str) -> Result<(), OrganizeError> {
|
||||
let annots = doc.get(page).as_dict().and_then(|d| d.get(b"Annots").cloned()).map(|a| doc.resolve(&a).as_ref().clone());
|
||||
let mut tops: Vec<ObjRef> = Vec::new();
|
||||
for annot in annots.as_ref().and_then(Object::as_array).into_iter().flatten() {
|
||||
let Some(widget) = annot.as_ref() else { continue };
|
||||
if doc.get(widget).as_dict().is_none_or(|d| d.name(b"Subtype") != Some(b"Widget")) {
|
||||
continue;
|
||||
}
|
||||
if let Some(top) = top_field(doc, widget)
|
||||
&& !tops.contains(&top)
|
||||
{
|
||||
tops.push(top);
|
||||
}
|
||||
}
|
||||
if tops.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let named = |t: &str| {
|
||||
let mut d = Dict::new();
|
||||
d.set(b"T".to_vec(), Object::String(PdfString::text(t)));
|
||||
d
|
||||
};
|
||||
let mut middle = named(inner);
|
||||
middle.set(b"Kids".to_vec(), Object::Array(tops.iter().map(|r| Object::Ref(*r)).collect()));
|
||||
let middle = doc.add(middle);
|
||||
let mut top = named(outer);
|
||||
top.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(middle)]));
|
||||
let top = doc.add(top);
|
||||
doc.update_dict(middle, |d| d.set(b"Parent".to_vec(), Object::Ref(top)))?;
|
||||
for field in tops {
|
||||
doc.update_dict(field, |d| d.set(b"Parent".to_vec(), Object::Ref(middle)))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The top-level field `widget` belongs to (itself, when it is its own field), following
|
||||
/// `/Parent` at most [`MAX_FIELD_DEPTH`] levels and never through a node twice.
|
||||
fn top_field(doc: &Document, widget: ObjRef) -> Option<ObjRef> {
|
||||
let mut node = widget;
|
||||
let mut seen = HashSet::new();
|
||||
for _ in 0..MAX_FIELD_DEPTH {
|
||||
if !seen.insert(node) {
|
||||
return None;
|
||||
}
|
||||
match doc.get(node).as_dict()?.reference(b"Parent") {
|
||||
Some(parent) => node = parent,
|
||||
None => return Some(node),
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The (key, value) pairs of the name dictionary's tree `key`, at most [`MAX_NAMES`] (for listing).
|
||||
fn entries(doc: &Document, key: &[u8]) -> Vec<(Vec<u8>, Object)> {
|
||||
let mut out = all_entries(doc, key);
|
||||
out.truncate(MAX_NAMES);
|
||||
out
|
||||
}
|
||||
|
||||
/// Every (key, value) pair of the name dictionary's tree `key`, for rewriting it. The walk is
|
||||
/// bounded by the tree reader's depth limit and seen-set; the entries are already in memory.
|
||||
fn all_entries(doc: &Document, key: &[u8]) -> Vec<(Vec<u8>, Object)> {
|
||||
let Some(tree) = names(doc).and_then(|n| n.get(key).cloned()) else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
crate::import::name_tree_entries(doc, &tree, 0, &mut HashSet::new(), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// The catalog's name dictionary.
|
||||
fn names(doc: &Document) -> Option<Dict> {
|
||||
let catalog = doc.get(doc.root()?).as_dict()?.clone();
|
||||
doc.resolve(catalog.get(b"Names")?).as_dict().cloned()
|
||||
}
|
||||
|
||||
/// A tree key as text (keys are PDF text strings).
|
||||
fn text(key: &[u8]) -> String {
|
||||
PdfString::literal(key.to_vec()).to_text()
|
||||
}
|
||||
|
||||
/// Write the name dictionary's tree `key` as one sorted leaf holding `entries`, or leave it out
|
||||
/// when there are none. The dictionary's other trees stay where they are.
|
||||
fn write_tree(doc: &mut Document, key: &[u8], mut entries: Vec<(Vec<u8>, Object)>) -> Result<(), OrganizeError> {
|
||||
entries.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
let tree = (!entries.is_empty()).then(|| {
|
||||
let mut names = Vec::with_capacity(entries.len().saturating_mul(2));
|
||||
for (k, v) in entries {
|
||||
names.push(Object::String(PdfString::literal(k)));
|
||||
names.push(v);
|
||||
}
|
||||
let mut leaf = Dict::new();
|
||||
leaf.set(b"Names".to_vec(), Object::Array(names));
|
||||
doc.add(leaf)
|
||||
});
|
||||
let set = |n: &mut Dict| match tree {
|
||||
Some(t) => n.set(key.to_vec(), Object::Ref(t)),
|
||||
None => {
|
||||
n.remove(key);
|
||||
}
|
||||
};
|
||||
let root = doc.root().ok_or(OrganizeError::NoPageTree)?;
|
||||
// `/Names` may be an indirect dictionary: update it where it is.
|
||||
if let Some(Object::Ref(names)) = doc.get(root).as_dict().and_then(|c| c.get(b"Names").cloned())
|
||||
&& doc.get(names).as_dict().is_some()
|
||||
{
|
||||
doc.update_dict(names, set)?;
|
||||
return Ok(());
|
||||
}
|
||||
doc.update_dict(root, |c| {
|
||||
let mut n = match c.get(b"Names") {
|
||||
Some(Object::Dict(d)) => d.clone(),
|
||||
_ => Dict::new(),
|
||||
};
|
||||
set(&mut n);
|
||||
c.set(b"Names".to_vec(), Object::Dict(n));
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,311 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use pdfcraft_cos::{Dict, Document, ObjRef, Object, SaveOptions, write_full};
|
||||
|
||||
use super::*;
|
||||
use crate::pages;
|
||||
|
||||
fn build(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")
|
||||
}
|
||||
|
||||
/// One visible page and a hidden template, `More`, whose page holds the text field `Extra`
|
||||
/// (a field that is its own widget, as forms write it) and has no media box of its own.
|
||||
fn form() -> Document {
|
||||
build(&form_bodies())
|
||||
}
|
||||
|
||||
/// The objects of [`form`], numbered from 1.
|
||||
fn form_bodies() -> [&'static str; 9] {
|
||||
[
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /Templates 6 0 R >> /AcroForm << /Fields [7 0 R] >> >>",
|
||||
"<< /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) /V (x) /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 >>",
|
||||
]
|
||||
}
|
||||
|
||||
/// What each page says, through its content stream.
|
||||
fn texts(doc: &Document) -> Vec<String> {
|
||||
pages(doc)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let contents = doc.get(p.obj).as_dict().and_then(|d| d.get(b"Contents").cloned()).expect("contents");
|
||||
let Object::Stream(s) = doc.resolve(&contents).as_ref().clone() else { panic!("a stream") };
|
||||
let data = s.decoded().unwrap();
|
||||
let t = String::from_utf8_lossy(&data).into_owned();
|
||||
t.split('(').nth(1).and_then(|x| x.split(')').next()).unwrap_or_default().to_string()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The fully-qualified names of the form's fields that have a widget on page `page` (0-based).
|
||||
fn fields_on(doc: &Document, page: usize) -> Vec<String> {
|
||||
let page = pages(doc).unwrap()[page].obj;
|
||||
let annots = doc.get(page).as_dict().and_then(|d| d.get(b"Annots").cloned()).map(|a| doc.resolve(&a).as_ref().clone());
|
||||
let mut out = Vec::new();
|
||||
for w in annots.as_ref().and_then(Object::as_array).into_iter().flatten().filter_map(Object::as_ref) {
|
||||
out.push(full_name(doc, w));
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
fn full_name(doc: &Document, node: ObjRef) -> String {
|
||||
let mut parts = Vec::new();
|
||||
let mut at = Some(node);
|
||||
while let Some(r) = at {
|
||||
let d = doc.get(r).as_dict().cloned().unwrap_or_default();
|
||||
if let Some(t) = d.get(b"T").and_then(|t| doc.resolve(t).as_string().map(|s| s.to_text())) {
|
||||
parts.push(t);
|
||||
}
|
||||
at = d.reference(b"Parent");
|
||||
}
|
||||
parts.reverse();
|
||||
parts.join(".")
|
||||
}
|
||||
|
||||
/// The top-level fields the form lists, by name.
|
||||
fn listed_fields(doc: &Document) -> Vec<String> {
|
||||
let catalog = doc.get(doc.root().unwrap()).as_dict().cloned().unwrap();
|
||||
let form = doc.resolve(catalog.get(b"AcroForm").unwrap()).as_dict().cloned().unwrap();
|
||||
let fields = doc.resolve(form.get(b"Fields").unwrap()).as_array().cloned().unwrap();
|
||||
let mut names: Vec<String> = fields.iter().filter_map(Object::as_ref).map(|r| full_name(doc, r)).collect();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
fn reopen(doc: &Document) -> Document {
|
||||
let bytes = write_full(doc, &SaveOptions::default()).expect("writes");
|
||||
let independent = hayro_syntax::Pdf::new(bytes.clone()).expect("another reader opens it");
|
||||
let reopened = Document::open(Arc::new(bytes)).expect("reopens");
|
||||
assert_eq!(independent.pages().len(), page_count(&reopened).unwrap(), "the readers agree on the pages");
|
||||
reopened
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_templates_and_named_pages_are_listed() {
|
||||
assert_eq!(templates(&form()), [Template { name: "More".into(), hidden: true }]);
|
||||
let mut doc = form();
|
||||
set_template_hidden(&mut doc, "More", false).unwrap();
|
||||
assert_eq!(templates(&doc), [Template { name: "More".into(), hidden: false }]);
|
||||
}
|
||||
|
||||
/// `spawn(1, false, false)`: a copy of the template's page, whose widget joins the template's
|
||||
/// own field, so the two share the value, as in Acrobat.
|
||||
#[test]
|
||||
fn a_spawned_page_without_renaming_shares_the_templates_fields() {
|
||||
let mut doc = form();
|
||||
assert_eq!(spawn_template(&mut doc, "More", 1, false).unwrap(), 1);
|
||||
let doc = reopen(&doc);
|
||||
assert_eq!(texts(&doc), ["Visible", "Template"]);
|
||||
assert_eq!(fields_on(&doc, 1), ["Extra"]);
|
||||
assert_eq!(listed_fields(&doc), ["Extra"], "no second field of the same name");
|
||||
let page = pages(&doc).unwrap()[1].obj;
|
||||
let media = doc.get(page).as_dict().and_then(|d| d.get(b"MediaBox").cloned());
|
||||
assert!(media.is_some(), "a template without a media box takes the first page's");
|
||||
assert_eq!(templates(&doc), [Template { name: "More".into(), hidden: true }], "the template stays");
|
||||
}
|
||||
|
||||
/// `spawn(0, true, false)`: the copy's fields are its own, named `P0.More.Extra`.
|
||||
#[test]
|
||||
fn a_spawned_page_with_renaming_has_fields_of_its_own() {
|
||||
let mut doc = form();
|
||||
assert_eq!(spawn_template(&mut doc, "More", 0, true).unwrap(), 0);
|
||||
let doc = reopen(&doc);
|
||||
assert_eq!(texts(&doc), ["Template", "Visible"]);
|
||||
assert_eq!(fields_on(&doc, 0), ["P0.More.Extra"]);
|
||||
assert_eq!(listed_fields(&doc), ["Extra", "P0"]);
|
||||
}
|
||||
|
||||
/// A position past the end appends the page.
|
||||
#[test]
|
||||
fn spawning_past_the_end_appends() {
|
||||
let mut doc = form();
|
||||
assert_eq!(spawn_template(&mut doc, "More", 99, false).unwrap(), 1);
|
||||
assert_eq!(texts(&reopen(&doc)), ["Visible", "Template"]);
|
||||
}
|
||||
|
||||
/// `hidden = false` moves the template's own page into the document, so its fields have a page;
|
||||
/// `hidden = true` takes it out again, with what it inherited.
|
||||
#[test]
|
||||
fn showing_and_hiding_a_template_moves_its_own_page() {
|
||||
let mut doc = form();
|
||||
set_template_hidden(&mut doc, "More", false).unwrap();
|
||||
assert_eq!(pages(&doc).unwrap()[1].obj, ObjRef::new(5, 0), "the template's own page, not a copy");
|
||||
let shown = reopen(&doc);
|
||||
assert_eq!(texts(&shown), ["Visible", "Template"]);
|
||||
assert_eq!(fields_on(&shown, 1), ["Extra"]);
|
||||
|
||||
// Showing it again changes nothing.
|
||||
set_template_hidden(&mut doc, "More", false).unwrap();
|
||||
assert_eq!(page_count(&doc).unwrap(), 2);
|
||||
|
||||
set_template_hidden(&mut doc, "More", true).unwrap();
|
||||
let page: Dict = doc.get(ObjRef::new(5, 0)).as_dict().cloned().unwrap();
|
||||
assert_eq!(page.name(b"Type"), Some(&b"Template"[..]));
|
||||
assert!(page.get(b"MediaBox").is_some() && page.get(b"Parent").is_none(), "{page:?}");
|
||||
let hidden = reopen(&doc);
|
||||
assert_eq!(texts(&hidden), ["Visible"]);
|
||||
assert_eq!(templates(&hidden), [Template { name: "More".into(), hidden: true }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_templates_and_the_last_page_are_refused() {
|
||||
let mut doc = form();
|
||||
assert!(spawn_template(&mut doc, "Nope", 0, true).is_err());
|
||||
assert!(set_template_hidden(&mut doc, "Nope", false).is_err());
|
||||
// A document whose only page is named in /Pages can't hide it.
|
||||
let mut only = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /Pages << /Names [(Only) 3 0 R] >> >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>",
|
||||
"<< /Type /Page /Parent 2 0 R >>",
|
||||
]);
|
||||
assert!(matches!(set_template_hidden(&mut only, "Only", true), Err(OrganizeError::WouldRemoveAllPages)));
|
||||
assert_eq!(page_count(&only).unwrap(), 1);
|
||||
}
|
||||
|
||||
/// A name tree that lists itself, and one whose entry is not a page, list nothing usable.
|
||||
#[test]
|
||||
fn hostile_template_trees_end() {
|
||||
let mut doc = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /Templates 4 0 R >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>",
|
||||
"<< /Type /Page /Parent 2 0 R >>",
|
||||
"<< /Kids [4 0 R 5 0 R] >>",
|
||||
"<< /Names [(Broken) 42] >>",
|
||||
]);
|
||||
assert_eq!(templates(&doc), []);
|
||||
assert!(spawn_template(&mut doc, "Broken", 0, false).is_err());
|
||||
assert!(set_template_hidden(&mut doc, "Broken", false).is_err());
|
||||
}
|
||||
|
||||
/// Two copies without renaming: still one field, now with the template's widget and both copies'
|
||||
/// as its kids, and its value held once, by the field.
|
||||
#[test]
|
||||
fn every_unrenamed_copy_is_one_more_widget_of_the_one_field() {
|
||||
let mut doc = form();
|
||||
spawn_template(&mut doc, "More", 1, false).unwrap();
|
||||
spawn_template(&mut doc, "More", 2, false).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
assert_eq!(listed_fields(&doc), ["Extra"]);
|
||||
let catalog = doc.get(doc.root().unwrap()).as_dict().cloned().unwrap();
|
||||
let form = doc.resolve(catalog.get(b"AcroForm").unwrap()).as_dict().cloned().unwrap();
|
||||
let field = doc.resolve(form.get(b"Fields").unwrap()).as_array().cloned().unwrap()[0].as_ref().unwrap();
|
||||
let field = doc.get(field).as_dict().cloned().unwrap();
|
||||
assert_eq!(field.get(b"V").and_then(|v| v.as_string()).map(|s| s.to_text()).as_deref(), Some("x"), "the value is the field's");
|
||||
let kids = doc.resolve(field.get(b"Kids").unwrap()).as_array().cloned().unwrap();
|
||||
assert_eq!(kids.len(), 3, "{field:?}");
|
||||
for kid in kids.iter().filter_map(Object::as_ref) {
|
||||
let w = doc.get(kid).as_dict().cloned().unwrap();
|
||||
assert!(w.name(b"Subtype") == Some(&b"Widget"[..]) && !w.contains(b"T") && !w.contains(b"V"), "a plain widget: {w:?}");
|
||||
}
|
||||
assert_eq!(fields_on(&doc, 1), ["Extra"]);
|
||||
assert_eq!(fields_on(&doc, 2), ["Extra"]);
|
||||
}
|
||||
|
||||
/// A visible named page that inherits its media box from the page tree keeps it when hidden:
|
||||
/// out of the tree, nothing would give it one.
|
||||
#[test]
|
||||
fn a_hidden_page_keeps_what_it_inherited() {
|
||||
let mut doc = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /Pages << /Names [(Cover) 4 0 R] >> >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 210 297] >>",
|
||||
"<< /Type /Page /Parent 2 0 R >>",
|
||||
"<< /Type /Page /Parent 2 0 R >>",
|
||||
]);
|
||||
set_template_hidden(&mut doc, "Cover", true).unwrap();
|
||||
assert_eq!(page_count(&doc).unwrap(), 1);
|
||||
let page: Dict = doc.get(ObjRef::new(4, 0)).as_dict().cloned().unwrap();
|
||||
let media = page.get(b"MediaBox").and_then(|m| m.as_array().cloned()).expect("its media box, inherited before");
|
||||
assert_eq!(media.len(), 4);
|
||||
assert_eq!(templates(&doc), [Template { name: "Cover".into(), hidden: true }]);
|
||||
}
|
||||
|
||||
/// Showing or hiding a template rewrites both name trees from every entry, not from the first
|
||||
/// [`MAX_NAMES`] the listing reads, so a long `/Pages` tree loses no name.
|
||||
#[test]
|
||||
fn showing_and_hiding_keep_every_name_of_a_long_tree() {
|
||||
let names: String = (0..MAX_NAMES + 10).map(|i| format!("(N{i:05}) 3 0 R ")).collect();
|
||||
let pages_tree = format!("<< /Names [{names}] >>");
|
||||
let mut bodies =
|
||||
vec!["<< /Type /Catalog /Pages 2 0 R /Names << /Templates 6 0 R /Pages 10 0 R >> /AcroForm << /Fields [7 0 R] >> >>".to_string()];
|
||||
|
||||
bodies.extend(form_bodies().iter().skip(1).map(|b| b.to_string()));
|
||||
bodies.push(pages_tree);
|
||||
let mut doc = build(&bodies.iter().map(String::as_str).collect::<Vec<_>>());
|
||||
let count = |doc: &Document, tree: &[u8]| all_entries(doc, tree).len();
|
||||
assert_eq!(count(&doc, b"Pages"), MAX_NAMES + 10);
|
||||
set_template_hidden(&mut doc, "More", false).unwrap();
|
||||
assert_eq!((count(&doc, b"Pages"), count(&doc, b"Templates")), (MAX_NAMES + 11, 0));
|
||||
set_template_hidden(&mut doc, "More", true).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
assert_eq!((count(&doc, b"Pages"), count(&doc, b"Templates")), (MAX_NAMES + 10, 1));
|
||||
}
|
||||
|
||||
/// Two renamed copies spawned at the same page get fields of their own, not two fields with one
|
||||
/// name: the second takes the first free variant of `P0`.
|
||||
#[test]
|
||||
fn renamed_copies_at_the_same_page_never_share_a_name() {
|
||||
let mut doc = form();
|
||||
spawn_template(&mut doc, "More", 0, true).unwrap();
|
||||
spawn_template(&mut doc, "More", 0, true).unwrap();
|
||||
let doc = reopen(&doc);
|
||||
let listed = listed_fields(&doc);
|
||||
let mut unique = listed.clone();
|
||||
unique.dedup();
|
||||
assert_eq!(listed, unique, "{listed:?}");
|
||||
assert_eq!(listed.len(), 3, "the template's field and one per copy: {listed:?}");
|
||||
assert_ne!(fields_on(&doc, 0), fields_on(&doc, 1));
|
||||
}
|
||||
|
||||
/// Every field that lists a kid is that kid's `/Parent`: no widget has two parents.
|
||||
fn every_kid_names_its_parent(doc: &Document) {
|
||||
for r in doc.object_numbers().into_iter().map(|n| ObjRef::new(n, 0)) {
|
||||
let obj = doc.get(r);
|
||||
let Some(d) = obj.as_dict() else { continue };
|
||||
let kids = d.get(b"Kids").map(|k| doc.resolve(k).as_ref().clone());
|
||||
for kid in kids.as_ref().and_then(Object::as_array).into_iter().flatten().filter_map(Object::as_ref) {
|
||||
let parent = doc.get(kid).as_dict().and_then(|k| k.reference(b"Parent"));
|
||||
assert!(parent.is_none_or(|p| p == r), "{kid:?} is listed by {r:?} but its parent is {parent:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A copied group with one widget that joins the template's field and one that doesn't: the
|
||||
/// copied group no longer lists the widget that left it.
|
||||
#[test]
|
||||
fn a_widget_that_joins_its_original_leaves_the_copied_group() {
|
||||
let mut doc = build(&[
|
||||
"<< /Type /Catalog /Pages 2 0 R /Names << /Templates 6 0 R >> /AcroForm << /Fields [7 0 R] >> >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 200 300] >>",
|
||||
"<< /Type /Page /Parent 2 0 R >>",
|
||||
"<< /Length 0 >>\nstream\n\nendstream",
|
||||
"<< /Type /Template /Contents 4 0 R /Annots [8 0 R 9 0 R] >>",
|
||||
"<< /Names [(More) 5 0 R] >>",
|
||||
"<< /FT /Tx /T (G) /Kids [8 0 R] >>",
|
||||
"<< /T (a) /Parent 7 0 R /Subtype /Widget /Rect [20 100 180 120] /P 5 0 R >>",
|
||||
"<< /T (b) /Parent 7 0 R /Subtype /Widget /Rect [20 140 180 160] /P 5 0 R >>",
|
||||
]);
|
||||
spawn_template(&mut doc, "More", 1, false).unwrap();
|
||||
every_kid_names_its_parent(&doc);
|
||||
every_kid_names_its_parent(&reopen(&doc));
|
||||
}
|
||||
@@ -115,7 +115,8 @@ impl PdfCraftApp {
|
||||
Request::Highlight(on) => self.script_highlight(id, on),
|
||||
Request::Focus(name) => self.focus_script_field(id, view, &name, None),
|
||||
Request::FocusField { name, object_id } => self.focus_script_field(id, view, &name, Some(object_id)),
|
||||
Request::Beep | Request::Reset(_) => {}
|
||||
// The engine applies these with the script's other changes (resets, templates).
|
||||
Request::Beep | Request::Reset(_) | Request::SpawnTemplate { .. } | Request::SetTemplateHidden { .. } => {}
|
||||
}
|
||||
}
|
||||
self.show_script_messages(out.alerts);
|
||||
|
||||
@@ -3307,11 +3307,11 @@ title = "Page templates"
|
||||
area = "D"
|
||||
tier = "P3"
|
||||
milestone = "M12"
|
||||
status = "planned"
|
||||
status = "partial"
|
||||
commands = []
|
||||
tools = []
|
||||
evidence = []
|
||||
notes = ""
|
||||
tools = ["page_templates", "page_template_spawn", "page_template_set_hidden", "js_run"]
|
||||
evidence = ["crates/organize/src/templates/tests.rs::a_spawned_page_with_renaming_has_fields_of_its_own", "crates/organize/src/templates/tests.rs::every_unrenamed_copy_is_one_more_widget_of_the_one_field", "crates/organize/src/templates/tests.rs::showing_and_hiding_a_template_moves_its_own_page", "crates/js/src/tests.rs::spawn_asks_for_a_page_from_the_template", "crates/engine/tests/it/page_templates.rs::a_script_adds_pages_from_a_template_renamed_or_shared", "crates/engine/tests/it/page_templates.rs::a_spawning_loop_stops_at_its_page_budget", "crates/automation/tests/it/page_templates.rs::templates_are_listed_spawned_shown_and_hidden_through_tools"]
|
||||
notes = "Forms' JavaScript reads this.templates and getTemplate(name), adds a page from a template with Template.spawn or spawnPageFromTemplate (nPage, bRename, bOverlay, positional or named; renamed fields go under P<page>.<template>, unrenamed copies are more widgets of the template's fields and share their values) and shows or hides one with Template.hidden (the template's own page moves into or out of the document; /Templates and /Pages name trees, ISO 32000-2 §7.7.4). Only a button's or the console's script may change the pages, as one undo step with its field changes, at most 100 pages per run. Still missing: bOverlay true (laying a template over an existing page; the script is told on the console), creating or removing templates (Doc.createTemplate, removeTemplate) and an Organize Pages ▸ Page templates panel; numPages doesn't change within the script that spawned, and the new page's fields can't be read or set (getField returns null) until that script has finished."
|
||||
|
||||
[[feature]]
|
||||
id = "organize.bookmark-add"
|
||||
|
||||
Reference in New Issue
Block a user