Files
pdfcraft/crates/engine/src/edit/labels.rs
T
Livio Oswald 55983f1f92 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.
2026-11-18 16:32:59 +07:00

397 lines
19 KiB
Rust

use super::{Edit, FillMark, ImageEdit, Label, LineEnding, MarkKind, Markup, PageBox, ReviewState, Shape, field_table};
/// Every wording [`Edit::label`] can produce, for an interface to translate. `Edit::Batch` is not
/// here: its wording is only the hole, because a batch carries its name as text (see
/// [`BATCH_LABELS`]).
pub const EDIT_LABELS: &[&str] = &[
"Rotate page",
"Change tag properties",
"Rotate pages",
"Delete page",
"Delete pages",
"Move page",
"Move pages",
"Reverse pages",
"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",
"Crop pages",
"Set page boxes",
"Set page transitions",
"Change Title",
"Change Author",
"Change Subject",
"Change Keywords",
"Change {key}",
"Insert pages from {name}",
"Insert pages from {name} — 1 field renamed",
"Insert pages from {name} — fields renamed",
"Attach {name}",
"Delete attachment {key}",
"Edit attachment description",
"Add bookmark",
"Rename bookmark",
"Delete bookmark",
"Move bookmark",
"Set bookmark destination",
"Colour",
"Style",
"Import bookmarks",
"New bookmarks from structure",
"New bookmarks from text styles",
"Number pages",
"Measure distance",
"Measure perimeter",
"Measure area",
"Set measurement scale",
"Add sticky note",
"Add highlight",
"Add underline",
"Add strikethrough",
"Add squiggly underline",
"Add rectangle",
"Add oval",
"Add arrow",
"Add line",
"Add drawing",
"Add text box",
"Add checkmark",
"Add cross",
"Add dot",
"Add signature",
"Add redaction mark",
"Add cloud",
"Add polygon",
"Add connected lines",
"Add callout",
"Add inserted text",
"Add file attachment",
"Add stamp",
"Add 3D model",
"Delete comment",
"Paste comments",
"Edit comment",
"Reply",
"Set status None",
"Set status Accepted",
"Set status Rejected",
"Set status Cancelled",
"Set status Completed",
"Replace text",
"Erase",
"Mark with checkmark",
"Remove checkmark",
"Lock comment",
"Unlock comment",
"Move comment",
"Reshape comment",
"Open comment pop-up",
"Close comment pop-up",
"Move comment pop-up",
"Resize comment",
"Change comment properties",
"Fill in {name}",
"Set the image of {name}",
"Clear form",
"Add field",
"Change field properties",
"Delete field",
"Duplicate field",
"Set tab order",
"Set calculation order",
"Change initial view",
"Set alternate text",
"Mark figure as decorative",
"Recognize text",
"Enhance scanned file",
"Run JavaScript",
"Run form script",
"Save as {level}",
"Remove {standard} identification",
"Edit script of {name}",
"Delete document JavaScript",
"Edit document JavaScript",
"Edit text",
"Prepare grouped text",
"Load document font",
"Move object",
"Move objects",
"Move image",
"Transform image",
"Rotate image",
"Crop image",
"Flip image",
"Replace image",
"Delete image",
"Bring to front",
"Bring forward",
"Send backward",
"Send to back",
"Remove crop",
"Add header & footer",
"Update header & footer",
"Add watermark",
"Update watermark",
"Add background",
"Update background",
"Remove header & footer",
"Remove watermark",
"Remove background",
"Add text",
"Add image",
"Edit content",
"Delete content",
"Paste",
"Apply redactions",
"Remove redaction marks",
"Remove hidden information",
"Import {name}",
"Add link",
"Change link properties",
"Delete link",
"Remove all links",
"Create link",
"Create links",
"Sanitize document",
"Flatten comments",
"Flatten form fields",
"Flatten",
"Flatten Fill & Sign",
"Protect with password",
"Remove security",
];
/// The names of the batches built below L7, which an interface shows in the same places as
/// [`EDIT_LABELS`] and so translates the same way. A batch built in the interface itself arrives
/// already worded in the interface's language.
pub const BATCH_LABELS: &[&str] = &[
"Set document title",
"Mark differences",
"Detect form fields",
"Run JavaScript",
"Recognize text",
field_table::LABEL,
"Style",
crate::find_replace::REPLACE_ALL,
];
impl Edit {
/// Label for the Edit menu and history ("Undo Rotate pages").
pub fn label(&self) -> Label {
match self {
Edit::RotatePages { pages, .. } => plural("Rotate page", "Rotate pages", pages.len()),
Edit::DeletePages { pages } => plural("Delete page", "Delete pages", pages.len()),
Edit::MovePages { pages, .. } => plural("Move page", "Move pages", pages.len()),
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"),
Edit::SetTransition { .. } => Label::of("Set page transitions"),
// The four `/Info` keys PdfCraft itself offers get a wording of their own, so each can
// be said in another language; any other key is the document's and goes in as it stands.
Edit::SetInfo { key, .. } => match key.as_str() {
"Title" => Label::of("Change Title"),
"Author" => Label::of("Change Author"),
"Subject" => Label::of("Change Subject"),
"Keywords" => Label::of("Change Keywords"),
_ => Label::with("Change {key}", key.as_str()),
},
Edit::InsertPagesFrom { name, .. } => Label::with("Insert pages from {name}", name.as_str()),
Edit::AddBookmark { .. } => Label::of("Add bookmark"),
Edit::RenameBookmark { .. } => Label::of("Rename bookmark"),
Edit::DeleteBookmark { .. } => Label::of("Delete bookmark"),
Edit::MoveBookmark { .. } => Label::of("Move bookmark"),
Edit::SetBookmarkPage { .. } => Label::of("Set bookmark destination"),
// The bookmark Style and Colour menus' own names, already said in every language.
Edit::SetBookmarkColor { .. } => Label::of("Colour"),
Edit::SetBookmarkStyle { .. } => Label::of("Style"),
Edit::ImportBookmarks { .. } => Label::of("Import bookmarks"),
Edit::BookmarksFromStructure => Label::of("New bookmarks from structure"),
Edit::BookmarksFromTextStyles { .. } => Label::of("New bookmarks from text styles"),
Edit::NumberPages { .. } => Label::of("Number pages"),
// What was measured is part of the wording too, for the same reason.
Edit::AddMeasurement(m) => Label::of(match m.kind {
pdfcraft_measure::Kind::Distance => "Measure distance",
pdfcraft_measure::Kind::Perimeter => "Measure perimeter",
pdfcraft_measure::Kind::Area => "Measure area",
}),
Edit::SetMeasurementScale { .. } => Label::of("Set measurement scale"),
Edit::AddAnnotation(a) => Label::of(add_annotation(&a.shape)),
Edit::AddCustomStamp { .. } => Label::of("Add stamp"),
Edit::AddModel3d { .. } => Label::of("Add 3D model"),
Edit::DeleteAnnotation { .. } => Label::of("Delete comment"),
Edit::PasteComments { .. } => Label::of("Paste comments"),
Edit::SetAnnotationContents { .. } => Label::of("Edit comment"),
Edit::ReplyToAnnotation { .. } => Label::of("Reply"),
// The state's name is part of the wording: a language may need to agree it with the rest.
Edit::SetAnnotationStatus { state, .. } => Label::of(match state {
ReviewState::None => "Set status None",
ReviewState::Accepted => "Set status Accepted",
ReviewState::Rejected => "Set status Rejected",
ReviewState::Cancelled => "Set status Cancelled",
ReviewState::Completed => "Set status Completed",
}),
Edit::ReplaceText { .. } => Label::of("Replace text"),
Edit::EraseInk { .. } => Label::of("Erase"),
Edit::MarkAnnotation { marked: true, .. } => Label::of("Mark with checkmark"),
Edit::MarkAnnotation { .. } => Label::of("Remove checkmark"),
Edit::LockAnnotation { locked: true, .. } => Label::of("Lock comment"),
Edit::LockAnnotation { .. } => Label::of("Unlock comment"),
Edit::MoveAnnotation { .. } => Label::of("Move comment"),
Edit::ReshapeAnnotation { .. } => Label::of("Reshape comment"),
Edit::SetAnnotationPopup { rect: Some(_), .. } => Label::of("Move comment pop-up"),
Edit::SetAnnotationPopup { open: Some(true), .. } => Label::of("Open comment pop-up"),
Edit::SetAnnotationPopup { .. } => Label::of("Close comment pop-up"),
Edit::ResizeAnnotation { .. } => Label::of("Resize comment"),
Edit::StyleAnnotation { .. }
| Edit::FillAnnotation { .. }
| Edit::PartOpacity { .. }
| Edit::FontSizeAnnotation { .. }
| Edit::BorderColorAnnotation { .. }
| Edit::BorderShapeAnnotation { .. }
| Edit::SetAnnotationInfo { .. } => Label::of("Change comment properties"),
Edit::SetFieldValue { name, .. } => Label::with("Fill in {name}", name.as_str()),
Edit::SetFieldImage { name, .. } | Edit::SetFieldImageTarget { name, .. } => Label::with("Set the image of {name}", name.as_str()),
Edit::ResetForm { .. } => Label::of("Clear form"),
Edit::AddField { .. } => Label::of("Add field"),
Edit::SetFieldProps { .. } => Label::of("Change field properties"),
Edit::DeleteField { .. } | Edit::DeleteWidget { .. } => Label::of("Delete field"),
Edit::DuplicateField { .. } => Label::of("Duplicate field"),
Edit::SetTabOrder { .. } | Edit::MoveInTabOrder { .. } => Label::of("Set tab order"),
Edit::SetCalculationOrder { .. } => Label::of("Set calculation order"),
Edit::SetInitialView(_) => Label::of("Change initial view"),
Edit::FixHairlines { .. } => Label::of("Fix hairlines"),
Edit::AddAttachment { name, .. } => Label::with("Attach {name}", name.as_str()),
Edit::DeleteAttachment { key } => Label::with("Delete attachment {key}", key.as_str()),
Edit::ConvertColours { .. } => Label::of("Convert colours"),
Edit::EditAttachmentDescription { .. } => Label::of("Edit attachment description"),
Edit::AutoTagText => Label::of("Automatically tag text"),
Edit::SetAltText { .. } => Label::of("Set alternate text"),
Edit::AutoTagFormFields => Label::of("Tag form fields"),
Edit::SetTagProperty { .. } => Label::of("Change tag properties"),
Edit::MoveTag { .. } => Label::of("Move object"),
Edit::MarkDecorative { .. } => Label::of("Mark figure as decorative"),
Edit::MarkTagArtifact { .. } => Label::of("Mark content as artifact"),
Edit::LayoutTableToBlocks { .. } => Label::of("Change tag properties"),
Edit::AddOcrText { .. } => Label::of("Recognize text"),
Edit::EnhanceScan { .. } => Label::of("Enhance scanned file"),
Edit::ApplyScriptChanges { .. } => Label::of("Run JavaScript"),
Edit::XfaEvent { .. } => Label::of("Run form script"),
// The level is the standard's own name ("PDF/A-2b"), so it goes in as it stands.
Edit::ConvertPdfA { level } => Label::with("Save as {level}", level.label()),
Edit::RemoveStandardId { standard } => Label::with("Remove {standard} identification", standard.label()),
Edit::SetFieldScript { name, .. } => Label::with("Edit script of {name}", name.as_str()),
Edit::SetDocumentScript { script: None, .. } => Label::of("Delete document JavaScript"),
Edit::SetDocumentScript { .. } => Label::of("Edit document JavaScript"),
Edit::EditTextLine { .. } | Edit::EditTextBlock { .. } => Label::of("Edit text"),
Edit::PrepareText { .. } => Label::of("Prepare grouped text"),
Edit::RegisterTextFont { .. } => Label::of("Load document font"),
Edit::MoveObjects { objects, .. } => plural("Move object", "Move objects", objects.len()),
Edit::EditPageImage { change, .. } => Label::of(match change {
ImageEdit::Move(_) => "Move image",
ImageEdit::Transform(_) => "Transform image",
ImageEdit::Rotate(_) | ImageEdit::RotateBy(_) => "Rotate image",
ImageEdit::Crop(_) => "Crop image",
ImageEdit::Flip { .. } => "Flip image",
ImageEdit::Replace { .. } => "Replace image",
ImageEdit::Delete => "Delete image",
ImageEdit::Arrange(ord) => match ord {
pdfcraft_edit::ArrangeOrder::BringToFront => "Bring to front",
pdfcraft_edit::ArrangeOrder::BringForward => "Bring forward",
pdfcraft_edit::ArrangeOrder::SendBackward => "Send backward",
pdfcraft_edit::ArrangeOrder::SendToBack => "Send to back",
},
ImageEdit::RemoveCrop => "Remove crop",
ImageEdit::Ungroup => "Ungroup artwork",
}),
Edit::AddHeaderFooter { replace: false, .. } => Label::of("Add header & footer"),
Edit::AddHeaderFooter { .. } => Label::of("Update header & footer"),
Edit::AddWatermark { replace: false, .. } => Label::of("Add watermark"),
Edit::AddWatermark { .. } => Label::of("Update watermark"),
Edit::AddBackground { replace: false, .. } => Label::of("Add background"),
Edit::AddBackground { .. } => Label::of("Update background"),
Edit::RemoveMarks { kind: MarkKind::HeaderFooter } => Label::of("Remove header & footer"),
Edit::RemoveMarks { kind: MarkKind::Watermark } => Label::of("Remove watermark"),
Edit::RemoveMarks { kind: MarkKind::Background } => Label::of("Remove background"),
Edit::RemoveMarks { kind: MarkKind::PrinterMarks } => Label::of("Remove printer marks"),
Edit::AddPrinterMarks { .. } => Label::of("Add printer marks"),
Edit::AddText { .. } => Label::of("Add text"),
Edit::AddImage { .. } => Label::of("Add image"),
Edit::UpdateContent { .. } => Label::of("Edit content"),
Edit::DeleteContent { .. } | Edit::DeleteObjects { .. } => Label::of("Delete content"),
Edit::ReplaceImage { .. } => Label::of("Replace image"),
Edit::PasteContent { .. } | Edit::PasteObjects { .. } => Label::of("Paste"),
Edit::ApplyRedactions { .. } => Label::of("Apply redactions"),
Edit::ClearRedactions => Label::of("Remove redaction marks"),
Edit::RemoveHidden { .. } => Label::of("Remove hidden information"),
Edit::ImportData { name, .. } => Label::with("Import {name}", name.as_str()),
Edit::AddLink { .. } => Label::of("Add link"),
Edit::SetLink { .. } => Label::of("Change link properties"),
Edit::DeleteLink { .. } => Label::of("Delete link"),
Edit::RemoveLinks { .. } => Label::of("Remove all links"),
Edit::AddLinks { links, .. } => plural("Create link", "Create links", links.len()),
Edit::Sanitize => Label::of("Sanitize document"),
Edit::XfaToStatic => Label::of("Convert to a static form"),
Edit::Flatten { comments: true, fields: false } => Label::of("Flatten comments"),
Edit::Flatten { comments: false, fields: true } => Label::of("Flatten form fields"),
Edit::Flatten { .. } => Label::of("Flatten"),
Edit::FlattenFillSign => Label::of("Flatten Fill & Sign"),
Edit::Protect(_) => Label::of("Protect with password"),
Edit::RemoveProtection => Label::of("Remove security"),
// A batch carries its own name, already worded by whoever built it.
// A batch carries its name as text, so the wording is only the hole (see `BATCH_LABELS`).
Edit::Batch { label, .. } => Label::with("{batch}", label.as_str()),
}
}
}
/// What the Edit menu calls a new comment ("Undo Add highlight"). A whole wording for each kind,
/// so a language can give the noun the article and the gender its own grammar asks for.
fn add_annotation(s: &Shape) -> &'static str {
match s {
Shape::Note { .. } => "Add sticky note",
Shape::TextMarkup { kind: Markup::Highlight, .. } => "Add highlight",
Shape::TextMarkup { kind: Markup::Underline, .. } => "Add underline",
Shape::TextMarkup { kind: Markup::StrikeOut, .. } => "Add strikethrough",
Shape::TextMarkup { kind: Markup::Squiggly, .. } => "Add squiggly underline",
Shape::Rectangle { .. } => "Add rectangle",
Shape::Oval { .. } => "Add oval",
Shape::Line { start: LineEnding::None, end: LineEnding::OpenArrow, .. } => "Add arrow",
Shape::Line { .. } => "Add line",
Shape::FreehandHighlight { .. } => "Add freehand highlight",
Shape::Ink { .. } => "Add drawing",
Shape::TextBox { .. } => "Add text box",
Shape::Typewriter { .. } => "Add text",
Shape::Mark { mark: FillMark::Check, .. } => "Add checkmark",
Shape::Mark { mark: FillMark::Cross, .. } => "Add cross",
Shape::Mark { mark: FillMark::Dot, .. } => "Add dot",
Shape::Mark { mark: FillMark::Line, .. } => "Add line",
Shape::Signature { .. } | Shape::TypedSignature { .. } => "Add signature",
Shape::Redact { .. } => "Add redaction mark",
Shape::Stamp { .. } | Shape::CustomStamp { .. } => "Add stamp",
Shape::Polygon { cloud: true, .. } => "Add cloud",
Shape::Polygon { .. } => "Add polygon",
Shape::PolyLine { .. } => "Add connected lines",
Shape::Callout { .. } => "Add callout",
Shape::Caret { .. } => "Add inserted text",
Shape::Attachment { .. } => "Add file attachment",
}
}
/// The singular or the plural wording, by count. Both are written out: a language forms its plural
/// its own way, and `one` and `many` may differ in more than an "s".
fn plural(one: &'static str, many: &'static str, n: usize) -> Label {
Label::of(if n == 1 { one } else { many })
}