PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
M5: Add a stamp: palette of Dynamic (By author at time, date), Sign Here and Standard Business stamps in PrintCraft's own design (ISO stamp names where defined; foreign stamps keep their artwork); click to place; comment_add type stamp
Brandon Thomasf31d89bc9d99
diff --git a/crates/annot/src/appearance.rs b/crates/annot/src/appearance.rsindex d4fe78d58..8c5a31fa4 100644--- a/crates/annot/src/appearance.rs+++ b/crates/annot/src/appearance.rs@@ -341,7 +341,15 @@ pub fn build(d: &Dict) -> Option<Stream> {n(x1),n(y0 + h / 2.0))),- _ => return None,+ other => {+ // Only stamps PrintCraft made: others keep their own artwork.+ if !matches!(d.get(b"PCStamp"), Some(Object::Bool(true))) {+ return None;+ }+ let kind = crate::StampKind::from_name(other)?;+ let by = d.get(b"PCByLine").and_then(|o| o.as_string()).map(PdfString::to_text);+ return Some(stamp(kind, rect, stroke.unwrap_or(kind.color()), by.as_deref(), opacity, res));+ }}}b"FreeText" => {@@ -414,6 +422,130 @@ pub fn build(d: &Dict) -> Option<Stream> {Some(form(rect, c.as_bytes(), res))}+/// A rubber stamp: a rounded frame (a pointed tag for sign-here stamps) with the label in bold+/// capitals, and the dynamic stamps' "By … at …" line.+fn stamp(kind: crate::StampKind, rect: [f64; 4], col: Rgb, by: Option<&str>, opacity: f64, mut res: Dict) -> Stream {+ let [x0, y0, x1, y1] = rect;+ let h = y1 - y0;+ let mut c = String::new();+ if opacity < 1.0 {+ c.push_str("/GS0 gs\n");+ }+ let lw = (h * 0.07).clamp(1.0, 3.0);+ let inset = lw / 2.0 + 0.5;+ if kind.group() == crate::StampGroup::SignHere {+ // A tag pointing left, filled, with white text.+ let tip = h * 0.45;+ c.push_str(&format!(+ "{}{}{} w 1 j\n{} {} m {} {} l {} {} l {} {} l {} {} l h B\n",+ rg(col),+ rg_stroke(col),+ n(lw),+ n(x0 + inset),+ n(y0 + h / 2.0),+ n(x0 + tip),+ n(y1 - inset),+ n(x1 - inset),+ n(y1 - inset),+ n(x1 - inset),+ n(y0 + inset),+ n(x0 + tip),+ n(y0 + inset)+ ));+ } else {+ // A rounded frame with a light tint.+ let r = (h * 0.2).min(8.0);+ let k = 0.552_284_75 * r;+ let (a0, b0, a1, b1) = (x0 + inset, y0 + inset, x1 - inset, y1 - inset);+ let tint = col.map(|v| 1.0 - (1.0 - v) * 0.12);+ c.push_str(&format!(+ "{}{}{} w\n{} {} m {} {} l {} {} {} {} {} {} c {} {} l {} {} {} {} {} {} c {} {} l {} {} {} {} {} {} c {} {} l {} {} {} {} {} {} c h B\n",+ rg(tint),+ rg_stroke(col),+ n(lw),+ n(a0 + r),+ n(b0),+ n(a1 - r),+ n(b0),+ n(a1 - r + k),+ n(b0),+ n(a1),+ n(b0 + r - k),+ n(a1),+ n(b0 + r),+ n(a1),+ n(b1 - r),+ n(a1),+ n(b1 - r + k),+ n(a1 - r + k),+ n(b1),+ n(a1 - r),+ n(b1),+ n(a0 + r),+ n(b1),+ n(a0 + r - k),+ n(b1),+ n(a0),+ n(b1 - r + k),+ n(a0),+ n(b1 - r),+ n(a0),+ n(b0 + r),+ n(a0),+ n(b0 + r - k),+ n(a0 + r - k),+ n(b0),+ n(a0 + r),+ n(b0)+ ));+ }+ let label = kind.label();+ let (title_h, by_h) = if by.is_some() { (h * 0.5, h * 0.22) } else { (h * 0.52, 0.0) };+ let text_area = if kind.group() == crate::StampGroup::SignHere { (x0 + h * 0.45, x1 - lw * 2.0) } else { (x0 + lw * 2.0, x1 - lw * 2.0) };+ let mut size = title_h;+ let tw = text_width(label, size) * 1.12;+ if tw > text_area.1 - text_area.0 - 4.0 {+ size *= (text_area.1 - text_area.0 - 4.0) / tw;+ }+ let tw = text_width(label, size) * 1.12;+ let text_col = if kind.group() == crate::StampGroup::SignHere { [1.0, 1.0, 1.0] } else { col };+ let ty = if by.is_some() { y0 + h * 0.48 } else { y0 + (h - size * 0.72) / 2.0 };+ let mut out = c.into_bytes();+ out.extend(+ format!("BT\n{}/HelvB {} Tf\n1 0 0 1 {} {} Tm ", rg(text_col), n(size), n(text_area.0 + (text_area.1 - text_area.0 - tw) / 2.0), n(ty))+ .bytes(),+ );+ out.extend(literal(&win_ansi(label)));+ out.extend_from_slice(b" Tj\n");+ if let Some(b) = by {+ let mut s = by_h;+ let bw = text_width(b, s);+ if bw > text_area.1 - text_area.0 - 4.0 {+ s *= (text_area.1 - text_area.0 - 4.0) / bw;+ }+ let bw = text_width(b, s);+ out.extend(+ format!("/Helv {} Tf\n1 0 0 1 {} {} Tm ", n(s), n(text_area.0 + (text_area.1 - text_area.0 - bw) / 2.0), n(y0 + h * 0.18)).bytes(),+ );+ out.extend(literal(&win_ansi(b)));+ out.extend_from_slice(b" Tj\n");+ }+ out.extend_from_slice(b"ET\n");+ let font = |base: &str| {+ let mut f = Dict::new();+ f.set(b"Type".to_vec(), Object::name("Font"));+ f.set(b"Subtype".to_vec(), Object::name("Type1"));+ f.set(b"BaseFont".to_vec(), Object::name(base));+ f.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));+ Object::Dict(f)+ };+ let mut fonts = Dict::new();+ fonts.set(b"HelvB".to_vec(), font("Helvetica-Bold"));+ fonts.set(b"Helv".to_vec(), font("Helvetica"));+ res.set(b"Font".to_vec(), Object::Dict(fonts));+ form(rect, &out, res)+}+/// An ellipse inscribed in a rectangle, as four Bézier arcs.fn ellipse(x0: f64, y0: f64, x1: f64, y1: f64) -> String {let k = 0.552_284_75;diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rsindex e47aefc2c..5f68ab966 100644--- a/crates/annot/src/lib.rs+++ b/crates/annot/src/lib.rs@@ -118,6 +118,159 @@ impl FillMark {}}+/// The stamps of Acrobat's stamp palette (drawn in PrintCraft's own style).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum StampKind {+ // Standard business.+ Approved,+ Completed,+ Confidential,+ Draft,+ Final,+ ForComment,+ ForPublicRelease,+ InformationOnly,+ NotApproved,+ NotForPublicRelease,+ PreliminaryResults,+ Void,+ // Sign here.+ Accepted,+ InitialHere,+ Rejected,+ SignHere,+ Witness,+ // Dynamic (with a "By … at …" line).+ DynApproved,+ DynConfidential,+ DynReceived,+ DynReviewed,+ DynRevised,+}++/// The palette's sections.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum StampGroup {+ Dynamic,+ SignHere,+ StandardBusiness,+}++impl StampKind {+ pub const ALL: [StampKind; 22] = [+ StampKind::DynApproved,+ StampKind::DynConfidential,+ StampKind::DynReceived,+ StampKind::DynReviewed,+ StampKind::DynRevised,+ StampKind::Accepted,+ StampKind::InitialHere,+ StampKind::Rejected,+ StampKind::SignHere,+ StampKind::Witness,+ StampKind::Approved,+ StampKind::Completed,+ StampKind::Confidential,+ StampKind::Draft,+ StampKind::Final,+ StampKind::ForComment,+ StampKind::ForPublicRelease,+ StampKind::InformationOnly,+ StampKind::NotApproved,+ StampKind::NotForPublicRelease,+ StampKind::PreliminaryResults,+ StampKind::Void,+ ];++ pub fn group(self) -> StampGroup {+ use StampKind::*;+ match self {+ DynApproved | DynConfidential | DynReceived | DynReviewed | DynRevised => StampGroup::Dynamic,+ Accepted | InitialHere | Rejected | SignHere | Witness => StampGroup::SignHere,+ _ => StampGroup::StandardBusiness,+ }+ }++ /// The text on the stamp.+ pub fn label(self) -> &'static str {+ use StampKind::*;+ match self {+ Approved | DynApproved => "APPROVED",+ Completed => "COMPLETED",+ Confidential | DynConfidential => "CONFIDENTIAL",+ Draft => "DRAFT",+ Final => "FINAL",+ ForComment => "FOR COMMENT",+ ForPublicRelease => "FOR PUBLIC RELEASE",+ InformationOnly => "INFORMATION ONLY",+ NotApproved => "NOT APPROVED",+ NotForPublicRelease => "NOT FOR PUBLIC RELEASE",+ PreliminaryResults => "PRELIMINARY RESULTS",+ Void => "VOID",+ Accepted => "ACCEPTED",+ InitialHere => "INITIAL HERE",+ Rejected => "REJECTED",+ SignHere => "SIGN HERE",+ Witness => "WITNESS",+ DynReceived => "RECEIVED",+ DynReviewed => "REVIEWED",+ DynRevised => "REVISED",+ }+ }++ /// `/Name`: the standard stamp names of ISO 32000-2 Table 184 where one exists.+ pub fn name(self) -> &'static str {+ use StampKind::*;+ match self {+ Approved => "Approved",+ Confidential => "Confidential",+ Draft => "Draft",+ Final => "Final",+ ForComment => "ForComment",+ ForPublicRelease => "ForPublicRelease",+ NotApproved => "NotApproved",+ NotForPublicRelease => "NotForPublicRelease",+ Completed => "PCCompleted",+ InformationOnly => "PCInformationOnly",+ PreliminaryResults => "PCPreliminaryResults",+ Void => "PCVoid",+ Accepted => "PCAccepted",+ InitialHere => "PCInitialHere",+ Rejected => "PCRejected",+ SignHere => "PCSignHere",+ Witness => "PCWitness",+ DynApproved => "PCDynApproved",+ DynConfidential => "PCDynConfidential",+ DynReceived => "PCDynReceived",+ DynReviewed => "PCDynReviewed",+ DynRevised => "PCDynRevised",+ }+ }++ pub fn from_name(n: &[u8]) -> Option<Self> {+ Self::ALL.into_iter().find(|k| k.name().as_bytes() == n)+ }++ /// The stamp's colour: green for approval, red for refusal and restriction, blue otherwise.+ pub fn color(self) -> Rgb {+ use StampKind::*;+ match self {+ Approved | Completed | Final | Accepted | DynApproved | DynReceived | DynReviewed => [0.13, 0.55, 0.13],+ NotApproved | Rejected | Void | Confidential | NotForPublicRelease | DynConfidential => [0.80, 0.10, 0.10],+ SignHere | InitialHere | Witness => [0.85, 0.35, 0.05],+ _ => [0.10, 0.30, 0.70],+ }+ }++ /// The stamp's size (points) for its label, as placed with a click.+ pub fn size(self) -> (f64, f64) {+ let w = appearance::text_width(self.label(), 16.0) * 1.12 + 24.0;+ let h = if self.group() == StampGroup::Dynamic { 42.0 } else { 30.0 };+ let w = if self.group() == StampGroup::SignHere { w + 14.0 } else { w };+ (w.max(80.0), h)+ }+}+/// Geometry of a new comment, in PDF user space of its page.#[derive(Clone, Debug, PartialEq)]pub enum Shape {@@ -167,6 +320,12 @@ pub enum Shape {Signature {strokes: Vec<Vec<[f64; 2]>>,},+ /// A rubber stamp from the stamp palette; `by` is the dynamic stamps' second line.+ Stamp {+ rect: [f64; 4],+ stamp: StampKind,+ by: Option<String>,+ },/// A redaction mark (§12.5.6.23) over quadrilaterals (text) or one rectangle as a quad/// (areas, pages). `overlay` is the text shown on the box once applied.Redact {@@ -192,7 +351,7 @@ impl Shape {Shape::Line { .. } => "Line",Shape::Ink { .. } | Shape::Signature { .. } => "Ink",Shape::TextBox { .. } | Shape::Typewriter { .. } => "FreeText",- Shape::Mark { .. } => "Stamp",+ Shape::Mark { .. } | Shape::Stamp { .. } => "Stamp",Shape::Redact { .. } => "Redact",}}@@ -231,6 +390,7 @@ impl Style {Shape::TextBox { .. } | Shape::Typewriter { .. } => ([0.0, 0.0, 0.0], 0.0),Shape::Mark { .. } => ([0.0, 0.0, 0.0], 1.5),Shape::Signature { .. } => ([0.0, 0.0, 0.0], 1.5),+ Shape::Stamp { stamp, .. } => (stamp.color(), 2.0),// Red outline while marked; a black box once applied.Shape::Redact { .. } => return Self { color: [0.89, 0.13, 0.13], opacity: 1.0, width: 1.0, fill: Some([0.0, 0.0, 0.0]) },};@@ -419,6 +579,7 @@ fn rect_for(shape: &Shape, style: &Style) -> Result<[f64; 4], AnnotError> {| Shape::Oval { rect }| Shape::TextBox { rect, .. }| Shape::Typewriter { rect, .. }+ | Shape::Stamp { rect, .. }| Shape::Mark { rect, .. } => {let r = normalize(*rect);if !finite(rect) || r[2] - r[0] < 1.0 || r[3] - r[1] < 1.0 {@@ -482,6 +643,11 @@ fn subject(shape: &Shape) -> &'static str {Shape::Mark { mark, .. } => mark.label(),Shape::Signature { .. } => "Signature",Shape::Redact { .. } => "Redact",+ Shape::Stamp { stamp, .. } => match stamp.group() {+ StampGroup::Dynamic => "Dynamic stamp",+ StampGroup::SignHere => "Sign Here",+ StampGroup::StandardBusiness => "Stamp",+ },}}@@ -548,6 +714,16 @@ pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> Rd.set(b"Name".to_vec(), Object::name(mark.name()));border(&mut d);}+ Shape::Stamp { stamp, by, .. } => {+ d.set(b"C".to_vec(), rgb(style.color));+ d.set(b"Name".to_vec(), Object::name(stamp.name()));+ // Marks the stamp as drawn by PrintCraft: other stamps with standard names keep+ // their own artwork.+ d.set(b"PCStamp".to_vec(), Object::Bool(true));+ if let Some(b) = by {+ d.set(b"PCByLine".to_vec(), PdfString::text(b));+ }+ }Shape::Ink { strokes } | Shape::Signature { strokes } => {d.set(b"C".to_vec(), rgb(style.color));let list = strokes.iter().filter(|s| !s.is_empty()).map(|s| num_array(&s.concat())).collect();diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rsindex 4eeeecdda..d26360f27 100644--- a/crates/annot/src/tests.rs+++ b/crates/annot/src/tests.rs@@ -345,3 +345,30 @@ fn author_subject_and_note_icon_change() {assert_ne!(ap_content(&doc, d), before, "the icon was redrawn");assert!(matches!(set_info(&mut doc, 0, 0, None, None, Some(NoteIcon::Key), &meta("")), Err(AnnotError::Invalid(_))));}++#[test]+fn stamps_draw_their_label_and_by_line() {+ let mut doc = fixture();+ let shape =+ Shape::Stamp { rect: [100.0, 100.0, 260.0, 142.0], stamp: StampKind::DynApproved, by: Some("By Ada at 2:14 pm, Oct 02, 2026".into()) };+ let i = add_annotation(+ &mut doc,+ &NewAnnotation { page: 0, style: Style::default_for(&shape), shape, contents: String::new(), author: "Ada".into() },+ &Meta::default(),+ )+ .unwrap();+ let s = &summaries(&doc)[0];+ assert_eq!((s.subtype.as_str(), s.index), ("Stamp", i));+ let ap = ap_content(&doc, &list(&doc, 0)[i]);+ assert!(ap.contains("(APPROVED) Tj") && ap.contains("(By Ada at 2:14 pm, Oct 02, 2026) Tj") && ap.contains("/HelvB"), "{ap}");+ let sign = Shape::Stamp { rect: [100.0, 300.0, 220.0, 330.0], stamp: StampKind::SignHere, by: None };+ let j = add_annotation(+ &mut doc,+ &NewAnnotation { page: 0, style: Style::default_for(&sign), shape: sign, contents: String::new(), author: "Ada".into() },+ &Meta::default(),+ )+ .unwrap();+ assert!(ap_content(&doc, &list(&doc, 0)[j]).contains("(SIGN HERE) Tj"));+ assert_eq!(StampKind::from_name(b"Approved"), Some(StampKind::Approved), "standard names");+ assert!(StampKind::ALL.iter().all(|k| k.size().0 >= 80.0));+}diff --git a/crates/automation/src/comments.rs b/crates/automation/src/comments.rsindex 94f3ea247..50be4a1e2 100644--- a/crates/automation/src/comments.rs+++ b/crates/automation/src/comments.rs@@ -3,7 +3,7 @@//! Geometry follows the automation convention: points from the top-left of the displayed page,//! y down. It is converted to PDF user space (crop box, `/Rotate`) here.-use printcraft_engine::{Edit, Markup, NewAnnotation, NoteIcon, ReviewState, Rgb, Shape, Style};+use printcraft_engine::{Edit, Markup, NewAnnotation, NoteIcon, ReviewState, Rgb, Shape, StampGroup, StampKind, Style};use printcraft_render::{Annotation, PageInfo};use serde_json::{Value, json};@@ -189,6 +189,20 @@ impl Automation {};Shape::Note { at: to_user(&info, x, y), icon }}+ "stamp" => {+ let want = a.opt_str("stamp")?.unwrap_or("approved").to_ascii_lowercase().replace([' ', '-', '_'], "");+ let dynamic = a.opt_bool("dynamic")?.unwrap_or(false);+ let stamp = StampKind::ALL+ .into_iter()+ .find(|k| k.label().to_ascii_lowercase().replace(' ', "") == want && ((k.group() == StampGroup::Dynamic) == dynamic))+ .ok_or_else(|| ToolError::InvalidArgs(format!("unknown stamp {want:?} (see the tool description)")))?;+ let (w, h) = stamp.size();+ let [x, y] = a.need::<2>("at", "a stamp (its centre)")?;+ let rect = rect_to_user(&info, [x - w / 2.0, y - h / 2.0, x + w / 2.0, y + h / 2.0]);+ let author = a.opt_str("author")?.unwrap_or(DEFAULT_AUTHOR).to_string();+ let by = dynamic.then(|| self.session.stamp_by_line(&author));+ Shape::Stamp { rect, stamp, by }+ }"rectangle" => Shape::Rectangle { rect: rect_to_user(&info, a.need::<4>("rect", "a rectangle")?) },"oval" => Shape::Oval { rect: rect_to_user(&info, a.need::<4>("rect", "an oval")?) },"textbox" => {diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rsindex 85b5d99d2..e49349329 100644--- a/crates/automation/src/tools.rs+++ b/crates/automation/src/tools.rs@@ -407,14 +407,14 @@ pub fn tools() -> Vec<ToolDef> {"comment_add","Add a comment","Add a comment as Acrobat's commenting tools do. Geometry is in points with the origin at the top-left of the displayed page, y down (as in page_render images at 72 dpi and text_find rects). \- note: `at` [x, y] (icon top-left). highlight/underline/strikeout/squiggly: `find` (text on the page to mark; every match with all: true) or `quads`. \+ note: `at` [x, y] (icon top-left). stamp: `at` [x, y] (its centre) and `stamp`: approved, completed, confidential, draft, final, for comment, for public release, information only, not approved, not for public release, preliminary results, void, accepted, initial here, rejected, sign here, witness; dynamic: true for the dynamic approved/confidential/received/reviewed/revised stamps with a By … at … line. highlight/underline/strikeout/squiggly: `find` (text on the page to mark; every match with all: true) or `quads`. \rectangle/oval/textbox: `rect` [x0, y0, x1, y1]. line/arrow: `from`, `to`. ink: `strokes` [[[x, y], …], …]. Undoable.",).with(schema(json!({"doc": doc(),"page": { "type": "integer", "minimum": 1 },- "type": { "type": "string", "enum": ["note", "highlight", "underline", "strikeout", "squiggly", "rectangle", "oval", "line", "arrow", "ink", "textbox"] },+ "type": { "type": "string", "enum": ["note", "highlight", "underline", "strikeout", "squiggly", "rectangle", "oval", "line", "arrow", "ink", "textbox", "stamp"] },"contents": { "type": "string", "description": "The comment text (what a text box shows)." },"author": { "type": "string" },"at": point(),@@ -424,6 +424,8 @@ pub fn tools() -> Vec<ToolDef> {"find": { "type": "string", "description": "Text on the page to mark up (case-insensitive)." },"all": { "type": "boolean", "description": "Mark every match of `find` on the page, not just the first." },"quads": { "type": "array", "items": { "type": "array", "items": { "type": "number" }, "minItems": 8, "maxItems": 8 } },+ "stamp": { "type": "string" },+ "dynamic": { "type": "boolean" },"strokes": { "type": "array", "items": { "type": "array", "items": point() } },"icon": { "type": "string", "enum": ["Comment", "Note", "Help", "Insert", "Key", "NewParagraph", "Paragraph"] },"color": color(),diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rsindex 59a9df7de..7e8b7d90e 100644--- a/crates/automation/tests/automation.rs+++ b/crates/automation/tests/automation.rs@@ -803,3 +803,25 @@ fn comments_and_form_data_travel_as_xfdf_fdf_and_text() {assert_eq!(list["comments"][0]["contents"], "Please review", "{list}");assert_eq!(r["undo"], "Import all.xfdf");}++#[test]+fn stamps_through_tools() {+ let dir = workdir("stamps");+ let mut a = auto(&dir);+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();+ ok(&mut a, "comment_add", json!({ "doc": doc, "page": 1, "type": "stamp", "stamp": "approved", "at": [100, 100] }));+ ok(+ &mut a,+ "comment_add",+ json!({ "doc": doc, "page": 1, "type": "stamp", "stamp": "reviewed", "dynamic": true, "at": [100, 200], "author": "Ada" }),+ );+ ok(&mut a, "comment_add", json!({ "doc": doc, "page": 1, "type": "stamp", "stamp": "sign here", "at": [100, 250] }));+ let list = ok(&mut a, "comment_list", json!({ "doc": doc }));+ assert_eq!(list["count"], 3, "{list}");+ let text = page_text(&mut a, doc)[0].clone();+ assert!(text.contains("APPROVED") && text.contains("REVIEWED") && text.contains("By Ada at") && text.contains("SIGN HERE"), "{text}");+ assert!(matches!(+ a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "stamp", "stamp": "nonsense", "at": [1, 1] })),+ Err(ToolError::InvalidArgs(_))+ ));+}diff --git a/crates/engine/src/catalog.rs b/crates/engine/src/catalog.rsindex 52a69d1d6..a548bc670 100644--- a/crates/engine/src/catalog.rs+++ b/crates/engine/src/catalog.rs@@ -348,8 +348,8 @@ pub static TOOL_GROUPS: &[ToolGroup] = &[icon: "stamp",hue: PURPLE,badge: None,- availability: Planned("M5"),- sections: &[ToolSection { title: "Stamps", items: &[item("Stamp palette", "stamp", "comment.stamp", Planned("M5"))] }],+ availability: Ready,+ sections: &[ToolSection { title: "Stamps", items: &[item("Stamp palette", "stamp", "comment.stamp", Ready)] }],},ToolGroup {id: "certificate",diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 1aa601e85..ade571098 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -179,6 +179,7 @@ pub const COMMANDS: &[CommandSpec] = &[c("form.clear", "Clear form", EDIT, None, FillForms, "eraser"),c("comment.flatten", "Flatten comments", None, None, HasComments, "layers"),c("comment.import", "Import comments…", None, None, Modification, "file-input"),+ c("comment.stamp", "Add a stamp", None, None, Annotate, "stamp"),c("comment.export", "Export all comments to data file…", None, None, HasComments, "file-output"),c("form.import_data", "Import form data…", None, None, HasFields, "file-input"),c("form.export_data", "Export form data…", None, None, HasFields, "file-output"),diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex b7016f98f..b524e0f21 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -31,7 +31,9 @@ pub use printcraft_forms::{/// Comment geometry helpers (text-box line breaking) for frontends.pub use printcraft_annot::appearance as annot_text;-pub use printcraft_annot::{FillMark, Markup, NewAnnotation, NoteIcon, Props as CommentProps, ReviewState, Rgb, Shape, Style, rect_quad};+pub use printcraft_annot::{+ FillMark, Markup, NewAnnotation, NoteIcon, Props as CommentProps, ReviewState, Rgb, Shape, StampGroup, StampKind, Style, rect_quad,+};pub use printcraft_print as print;pub use printcraft_redact::patterns::{PATTERNS as REDACT_PATTERNS, Pattern as RedactPattern, find as find_pattern};pub use printcraft_redact::sanitize::{HIDDEN, Hidden};@@ -720,6 +722,7 @@ fn annotation_noun(s: &Shape) -> &'static str {Shape::Mark { mark: FillMark::Line, .. } => "line",Shape::Signature { .. } => "signature",Shape::Redact { .. } => "redaction mark",+ Shape::Stamp { .. } => "stamp",}}@@ -1162,6 +1165,18 @@ impl Session {/// Today's date in local time: (year, month, day). With an injected clock (tests) the clock/// is taken as local time.+ /// A dynamic stamp's second line: "By Ada at 2:14 pm, Oct 02, 2026" (local time).+ pub fn stamp_by_line(&self, author: &str) -> String {+ let offset = if self.clock.is_some() { 0 } else { local_utc_offset() };+ let d = self.now().map(|t| printcraft_cos::pdf_date(t + offset)).unwrap_or_default();+ let num = |a: usize, b: usize| d.get(a..b).and_then(|s| s.parse::<u32>().ok()).unwrap_or(0);+ let (y, mo, day, hh, mm) = (num(2, 6), num(6, 8), num(8, 10), num(10, 12), num(12, 14));+ const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];+ let h12 = if hh % 12 == 0 { 12 } else { hh % 12 };+ let who = if author.trim().is_empty() { String::new() } else { format!("By {} ", author.trim()) };+ format!("{who}at {h12}:{mm:02} {}, {} {day:02}, {y}", if hh < 12 { "am" } else { "pm" }, MONTHS[(mo.clamp(1, 12) - 1) as usize])+ }+pub fn today(&self) -> (i64, u32, u32) {let offset = if self.clock.is_some() { 0 } else { local_utc_offset() };self.now().map(|t| printcraft_cos::pdf_date(t + offset)).as_deref().and_then(parse_ymd).unwrap_or((1970, 1, 1))diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 8140467f4..4d09b5321 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -888,7 +888,7 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {QuickTool::Comment(t) => t.markup().is_some(),QuickTool::Select => !preparing,QuickTool::Redact => true,- QuickTool::Hand | QuickTool::Crop | QuickTool::Fill(_) | QuickTool::Field(_) | QuickTool::AddText => false,+ QuickTool::Hand | QuickTool::Crop | QuickTool::Fill(_) | QuickTool::Field(_) | QuickTool::AddText | QuickTool::Stamp(_) => false,};let prefs = &app.comment_prefs;let allowed = doc.allows_annotation();@@ -899,6 +899,8 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {let signature = app.signature.clone();let author = app.comment_prefs.author.clone();let today = app.session.today();+ let by_line = app.session.stamp_by_line(&author);+ let mut stamp_placed = false;let mut open_signature = false;let mut hover_text: Option<(Pos2, String)> = None;let mut clicked_link: Option<LinkTarget> = None;@@ -1038,6 +1040,30 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {let pcx = comments::PageCx { page: i, xf: &xf, info, tool, prefs, allowed };// Form fields take clicks first with the Select tool (as Acrobat fills fields in// every viewing mode); then comments; then text selection.+ if let QuickTool::Stamp(kind) = tool+ && allowed+ && let Some(p) = ui.input(|inp| inp.pointer.hover_pos()).filter(|p| xf.rect.contains(*p))+ {+ ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair);+ if resp.clicked() {+ // Centred on the click, upright as the page is shown.+ let (vx, vy) = xf.screen_to_view(p);+ let (w, h) = kind.size();+ let corners = [(vx as f64 - w / 2.0, vy as f64 - h / 2.0), (vx as f64 + w / 2.0, vy as f64 + h / 2.0)];+ let u: Vec<[f32; 2]> = corners.iter().map(|(x, y)| info.pages[i].view_to_user(*x as f32, *y as f32)).collect();+ let rect = [u[0][0].min(u[1][0]) as f64, u[0][1].min(u[1][1]) as f64, u[0][0].max(u[1][0]) as f64, u[0][1].max(u[1][1]) as f64];+ let by = (kind.group() == printcraft_engine::StampGroup::Dynamic).then(|| by_line.clone());+ let shape = printcraft_engine::Shape::Stamp { rect, stamp: kind, by };+ view.pending_edit = Some(printcraft_engine::Edit::AddAnnotation(printcraft_engine::NewAnnotation {+ page: i,+ style: printcraft_engine::Style::default_for(&shape),+ shape,+ contents: String::new(),+ author: author.clone(),+ }));+ stamp_placed = true;+ }+ }if let QuickTool::Fill(ft) = tool&& allowed{@@ -1310,6 +1336,9 @@ pub fn document_area(app: &mut PrintCraftApp, index: usize, ui: &mut egui::Ui) {if editing_content {crate::content_ui::keys(ui.ctx(), view);}+ if stamp_placed {+ tool = QuickTool::Select;+ }// One text box, then back to selecting (as Acrobat does).if content_done && tool == QuickTool::AddText {tool = QuickTool::Select;diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rsindex e9cd97ac6..cf4b7e75d 100644--- a/crates/ui-egui/src/commands.rs+++ b/crates/ui-egui/src/commands.rs@@ -278,6 +278,10 @@ impl PrintCraftApp {self.apply_edit(Edit::SetTabOrder { pages: (0..n).collect(), order });}"comment.import" | "form.import_data" => self.import_data_dialog(),+ "comment.stamp" => {+ self.left = crate::LeftPanel::Tool("stamp");+ self.left_open = true;+ }"comment.export" => self.export_data_dialog(true, false),"form.export_data" => self.export_data_dialog(false, true),"form.prepare" => {diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rsindex be0703b3d..668634de2 100644--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@ -540,6 +540,7 @@ impl Host for crate::PrintCraftApp {crate::QuickTool::Crop => "crop".to_string(),crate::QuickTool::Redact => "redact".to_string(),crate::QuickTool::AddText => "add-text".to_string(),+ crate::QuickTool::Stamp(k) => format!("stamp-{}", k.name().trim_start_matches("PC").to_ascii_lowercase()),crate::QuickTool::Fill(f) => format!("fill-{}", f.command().trim_start_matches("sign.fill.")),crate::QuickTool::Field(f) => format!("field-{}", f.command().trim_start_matches("form.add.")),crate::QuickTool::Comment(t) => t.command().trim_start_matches("comment.").to_string(),diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 8c8e391c5..b2d1b7a95 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -95,6 +95,8 @@ pub enum QuickTool {Redact,/// Edit a PDF ▸ Add content ▸ Text.AddText,+ /// Add a stamp: click to place this stamp.+ Stamp(printcraft_engine::StampKind),}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -706,6 +708,12 @@ impl PrintCraftApp {"crop" => QuickTool::Crop,"redact" => QuickTool::Redact,"add-text" => QuickTool::AddText,+ stamp if stamp.starts_with("stamp-") => QuickTool::Stamp(+ printcraft_engine::StampKind::ALL+ .into_iter()+ .find(|k| k.name().trim_start_matches("PC").eq_ignore_ascii_case(&stamp[6..]))+ .ok_or_else(|| format!("unknown stamp {stamp}"))?,+ ),field if field.starts_with("field-") => QuickTool::Field(prepare::FieldTool::from_command(&format!("form.add.{}", &field[6..])).ok_or_else(|| format!("unknown tool {field}"))?,),diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 4622c5e24..214e4286c 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -125,6 +125,11 @@ fn tool_detail(app: &mut PrintCraftApp, ui: &mut egui::Ui, t: &Tokens, g: &'stat);});}+ // Add a stamp: the palette.+ if g.id == "stamp" {+ stamp_palette(app, ui, t);+ return;+ }// Edit a PDF shows Format text at the top while text is selected or being added.if g.id == "edit" {format_section(app, ui, t);@@ -190,6 +195,67 @@ fn tool_detail(app: &mut PrintCraftApp, ui: &mut egui::Ui, t: &Tokens, g: &'stat}}+/// Add a stamp: Dynamic, Sign Here and Standard Business stamps; click one, then click on the+/// page to place it.+fn stamp_palette(app: &mut PrintCraftApp, ui: &mut egui::Ui, t: &Tokens) {+ use printcraft_engine::{StampGroup, StampKind};+ ui.label(egui::RichText::new("Choose a stamp, then click on the page to place it.").small().color(t.text_faint));+ egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {+ for (group, title) in+ [(StampGroup::Dynamic, "Dynamic"), (StampGroup::SignHere, "Sign Here"), (StampGroup::StandardBusiness, "Standard Business")]+ {+ widgets::section_title(ui, title);+ for kind in StampKind::ALL.into_iter().filter(|k| k.group() == group) {+ let active = app.quick_tool == crate::QuickTool::Stamp(kind);+ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 38.0), Sense::click());+ resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, true, active, kind.label()));+ if active {+ ui.painter().rect_filled(rect, CornerRadius::same(6), t.accent_soft);+ } else if resp.hovered() {+ ui.painter().rect_filled(rect, CornerRadius::same(6), t.hover);+ }+ let [r, g, b] = kind.color().map(|v| (v * 255.0) as u8);+ let col = Color32::from_rgb(r, g, b);+ let chip = Rect::from_min_size(rect.min + vec2(8.0, 5.0), vec2((rect.width() - 16.0).min(200.0), 28.0));+ if group == StampGroup::SignHere {+ let tip = chip.height() * 0.45;+ let pts = vec![+ chip.left_center(),+ chip.left_top() + vec2(tip, 0.0),+ chip.right_top(),+ chip.right_bottom(),+ chip.left_bottom() + vec2(tip, 0.0),+ ];+ ui.painter().add(egui::Shape::convex_polygon(pts, col, Stroke::NONE));+ ui.painter().text(+ chip.center() + vec2(tip / 2.0, 0.0),+ Align2::CENTER_CENTER,+ kind.label(),+ theme::semibold(11.0),+ Color32::WHITE,+ );+ } else {+ ui.painter().rect(chip, CornerRadius::same(5), col.gamma_multiply(0.1), Stroke::new(1.5, col), egui::StrokeKind::Inside);+ let y = if group == StampGroup::Dynamic { chip.center().y - 4.0 } else { chip.center().y };+ ui.painter().text(egui::pos2(chip.center().x, y), Align2::CENTER_CENTER, kind.label(), theme::semibold(11.0), col);+ if group == StampGroup::Dynamic {+ ui.painter().text(+ egui::pos2(chip.center().x, chip.bottom() - 6.0),+ Align2::CENTER_CENTER,+ "By name at time, date",+ theme::regular(7.5),+ col,+ );+ }+ }+ if resp.clicked() {+ app.quick_tool = crate::QuickTool::Stamp(kind);+ }+ }+ }+ });+}+/// Edit a PDF ▸ Format text: for the selected added text (one undoable change), or the style/// new text gets.fn format_section(app: &mut PrintCraftApp, ui: &mut egui::Ui, t: &Tokens) {diff --git a/crates/ui-egui/tests/stamps.rs b/crates/ui-egui/tests/stamps.rsnew file mode 100644index 000000000..daafe1ba7--- /dev/null+++ b/crates/ui-egui/tests/stamps.rs@@ -0,0 +1,44 @@+//! Add a stamp: the palette and placing stamps on the page.++use egui_kittest::Harness;+use egui_kittest::kittest::Queryable;+use printcraft_ui_egui::{PrintCraftApp, QuickTool};++#[test]+fn choosing_and_placing_stamps() {+ let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|_cc| {+ let mut app = PrintCraftApp::new();+ app.open_bytes("form.pdf", None, include_bytes!("data/form.pdf").to_vec()).unwrap();+ app.set_option("zoom", "150").unwrap();+ app+ });+ h.run_steps(6);+ assert!(h.state_mut().execute("comment.stamp"));+ h.run_steps(2);+ h.get_by_label("Add a stamp");+ h.get_all_by_label("APPROVED").next().expect("dynamic approved").click();+ h.run_steps(2);+ assert_eq!(h.state().quick_tool, QuickTool::Stamp(printcraft_engine::StampKind::DynApproved));+ let p = {+ let r = h.state().views[0].page_screen_rect(0).unwrap();+ r.min + egui::vec2(r.width() * 0.5, r.height() * 0.85)+ };+ h.hover_at(p);+ h.run_steps(1);+ h.drag_at(p);+ h.run_steps(1);+ h.drop_at(p);+ h.run_steps(4);+ let s = h.state();+ let doc = s.session.get(s.views[0].id).unwrap();+ let stamps: Vec<_> = doc.info.annotations.iter().filter(|a| a.subtype == "Stamp").collect();+ assert_eq!(stamps.len(), 1);+ assert_eq!(s.quick_tool, QuickTool::Select, "back to selecting after one stamp");+ for _ in 0..30 {+ h.run_steps(2);+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ if let Ok(dir) = std::env::var("PRINTCRAFT_SHOTS") {+ h.render().unwrap().save(format!("{dir}/stamps.png")).unwrap();+ }+}diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.tomlindex f5189e975..900e66515 100644--- a/parity/acrobat-features.toml+++ b/parity/acrobat-features.toml@@ -3959,11 +3959,11 @@ title = "Standard business stamps"area = "E"tier = "P1"milestone = "M5"-status = "planned"-commands = []-tools = []-evidence = []-notes = ""+status = "shipped"+commands = ["comment.stamp"]+tools = ["comment_add"]+evidence = ["crates/annot/src/tests.rs::stamps_draw_their_label_and_by_line", "crates/ui-egui/tests/stamps.rs::choosing_and_placing_stamps", "crates/automation/tests/automation.rs::stamps_through_tools"]+notes = "12 standard business stamps in PrintCraft's own design; ISO 32000 stamp names where defined"[[feature]]id = "comment.stamps-sign-here"@@ -3971,11 +3971,11 @@ title = "Sign-here stamps"area = "E"tier = "P1"milestone = "M5"-status = "planned"-commands = []-tools = []-evidence = []-notes = ""+status = "shipped"+commands = ["comment.stamp"]+tools = ["comment_add"]+evidence = ["crates/annot/src/tests.rs::stamps_draw_their_label_and_by_line", "crates/ui-egui/tests/stamps.rs::choosing_and_placing_stamps", "crates/automation/tests/automation.rs::stamps_through_tools"]+notes = "Accepted, Initial Here, Rejected, Sign Here, Witness as pointed tags"[[feature]]id = "comment.stamps-dynamic"@@ -3983,11 +3983,11 @@ title = "Dynamic stamps (name and date)"area = "E"tier = "P1"milestone = "M6"-status = "planned"-commands = []-tools = []-evidence = []-notes = ""+status = "shipped"+commands = ["comment.stamp"]+tools = ["comment_add"]+evidence = ["crates/annot/src/tests.rs::stamps_draw_their_label_and_by_line", "crates/ui-egui/tests/stamps.rs::choosing_and_placing_stamps", "crates/automation/tests/automation.rs::stamps_through_tools"]+notes = "Approved, Confidential, Received, Reviewed, Revised with a By author at time, date line (local time)"[[feature]]id = "comment.stamps-custom"