Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

Merge remote-tracking branch 'upstream/main' into fix/delete-one-radio-button

Claudef595a9677b80
diff --cc crates/engine/src/edit.rs
index 000000000,c31984ca1..64e052415
mode 000000,100644..100644
--- a/crates/engine/src/edit.rs
+++ b/crates/engine/src/edit.rs
@@@ -1,0 -1,553 +1,559 @@@
+ //! The edits a document takes: what each is called, whether its permissions allow it, and running it.
+
+ use std::sync::Arc;
+
+ use crate::{
+ AddedContent, AddedText, Background, BoxSpec, EditError, FieldProps, FieldValue, FillMark, HeaderFooter, Hidden, ImageEdit, InitialView, Label,
+ LineEnding, LinkAction, LinkStyle, MarkFile, MarkKind, Markup, NewAnnotation, NewField, NoteIcon, ObjectTarget, PageBox, Protection, ReviewState,
+ Rgb, Shape, Standard, Style, TabOrder, TransitionSpec, Watermark, a11y, copy_image, decode_data_file, embed_image, field_table, fit_picture,
+ image_content_type, is_xfa_data_file, js, mark_source, measure, open_source, strip_xfa, unrestricted, xfa, xfa_after_data_change,
+ };
+
+ mod labels;
+ mod run;
+
+ pub use labels::{BATCH_LABELS, EDIT_LABELS};
+ pub(crate) use run::{EditCtx, check_permission, run_edit};
+
+ /// Edits that can be applied to a document. Page indices are 0-based.
+ #[derive(Clone, Debug, PartialEq)]
+ pub enum Edit {
+ RotatePages {
+ pages: Vec<usize>,
+ degrees: i64,
+ },
+ DeletePages {
+ pages: Vec<usize>,
+ },
+ MovePages {
+ pages: Vec<usize>,
+ to: usize,
+ },
+ /// `pages` reversed among the positions they occupy.
+ ReversePages {
+ pages: Vec<usize>,
+ },
+ InsertBlankPage {
+ at: usize,
+ width: f64,
+ height: f64,
+ },
+ /// Copies of `pages` inserted at `at` (an index in the page order as it is now), or after
+ /// the last of them when `at` is `None`.
+ DuplicatePages {
+ pages: Vec<usize>,
+ at: Option<usize>,
+ },
+ /// Replace Pages: the content of `pages` is replaced by `src_pages` of another PDF; the
+ /// pages' links, comments and bookmarks stay.
+ ReplacePages {
+ pages: Vec<usize>,
+ name: String,
+ bytes: Arc<Vec<u8>>,
+ src_pages: Vec<usize>,
+ },
+ /// Set Page Boxes / Crop: set (or reset) one box on `pages`.
+ SetPageBox {
+ pages: Vec<usize>,
+ which: PageBox,
+ spec: BoxSpec,
+ },
+ /// Set or remove the page transition and display time of pages (ISO 32000-2 §12.4.4),
+ /// Organize ▸ Page Transitions.
+ SetTransition {
+ pages: Vec<usize>,
+ spec: TransitionSpec,
+ },
+ SetInfo {
+ key: String,
+ value: String,
+ },
+ /// Insert pages from another PDF (all pages when `pages` is `None`) at position `at`.
+ InsertPagesFrom {
+ name: String,
+ bytes: Arc<Vec<u8>>,
+ pages: Option<Vec<usize>>,
+ at: usize,
+ /// How a form field whose name the document already uses is kept separate.
+ field_conflicts: pdfcraft_organize::FieldConflicts,
+ },
+ /// Add a bookmark to `page` as child `index` of the bookmark at `parent` (`[]` = top level).
+ /// It goes to the user-space point (`left`, `top`) of the page at the reader's zoom, and
+ /// either may be `None` to keep the reader's position that way (both `None` is the page top).
+ /// A coordinate that is not finite fails the edit.
+ AddBookmark {
+ parent: Vec<usize>,
+ index: usize,
+ title: String,
+ page: usize,
+ left: Option<f64>,
+ top: Option<f64>,
+ },
+ RenameBookmark {
+ path: Vec<usize>,
+ title: String,
+ },
+ /// Delete a bookmark and the bookmarks under it.
+ DeleteBookmark {
+ path: Vec<usize>,
+ },
+ /// Move a bookmark to child `index` of `to_parent` (indices after removing it).
+ MoveBookmark {
+ from: Vec<usize>,
+ to_parent: Vec<usize>,
+ index: usize,
+ },
+ /// Point a bookmark at another page.
+ SetBookmarkPage {
+ path: Vec<usize>,
+ page: usize,
+ },
+ /// Colour a bookmark's title (`/C`); `None` or black is the default black.
+ SetBookmarkColor {
+ path: Vec<usize>,
+ color: Option<[f64; 3]>,
+ },
+ /// Make a bookmark's title bold or italic or not (`/F`); `None` keeps that one.
+ SetBookmarkStyle {
+ path: Vec<usize>,
+ bold: Option<bool>,
+ italic: Option<bool>,
+ },
+ /// Bookmarks for the tagged headings (H, H1–H6), nested by level under a new first
+ /// "Untitled" bookmark (New Bookmarks from Structure).
+ BookmarksFromStructure,
+ /// Label pages `from..=to` (0-based) as Acrobat's "Number pages" does; later pages keep their labels.
+ NumberPages {
+ from: usize,
+ to: usize,
+ style: pdfcraft_organize::LabelStyle,
+ prefix: String,
+ first: u32,
+ },
+ /// Add a calibrated distance, perimeter or area annotation.
+ AddMeasurement(measure::NewMeasurement),
+ /// Store a drawing scale for a rectangular viewport (PDF user space).
+ SetMeasurementScale {
+ page: usize,
+ bbox: [f64; 4],
+ name: String,
+ scale: measure::Scale,
+ },
+ /// Add a comment (sticky note, highlight, shape, drawing, text box…).
+ AddAnnotation(NewAnnotation),
+ /// A custom stamp from a picture file (a PDF page or an image) on `page`. A zero-size
+ /// `rect` is a point: the stamp is centred there at its natural size (at most 200 pt).
+ /// Any other `rect` is a box: the picture is scaled to fit inside it, keeping its shape,
+ /// and centred in it (#4077).
+ AddCustomStamp {
+ page: usize,
+ rect: [f64; 4],
+ name: String,
+ file: MarkFile,
+ author: String,
+ },
+ /// Delete the comment at `index` in the page's `/Annots`, with its pop-up and replies.
+ DeleteAnnotation {
+ page: usize,
+ index: usize,
+ },
+ SetAnnotationContents {
+ page: usize,
+ index: usize,
+ text: String,
+ },
+ ReplyToAnnotation {
+ page: usize,
+ index: usize,
+ text: String,
+ author: String,
+ },
+ /// Acrobat's "Set status" (a state reply by `author`).
+ SetAnnotationStatus {
+ page: usize,
+ index: usize,
+ state: ReviewState,
+ author: String,
+ },
+ /// The Eraser: rub out the parts of drawing `(page, index)` near `path` (user space).
+ EraseInk {
+ page: usize,
+ index: usize,
+ path: Vec<[f64; 2]>,
+ radius: f64,
+ },
+ /// Replace Text: strike out `quads` and add a grouped caret holding `text`.
+ ReplaceText {
+ page: usize,
+ quads: Vec<[f64; 8]>,
+ text: String,
+ author: String,
+ strike: Style,
+ caret: Style,
+ },
+ /// Acrobat's "Mark with checkmark" (a hidden `/StateModel /Marked` reply by `author`).
+ MarkAnnotation {
+ page: usize,
+ index: usize,
+ marked: bool,
+ author: String,
+ },
+ /// Properties ▸ Locked.
+ LockAnnotation {
+ page: usize,
+ index: usize,
+ locked: bool,
+ },
+ MoveAnnotation {
+ page: usize,
+ index: usize,
+ dx: f64,
+ dy: f64,
+ },
+ /// Reshape a line, connected lines, a polygon or a cloud: its points in user space (a line's
+ /// two ends, the others' corners).
+ ReshapeAnnotation {
+ page: usize,
+ index: usize,
+ points: Vec<[f64; 2]>,
+ },
+ /// Resize a rectangle, oval or text box.
+ ResizeAnnotation {
+ page: usize,
+ index: usize,
+ rect: [f64; 4],
+ },
+ StyleAnnotation {
+ page: usize,
+ index: usize,
+ color: Option<Rgb>,
+ opacity: Option<f64>,
+ width: Option<f64>,
+ /// Line or polyline: two endings. Callout: one. `None` leaves `/LE` unchanged.
+ endings: Option<Vec<pdfcraft_annot::LineEnding>>,
+ },
+ /// Fill a rectangle, oval or polygon comment, or remove its fill (`None`).
+ FillAnnotation {
+ page: usize,
+ index: usize,
+ fill: Option<Rgb>,
+ },
+ /// Change the font size (pt) of a text box, typewriter text or callout.
+ FontSizeAnnotation {
+ page: usize,
+ index: usize,
+ size: f64,
+ },
+ /// Comment properties ▸ General / note icon.
+ SetAnnotationInfo {
+ page: usize,
+ index: usize,
+ author: Option<String>,
+ subject: Option<String>,
+ icon: Option<NoteIcon>,
+ },
+ /// Fill in a form field.
+ SetFieldValue {
+ name: String,
+ value: FieldValue,
+ },
+ /// Clear form: the named fields (all when `None`) back to their defaults.
+ ResetForm {
+ names: Option<Vec<String>>,
+ },
+ /// Prepare a form: add a field on a page (`rect` in PDF user space); `name` defaults to
+ /// Acrobat's next free name ("Text1", "Check Box2", …).
+ AddField {
+ page: usize,
+ rect: [f64; 4],
+ kind: NewField,
+ name: Option<String>,
+ },
+ /// Field Properties ▸ General / Options.
+ SetFieldProps {
+ name: String,
+ props: Box<FieldProps>,
+ },
+ /// An image field (or any button): show this image file (PNG, JPEG, TIFF, GIF, BMP).
+ SetFieldImage {
+ name: String,
+ image: Arc<Vec<u8>>,
+ },
+ /// Duplicate a field onto other pages (same field, shared value).
+ DuplicateField {
+ name: String,
+ pages: Vec<usize>,
+ },
+ DeleteField {
+ name: String,
+ },
++ /// Delete one widget of a field (`widget`, 0-based in the field's widgets): one radio button
++ /// of a group, or one copy of a duplicated field. The last widget takes the field with it.
++ DeleteWidget {
++ name: String,
++ widget: usize,
++ },
+ /// Page properties ▸ Tab order, for pages (0-based).
+ SetTabOrder {
+ pages: Vec<usize>,
+ order: TabOrder,
+ },
+ /// Document Properties ▸ Initial View (and the language and binding).
+ SetInitialView(Box<InitialView>),
+ /// Edit ▸ Attach a file: a document-level attachment (`/Names /EmbeddedFiles`) under
+ /// `name`, made unique; `mime` is the embedded file's `/Subtype` when known.
+ AddAttachment {
+ name: String,
+ bytes: Vec<u8>,
+ description: Option<String>,
+ mime: Option<String>,
+ },
+ /// Remove the document-level attachment whose name-tree key is `key`.
+ DeleteAttachment {
+ key: String,
+ },
+ /// Build a tagged structure tree for an untagged, text-only document.
+ AutoTagText,
+ /// Add alternate text: set (or clear, with `None`) a figure's alternate text. `figure` is
+ /// the figure element's object number (from `Document::figures`).
+ SetAltText {
+ figure: u32,
+ alt: Option<String>,
+ },
+ /// Add `/Form` tags and object references for all widgets in an untagged AcroForm.
+ AutoTagFormFields,
+ /// Change one property on a reachable indirect structure tag.
+ SetTagProperty {
+ object: pdfcraft_cos::ObjRef,
+ property: a11y::TagProperty,
+ value: Option<String>,
+ },
+ /// Move a structure tag before or after a direct sibling in reading order.
+ MoveTag {
+ object: pdfcraft_cos::ObjRef,
+ anchor: pdfcraft_cos::ObjRef,
+ placement: a11y::TagPlacement,
+ },
+ /// Add alternate text ▸ Decorative figure: the figure's content becomes an artifact.
+ MarkDecorative {
+ figure: u32,
+ },
+ /// Tags panel ▸ Mark as artifact: retire a leaf tag and mark its content as an artifact.
+ MarkTagArtifact {
+ object: pdfcraft_cos::ObjRef,
+ },
+ /// Document JavaScripts: add, replace (`script`) or remove (`None`) the document-level
+ /// script `name`.
+ SetDocumentScript {
+ name: String,
+ script: Option<String>,
+ },
+ /// Field Properties ▸ a custom script: set or remove field `name`'s JavaScript for `event`
+ /// (keystroke, format, validate, calculate or mouse_up).
+ SetFieldScript {
+ name: String,
+ event: String,
+ script: Option<String>,
+ },
+ /// Standards ▸ Save as PDF/A: fix what can be fixed for `level` (metadata, output intent,
+ /// forbidden actions, annotation flags, …).
+ ConvertPdfA {
+ level: pdfcraft_preflight::Level,
+ },
+ /// Remove what identifies the document as meeting `standard` (PDF/A or PDF/X).
+ RemoveStandardId {
+ standard: Standard,
+ },
+ /// What a script (button or console) changed in form fields: values, read-only, required
+ /// and visibility.
+ ApplyScriptChanges {
+ changes: Vec<pdfcraft_forms::FieldChange>,
+ },
+ /// An XFA form's scripted event (a button's `click`, say) on the object at `som`: what the
+ /// script changes (values, rows, visibility) is applied and the form laid out again.
+ XfaEvent {
+ som: String,
+ activity: String,
+ },
+ /// Scan & OCR ▸ Recognize text: put recognised words on `page` as invisible text over the
+ /// image (from [`ocr::OcrJob::run`](crate::ocr::OcrJob::run)).
+ AddOcrText {
+ page: usize,
+ words: Vec<pdfcraft_ocr::PlacedWord>,
+ },
+ /// Edit a PDF ▸ Edit text: replace the text of line `line` (from `Document::text_lines`) on
+ /// `page`, in its own font when it can show it, else in Helvetica.
+ EditTextLine {
+ page: usize,
+ line: usize,
+ text: String,
+ },
+ /// Edit a PDF ▸ an existing image on `page` (index from `Document::page_images`).
+ EditPageImage {
+ page: usize,
+ index: usize,
+ change: ImageEdit,
+ },
+ /// Move mixed existing and added objects together. References resolve before any change;
+ /// offset is a user-space vector. No retyping, reflow or font substitution is involved.
+ MoveObjects {
+ page: usize,
+ objects: Vec<ObjectTarget>,
+ offset: [f64; 2],
+ },
+ /// Edit text in a paragraph box: replace paragraph `block` (from `Document::text_blocks`),
+ /// rewrapped to the box's width.
+ EditTextBlock {
+ page: usize,
+ block: usize,
+ text: String,
+ /// Formatting changes (font, size, colour, alignment); default keeps the paragraph's.
+ style: pdfcraft_edit::BlockStyle,
+ },
+ /// An explicit open-licensed full font program, completing subsets or selected by a user.
+ RegisterTextFont {
+ page: usize,
+ bytes: Arc<Vec<u8>>,
+ },
+ /// Order tabs manually: move a field one place earlier or later on its page.
+ MoveInTabOrder {
+ name: String,
+ earlier: bool,
+ },
+ /// Set the calculation order: these calculated fields first, in this order, then the others
+ /// in their current order (see [`Document::calculation_order`](crate::Document::calculation_order)). The form recalculates.
+ SetCalculationOrder {
+ names: Vec<String>,
+ },
+ /// Add a header and footer (with `replace`, existing ones on those pages go first).
+ AddHeaderFooter {
+ pages: Vec<usize>,
+ settings: HeaderFooter,
+ replace: bool,
+ },
+ /// `file`: a picture from a file (an image, or a page of a PDF) instead of text.
+ AddWatermark {
+ pages: Vec<usize>,
+ settings: Watermark,
+ replace: bool,
+ file: Option<MarkFile>,
+ },
+ /// `file`: a picture from a file instead of a colour.
+ AddBackground {
+ pages: Vec<usize>,
+ settings: Background,
+ replace: bool,
+ file: Option<MarkFile>,
+ },
+ /// Remove every mark of a kind from every page.
+ RemoveMarks {
+ kind: MarkKind,
+ },
+ /// Edit a PDF ▸ Add content ▸ Text (`text.rect` in display space).
+ AddText {
+ page: usize,
+ text: AddedText,
+ },
+ /// Edit a PDF ▸ Add content ▸ Image: an image file placed at `rect` (display space), or at
+ /// its natural size centred on the page (shrunk to fit).
+ AddImage {
+ page: usize,
+ rect: Option<[f64; 4]>,
+ name: String,
+ bytes: Arc<Vec<u8>>,
+ },
+ /// Move, resize, retype or reformat an added item (`index` among the page's added items).
+ UpdateContent {
+ page: usize,
+ index: usize,
+ content: AddedContent,
+ },
+ DeleteContent {
+ page: usize,
+ index: usize,
+ },
+ /// Replace an added image with another file (keeping its box and transforms).
+ ReplaceImage {
+ page: usize,
+ index: usize,
+ name: String,
+ bytes: Arc<Vec<u8>>,
+ },
+ /// Edit ▸ Paste: an added item copied in this document or another, as it was: text with its
+ /// style, an image in its box (display space) with its turns, flips and crop. An image's
+ /// picture is `file` (from [`Document::added_image_file`](crate::Document::added_image_file)): the copied image object is reused
+ /// while it is still that picture in this document, else one an added image here already draws
+ /// it from, else the file is embedded.
+ PasteContent {
+ page: usize,
+ content: AddedContent,
+ file: Option<(String, Arc<Vec<u8>>)>,
+ },
+ /// Apply redaction marks (all, or those on `pages`): remove what they cover for good.
+ ApplyRedactions {
+ pages: Option<Vec<usize>>,
+ },
+ /// Remove redaction marks without applying them.
+ ClearRedactions,
+ /// Edit a PDF ▸ Link: a new link over `rect` (user space).
+ AddLink {
+ page: usize,
+ rect: [f64; 4],
+ action: LinkAction,
+ style: LinkStyle,
+ },
+ /// Link Properties (`index` in the page's `/Annots`).
+ SetLink {
+ page: usize,
+ index: usize,
+ rect: Option<[f64; 4]>,
+ action: Option<LinkAction>,
+ style: Option<LinkStyle>,
+ },
+ DeleteLink {
+ page: usize,
+ index: usize,
+ },
+ /// Remove all links (on `pages`, or everywhere).
+ RemoveLinks {
+ pages: Option<Vec<usize>>,
+ },
+ /// Create links from URLs in the text: (page, line rects in user space, URI).
+ AddLinks {
+ links: Vec<(usize, Vec<[f64; 4]>, String)>,
+ style: LinkStyle,
+ },
+ /// Import comments and/or form data (XFDF, FDF, XML, CSV, tab-delimited text).
+ ImportData {
+ name: String,
+ bytes: Arc<Vec<u8>>,
+ },
+ /// Remove Hidden Information: the chosen categories.
+ RemoveHidden {
+ which: Vec<Hidden>,
+ },
+ /// Sanitize Document: every category, then a full rewrite on save.
+ Sanitize,
+ /// An XFA form made an ordinary (static) PDF form: the XFA packets, `/NeedsRendering` and
+ /// PdfCraft's private keys go, the pages as laid out and the fields with their values
+ /// stay, so every viewer shows the same form and none lays it out again. Its scripts no
+ /// longer run.
+ XfaToStatic,
+ /// Flatten comments and/or form fields on every page into page content.
+ Flatten {
+ comments: bool,
+ fields: bool,
+ },
+ /// Bake Fill & Sign text, marks and signatures into the page. Other comments and fields stay.
+ /// A no-op (no undo step) when the document has none.
+ FlattenFillSign,
+ /// Protect with passwords and permissions (written by the next save, which is a full rewrite).
+ Protect(Protection),
+ /// Remove password security (needs the owner password).
+ RemoveProtection,
+ /// Several edits applied as one undoable step (all or nothing).
+ Batch {
+ label: String,
+ edits: Vec<Edit>,
+ },
+ }
diff --cc crates/engine/src/edit/labels.rs
index 000000000,5e25ae465..e0ab8f92f
mode 000000,100644..100644
--- a/crates/engine/src/edit/labels.rs
+++ b/crates/engine/src/edit/labels.rs
@@@ -1,0 -1,336 +1,336 @@@
+ use super::*;
+
+ /// 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",
+ "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}",
+ "Add bookmark",
+ "Rename bookmark",
+ "Delete bookmark",
+ "Move bookmark",
+ "Set bookmark destination",
+ "Colour",
+ "Style",
+ "New bookmarks from structure",
+ "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",
+ "Delete comment",
+ "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",
+ "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",
+ "Run JavaScript",
+ "Run form script",
+ "Save as {level}",
+ "Remove {standard} identification",
+ "Edit script of {name}",
+ "Delete document JavaScript",
+ "Edit document JavaScript",
+ "Edit text",
+ "Load document font",
+ "Move object",
+ "Move objects",
+ "Move image",
+ "Rotate image",
+ "Flip image",
+ "Replace image",
+ "Delete image",
+ "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"];
+
+ 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::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::BookmarksFromStructure => Label::of("New bookmarks from structure"),
+ 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::DeleteAnnotation { .. } => Label::of("Delete comment"),
+ 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::ResizeAnnotation { .. } => Label::of("Resize comment"),
+ Edit::StyleAnnotation { .. } | Edit::FillAnnotation { .. } | Edit::FontSizeAnnotation { .. } | Edit::SetAnnotationInfo { .. } => {
+ Label::of("Change comment properties")
+ }
+ Edit::SetFieldValue { name, .. } => Label::with("Fill in {name}", name.as_str()),
+ Edit::SetFieldImage { 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 { .. } => Label::of("Delete field"),
++ 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::AddAttachment { name, .. } => Label::with("Attach {name}", name.as_str()),
+ Edit::DeleteAttachment { key } => Label::with("Delete attachment {key}", key.as_str()),
+ 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::AddOcrText { .. } => Label::of("Recognize text"),
+ 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::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::Rotate(_) | ImageEdit::RotateBy(_) => "Rotate image",
+ ImageEdit::Crop(_) => "Crop image",
+ ImageEdit::Flip { .. } => "Flip image",
+ ImageEdit::Replace { .. } => "Replace image",
+ ImageEdit::Delete => "Delete image",
+ }),
+ 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::AddText { .. } => Label::of("Add text"),
+ Edit::AddImage { .. } => Label::of("Add image"),
+ Edit::UpdateContent { .. } => Label::of("Edit content"),
+ Edit::DeleteContent { .. } => Label::of("Delete content"),
+ Edit::ReplaceImage { .. } => Label::of("Replace image"),
+ Edit::PasteContent { .. } => 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::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 })
+ }
diff --cc crates/engine/src/edit/run.rs
index 000000000,7901a3b7d..98eea3d40
mode 000000,100644..100644
--- a/crates/engine/src/edit/run.rs
+++ b/crates/engine/src/edit/run.rs
@@@ -1,0 -1,696 +1,698 @@@
+ use super::*;
+
+ /// Whether the opening password allows an edit (§7.6.4.2, Table 22).
+ pub(crate) fn check_permission(edit: &Edit, p: &pdfcraft_cos::Permissions) -> Result<(), EditError> {
+ match edit {
+ Edit::RotatePages { .. }
+ | Edit::DeletePages { .. }
+ | Edit::MovePages { .. }
+ | Edit::ReversePages { .. }
+ | Edit::InsertBlankPage { .. }
+ | Edit::DuplicatePages { .. }
+ | Edit::ReplacePages { .. }
+ | Edit::SetPageBox { .. }
+ | Edit::SetTransition { .. }
+ | Edit::InsertPagesFrom { .. }
+ // "Assemble the document: insert, rotate or delete pages and create bookmarks" (Table 22).
+ | Edit::AddBookmark { .. }
+ | Edit::RenameBookmark { .. }
+ | Edit::DeleteBookmark { .. }
+ | Edit::MoveBookmark { .. }
+ | Edit::SetBookmarkPage { .. }
+ | Edit::SetBookmarkColor { .. }
+ | Edit::SetBookmarkStyle { .. }
+ | Edit::BookmarksFromStructure
+ | Edit::NumberPages { .. } => {
+ if p.assemble() {
+ Ok(())
+ } else {
+ Err(EditError::NotPermitted("page changes"))
+ }
+ }
+ Edit::AddMeasurement(_)
+ | Edit::AddAnnotation(_)
+ | Edit::AddCustomStamp { .. }
+ | Edit::DeleteAnnotation { .. }
+ | Edit::SetAnnotationContents { .. }
+ | Edit::ReplyToAnnotation { .. }
+ | Edit::SetAnnotationStatus { .. }
+ | Edit::MarkAnnotation { .. }
+ | Edit::ReplaceText { .. }
+ | Edit::EraseInk { .. }
+ | Edit::LockAnnotation { .. }
+ | Edit::MoveAnnotation { .. }
+ | Edit::ReshapeAnnotation { .. }
+ | Edit::ResizeAnnotation { .. }
+ | Edit::StyleAnnotation { .. }
+ | Edit::FillAnnotation { .. }
+ | Edit::FontSizeAnnotation { .. }
+ | Edit::SetAnnotationInfo { .. }
+ | Edit::SetMeasurementScale { .. } => {
+ if p.annotate() {
+ Ok(())
+ } else {
+ Err(EditError::NotPermitted("comments"))
+ }
+ }
+ Edit::SetFieldValue { .. } | Edit::ResetForm { .. } | Edit::SetFieldImage { .. } | Edit::ApplyScriptChanges { .. } | Edit::XfaEvent { .. } => {
+ if p.fill_forms() {
+ Ok(())
+ } else {
+ Err(EditError::NotPermitted("filling in form fields"))
+ }
+ }
+ Edit::Protect(_) | Edit::RemoveProtection => {
+ if unrestricted(p) {
+ Ok(())
+ } else {
+ Err(EditError::NotPermitted("changing security"))
+ }
+ }
+ // Converting to PDF/A takes the encryption off (PDF/A forbids it), so on an encrypted
+ // document it is a change of security (#3921).
+ Edit::ConvertPdfA { .. } => {
+ if unrestricted(p) {
+ Ok(())
+ } else {
+ Err(EditError::NotPermitted("removing the encryption, which PDF/A forbids"))
+ }
+ }
+ Edit::SetInfo { .. }
+ | Edit::AddHeaderFooter { .. }
+ | Edit::AddWatermark { .. }
+ | Edit::AddBackground { .. }
+ | Edit::RemoveMarks { .. }
+ | Edit::AddField { .. }
+ | Edit::ApplyRedactions { .. }
+ | Edit::AddText { .. }
+ | Edit::AddImage { .. }
+ | Edit::UpdateContent { .. }
+ | Edit::MoveObjects { .. }
+ | Edit::DeleteContent { .. }
+ | Edit::ReplaceImage { .. }
+ | Edit::PasteContent { .. }
+ | Edit::ClearRedactions
+ | Edit::RemoveHidden { .. }
+ | Edit::ImportData { .. }
+ | Edit::AddLink { .. }
+ | Edit::SetLink { .. }
+ | Edit::DeleteLink { .. }
+ | Edit::RemoveLinks { .. }
+ | Edit::AddLinks { .. }
+ | Edit::Sanitize
+ | Edit::XfaToStatic
+ | Edit::SetFieldProps { .. }
+ | Edit::DeleteField { .. }
++ | Edit::DeleteWidget { .. }
+ | Edit::DuplicateField { .. }
+ | Edit::SetTabOrder { .. }
+ | Edit::MoveInTabOrder { .. }
+ | Edit::SetCalculationOrder { .. }
+ | Edit::SetInitialView(_)
+ | Edit::AddAttachment { .. }
+ | Edit::DeleteAttachment { .. }
+ | Edit::AutoTagText
+ | Edit::SetAltText { .. }
+ | Edit::AutoTagFormFields
+ | Edit::SetTagProperty { .. }
+ | Edit::MoveTag { .. }
+ | Edit::MarkDecorative { .. }
+ | Edit::MarkTagArtifact { .. }
+ | Edit::AddOcrText { .. }
+ | Edit::SetDocumentScript { .. }
+ | Edit::SetFieldScript { .. }
+ | Edit::RemoveStandardId { .. }
+ | Edit::EditTextLine { .. }
+ | Edit::EditTextBlock { .. }
+ | Edit::RegisterTextFont { .. }
+ | Edit::EditPageImage { .. }
+ | Edit::Flatten { .. }
+ | Edit::FlattenFillSign => {
+ if p.modify() {
+ Ok(())
+ } else {
+ Err(EditError::NotPermitted("changes to the document"))
+ }
+ }
+ Edit::Batch { edits, .. } => edits.iter().try_for_each(|e| check_permission(e, p)),
+ }
+ }
+
+ /// Dates and unique ids stamped onto what an edit creates.
+ pub(crate) struct EditCtx {
+ /// Field scripts run (`None`: JavaScript is off) and what they produced.
+ pub(crate) js: Option<js::JsRunner>,
+ /// A laid-out XFA form's template (`None`: not an XFA form, or JavaScript is off) and what
+ /// its scripts produced.
+ pub(crate) xfa: Option<Arc<pdfcraft_xfa::model::Template>>,
+ pub(crate) xfa_out: js::JsOutput,
+ /// The datasets stream this edit wrote (later writes in the edit replace it in place).
+ pub(crate) xfa_datasets: Option<pdfcraft_cos::ObjRef>,
+ /// A form script ran too long and was abandoned: the document's scripts go off.
+ pub(crate) xfa_ran_away: bool,
+ /// What the XFA scripts' time limits are multiplied by ([`Session::with_xfa_time_scale`]).
+ pub(crate) xfa_time_scale: u32,
+ /// The edit took the XFA out of the form: what went with it, for the document's warnings.
+ pub(crate) xfa_removed: Vec<String>,
+ /// Pages in the document, for `xfa.layout.pageCount()`.
+ pub(crate) pages: usize,
+ pub(crate) date: Option<String>,
+ /// Today in local time, for date tokens.
+ pub(crate) today: (i64, u32, u32),
+ pub(crate) seed: u64,
+ pub(crate) count: u64,
+ /// Fields the edit renamed to keep imported names separate (old → new), for the repair
+ /// log and the undo label.
+ pub(crate) renamed_fields: Vec<(String, String)>,
+ /// The overlay streams the edit's applied redactions added, which alone the renderer's check
+ /// leaves out.
+ pub(crate) redaction_overlays: Vec<pdfcraft_cos::ObjRef>,
+ }
+
+ impl EditCtx {
+ pub(crate) fn new(now: Option<i64>, salt: u64) -> Self {
+ let mut seed = 0x9E37_79B9_7F4A_7C15u64 ^ salt;
+ if let Some(t) = now {
+ seed ^= (t as u64).rotate_left(17);
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ if now.is_some() {
+ // Real clock: mix in sub-second time so ids from two sessions don't collide.
+ seed ^= std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.subsec_nanos() as u64).unwrap_or(0) << 32;
+ }
+ Self {
+ js: None,
+ xfa: None,
+ xfa_out: Default::default(),
+ xfa_datasets: None,
+ xfa_ran_away: false,
+ xfa_time_scale: 1,
+ xfa_removed: Vec::new(),
+ pages: 0,
+ date: now.map(pdfcraft_cos::pdf_date),
+ today: (1970, 1, 1),
+ seed,
+ count: 0,
+ renamed_fields: Vec::new(),
+ redaction_overlays: Vec::new(),
+ }
+ }
+
+ /// 32 bytes of entropy for new encryption keys and salts. `RandomState` is seeded by the
+ /// operating system, so no extra dependency is needed.
+ fn entropy(&mut self) -> [u8; 32] {
+ use std::hash::{BuildHasher, Hasher};
+ let mut out = [0u8; 32];
+ for (i, chunk) in out.chunks_mut(8).enumerate() {
+ let mut h = std::collections::hash_map::RandomState::new().build_hasher();
+ h.write_u64(self.seed ^ i as u64);
+ h.write_u64(self.count);
+ self.count += 1;
+ chunk.copy_from_slice(&h.finish().to_le_bytes());
+ }
+ out
+ }
+
+ /// A fresh `/NM`: a random-looking UUID (version 4 layout) from a splitmix64 stream.
+ fn meta(&mut self) -> pdfcraft_annot::Meta {
+ let mut next = || {
+ self.count += 1;
+ let mut z = self.seed.wrapping_add(self.count.wrapping_mul(0x9E37_79B9_7F4A_7C15));
+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
+ z ^ (z >> 31)
+ };
+ let (a, b) = (next(), next());
+ let id = format!(
+ "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",
+ a >> 32,
+ (a >> 16) & 0xffff,
+ a & 0xfff,
+ 0x8000 | (b >> 48) & 0x3fff,
+ b & 0xffff_ffff_ffff
+ );
+ pdfcraft_annot::Meta { date: self.date.clone(), id }
+ }
+ }
+
+ /// Perform an edit on a working copy (the caller discards it on error).
+ pub(crate) fn run_edit(doc: &mut pdfcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Result<(), EditError> {
+ match edit {
+ Edit::RotatePages { pages, degrees } => pdfcraft_organize::rotate_pages(doc, pages, *degrees)?,
+ Edit::DeletePages { pages } => pdfcraft_organize::delete_pages(doc, pages)?,
+ Edit::MovePages { pages, to } => pdfcraft_organize::move_pages(doc, pages, *to)?,
+ Edit::ReversePages { pages } => pdfcraft_organize::reverse_pages(doc, pages)?,
+ Edit::InsertBlankPage { at, width, height } => {
+ pdfcraft_organize::insert_blank_page(doc, *at, *width, *height)?;
+ }
+ Edit::SetInfo { key, value } => pdfcraft_organize::set_info(doc, key, value)?,
+ Edit::DuplicatePages { pages, at } => pdfcraft_organize::duplicate_pages(doc, pages, *at)?,
+ Edit::ReplacePages { pages, name, bytes, src_pages } => {
+ let src = open_source(name, bytes)?;
+ pdfcraft_organize::replace_pages(doc, pages, &src, src_pages)?;
+ }
+ Edit::SetPageBox { pages, which, spec } => pdfcraft_organize::set_page_box(doc, pages, *which, *spec)?,
+ Edit::SetTransition { pages, spec } => pdfcraft_organize::set_transition(doc, pages, spec)?,
+ Edit::InsertPagesFrom { name, bytes, pages, at, field_conflicts } => {
+ let src = open_source(name, bytes)?;
+ let pages = match pages {
+ Some(p) => p.clone(),
+ None => (0..pdfcraft_organize::page_count(&src)?).collect(),
+ };
+ // The file's bookmarks come along under one named after it, as in Combine Files.
+ let title = std::path::Path::new(name).file_stem().map_or_else(|| name.clone(), |s| s.to_string_lossy().into_owned());
+ let outcome = pdfcraft_organize::insert_file_pages(doc, &src, &title, &pages, *at, *field_conflicts)?;
+ cx.renamed_fields = outcome.renamed_fields;
+ }
+ Edit::AddBookmark { parent, index, title, page, left, top } => {
+ pdfcraft_organize::add_bookmark_at(doc, parent, *index, title, *page, *left, *top)?;
+ }
+ Edit::RenameBookmark { path, title } => pdfcraft_organize::rename_bookmark(doc, path, title)?,
+ Edit::DeleteBookmark { path } => pdfcraft_organize::delete_bookmark(doc, path)?,
+ Edit::MoveBookmark { from, to_parent, index } => {
+ pdfcraft_organize::move_bookmark(doc, from, to_parent, *index)?;
+ }
+ Edit::SetBookmarkPage { path, page } => pdfcraft_organize::set_bookmark_page(doc, path, *page)?,
+ Edit::SetBookmarkColor { path, color } => pdfcraft_organize::set_bookmark_color(doc, path, *color)?,
+ Edit::SetBookmarkStyle { path, bold, italic } => pdfcraft_organize::set_bookmark_style(doc, path, *bold, *italic)?,
+ Edit::BookmarksFromStructure => {
+ let entries: Vec<_> = pdfcraft_a11y::headings(doc)
+ .into_iter()
+ .map(|h| pdfcraft_organize::OutlineEntry { level: h.level, title: h.title, page: h.page, element: h.obj })
+ .collect();
+ pdfcraft_organize::add_bookmark_tree(doc, "Untitled", &entries)?;
+ }
+ Edit::NumberPages { from, to, style, prefix, first } => pdfcraft_organize::number_pages(doc, *from, *to, *style, prefix, *first)?,
+ Edit::AddMeasurement(m) => {
+ measure::add(doc, m, &cx.meta())?;
+ }
+ Edit::SetMeasurementScale { page, bbox, name, scale } => measure::set_scale(doc, *page, *bbox, name, scale)?,
+ Edit::AddAnnotation(a) => {
+ pdfcraft_annot::add_annotation(doc, a, &cx.meta())?;
+ }
+ Edit::AddCustomStamp { page, rect, name, file, author } => {
+ let src = mark_source(doc, file)?;
+ let (sw, sh) = (src.size.0.max(1.0), src.size.1.max(1.0));
+ let natural = rect[2] == rect[0] && rect[3] == rect[1];
+ let rotation = pdfcraft_organize::page_rotation(doc, *page)?;
+ // The picture as displayed: a quarter turn swaps its sides in user space.
+ let (dw, dh) = if matches!(rotation, 90 | 270) { (sh, sw) } else { (sw, sh) };
+ let rect = if natural {
+ let k = (200.0 / sw.max(sh)).min(1.0);
+ let (w, h) = (dw * k, dh * k);
+ [rect[0] - w / 2.0, rect[1] - h / 2.0, rect[0] + w / 2.0, rect[1] + h / 2.0]
+ } else {
+ fit_picture(*rect, dw, dh)
+ };
+ let shape = Shape::CustomStamp { rect, name: name.clone(), picture: src.xobject, image: src.image, size: (sw, sh) };
+ let style = pdfcraft_annot::Style::default_for(&shape);
+ let new = NewAnnotation { page: *page, shape, style, contents: name.clone(), author: author.clone() };
+ let index = pdfcraft_annot::add_annotation(doc, &new, &cx.meta())?;
+ pdfcraft_annot::orient_image_stamp(doc, *page, index, rotation)?;
+ }
+ Edit::DeleteAnnotation { page, index } => pdfcraft_annot::delete_annotation(doc, *page, *index)?,
+ Edit::SetAnnotationContents { page, index, text } => pdfcraft_annot::set_contents(doc, *page, *index, text, &cx.meta())?,
+ Edit::ReplyToAnnotation { page, index, text, author } => {
+ pdfcraft_annot::add_reply(doc, *page, *index, text, author, &cx.meta())?;
+ }
+ Edit::SetAnnotationStatus { page, index, state, author } => {
+ pdfcraft_annot::set_review_state(doc, *page, *index, *state, author, &cx.meta())?;
+ }
+ Edit::EraseInk { page, index, path, radius } => {
+ pdfcraft_annot::erase_ink(doc, *page, *index, path, *radius, &cx.meta())?;
+ }
+ Edit::AddAttachment { name, bytes, description, mime } => {
+ pdfcraft_organize::add_attachment(doc, name, bytes, description.as_deref(), mime.as_deref(), cx.date.as_deref())?;
+ }
+ Edit::DeleteAttachment { key } => pdfcraft_organize::delete_attachment(doc, key)?,
+ Edit::ReplaceText { page, quads, text, author, strike, caret } => {
+ // One `/NM` each: the caret replies to the strikeout, and XFDF names that reply by
+ // the strikeout's `/NM` (#2666).
+ let (strike_meta, caret_meta) = (cx.meta(), cx.meta());
+ pdfcraft_annot::add_text_replacement(doc, *page, quads, text, author, strike, caret, &strike_meta, &caret_meta)?;
+ }
+ Edit::MarkAnnotation { page, index, marked, author } => {
+ pdfcraft_annot::set_marked(doc, *page, *index, *marked, author, &cx.meta())?;
+ }
+ Edit::LockAnnotation { page, index, locked } => pdfcraft_annot::set_locked(doc, *page, *index, *locked)?,
+ Edit::MoveAnnotation { page, index, dx, dy } => pdfcraft_annot::move_annotation(doc, *page, *index, *dx, *dy, &cx.meta())?,
+ Edit::ReshapeAnnotation { page, index, points } => pdfcraft_annot::set_points(doc, *page, *index, points, &cx.meta())?,
+ Edit::ResizeAnnotation { page, index, rect } => pdfcraft_annot::set_rect(doc, *page, *index, *rect, &cx.meta())?,
+ Edit::StyleAnnotation { page, index, color, opacity, width, endings } => {
+ pdfcraft_annot::set_style(doc, *page, *index, *color, *opacity, *width, endings.as_deref(), &cx.meta())?;
+ }
+ Edit::FillAnnotation { page, index, fill } => pdfcraft_annot::set_fill(doc, *page, *index, *fill, &cx.meta())?,
+ Edit::FontSizeAnnotation { page, index, size } => pdfcraft_annot::set_font_size(doc, *page, *index, *size, &cx.meta())?,
+ Edit::SetAnnotationInfo { page, index, author, subject, icon } => {
+ pdfcraft_annot::set_info(doc, *page, *index, author.as_deref(), subject.as_deref(), *icon, &cx.meta())?;
+ }
+ Edit::SetFieldValue { name, value } => {
+ let mut set = |doc: &mut pdfcraft_cos::Document, value: &FieldValue| match cx.js.as_mut() {
+ Some(js) => pdfcraft_forms::set_value_with(doc, name, value, js),
+ None => pdfcraft_forms::set_value(doc, name, value),
+ };
+ match set(doc, value) {
+ Ok(()) => {}
+ // A date the field's format doesn't read may be typed by another of an XFA date
+ // field's patterns: it is kept in the first. Only a format refusal is tried
+ // again: it comes before any of the field's scripts run, so they run once.
+ Err(refused @ pdfcraft_forms::FormError::Format(_)) => match xfa::typed_date(doc, cx.xfa.as_deref(), name, value) {
+ Some(typed) => set(doc, &typed)?,
+ None => return Err(refused.into()),
+ },
+ Err(refused) => return Err(refused.into()),
+ }
+ }
+ Edit::ApplyScriptChanges { changes } => match cx.js.as_mut() {
+ Some(js) => pdfcraft_forms::apply_script_changes(doc, changes, js)?,
+ None => pdfcraft_forms::apply_script_changes(doc, changes, &mut pdfcraft_forms::NoScripts)?,
+ },
+ Edit::XfaEvent { som, activity } => {
+ let tpl = cx.xfa.clone().ok_or_else(|| EditError::Invalid("this is not a laid-out XFA form, or JavaScript is off".into()))?;
+ let mut run =
+ xfa::XfaRun { page_count: cx.pages, out: &mut cx.xfa_out, datasets: cx.xfa_datasets, ran_away: false, time_scale: cx.xfa_time_scale };
+ let ran = xfa::on_event(doc, &tpl, som, activity, &mut run);
+ cx.xfa_datasets = run.datasets;
+ cx.xfa_ran_away |= run.ran_away;
+ ran.map_err(EditError::Invalid)?;
+ }
+ Edit::SetFieldImage { name, image } => {
+ let (img, _) = embed_image(doc, name, image)?;
+ let px = match &*doc.get(img) {
+ pdfcraft_cos::Object::Stream(s) => (s.dict.int(b"Width").unwrap_or(1) as u32, s.dict.int(b"Height").unwrap_or(1) as u32),
+ _ => (1, 1),
+ };
+ // An XFA image field keeps the picture in the data too (as Designer saves it), and a
+ // laid-out form shows it from there: so only pictures the layout can show, and only
+ // for image fields (a laid-out one carries its SOM path; a static form's field name
+ // is its path).
+ let is_xfa = pdfcraft_xfa::read_packets(doc).ok().flatten().is_some();
+ let image_field = is_xfa
+ && pdfcraft_forms::fields(doc).iter().any(|f| f.name == *name && f.button == Some(pdfcraft_forms::af::ButtonAction::ImportIcon));
+ if image_field {
+ let Some(content_type) = image_content_type(image) else {
+ return Err(EditError::Invalid(format!("{name}: an XFA form keeps a PNG, JPEG, GIF, BMP or TIFF picture; choose one of those")));
+ };
+ pdfcraft_forms::set_button_icon(doc, name, img, px)?;
+ let som = pdfcraft_xfa::fields_by_som(doc).into_iter().find(|(_, n)| n == name).map(|(s, _)| s).unwrap_or_else(|| name.clone());
+ let path = match cx.xfa.as_deref() {
+ Some(tpl) => pdfcraft_xfa::data_path(tpl, &som),
+ None => pdfcraft_xfa::som_to_path(&som),
+ };
+ let r =
+ pdfcraft_xfa::write_data_image(doc, &path, content_type, image, cx.xfa_datasets).map_err(|e| EditError::Write(e.to_string()))?;
+ if !r.written && r.warnings.is_empty() {
+ return Err(EditError::Write(format!("{name}: the picture could not be written into the form's data")));
+ }
+ cx.xfa_datasets = r.stream.or(cx.xfa_datasets);
+ cx.xfa_out.errors.extend(r.warnings);
+ xfa_after_data_change(doc, cx, false)?;
+ } else {
+ pdfcraft_forms::set_button_icon(doc, name, img, px)?;
+ }
+ }
+ Edit::ResetForm { names } => {
+ pdfcraft_forms::reset(doc, names.as_deref())?;
+ }
+ Edit::AddField { page, rect, kind, name } => {
+ pdfcraft_forms::add_field(doc, *page, *rect, kind, name.as_deref())?;
+ }
+ Edit::SetFieldProps { name, props } => {
+ pdfcraft_forms::set_props(doc, name, props)?;
+ }
+ Edit::DuplicateField { name, pages } => {
+ if pdfcraft_forms::duplicate_field(doc, name, pages)? == 0 {
+ return Err(EditError::Form(pdfcraft_forms::FormError::Invalid(format!("{name} is already on those pages"))));
+ }
+ }
+ Edit::DeleteField { name } => pdfcraft_forms::delete_field(doc, name)?,
++ Edit::DeleteWidget { name, widget } => pdfcraft_forms::delete_widget(doc, name, *widget)?,
+ Edit::SetTabOrder { pages, order } => pdfcraft_forms::set_tab_order(doc, pages, *order)?,
+ Edit::MoveInTabOrder { name, earlier } => pdfcraft_forms::move_in_tab_order(doc, name, *earlier)?,
+ // As after a script edit: the values the new order gives show at once.
+ Edit::SetCalculationOrder { names } => {
+ pdfcraft_forms::set_calculation_order(doc, names)?;
+ match cx.js.as_mut() {
+ Some(js) => pdfcraft_forms::recalculate_with(doc, js)?,
+ None => pdfcraft_forms::recalculate(doc)?,
+ };
+ }
+ Edit::SetInitialView(v) => pdfcraft_organize::set_initial_view(doc, v)?,
+ Edit::AutoTagText => {
+ a11y::autotag_text(doc).map_err(|e| EditError::Accessibility(e.to_string()))?;
+ }
+ Edit::SetAltText { figure, alt } => {
+ let r = pdfcraft_cos::ObjRef::new(*figure, doc.generation(*figure));
+ a11y::set_alt(doc, r, alt.as_deref()).map_err(|e| EditError::Accessibility(e.to_string()))?;
+ }
+ Edit::AutoTagFormFields => {
+ a11y::tag_form_fields(doc).map_err(EditError::Accessibility)?;
+ }
+ Edit::SetTagProperty { object, property, value } => {
+ a11y::set_tag_property(doc, *object, *property, value.as_deref()).map_err(|e| EditError::Accessibility(e.to_string()))?;
+ }
+ Edit::MoveTag { object, anchor, placement } => {
+ a11y::move_tag(doc, *object, *anchor, *placement).map_err(|e| EditError::Accessibility(e.to_string()))?;
+ }
+ Edit::EditTextLine { page, line, text } => {
+ pdfcraft_edit::replace_line(doc, *page, *line, text)?;
+ }
+ Edit::SetFieldScript { name, event, script } => {
+ pdfcraft_forms::set_field_script(doc, name, event, script.as_deref())?;
+ match cx.js.as_mut() {
+ Some(js) => pdfcraft_forms::recalculate_with(doc, js)?,
+ None => pdfcraft_forms::recalculate(doc)?,
+ };
+ }
+ Edit::ConvertPdfA { level } => {
+ pdfcraft_preflight::convert(doc, *level).map_err(|e| EditError::Invalid(e.to_string()))?;
+ }
+ Edit::RemoveStandardId { standard } => pdfcraft_organize::remove_standard_id(doc, *standard)?,
+ Edit::SetDocumentScript { name, script } => pdfcraft_forms::set_document_script(doc, name, script.as_deref())?,
+ Edit::AddOcrText { page, words } => {
+ pdfcraft_edit::stamp(doc, *page, "OCR", pdfcraft_ocr::text_layer(words))?;
+ }
+ Edit::EditPageImage { page, index, change } => {
+ let img = pdfcraft_edit::page_images(doc, *page)?
+ .into_iter()
+ .nth(*index)
+ .ok_or_else(|| EditError::Edit(pdfcraft_edit::EditError::Invalid(format!("page {} has no image {}", page + 1, index + 1))))?;
+ let c = match change {
+ ImageEdit::Move(to) => pdfcraft_edit::ImageChange::Transform(pdfcraft_edit::rect_to_rect(img.rect, *to)),
+ ImageEdit::Rotate(q) => {
+ pdfcraft_edit::ImageChange::Transform(pdfcraft_edit::turn_about_centre(img.visible_rect.unwrap_or(img.rect), *q, false, false))
+ }
+ ImageEdit::RotateBy(degrees) => {
+ let t = pdfcraft_edit::turn_by_degrees(img.visible_rect.unwrap_or(img.rect), *degrees)
+ .ok_or_else(|| EditError::Edit(pdfcraft_edit::EditError::Invalid("the rotation angle must be a finite number".into())))?;
+ pdfcraft_edit::ImageChange::Transform(t)
+ }
+ ImageEdit::Flip { horizontal } => pdfcraft_edit::ImageChange::Transform(pdfcraft_edit::turn_about_centre(
+ img.visible_rect.unwrap_or(img.rect),
+ 0,
+ *horizontal,
+ !*horizontal,
+ )),
+ ImageEdit::Replace { name, bytes } => {
+ if img.is_form {
+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid(
+ "grouped Form artwork cannot be replaced with a bitmap".into(),
+ )));
+ }
+ pdfcraft_edit::ImageChange::Replace(embed_image(doc, name, bytes)?.0)
+ }
+ ImageEdit::Crop(keep) => pdfcraft_edit::ImageChange::Crop(*keep),
+ ImageEdit::Delete => pdfcraft_edit::ImageChange::Delete,
+ };
+ pdfcraft_edit::change_image(doc, *page, *index, &c)?;
+ }
+ Edit::MoveObjects { page, objects, offset } => pdfcraft_edit::move_objects(doc, *page, objects, *offset)?,
+ Edit::EditTextBlock { page, block, text, style } => {
+ pdfcraft_edit::rewrite_block(doc, *page, *block, Some(text), style)?;
+ }
+ Edit::RegisterTextFont { page, bytes } => {
+ pdfcraft_edit::text::register_text_font(doc, *page, bytes)?;
+ }
+ Edit::MarkDecorative { figure } => {
+ let r = pdfcraft_cos::ObjRef::new(*figure, doc.generation(*figure));
+ a11y::mark_decorative(doc, r).map_err(|e| EditError::Accessibility(e.to_string()))?;
+ }
+ Edit::MarkTagArtifact { object } => {
+ a11y::mark_tag_artifact(doc, *object).map_err(|e| EditError::Accessibility(e.to_string()))?;
+ }
+ Edit::AddHeaderFooter { pages, settings, replace } => {
+ let date = cx.today;
+ pdfcraft_edit::add_header_footer(doc, pages, settings, *replace, &pdfcraft_edit::Context { date })?;
+ }
+ Edit::AddWatermark { pages, settings, replace, file } => {
+ let mut s = settings.clone();
+ if let Some(f) = file {
+ s.source = Some(mark_source(doc, f)?);
+ }
+ pdfcraft_edit::add_watermark(doc, pages, &s, *replace)?
+ }
+ Edit::AddBackground { pages, settings, replace, file } => {
+ let mut s = settings.clone();
+ if let Some(f) = file {
+ s.source = Some(mark_source(doc, f)?);
+ }
+ pdfcraft_edit::add_background(doc, pages, &s, *replace)?
+ }
+ Edit::RemoveMarks { kind } => {
+ let n = pdfcraft_model::pages(doc).len();
+ if pdfcraft_edit::remove_marks(doc, &(0..n).collect::<Vec<_>>(), *kind)? == 0 {
+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("there is nothing to remove".into())));
+ }
+ }
+ Edit::AddText { page, text } => {
+ pdfcraft_edit::add_content(doc, *page, &AddedContent::Text(text.clone()))?;
+ }
+ Edit::AddImage { page, rect, name, bytes } => {
+ let (image, natural) = embed_image(doc, name, bytes)?;
+ let rect = match rect {
+ Some(r) => *r,
+ None => {
+ let p = pdfcraft_model::pages(doc).swap_remove(*page);
+ let (pw, ph) = p.display_size(doc);
+ let k = ((pw * 0.8) / natural.0).min((ph * 0.8) / natural.1).min(1.0);
+ let (w, h) = (natural.0 * k, natural.1 * k);
+ [(pw - w) / 2.0, (ph - h) / 2.0, (pw + w) / 2.0, (ph + h) / 2.0]
+ }
+ };
+ pdfcraft_edit::add_content(doc, *page, &AddedContent::Image(pdfcraft_edit::AddedImage::new(rect, image)))?;
+ }
+ Edit::UpdateContent { page, index, content } => pdfcraft_edit::update_content(doc, *page, *index, content)?,
+ Edit::DeleteContent { page, index } => pdfcraft_edit::delete_content(doc, *page, *index)?,
+ Edit::ReplaceImage { page, index, name, bytes } => {
+ let item = pdfcraft_edit::list_added(doc).into_iter().filter(|a| a.page == *page).nth(*index);
+ let Some(AddedContent::Image(old)) = item.map(|a| a.content) else {
+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("that item is not an image".into())));
+ };
+ let (image, _) = embed_image(doc, name, bytes)?;
+ pdfcraft_edit::update_content(doc, *page, *index, &AddedContent::Image(pdfcraft_edit::AddedImage { image, ..old }))?;
+ }
+ Edit::PasteContent { page, content, file } => {
+ let content = match content {
+ AddedContent::Text(_) => content.clone(),
+ AddedContent::Image(img) => {
+ let Some((name, bytes)) = file else {
+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("a pasted image needs its picture".into())));
+ };
+ // The same picture in this document (copied here, pasted here before, or an
+ // identical file): drawn again from the one image object rather than stored twice.
+ let image = if copy_image::is_picture(doc, img.image, bytes) {
+ img.image
+ } else {
+ match copy_image::added_picture(doc, bytes) {
+ Some(image) => image,
+ None => embed_image(doc, name, bytes)?.0,
+ }
+ };
+ AddedContent::Image(pdfcraft_edit::AddedImage { image, ..img.clone() })
+ }
+ };
+ pdfcraft_edit::add_content(doc, *page, &content)?;
+ }
+ Edit::ApplyRedactions { pages } => {
+ cx.redaction_overlays = pdfcraft_redact::apply(doc, pages.as_deref())?.overlays;
+ }
+ Edit::ClearRedactions => {
+ pdfcraft_redact::clear_marks(doc, None)?;
+ }
+ Edit::AddLink { page, rect, action, style } => {
+ pdfcraft_annot::links::add(doc, *page, *rect, action, style)?;
+ }
+ Edit::SetLink { page, index, rect, action, style } => pdfcraft_annot::links::set(doc, *page, *index, *rect, action.as_ref(), style.as_ref())?,
+ Edit::DeleteLink { page, index } => pdfcraft_annot::links::delete(doc, *page, *index)?,
+ Edit::RemoveLinks { pages } => {
+ if pdfcraft_annot::links::remove_all(doc, pages.as_deref())? == 0 {
+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("there are no links to remove".into())));
+ }
+ }
+ Edit::AddLinks { links, style } => {
+ if pdfcraft_annot::links::add_many(doc, links, style)? == 0 {
+ return Err(EditError::Edit(pdfcraft_edit::EditError::Invalid("no web addresses were found".into())));
+ }
+ }
+ Edit::ImportData { bytes, .. } => {
+ // An XFA form takes XFA data files (XDP, datasets, or a data document) as its data;
+ // XFDF, FDF, Acrobat's XML and tables go the usual way.
+ let text = (pdfcraft_xfa::read_packets(doc).ok().flatten().is_some()).then(|| decode_data_file(bytes)).flatten();
+ match text {
+ Some(Ok(text)) if is_xfa_data_file(&text) => {
+ let expect_root = cx.xfa.as_ref().and_then(|t| t.root.common.name.clone());
+ let r = pdfcraft_xfa::import_data(doc, &text, expect_root.as_deref(), cx.xfa_datasets)
+ .map_err(|e| EditError::Write(e.to_string()))?;
+ cx.xfa_datasets = r.stream.or(cx.xfa_datasets);
+ cx.xfa_out.errors.extend(r.warnings);
+ cx.xfa_out.console.push(format!("Imported XFA data: {} node(s)", r.nodes));
+ xfa_after_data_change(doc, cx, true)?;
+ }
+ Some(Err(why)) => return Err(EditError::Invalid(why)),
+ _ => {
+ pdfcraft_xfdf::import(doc, bytes)?;
+ }
+ }
+ }
+ Edit::RemoveHidden { which } => {
+ pdfcraft_redact::sanitize::remove_hidden(doc, which)?;
+ }
+ Edit::Sanitize => {
+ pdfcraft_redact::sanitize::sanitize(doc)?;
+ }
+ Edit::Flatten { comments, fields } => {
+ // An XFA form's fields baked into the pages: the XFA goes too, or Adobe's viewers
+ // would lay the form out again from its template over the baked pages. A dynamic
+ // form that was never laid out keeps its XFA: without it only placeholders remain.
+ let shape = (*fields).then(|| pdfcraft_xfa::xfa_shape(doc)).flatten();
+ let n = pdfcraft_model::pages(doc).len();
+ pdfcraft_edit::flatten(doc, &(0..n).collect::<Vec<_>>(), *comments, *fields)?;
+ match shape {
+ Some(shape) if shape.strippable() => strip_xfa(doc, cx)?,
+ Some(_) => cx.xfa_removed.push("The XFA was kept: this dynamic form was not laid out, so its fields were not baked in".into()),
+ None => {}
+ }
+ }
+ Edit::XfaToStatic => {
+ let Some(shape) = pdfcraft_xfa::xfa_shape(doc) else {
+ return Err(EditError::Invalid("this document is not an XFA form".into()));
+ };
+ if !shape.strippable() {
+ return Err(EditError::Invalid("this dynamic XFA form was not laid out, so there is no static form to keep".into()));
+ }
+ strip_xfa(doc, cx)?;
+ }
+ Edit::FlattenFillSign => {
+ let n = pdfcraft_model::pages(doc).len();
+ pdfcraft_edit::flatten_fill_sign(doc, &(0..n).collect::<Vec<_>>())?;
+ }
+ Edit::Protect(p) => {
+ p.validate()?;
+ let seed = cx.entropy();
+ // Without a permissions password nothing is restricted, so the owner password is a
+ // random one nobody needs.
+ let random_owner: String = cx.entropy().iter().map(|b| format!("{b:02x}")).collect();
+ let params = pdfcraft_cos::NewEncryption {
+ algorithm: p.algorithm,
+ user_password: p.open_password.as_deref().unwrap_or(""),
+ owner_password: p.permissions_password.as_deref().unwrap_or(&random_owner),
+ permissions: p.permission_bits(),
+ encrypt_metadata: p.encrypt_metadata,
+ seed,
+ };
+ doc.set_encryption(&params).map_err(|e| EditError::Protection(e.to_string()))?;
+ }
+ Edit::RemoveProtection => {
+ if doc.output_handler().is_none() {
+ return Err(EditError::Protection("the document isn't protected".into()));
+ }
+ doc.remove_encryption();
+ }
+ Edit::Batch { edits, .. } => {
+ for e in edits {
+ run_edit(doc, e, cx)?;
+ }
+ }
+ }
+ Ok(())
+ }
diff --cc crates/forms/src/author.rs
index 8165f56af,ce89fad80..79bf4eac1
--- a/crates/forms/src/author.rs
+++ b/crates/forms/src/author.rs
@@@ -10,6 -10,17 +10,17 @@@ use pdfcraft_cos::{Dict, Document, ObjR
use crate::{Field, FieldKind, FormError, Widget, appearance, fields, flags, page_refs};
+ mod edit;
+ mod lifecycle;
+ mod look;
+ mod tree;
+
+ pub use edit::set_props;
-pub use lifecycle::{add_field, delete_field, delete_field_object, duplicate_field};
++pub use lifecycle::{add_field, delete_field, delete_field_object, delete_widget, duplicate_field};
+ pub(crate) use look::button_appearance;
+ pub use look::{BorderStyle, CheckStyle, FieldFont, Look, LookPatch, check_style, look, redraw_field, set_button_icon};
+ pub(crate) use tree::{ensure_form, form_fonts_as_objects};
+
/// The smallest width and height of a field's widget, in points: a smaller one is refused.
pub const MIN_FIELD_SIDE: f64 = 4.0;
diff --cc crates/forms/src/author/lifecycle.rs
index 000000000,745ab3b34..4fb045d7b
mode 000000,100644..100644
--- a/crates/forms/src/author/lifecycle.rs
+++ b/crates/forms/src/author/lifecycle.rs
@@@ -1,0 -1,326 +1,384 @@@
+ use super::look::redraw_field;
+ use super::tree::{add_to_page, attach, clash, detach, ensure_form, free_name, name_parts, top_names};
+ use super::*;
+
+ fn widget_dict(page: ObjRef, rect: [f64; 4]) -> Dict {
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("Annot"));
+ d.set(b"Subtype".to_vec(), Object::name("Widget"));
+ d.set(b"Rect".to_vec(), Object::Array(rect.iter().map(|v| Object::Real(*v)).collect()));
+ d.set(b"P".to_vec(), Object::Ref(page));
+ d.set(b"F".to_vec(), Object::Int(4));
+ let mut mk = Dict::new();
+ mk.set(b"BC".to_vec(), rgb([0.55, 0.55, 0.55]));
+ mk.set(b"BG".to_vec(), rgb([1.0, 1.0, 1.0]));
+ d.set(b"MK".to_vec(), Object::Dict(mk));
+ let mut bs = Dict::new();
+ bs.set(b"W".to_vec(), Object::Int(1));
+ bs.set(b"S".to_vec(), Object::name("S"));
+ d.set(b"BS".to_vec(), Object::Dict(bs));
+ d
+ }
+
+ /// Add a field on `page` (0-based) in `rect` (user space). Returns its full name.
+ pub fn add_field(doc: &mut Document, page: usize, rect: [f64; 4], kind: &NewField, name: Option<&str>) -> Result<String, FormError> {
+ let pages = page_refs(doc);
+ let page_ref = *pages.get(page).ok_or_else(|| FormError::Invalid(format!("page {} does not exist", page + 1)))?;
+ let rect = [rect[0].min(rect[2]), rect[1].min(rect[3]), rect[0].max(rect[2]), rect[1].max(rect[3])];
+ if !rect.iter().all(|v| v.is_finite()) || rect[2] - rect[0] < MIN_FIELD_SIDE || rect[3] - rect[1] < MIN_FIELD_SIDE {
+ return invalid("the field is too small");
+ }
+ let existing = fields(doc);
+ // A radio button names its group: a new group takes that name.
+ let name = match (name, kind) {
+ (None, NewField::Radio { group: Some(g), .. }) => Some(g.as_str()),
+ _ => name,
+ };
+ let name = match name.map(str::trim) {
+ Some(n) if !n.is_empty() => n.to_string(),
+ _ => free_name(&existing, &top_names(doc), kind.base_name()),
+ };
+ let parts = name_parts(&name)?;
+ let radio_group = match kind {
+ NewField::Radio { group, .. } => existing.iter().find(|f| f.kind == FieldKind::Radio && Some(&f.name) == group.as_ref()).cloned(),
+ _ => None,
+ };
+ if radio_group.is_none()
+ && let Some(why) = existing.iter().find_map(|f| clash(&name, &f.name))
+ {
+ return invalid(why);
+ }
+ let af = ensure_form(doc)?;
+ let mut w = widget_dict(page_ref, rect);
+ let field_name = match kind {
+ NewField::Radio { group: Some(g), .. } if radio_group.is_some() => g.clone(),
+ _ => name.clone(),
+ };
+ match kind {
+ NewField::Text { multiline } => {
+ w.set(b"FT".to_vec(), Object::name("Tx"));
+ // Auto size (0): a fixed 12 pt is clipped in a box shorter than that (#1888).
+ w.set(b"DA".to_vec(), PdfString::literal(b"/Helv 0 Tf 0 g".to_vec()));
+ if *multiline {
+ w.set(b"Ff".to_vec(), Object::Int(flags::MULTILINE as i64));
+ }
+ }
+ NewField::Date => {
+ w.set(b"FT".to_vec(), Object::name("Tx"));
+ w.set(b"DA".to_vec(), PdfString::literal(b"/Helv 0 Tf 0 g".to_vec()));
+ // Acrobat's format and keystroke actions for mm/dd/yyyy (run by its JavaScript engine).
+ let js = |s: &str| {
+ let mut a = Dict::new();
+ a.set(b"S".to_vec(), Object::name("JavaScript"));
+ a.set(b"JS".to_vec(), PdfString::literal(s.as_bytes().to_vec()));
+ Object::Dict(a)
+ };
+ let mut aa = Dict::new();
+ aa.set(b"F".to_vec(), js("AFDate_FormatEx(\"mm/dd/yyyy\");"));
+ aa.set(b"K".to_vec(), js("AFDate_KeystrokeEx(\"mm/dd/yyyy\");"));
+ w.set(b"AA".to_vec(), Object::Dict(aa));
+ }
+ NewField::CheckBox => {
+ w.set(b"FT".to_vec(), Object::name("Btn"));
+ w.set(b"V".to_vec(), Object::name("Off"));
+ w.set(b"AS".to_vec(), Object::name("Off"));
+ w.set(b"DA".to_vec(), PdfString::literal(b"/ZaDb 0 Tf 0 g".to_vec()));
+ }
+ NewField::Radio { export, .. } => {
+ w.set(b"AS".to_vec(), Object::name("Off"));
+ if export.trim().is_empty() || export == "Off" {
+ return invalid("a radio button needs an export value other than Off");
+ }
+ }
+ NewField::Combo { options, editable } | NewField::List { options, multi: editable } => {
+ w.set(b"FT".to_vec(), Object::name("Ch"));
+ w.set(b"DA".to_vec(), PdfString::literal(b"/Helv 12 Tf 0 g".to_vec()));
+ let combo = matches!(kind, NewField::Combo { .. });
+ let mut ff = 0;
+ if combo {
+ ff |= flags::COMBO;
+ if *editable {
+ ff |= flags::EDIT;
+ }
+ } else if *editable {
+ ff |= flags::MULTI_SELECT;
+ }
+ w.set(b"Ff".to_vec(), Object::Int(ff as i64));
+ w.set(b"Opt".to_vec(), Object::Array(options.iter().map(|o| Object::String(PdfString::text(o))).collect()));
+ }
+ NewField::Button { caption } => {
+ w.set(b"FT".to_vec(), Object::name("Btn"));
+ w.set(b"Ff".to_vec(), Object::Int(flags::PUSH_BUTTON as i64));
+ w.set(b"DA".to_vec(), PdfString::literal(b"/Helv 0 Tf 0 g".to_vec()));
+ let mut mk = w.get(b"MK").and_then(|m| m.as_dict()).cloned().unwrap_or_default();
+ mk.set(b"BG".to_vec(), rgb([0.86, 0.86, 0.86]));
+ mk.set(b"CA".to_vec(), PdfString::text(caption));
+ w.set(b"MK".to_vec(), Object::Dict(mk));
+ }
+ NewField::Image => {
+ w.set(b"FT".to_vec(), Object::name("Btn"));
+ w.set(b"Ff".to_vec(), Object::Int(flags::PUSH_BUTTON as i64));
+ w.set(b"DA".to_vec(), PdfString::literal(b"/Helv 0 Tf 0 g".to_vec()));
+ let mut mk = w.get(b"MK").and_then(|m| m.as_dict()).cloned().unwrap_or_default();
+ // Icon only, no border or fill: the picture is the field.
+ mk.remove(b"BC");
+ mk.remove(b"BG");
+ mk.set(b"TP".to_vec(), Object::Int(1));
+ w.set(b"MK".to_vec(), Object::Dict(mk));
+ let mut a = Dict::new();
+ a.set(b"S".to_vec(), Object::name("JavaScript"));
+ a.set(b"JS".to_vec(), PdfString::literal(b"event.target.buttonImportIcon();".to_vec()));
+ w.set(b"A".to_vec(), Object::Dict(a));
+ }
+ NewField::Signature => {
+ w.set(b"FT".to_vec(), Object::name("Sig"));
+ }
+ }
+ let widget = doc.add(Object::Dict(w));
+ match kind {
+ NewField::Radio { export, .. } => {
+ let group = match &radio_group {
+ Some(g) => g.obj,
+ None => {
+ let mut g = Dict::new();
+ g.set(b"FT".to_vec(), Object::name("Btn"));
+ g.set(b"Ff".to_vec(), Object::Int((flags::RADIO | flags::NO_TOGGLE_TO_OFF) as i64));
+ g.set(b"V".to_vec(), Object::name("Off"));
+ g.set(b"DA".to_vec(), PdfString::literal(b"/ZaDb 0 Tf 0 g".to_vec()));
+ g.set(b"Kids".to_vec(), Object::Array(Vec::new()));
+ let g = doc.add(Object::Dict(g));
+ attach(doc, af, g, &parts)?;
+ g
+ }
+ };
+ doc.update_dict(widget, |d| d.set(b"Parent".to_vec(), Object::Ref(group)))?;
+ doc.update_dict(group, |d| {
+ let mut kids = d.get(b"Kids").and_then(|k| k.as_array().cloned()).unwrap_or_default();
+ kids.push(Object::Ref(widget));
+ d.set(b"Kids".to_vec(), Object::Array(kids));
+ })?;
+ let w = Widget {
+ obj: widget,
+ page: Some(page),
+ rect,
+ on_state: Some(export.clone()),
+ state: Some("Off".into()),
+ tab: usize::MAX,
+ locked: false,
+ hidden: false,
+ read_only: false,
+ rotation: 0,
+ caption: None,
+ list: None,
+ round: true,
+ };
+ let ap = appearance::check_box_states(doc, &w, FieldKind::Radio, export, "/ZaDb 0 Tf 0 g");
+ doc.update_dict(widget, |d| d.set(b"AP".to_vec(), Object::Dict(ap)))?;
+ }
+ _ => attach(doc, af, widget, &parts)?,
+ }
+ add_to_page(doc, page_ref, widget)?;
+ redraw_field(doc, &field_name)?;
+ Ok(field_name)
+ }
+
+ /// Delete a field: its widgets leave their pages and the field leaves the form.
+ pub fn delete_field(doc: &mut Document, name: &str) -> Result<(), FormError> {
+ let f = fields(doc).into_iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?;
+ delete_found_field(doc, f)
+ }
+
+ /// [`delete_field`] for the field object `obj`, when separate fields share one name.
+ pub fn delete_field_object(doc: &mut Document, obj: ObjRef) -> Result<(), FormError> {
+ let f = fields(doc).into_iter().find(|f| f.obj == obj).ok_or_else(|| FormError::NoSuchField(format!("{obj:?}")))?;
+ delete_found_field(doc, f)
+ }
+
++/// Delete widget `widget` (an index into the field's widgets) of the field `name`, keeping the
++/// field and its other widgets: one radio button of a group, or one copy of a duplicated field,
++/// as Acrobat's Prepare Form deletes the selected one (#4609). A field with one widget is deleted
++/// whole. A per-widget `/Opt` entry goes with its widget, and a check box or radio group that was
++/// on through the deleted widget alone turns off.
++pub fn delete_widget(doc: &mut Document, name: &str, widget: usize) -> Result<(), FormError> {
++ let f = fields(doc).into_iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?;
++ let Some(w) = f.widgets.get(widget).cloned() else {
++ return invalid(format!("{name} has no widget {}", widget.saturating_add(1)));
++ };
++ // A field merged with its widget is that widget's only one.
++ if f.widgets.len() < 2 || w.obj == f.obj {
++ return delete_found_field(doc, f);
++ }
++ let per_widget_opt = matches!(f.kind, FieldKind::CheckBox | FieldKind::Radio) && f.options.len() == f.widgets.len();
++ // Turn the group off when no button left *shows* the deleted one's state: a twin with the same
++ // on-state name that is currently off does not keep the choice visible.
++ let on_only_here = w.on_state.as_deref().is_some_and(|on| {
++ f.value.iter().any(|v| v == on) && !f.widgets.iter().enumerate().any(|(i, o)| i != widget && o.state.as_deref() == Some(on))
++ });
++ drop_from_pages(doc, &std::iter::once(w.obj).collect())?;
++ detach(doc, w.obj)?;
++ drop_from_calculation_order(doc, |r| r == w.obj)?;
++ let mut d = doc.get(f.obj).as_dict().cloned().unwrap_or_default();
++ let mut changed = false;
++ if per_widget_opt
++ && let Some(opt) = d.get(b"Opt").map(|o| doc.resolve(o)).and_then(|o| o.as_array().cloned())
++ && opt.len() == f.widgets.len()
++ {
++ let kept: Vec<Object> = opt.into_iter().enumerate().filter(|(i, _)| *i != widget).map(|(_, o)| o).collect();
++ d.set(b"Opt".to_vec(), Object::Array(kept));
++ changed = true;
++ }
++ if on_only_here && d.get(b"V").is_some() {
++ d.set(b"V".to_vec(), Object::name("Off"));
++ changed = true;
++ }
++ // The default (`/DV`, what Reset puts back) can't name a state no button has any more.
++ let dv_only_here = w.on_state.as_deref().is_some_and(|on| {
++ d.get(b"DV").map(|v| doc.resolve(v)).and_then(|v| v.as_name().map(<[u8]>::to_vec)).is_some_and(|dv| dv == on.as_bytes())
++ && !f.widgets.iter().enumerate().any(|(i, o)| i != widget && o.on_state.as_deref() == Some(on))
++ });
++ if dv_only_here {
++ d.set(b"DV".to_vec(), Object::name("Off"));
++ changed = true;
++ }
++ if changed {
++ doc.set(f.obj, Object::Dict(d));
++ }
++ Ok(())
++}
++
+ fn delete_found_field(doc: &mut Document, f: Field) -> Result<(), FormError> {
+ let widgets: std::collections::HashSet<ObjRef> = f.widgets.iter().map(|w| w.obj).collect();
++ drop_from_pages(doc, &widgets)?;
++ detach(doc, f.obj)?;
++ // Out of the calculation order too: a `/CO` entry would keep the field, its value and its
++ // widgets reachable for a full save.
++ drop_from_calculation_order(doc, |r| r == f.obj || widgets.contains(&r))
++}
++
++/// Take the annotations `widgets` off every page's `/Annots`, held directly or by reference.
++fn drop_from_pages(doc: &mut Document, widgets: &std::collections::HashSet<ObjRef>) -> Result<(), FormError> {
+ for p in page_refs(doc) {
+ let Some(a) = doc.get(p).as_dict().and_then(|d| d.get(b"Annots").cloned()) else { continue };
+ let list = doc.resolve(&a).as_array().cloned().unwrap_or_default();
+ let kept: Vec<Object> = list.iter().filter(|o| !o.as_ref().is_some_and(|r| widgets.contains(&r))).cloned().collect();
+ if kept.len() != list.len() {
+ match a.as_ref() {
+ Some(r) if doc.get(r).as_array().is_some() => doc.set(r, Object::Array(kept)),
+ _ => doc.update_dict(p, |d| d.set(b"Annots".to_vec(), Object::Array(kept)))?,
+ }
+ }
+ }
- detach(doc, f.obj)?;
- // Out of the calculation order too: a `/CO` entry would keep the field, its value and its
- // widgets reachable for a full save.
- drop_from_calculation_order(doc, |r| r == f.obj || widgets.contains(&r))
++ Ok(())
+ }
+
+ /// Remove the `/CO` entries `gone` matches, whether the form and the array are held directly or
+ /// by reference.
+ fn drop_from_calculation_order(doc: &mut Document, gone: impl Fn(ObjRef) -> bool) -> Result<(), FormError> {
+ let Some(root) = doc.root() else { return Ok(()) };
+ let Some(af_obj) = doc.get(root).as_dict().and_then(|d| d.get(b"AcroForm").cloned()) else { return Ok(()) };
+ let Some(mut af) = doc.resolve(&af_obj).as_dict().cloned() else { return Ok(()) };
+ let Some(co_obj) = af.get(b"CO").cloned() else { return Ok(()) };
+ let co = doc.resolve(&co_obj).as_array().cloned().unwrap_or_default();
+ let kept: Vec<Object> = co.iter().filter(|o| !o.as_ref().is_some_and(&gone)).cloned().collect();
+ if kept.len() == co.len() {
+ return Ok(());
+ }
+ match (co_obj.as_ref(), af_obj.as_ref()) {
+ (Some(r), _) if doc.get(r).as_array().is_some() => doc.set(r, Object::Array(kept)),
+ (_, Some(af_ref)) => doc.update_dict(af_ref, |d| d.set(b"CO".to_vec(), Object::Array(kept)))?,
+ (_, None) => {
+ af.set(b"CO".to_vec(), Object::Array(kept));
+ doc.update_dict(root, |d| d.set(b"AcroForm".to_vec(), Object::Dict(af)))?;
+ }
+ }
+ Ok(())
+ }
+
+ /// Widget-only keys: they stay with each widget when a merged field is split.
+ const WIDGET_KEYS: [&[u8]; 12] = [b"Type", b"Subtype", b"Rect", b"P", b"AP", b"AS", b"MK", b"F", b"BS", b"Border", b"H", b"StructParent"];
+
+ /// Duplicate a field onto other pages (Acrobat: right-click a field ▸ Duplicate): each page
+ /// gets a widget at the same place, belonging to the same field, so they share one value.
+ /// A field that is its own widget is first split into a field and a widget kid. Returns how
+ /// many widgets were added (pages that already have one are skipped).
+ pub fn duplicate_field(doc: &mut Document, name: &str, pages: &[usize]) -> Result<usize, FormError> {
+ let f = fields(doc).into_iter().find(|f| f.name == name).ok_or_else(|| FormError::NoSuchField(name.into()))?;
+ let model = f.widgets.first().cloned().ok_or_else(|| FormError::Invalid(format!("{name} has no widget")))?;
+ let refs = page_refs(doc);
+ for p in pages {
+ if *p >= refs.len() {
+ return invalid(format!("page {} does not exist", p + 1));
+ }
+ }
+ let have: std::collections::HashSet<usize> = f.widgets.iter().filter_map(|w| w.page).collect();
+ let targets: Vec<usize> = pages.iter().copied().filter(|p| !have.contains(p)).collect();
+ if targets.is_empty() {
+ return Ok(0);
+ }
+ // A merged field/widget becomes a field with one widget kid.
+ let mut model_ref = model.obj;
+ if model.obj == f.obj {
+ let d = doc.get(f.obj).as_dict().cloned().unwrap_or_default();
+ let mut kid = Dict::new();
+ for k in WIDGET_KEYS {
+ if let Some(v) = d.get(k) {
+ kid.set(k.to_vec(), v.clone());
+ }
+ }
+ kid.set(b"Parent".to_vec(), Object::Ref(f.obj));
+ let kr = doc.add(Object::Dict(kid));
+ doc.update_dict(f.obj, |d| {
+ for k in WIDGET_KEYS {
+ d.remove(k);
+ }
+ d.set(b"Kids".to_vec(), Object::Array(vec![Object::Ref(kr)]));
+ })?;
+ // The page lists the widget now, not the field.
+ if let Some(p) = model.page {
+ let pr = refs[p];
+ let annots = doc.get(pr).as_dict().and_then(|d| d.get(b"Annots").cloned());
+ let swap =
+ |a: Vec<Object>| -> Vec<Object> { a.into_iter().map(|o| if o.as_ref() == Some(f.obj) { Object::Ref(kr) } else { o }).collect() };
+ match annots {
+ Some(Object::Ref(ar)) => {
+ let a = doc.get(ar).as_array().cloned().unwrap_or_default();
+ doc.set(ar, Object::Array(swap(a)));
+ }
+ Some(Object::Array(a)) => doc.update_dict(pr, |d| d.set(b"Annots".to_vec(), Object::Array(swap(a))))?,
+ _ => {}
+ }
+ }
+ model_ref = kr;
+ }
+ let template = doc.get(model_ref).as_dict().cloned().unwrap_or_default();
+ let mut added = Vec::new();
+ for p in &targets {
+ let pr = refs[*p];
+ let mut w = template.clone();
+ w.set(b"P".to_vec(), Object::Ref(pr));
+ w.set(b"Parent".to_vec(), Object::Ref(f.obj));
+ w.remove(b"StructParent");
+ let wr = doc.add(Object::Dict(w));
+ let annots = doc.get(pr).as_dict().and_then(|d| d.get(b"Annots").cloned());
+ match annots {
+ Some(Object::Ref(ar)) => {
+ let mut a = doc.get(ar).as_array().cloned().unwrap_or_default();
+ a.push(Object::Ref(wr));
+ doc.set(ar, Object::Array(a));
+ }
+ other => {
+ let mut a = other.and_then(|o| o.as_array().cloned()).unwrap_or_default();
+ a.push(Object::Ref(wr));
+ doc.update_dict(pr, |d| d.set(b"Annots".to_vec(), Object::Array(a)))?;
+ }
+ }
+ added.push(wr);
+ }
+ doc.update_dict(f.obj, |d| {
+ let mut kids = d.get(b"Kids").and_then(|k| k.as_array().cloned()).unwrap_or_default();
+ kids.extend(added.iter().map(|r| Object::Ref(*r)));
+ d.set(b"Kids".to_vec(), Object::Array(kids));
+ })?;
+ redraw_field(doc, name)?;
+ Ok(added.len())
+ }
diff --cc crates/ui-egui/src/tools/prepare.rs
index 000000000,9713791e3..ae24c6870
mode 000000,100644..100644
--- a/crates/ui-egui/src/tools/prepare.rs
+++ b/crates/ui-egui/src/tools/prepare.rs
@@@ -1,0 -1,759 +1,763 @@@
+ //! Prepare a form (Acrobat's Prepare Form, execution plan M6.6): add fields with the field
+ //! tools (click for the default size, or drag a rectangle), select, move and resize them, see
+ //! their name tags, delete them, and edit them in Field Properties.
+ //!
+ //! While the Prepare a form panel is open the page shows every field with a light-blue fill and
+ //! its name; clicks select fields instead of filling them in, as in Acrobat.
+
+ use egui::{Color32, CornerRadius, Pos2, Rect, Stroke, vec2};
+ use pdfcraft_engine::form_scripts::{CalcOp, Calculate, DATE_PRESETS, Format, TIME_PRESETS, Validate, format_value};
+ use pdfcraft_engine::{BorderStyle, Document, Edit, FieldFont, FieldLook, FieldProps, FormField, FormFieldKind, NewField};
+ use pdfcraft_render::DocInfo;
+
+ use crate::canvas::{DocView, PageXform};
+ use crate::comments;
+ use crate::page_pointer::PagePointer;
+ use crate::theme;
+ use crate::widgets;
+
+ mod draft;
+ mod properties;
+ mod tabs;
+
+ pub use draft::{ACTION_KINDS, ActionDraft, FieldDraft, FieldTab};
+ pub(crate) use draft::{da_font, da_size};
+ pub(crate) use properties::body;
+
+ const SELECT_BLUE: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6);
+ /// Acrobat's field fill in Prepare Form (light blue).
+ pub(crate) const FIELD_FILL: Color32 = Color32::from_rgba_premultiplied(0x1B, 0x34, 0x54, 0x59);
+
+ /// The Add form components tools.
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+ pub enum FieldTool {
+ Text,
+ /// Rows and columns of text fields in the area drawn, set up in a window first.
+ TextTable,
+ CheckBox,
+ Radio,
+ Combo,
+ List,
+ Button,
+ Image,
+ Date,
+ Signature,
+ }
+
+ pub const FIELD_TOOLS: [FieldTool; 10] = [
+ FieldTool::Text,
+ FieldTool::TextTable,
+ FieldTool::CheckBox,
+ FieldTool::Radio,
+ FieldTool::Combo,
+ FieldTool::List,
+ FieldTool::Button,
+ FieldTool::Image,
+ FieldTool::Date,
+ FieldTool::Signature,
+ ];
+
+ impl FieldTool {
+ pub fn command(self) -> &'static str {
+ match self {
+ FieldTool::Text => "form.add.text",
+ FieldTool::TextTable => "form.add.text_table",
+ FieldTool::CheckBox => "form.add.checkbox",
+ FieldTool::Radio => "form.add.radio",
+ FieldTool::Combo => "form.add.combo",
+ FieldTool::List => "form.add.list",
+ FieldTool::Button => "form.add.button",
+ FieldTool::Image => "form.add.image",
+ FieldTool::Date => "form.add.date",
+ FieldTool::Signature => "form.add.signature",
+ }
+ }
+
+ pub fn from_command(id: &str) -> Option<Self> {
+ FIELD_TOOLS.into_iter().find(|t| t.command() == id)
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ FieldTool::Text => "Text field",
+ FieldTool::TextTable => "Text field table",
+ FieldTool::CheckBox => "Checkbox",
+ FieldTool::Radio => "Radio button",
+ FieldTool::Combo => "Drop-down list",
+ FieldTool::List => "List box",
+ FieldTool::Button => "Button",
+ FieldTool::Image => "Image field",
+ FieldTool::Date => "Date field",
+ FieldTool::Signature => "Digital signature",
+ }
+ }
+
+ /// The field a click or drag creates. Radio buttons dropped next to a selected radio group
+ /// join it with the next free choice.
+ pub fn new_field(self, join: Option<&FormField>) -> NewField {
+ match self {
+ // A table's cells are text fields.
+ FieldTool::Text | FieldTool::TextTable => NewField::Text { multiline: false },
+ FieldTool::CheckBox => NewField::CheckBox,
+ FieldTool::Radio => match join.filter(|f| f.kind == FormFieldKind::Radio) {
+ Some(g) => {
+ let taken: Vec<&str> = g.widgets.iter().filter_map(|w| w.on_state.as_deref()).collect();
+ let export =
+ (1..=u64::MAX).map(|i| format!("Choice{i}")).find(|c| !taken.contains(&c.as_str())).unwrap_or_else(|| "Choice".into());
+ NewField::Radio { group: Some(g.name.clone()), export }
+ }
+ None => NewField::Radio { group: None, export: "Choice1".into() },
+ },
+ FieldTool::Combo => NewField::Combo { options: Vec::new(), editable: false },
+ FieldTool::List => NewField::List { options: Vec::new(), multi: false },
+ FieldTool::Button => NewField::Button { caption: String::new() },
+ FieldTool::Image => NewField::Image,
+ FieldTool::Date => NewField::Date,
+ FieldTool::Signature => NewField::Signature,
+ }
+ }
+
+ /// Width and height in points of a field placed with a single click.
+ pub fn default_size(self) -> (f64, f64) {
+ match self {
+ FieldTool::TextTable => (180.0, 110.0),
+ FieldTool::CheckBox | FieldTool::Radio => (14.0, 14.0),
+ FieldTool::List => (144.0, 54.0),
+ FieldTool::Button => (72.0, 22.0),
+ FieldTool::Image => (144.0, 108.0),
+ FieldTool::Signature => (180.0, 36.0),
+ FieldTool::Date => (108.0, 22.0),
+ FieldTool::Text | FieldTool::Combo => (144.0, 22.0),
+ }
+ }
+ }
+
+ /// What the pointer is doing to a field.
+ #[derive(Clone, Copy, Debug, PartialEq)]
+ enum Grab {
+ /// Drawing a new field from this screen point.
+ Draw(Pos2),
+ /// Selecting fields inside a dragged rectangle.
+ Select(Pos2),
+ Move,
+ /// Resizing by a corner: (moves left edge, moves top edge) in screen terms.
+ Corner(bool, bool),
+ }
+
+ #[derive(Clone, Debug, Default, PartialEq)]
+ pub struct PrepareView {
+ /// The selected field and which of its widgets (the anchor of Align and Match Size).
+ pub selected: Option<(String, usize)>,
+ /// More fields selected with Shift- or ⌘-click.
+ pub also: Vec<(String, usize)>,
+ /// Select the field an Add field edit creates (the form's length before it).
+ pub select_added: Option<usize>,
+ grab: Option<(usize, Grab, Pos2)>,
+ marquee_before: Option<Vec<(String, usize)>>,
+ /// Escape ends egui's drag too; ignore its release until the mouse is up.
+ ignore_release: bool,
+ }
+
+ impl PrepareView {
+ /// Cancel a preparation marquee without injecting the terminal pointer release that Escape does.
+ pub(crate) fn cancel_pointer_gesture(&mut self) {
+ cancel_marquee(self);
+ // Unlike Escape, control cancellation never injects a terminal pointer release.
+ self.ignore_release = false;
+ }
+
+ /// Unique field names: selecting several widgets of one radio group still edits one field.
+ pub fn names(&self) -> Vec<String> {
+ let mut names = Vec::new();
+ for (name, _) in self.selected.iter().chain(self.also.iter()) {
+ if !names.contains(name) {
+ names.push(name.clone());
+ }
+ }
+ names
+ }
+
+ pub(crate) fn select(&mut self, key: (String, usize), extend: bool) {
+ if !extend || self.selected.is_none() {
+ self.selected = Some(key);
+ self.also.clear();
+ } else if self.selected.as_ref() == Some(&key) {
+ self.selected = if self.also.is_empty() { None } else { Some(self.also.remove(0)) };
+ } else if let Some(index) = self.also.iter().position(|k| *k == key) {
+ self.also.remove(index);
+ } else {
+ self.also.push(key);
+ }
+ }
+ }
+
+ fn screen_rect(xf: &PageXform, info: &DocInfo, page: usize, r: [f64; 4]) -> Rect {
+ xf.user_rect(info, page, [r[0] as f32, r[1] as f32, r[2] as f32, r[3] as f32])
+ }
+
+ fn to_user(xf: &PageXform, info: &DocInfo, page: usize, p: Pos2) -> [f64; 2] {
+ let (vx, vy) = xf.screen_to_view(p);
+ let u = info.pages[page].view_to_user(vx, vy);
+ [u[0] as f64, u[1] as f64]
+ }
+
+ /// Where a table goes, in view space, for a screen rect drawn with the table tool: a click (a rect
+ /// under 4 pixels either way) puts the default size's top-left corner at the pointer, moved in from
+ /// the page's edges as far as it takes to stay on the page.
+ fn table_rect(xf: &PageXform, r: Rect) -> [f64; 4] {
+ let (x0, y0) = xf.screen_to_view(r.min);
+ if r.width() < 4.0 || r.height() < 4.0 {
+ let (pw, ph) = (f64::from(xf.pw), f64::from(xf.ph));
+ let (dw, dh) = FieldTool::TextTable.default_size();
+ // Smaller than the default only on a page smaller than it.
+ let (w, h) = (dw.min(pw), dh.min(ph));
+ let (x, y) = (f64::from(x0).min(pw - w).max(0.0), f64::from(y0).min(ph - h).max(0.0));
+ return [x, y, x + w, y + h];
+ }
+ let (x1, y1) = xf.screen_to_view(r.max);
+ [x0, y0, x1, y1].map(f64::from)
+ }
+
+ /// A screen rect → a normalised user-space rect.
+ fn user_rect(xf: &PageXform, info: &DocInfo, page: usize, r: Rect) -> [f64; 4] {
+ let (a, b) = (to_user(xf, info, page, r.min), to_user(xf, info, page, r.max));
+ [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]
+ }
+
+ fn handles(r: Rect) -> [(Pos2, bool, bool); 4] {
+ [(r.left_top(), true, true), (r.right_top(), false, true), (r.left_bottom(), true, false), (r.right_bottom(), false, false)]
+ }
+
+ /// The rect while a move or resize is in progress. With `shift` held a corner keeps the field's
+ /// proportions, as it does for comments and stamps.
+ fn dragged(r: Rect, grab: Grab, delta: egui::Vec2, shift: bool) -> Rect {
+ match grab {
+ Grab::Move => r.translate(delta),
+ Grab::Corner(left, top) => {
+ let handle = (if left { -1 } else { 1 }, if top { -1 } else { 1 });
+ comments::resized(r, handle, delta, comments::corner_ratio(r, None, shift))
+ }
+ Grab::Draw(_) | Grab::Select(_) => r,
+ }
+ }
+
+ pub(crate) struct Outcome {
+ /// The click or drag belonged to Prepare a form.
+ pub consumed: bool,
+ /// Open Field Properties for the selected field.
+ pub properties: bool,
+ /// A field was placed: go back to the Select tool.
+ pub placed: bool,
+ /// A table of text fields was drawn: open its window for this page and area (view space).
+ pub table: Option<(usize, [f64; 4])>,
+ }
+
+ /// Pointer input on one page while preparing a form.
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn page_input(
+ ui: &egui::Ui,
+ resp: &egui::Response,
+ xf: &PageXform,
+ ptr: &PagePointer,
+ page: usize,
+ info: &DocInfo,
+ form: &[FormField],
+ tool: Option<FieldTool>,
+ allowed: bool,
+ view: &mut DocView,
+ ) -> Outcome {
+ let mut out = Outcome { consumed: false, properties: false, placed: false, table: None };
+ let pointer = ptr.pos;
+ let prep = &mut view.prepare;
+
+ if prep.marquee_before.is_some() && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
+ cancel_marquee(prep);
+ out.consumed = true;
+ return out;
+ }
+ if prep.ignore_release {
+ if !ptr.primary_down {
+ prep.ignore_release = false;
+ }
+ out.consumed = true;
+ return out;
+ }
+
+ // A grab in progress on this page.
+ if let Some((gp, grab, start)) = prep.grab
+ && gp == page
+ {
+ out.consumed = true;
+ if resp.drag_stopped() || !ptr.primary_down {
+ prep.grab = None;
+ let end = pointer.unwrap_or(start);
+ match grab {
+ Grab::Select(from) => {
+ prep.marquee_before = None;
+ let rect = Rect::from_two_pos(from, end).intersect(xf.rect);
+ for f in form {
+ for (wi, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(page)) {
+ if screen_rect(xf, info, page, w.rect).intersects(rect) {
+ let key = (f.name.clone(), wi);
+ if prep.selected.is_none() {
+ prep.selected = Some(key);
+ } else if prep.selected.as_ref() != Some(&key) && !prep.also.contains(&key) {
+ prep.also.push(key);
+ }
+ }
+ }
+ }
+ }
+ Grab::Draw(from) => {
+ let Some(tool) = tool else { return out };
+ if tool == FieldTool::TextTable {
+ out.table = Some((page, table_rect(xf, Rect::from_two_pos(from, end).intersect(xf.rect))));
+ out.placed = true;
+ return out;
+ }
+ let r = Rect::from_two_pos(from, end).intersect(xf.rect);
+ let rect = user_rect(xf, info, page, r);
+ let rect = if r.width() < 4.0 || r.height() < 4.0 {
+ // A click: the default size, top-left at the pointer.
+ let at = to_user(xf, info, page, from);
+ let (w, h) = tool.default_size();
+ [at[0], at[1] - h, at[0] + w, at[1]]
+ } else {
+ rect
+ };
+ let join = prep.selected.as_ref().and_then(|(n, _)| form.iter().find(|f| &f.name == n));
+ prep.select_added = Some(form.len());
+ view.pending_edit = Some(Edit::AddField { page, rect, kind: tool.new_field(join), name: None });
+ out.placed = true;
+ }
+ Grab::Move | Grab::Corner(..) => {
+ let Some((name, wi)) = prep.selected.clone() else { return out };
+ let Some(w) = form.iter().find(|f| f.name == name).and_then(|f| f.widgets.get(wi)) else { return out };
+ let delta = end - start;
+ if delta.length() >= 1.0 {
+ let shift = ui.input(|i| i.modifiers.shift);
+ let r = dragged(screen_rect(xf, info, page, w.rect), grab, delta, shift);
+ let rect = user_rect(xf, info, page, r);
+ view.pending_edit =
+ Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, rect)), ..Default::default() }) });
+ }
+ }
+ }
+ }
+ return out;
+ }
+
+ let Some(p) = pointer.filter(|p| xf.rect.contains(*p)) else { return out };
+ if !allowed {
+ return out;
+ }
+ if let Some(tool) = tool {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);
+ if resp.drag_started() || resp.clicked() {
+ let origin = ptr.origin.filter(|o| xf.rect.contains(*o)).unwrap_or(p);
+ prep.grab = Some((page, Grab::Draw(origin), origin));
+ out.consumed = true;
+ if resp.clicked() {
+ // A click without a drag: finish at once.
+ prep.grab = None;
+ if tool == FieldTool::TextTable {
+ out.table = Some((page, table_rect(xf, Rect::from_min_size(p, egui::Vec2::ZERO))));
+ out.placed = true;
+ return out;
+ }
+ let at = to_user(xf, info, page, p);
+ let (w, h) = tool.default_size();
+ let join = prep.selected.as_ref().and_then(|(n, _)| form.iter().find(|f| &f.name == n));
+ prep.select_added = Some(form.len());
+ view.pending_edit = Some(Edit::AddField { page, rect: [at[0], at[1] - h, at[0] + w, at[1]], kind: tool.new_field(join), name: None });
+ out.placed = true;
+ }
+ }
+ return out;
+ }
+
+ // Right-click a field: select it (the context menu acts on it).
+ if resp.secondary_clicked()
+ && let Some((f, wi)) = form.iter().find_map(|f| {
+ f.widgets.iter().enumerate().find(|(_, w)| w.page == Some(page) && screen_rect(xf, info, page, w.rect).contains(p)).map(|(i, _)| (f, i))
+ })
+ {
+ let key = (f.name.clone(), wi);
+ if let Some(i) = prep.also.iter().position(|k| *k == key) {
+ // Part of the selection: it becomes the anchor the others line up with.
+ prep.also.remove(i);
+ if let Some(old) = prep.selected.replace(key) {
+ prep.also.push(old);
+ }
+ } else if prep.selected.as_ref() != Some(&key) {
+ prep.selected = Some(key);
+ prep.also.clear();
+ }
+ }
+ // The Select tool: corner handles of the selection, then fields.
+ let selected_rect = prep
+ .selected
+ .as_ref()
+ .and_then(|(n, wi)| form.iter().find(|f| &f.name == n)?.widgets.get(*wi).filter(|w| w.page == Some(page)))
+ .map(|w| screen_rect(xf, info, page, w.rect));
+ let corner = selected_rect.and_then(|r| handles(r).into_iter().find(|(c, ..)| c.distance(p) <= 6.0));
+ let hit = form.iter().find_map(|f| {
+ f.widgets.iter().enumerate().find(|(_, w)| w.page == Some(page) && screen_rect(xf, info, page, w.rect).contains(p)).map(|(i, _)| (f, i))
+ });
+ if let Some((_, left, top)) = corner {
+ ui.ctx().set_cursor_icon(if left == top { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw });
+ } else if hit.is_some() {
+ ui.ctx().set_cursor_icon(egui::CursorIcon::Move);
+ }
+ if resp.drag_started() {
+ let origin = ptr.origin.unwrap_or(p);
+ if let Some((_, left, top)) = selected_rect.and_then(|r| handles(r).into_iter().find(|(c, ..)| c.distance(origin) <= 6.0)) {
+ prep.grab = Some((page, Grab::Corner(left, top), origin));
+ out.consumed = true;
+ } else if let Some((f, wi)) = form.iter().find_map(|f| {
+ f.widgets
+ .iter()
+ .enumerate()
+ .find(|(_, w)| w.page == Some(page) && screen_rect(xf, info, page, w.rect).contains(origin))
+ .map(|(i, _)| (f, i))
+ }) {
+ prep.selected = Some((f.name.clone(), wi));
+ prep.grab = Some((page, Grab::Move, origin));
+ out.consumed = true;
+ } else {
+ prep.marquee_before = Some(prep.selected.iter().chain(prep.also.iter()).cloned().collect());
+ if !ui.input(|i| i.modifiers.shift || i.modifiers.command) {
+ prep.selected = None;
+ prep.also.clear();
+ }
+ prep.grab = Some((page, Grab::Select(origin), origin));
+ out.consumed = true;
+ }
+ return out;
+ }
+ if resp.double_clicked() && hit.is_some() && !ui.input(|i| i.modifiers.shift || i.modifiers.command) {
+ out.consumed = true;
+ out.properties = true;
+ return out;
+ }
+ if resp.clicked() {
+ let extend = ui.input(|i| i.modifiers.shift || i.modifiers.command);
+ match hit {
+ // Shift/⌘-click adds or removes a field from the selection.
+ Some((f, wi)) => {
+ prep.select((f.name.clone(), wi), extend);
+ out.consumed = true;
+ }
+ None if corner.is_none() => {
+ prep.selected = None;
+ prep.also.clear();
+ }
+ None => out.consumed = true,
+ }
+ }
+ out.consumed |= hit.is_some() && resp.is_pointer_button_down_on();
+ out
+ }
+
+ /// Align, Center, Distribute and Set Fields to Same Size (Prepare a form, several fields
+ /// selected).
+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]
+ pub enum Arrange {
+ AlignLeft,
+ AlignRight,
+ AlignTop,
+ AlignBottom,
+ /// Centres on one vertical line (the anchor's).
+ AlignCenterH,
+ /// Centres on one horizontal line.
+ AlignCenterV,
+ DistributeH,
+ DistributeV,
+ SameWidth,
+ SameHeight,
+ SameSize,
+ }
+
+ impl Arrange {
+ pub fn label(self) -> &'static str {
+ match self {
+ Arrange::AlignLeft | Arrange::AlignRight | Arrange::AlignTop | Arrange::AlignBottom | Arrange::AlignCenterH | Arrange::AlignCenterV => {
+ "Align fields"
+ }
+ Arrange::DistributeH | Arrange::DistributeV => "Distribute fields",
+ Arrange::SameWidth | Arrange::SameHeight | Arrange::SameSize => "Match field sizes",
+ }
+ }
+ }
+
+ /// The edits that arrange the selected widgets (user space; the anchor stays put).
+ pub fn arrange(form: &[FormField], anchor: &(String, usize), others: &[(String, usize)], op: Arrange) -> Option<Edit> {
+ let rect_of = |k: &(String, usize)| form.iter().find(|f| f.name == k.0).and_then(|f| f.widgets.get(k.1)).map(|w| w.rect);
+ let a = rect_of(anchor)?;
+ let mut items: Vec<((String, usize), [f64; 4])> = others.iter().filter_map(|k| rect_of(k).map(|r| (k.clone(), r))).collect();
+ if items.is_empty() {
+ return None;
+ }
+ let (aw, ah) = (a[2] - a[0], a[3] - a[1]);
+ let mut moved: Vec<((String, usize), [f64; 4])> = Vec::new();
+ match op {
+ Arrange::DistributeH | Arrange::DistributeV => {
+ // Even gaps between all selected fields (the outermost stay).
+ items.push((anchor.clone(), a));
+ if items.len() < 3 {
+ return None;
+ }
+ let horiz = op == Arrange::DistributeH;
+ items.sort_by(|x, y| if horiz { x.1[0].total_cmp(&y.1[0]) } else { y.1[3].total_cmp(&x.1[3]) });
+ let size = |r: &[f64; 4]| if horiz { r[2] - r[0] } else { r[3] - r[1] };
+ let (first, last) = (items[0].1, items[items.len() - 1].1);
+ let span = if horiz { last[2] - first[0] } else { first[3] - last[1] };
+ let total: f64 = items.iter().map(|(_, r)| size(r)).sum();
+ let gap = (span - total) / (items.len() - 1) as f64;
+ let mut at = if horiz { first[0] } else { first[3] };
+ for (k, r) in &items {
+ let s = size(r);
+ let nr = if horiz { [at, r[1], at + s, r[3]] } else { [r[0], at - s, r[2], at] };
+ at = if horiz { at + s + gap } else { at - s - gap };
+ moved.push((k.clone(), nr));
+ }
+ }
+ _ => {
+ for (k, r) in items {
+ let (w, h) = (r[2] - r[0], r[3] - r[1]);
+ let nr = match op {
+ Arrange::AlignLeft => [a[0], r[1], a[0] + w, r[3]],
+ Arrange::AlignRight => [a[2] - w, r[1], a[2], r[3]],
+ Arrange::AlignTop => [r[0], a[3] - h, r[2], a[3]],
+ Arrange::AlignBottom => [r[0], a[1], r[2], a[1] + h],
+ Arrange::AlignCenterH => {
+ let cx = (a[0] + a[2]) / 2.0;
+ [cx - w / 2.0, r[1], cx + w / 2.0, r[3]]
+ }
+ Arrange::AlignCenterV => {
+ let cy = (a[1] + a[3]) / 2.0;
+ [r[0], cy - h / 2.0, r[2], cy + h / 2.0]
+ }
+ Arrange::SameWidth => [r[0], r[1], r[0] + aw, r[3]],
+ Arrange::SameHeight => [r[0], r[3] - ah, r[2], r[3]],
+ _ => [r[0], r[3] - ah, r[0] + aw, r[3]],
+ };
+ moved.push((k, nr));
+ }
+ }
+ }
+ let edits: Vec<Edit> = moved
+ .into_iter()
+ .filter(|(k, nr)| rect_of(k).is_some_and(|r| r.iter().zip(nr).any(|(x, y)| (x - y).abs() > 1e-6)))
+ .map(|((name, wi), rect)| Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, rect)), ..Default::default() }) })
+ .collect();
+ (!edits.is_empty()).then(|| Edit::Batch { label: op.label().into(), edits })
+ }
+
+ /// Fields with their light-blue fill and name tags, the selection with its handles, and the
+ /// rectangle being drawn or dragged to the pages' `pointer`.
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn paint_page(
+ ui: &egui::Ui,
+ painter: &egui::Painter,
+ xf: &PageXform,
+ page: usize,
+ info: &DocInfo,
+ form: &[FormField],
+ view: &DocView,
+ pointer: Option<Pos2>,
+ ) {
+ let prep = &view.prepare;
+ let grab = prep.grab.filter(|(gp, ..)| *gp == page);
+ let zoom = xf.zoom().clamp(0.5, 3.0);
+ for f in form {
+ for (wi, w) in f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(page)) {
+ let mut r = screen_rect(xf, info, page, w.rect);
+ let selected = prep.selected.as_ref().is_some_and(|(n, i)| n == &f.name && *i == wi);
+ let also = prep.also.iter().any(|(n, i)| n == &f.name && *i == wi);
+ if selected && let (Some((_, g, start)), Some(p)) = (grab, pointer) {
+ r = dragged(r, g, p - start, ui.input(|i| i.modifiers.shift));
+ }
+ painter.rect_filled(r, CornerRadius::ZERO, FIELD_FILL);
+ painter.rect_stroke(
+ r,
+ CornerRadius::ZERO,
+ Stroke::new(if also { 2.0 } else { 1.0 }, if selected || also { SELECT_BLUE } else { Color32::from_gray(90) }),
+ egui::StrokeKind::Inside,
+ );
+ // The name tag: white text on black, clipped to the field.
+ // The full name, as Acrobat shows it: MASTER.first, not first (#2696).
+ let label = f.name.as_str();
+ let font = theme::regular((9.0 * zoom).clamp(7.0, 13.0));
+ let galley = painter.layout_no_wrap(label.to_string(), font, Color32::WHITE);
+ let size = galley.size() + vec2(6.0, 2.0);
+ let tag = Rect::from_center_size(r.center(), size);
+ let clip = painter.clip_rect().intersect(r);
+ let p2 = painter.with_clip_rect(clip);
+ p2.rect_filled(tag, CornerRadius::same(1), if selected { SELECT_BLUE } else { Color32::BLACK });
+ p2.galley(tag.min + vec2(3.0, 1.0), galley, Color32::WHITE);
+ if selected {
+ painter.rect_stroke(r.expand(1.0), CornerRadius::ZERO, Stroke::new(2.0, SELECT_BLUE), egui::StrokeKind::Outside);
+ for (c, ..) in handles(r) {
+ painter.circle(c, 3.5, Color32::WHITE, Stroke::new(1.5, SELECT_BLUE));
+ }
+ }
+ }
+ }
+ if let (Some((_, Grab::Draw(from) | Grab::Select(from), _)), Some(p)) = (grab, pointer) {
+ let r = Rect::from_two_pos(from, p).intersect(xf.rect);
+ painter.rect_filled(r, CornerRadius::ZERO, FIELD_FILL);
+ painter.rect_stroke(r, CornerRadius::ZERO, Stroke::new(1.0, SELECT_BLUE), egui::StrokeKind::Inside);
+ }
+ }
+
+ /// Delete the selected field and every field selected with it (#95), as one undoable step, and
-/// clear the selection.
++/// clear the selection. Each selection is one widget, so selecting one radio button of a group,
++/// or one copy of a duplicated field, deletes only that one, as in Acrobat (#4609); a field's
++/// last widget takes the field with it.
+ pub(crate) fn delete_selected(view: &mut DocView) -> Option<Edit> {
- let (first, _) = view.prepare.selected.take()?;
- let mut names = vec![first];
- for (name, _) in std::mem::take(&mut view.prepare.also) {
- if !names.contains(&name) {
- names.push(name);
++ let first = view.prepare.selected.take()?;
++ let mut picked = vec![first];
++ for w in std::mem::take(&mut view.prepare.also) {
++ if !picked.contains(&w) {
++ picked.push(w);
+ }
+ }
- if names.len() == 1 {
- return names.pop().map(|name| Edit::DeleteField { name });
++ // A field's later widgets first, so the indices of the ones still to go don't shift.
++ picked.sort_by_key(|w| std::cmp::Reverse(w.1));
++ if picked.len() == 1 {
++ return picked.pop().map(|(name, widget)| Edit::DeleteWidget { name, widget });
+ }
- let label = format!("Delete {} fields", names.len());
- Some(Edit::Batch { label, edits: names.into_iter().map(|name| Edit::DeleteField { name }).collect() })
++ let label = format!("Delete {} fields", picked.len());
++ Some(Edit::Batch { label, edits: picked.into_iter().map(|(name, widget)| Edit::DeleteWidget { name, widget }).collect() })
+ }
+
+ /// The arrow keys move the selected field a point, Shift and an arrow ten points, as in Acrobat,
+ /// as the object nudge does (`object_ui::nudge_keys`) and as dragging it does (#2608). The keys
+ /// are consumed before the view turns the page with them; one press is one undo step.
+ pub(crate) fn nudge_keys(ctx: &egui::Context, view: &mut DocView, doc: &Document) {
+ // `consume_key` lets an extra Alt through, and Alt+↑/↓ belongs to Calculation order's move.
+ if ctx.egui_wants_keyboard_input() || view.prepare.grab.is_some() || ctx.input(|i| i.modifiers.alt) {
+ return;
+ }
+ let Some((name, wi)) = view.prepare.selected.clone() else { return };
+ let Some(w) = doc.form.iter().find(|f| f.name == name).and_then(|f| f.widgets.get(wi)) else { return };
+ let Some(page) = w.page else { return };
+ let Some(xf) = view.page_xform(page) else { return };
+ use egui::{Key, Modifiers};
+ let mut step = egui::Vec2::ZERO;
+ ctx.input_mut(|i| {
+ for (key, direction) in [
+ (Key::ArrowLeft, egui::vec2(-1.0, 0.0)),
+ (Key::ArrowRight, egui::vec2(1.0, 0.0)),
+ (Key::ArrowUp, egui::vec2(0.0, -1.0)),
+ (Key::ArrowDown, egui::vec2(0.0, 1.0)),
+ ] {
+ // Shift first: a plain key pattern also matches a Shift press.
+ if i.consume_key(Modifiers::SHIFT, key) {
+ step += direction * 10.0;
+ } else if i.consume_key(Modifiers::NONE, key) {
+ step += direction;
+ }
+ }
+ });
+ if step == egui::Vec2::ZERO {
+ return;
+ }
+ // A point in view space whatever the zoom and whatever way the view is turned; the page's own
+ // rotation turns it into the user-space move the widget's rect is stored in.
+ let c = xf.rect.center();
+ let unit = |d: egui::Vec2| {
+ let (a, b) = (xf.screen_to_view(c), xf.screen_to_view(c + d));
+ let v = egui::vec2(b.0 - a.0, b.1 - a.1);
+ if v.length() > 0.0 { v / v.length() } else { egui::Vec2::ZERO }
+ };
+ let delta = unit(egui::vec2(1.0, 0.0)) * step.x + unit(egui::vec2(0.0, 1.0)) * step.y;
+ let Ok(offset) = doc.object_move_offset(page, [f64::from(delta.x), f64::from(delta.y)]) else { return };
+ let r = w.rect;
+ let rect = [r[0] + offset[0], r[1] + offset[1], r[2] + offset[0], r[3] + offset[1]];
+ view.pending_edit = Some(Edit::SetFieldProps { name, props: Box::new(FieldProps { rect: Some((wi, rect)), ..Default::default() }) });
+ }
+
+ /// Delete removes the selected fields; Escape clears the selection.
+ pub(crate) fn select_all(view: &mut DocView, form: &[FormField]) {
+ let mut selected =
+ form.iter().flat_map(|f| f.widgets.iter().enumerate().filter(|(_, w)| w.page == Some(view.current)).map(|(wi, _)| (f.name.clone(), wi)));
+ view.prepare.selected = selected.next();
+ view.prepare.also = selected.collect();
+ }
+
+ fn cancel_marquee(prep: &mut PrepareView) {
+ prep.grab = None;
+ prep.ignore_release = true;
+ if let Some(before) = prep.marquee_before.take() {
+ let mut before = before.into_iter();
+ prep.selected = before.next();
+ prep.also = before.collect();
+ }
+ }
+
+ pub(crate) fn keys(ctx: &egui::Context, view: &mut DocView) {
+ if ctx.egui_wants_keyboard_input() {
+ return;
+ }
+ if view.prepare.marquee_before.is_some() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
+ cancel_marquee(&mut view.prepare);
+ return;
+ }
+ if view.prepare.selected.is_none() {
+ return;
+ }
+ let (del, esc) = ctx.input(|i| (i.key_pressed(egui::Key::Delete) || i.key_pressed(egui::Key::Backspace), i.key_pressed(egui::Key::Escape)));
+ if del {
+ view.pending_edit = delete_selected(view);
+ } else if esc {
+ view.prepare.selected = None;
+ view.prepare.also.clear();
+ }
+ }
+
+ /// After an Add field edit: select the new field (the form's last).
+ pub(crate) fn after_refresh(view: &mut DocView, form: &[FormField]) {
+ view.prepare.also.retain(|(name, wi)| form.iter().any(|f| &f.name == name && *wi < f.widgets.len()));
+ if let Some(n) = view.prepare.select_added.take() {
+ if form.len() > n
+ && let Some(f) = form.last()
+ {
+ view.prepare.selected = Some((f.name.clone(), 0));
+ } else if let Some((name, _)) = &view.prepare.selected
+ && let Some(f) = form.iter().find(|f| &f.name == name)
+ {
+ // A radio button joined the selected group: select the new button.
+ view.prepare.selected = Some((f.name.clone(), f.widgets.len().saturating_sub(1)));
+ }
+ }
+ if let Some((name, wi)) = &view.prepare.selected
+ && !form.iter().any(|f| &f.name == name && *wi < f.widgets.len())
+ {
+ view.prepare.selected = None;
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use egui::pos2;
+
+ use super::*;
+
+ #[test]
+ fn corner_drags_stretch_freely_and_keep_proportions_with_shift() {
+ let r = Rect::from_min_max(pos2(100.0, 100.0), pos2(196.0, 132.0));
+ let free = dragged(r, Grab::Corner(false, false), vec2(24.0, 0.0), false);
+ assert_eq!(free, Rect::from_min_max(pos2(100.0, 100.0), pos2(220.0, 132.0)));
+ for (left, top) in [(true, true), (false, true), (true, false), (false, false)] {
+ let d = vec2(if left { -48.0 } else { 48.0 }, 0.0);
+ let out = dragged(r, Grab::Corner(left, top), d, true);
+ assert!((out.width() / out.height() - 3.0).abs() < 0.001, "{left} {top}: {out:?}");
+ // The opposite corner stays put.
+ assert_eq!(if left { out.max.x } else { out.min.x }, if left { r.max.x } else { r.min.x });
+ assert_eq!(if top { out.max.y } else { out.min.y }, if top { r.max.y } else { r.min.y });
+ }
+ assert_eq!(dragged(r, Grab::Move, vec2(5.0, 6.0), true), r.translate(vec2(5.0, 6.0)));
+ }
+ }
diff --cc parity/acrobat-features.toml
index 8a45bc069,bcba7a0ec..42d361c9a
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@@ -4811,8 -4811,8 +4811,8 @@@ milestone = "M6
status = "shipped"
commands = ["form.prepare"]
tools = ["form_add_field", "form_set_props", "form_delete_field"]
- evidence = ["crates/ui-egui/tests/it/prepare.rs::placing_moving_editing_and_deleting_a_field", "crates/ui-egui/tests/it/prepare.rs::deleting_one_radio_button_keeps_the_rest_of_its_group", "crates/ui-egui/tests/it/prepare.rs::deleting_two_radio_buttons_of_a_group_at_once", "crates/forms/src/tests.rs::deleting_one_radio_button_keeps_the_group_and_its_other_buttons", "crates/forms/src/tests.rs::deleting_the_chosen_radio_button_turns_the_group_off", "crates/forms/src/tests.rs::deleting_one_copy_of_a_field_keeps_the_field_and_its_value", "crates/automation/tests/it/automation.rs::deleting_one_radio_button_through_tools_keeps_the_group", "crates/ui-egui/tests/it/prepare.rs::arrow_keys_nudge_the_selected_field_instead_of_turning_the_page", "crates/ui-egui/src/prepare.rs::corner_drags_stretch_freely_and_keep_proportions_with_shift", "crates/ui-egui/tests/it/prepare.rs::deleting_several_selected_fields_and_detecting_fields_from_the_panel", "crates/engine/src/tests.rs::preparing_a_form_adds_renames_and_deletes_fields", "crates/ui-egui/tests/it/bulk_fields.rs::shared_properties_preserve_mixed_values_and_undo_the_whole_change", "crates/ui-egui/tests/it/bulk_fields.rs::select_all_in_prepare_a_form_selects_only_the_current_pages_fields", "crates/ui-egui/tests/it/bulk_fields.rs::dragging_an_empty_page_area_selects_fields_without_moving_them"]
-evidence = ["crates/ui-egui/tests/it/prepare.rs::placing_moving_editing_and_deleting_a_field", "crates/ui-egui/tests/it/prepare.rs::arrow_keys_nudge_the_selected_field_instead_of_turning_the_page", "crates/ui-egui/src/tools/prepare.rs::corner_drags_stretch_freely_and_keep_proportions_with_shift", "crates/ui-egui/tests/it/prepare.rs::deleting_several_selected_fields_and_detecting_fields_from_the_panel", "crates/engine/src/tests.rs::preparing_a_form_adds_renames_and_deletes_fields", "crates/ui-egui/tests/it/bulk_fields.rs::shared_properties_preserve_mixed_values_and_undo_the_whole_change", "crates/ui-egui/tests/it/bulk_fields.rs::select_all_in_prepare_a_form_selects_only_the_current_pages_fields", "crates/ui-egui/tests/it/bulk_fields.rs::dragging_an_empty_page_area_selects_fields_without_moving_them"]
-notes = "fields shown with blue fill and name tags; select, move (drag, or the arrow keys: a point, Shift ten points, #2608), resize by corners (Shift keeps the field's proportions, #2199), Delete (every selected field, one undo step); field tools return to Select after one field. Shared General, Appearance and applicable Options edits are atomic and opt-in; Ctrl/Command+A selects the current page, rectangle and panel selection are supported. Names, positions, choices/defaults and script tabs remain individual GUI edits"
++evidence = ["crates/ui-egui/tests/it/prepare.rs::placing_moving_editing_and_deleting_a_field", "crates/ui-egui/tests/it/prepare.rs::deleting_one_radio_button_keeps_the_rest_of_its_group", "crates/ui-egui/tests/it/prepare.rs::deleting_two_radio_buttons_of_a_group_at_once", "crates/forms/src/tests.rs::deleting_one_radio_button_keeps_the_group_and_its_other_buttons", "crates/forms/src/tests.rs::deleting_the_chosen_radio_button_turns_the_group_off", "crates/forms/src/tests.rs::deleting_one_copy_of_a_field_keeps_the_field_and_its_value", "crates/automation/tests/it/automation.rs::deleting_one_radio_button_through_tools_keeps_the_group", "crates/ui-egui/tests/it/prepare.rs::arrow_keys_nudge_the_selected_field_instead_of_turning_the_page", "crates/ui-egui/src/tools/prepare.rs::corner_drags_stretch_freely_and_keep_proportions_with_shift", "crates/ui-egui/tests/it/prepare.rs::deleting_several_selected_fields_and_detecting_fields_from_the_panel", "crates/engine/src/tests.rs::preparing_a_form_adds_renames_and_deletes_fields", "crates/ui-egui/tests/it/bulk_fields.rs::shared_properties_preserve_mixed_values_and_undo_the_whole_change", "crates/ui-egui/tests/it/bulk_fields.rs::select_all_in_prepare_a_form_selects_only_the_current_pages_fields", "crates/ui-egui/tests/it/bulk_fields.rs::dragging_an_empty_page_area_selects_fields_without_moving_them"]
+notes = "fields shown with blue fill and name tags; select, move (drag, or the arrow keys: a point, Shift ten points, #2608), resize by corners (Shift keeps the field's proportions, #2199), Delete (every selected field, one undo step; a selected radio button or copy of a duplicated field goes on its own and the rest of its group stays, a field's last widget takes the field, #4609); field tools return to Select after one field. Shared General, Appearance and applicable Options edits are atomic and opt-in; Ctrl/Command+A selects the current page, rectangle and panel selection are supported. Names, positions, choices/defaults and script tabs remain individual GUI edits"
[[feature]]
id = "form.add-text-field"