Skip to content

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

M5.1/M5.2: comments engine: new annot crate (L3) with builders and appearance streams for sticky note, highlight, underline, strikeout, squiggly, rectangle, oval, line/arrow, ink, text box; reply, review status, move, resize, restyle, delete (with pop-ups and replies); undoable engine edits with /NM ids and dates, annotate-permission check; inspector reports index, state, quads; 6 automation tools (comment_list/add/reply/set_status/edit/delete, highlight by text search)

Brandon Thomas4058c156f74f
diff --git a/Cargo.lock b/Cargo.lock
index 03fe8d7d5..f13c73934 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3026,6 +3026,15 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "printcraft-annot"
+version = "0.1.0"
+dependencies = [
+ "hayro-syntax",
+ "printcraft-cos",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "printcraft-automation"
version = "0.1.0"
@@ -3078,6 +3087,7 @@ dependencies = [
name = "printcraft-engine"
version = "0.1.0"
dependencies = [
+ "printcraft-annot",
"printcraft-cos",
"printcraft-organize",
"printcraft-render",
diff --git a/Cargo.toml b/Cargo.toml
index 6d041d806..080927d2b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -18,6 +18,7 @@ printcraft-filters = { path = "crates/filters", version = "0.1.0" }
printcraft-cos = { path = "crates/cos", version = "0.1.0" }
printcraft-crypt = { path = "crates/crypt", version = "0.1.0" }
printcraft-organize = { path = "crates/organize", version = "0.1.0" }
+printcraft-annot = { path = "crates/annot", version = "0.1.0" }
printcraft-render = { path = "crates/render", version = "0.1.0" }
printcraft-engine = { path = "crates/engine", version = "0.1.0" }
printcraft-ui-egui = { path = "crates/ui-egui", version = "0.1.0" }
diff --git a/crates/annot/Cargo.toml b/crates/annot/Cargo.toml
new file mode 100644
index 000000000..77623b50f
--- /dev/null
+++ b/crates/annot/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "printcraft-annot"
+description = "Annotations (comments): builders, appearance streams and edits, ISO 32000-2 §12.5"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[lints]
+workspace = true
+
+[dependencies]
+printcraft-cos = { workspace = true }
+thiserror = { workspace = true }
+
+[dev-dependencies]
+hayro-syntax = { workspace = true }
diff --git a/crates/annot/README.md b/crates/annot/README.md
new file mode 100644
index 000000000..85d83065a
--- /dev/null
+++ b/crates/annot/README.md
@@ -0,0 +1,44 @@
+# printcraft-annot
+
+Comments (annotations), ISO 32000-2 §12.5. Layer L3, depends only on `printcraft-cos`.
+
+## What it does
+
+- **Builders** for the comment types Acrobat's commenting tools create: sticky note (`Text` +
+ `Popup`), highlight, underline, strikethrough, squiggly, rectangle (`Square`), oval (`Circle`),
+ line and arrow (`Line` with `/LE`), freehand drawing (`Ink`) and text box (`FreeText`).
+- **Appearance streams** (`appearance::build`) generated from the annotation dictionary, so new
+ and restyled comments look the same in every viewer. Highlights multiply (`/BM /Multiply`).
+ Note icons are PrintCraft's own drawings. Text boxes use standard Helvetica (WinAnsi), with
+ line breaking by approximate Helvetica proportions (no font program is bundled).
+- **Edits:** reply (`/IRT`), set review status (a `/State` reply, as Acrobat's "Set status"
+ does), change text, move, resize, restyle, delete (with pop-up and replies).
+
+## API sketch
+
+```rust
+let index = add_annotation(&mut doc, &NewAnnotation { page, shape, style, contents, author }, &meta)?;
+add_reply(&mut doc, page, index, "Agreed", "Ada", &meta)?;
+set_review_state(&mut doc, page, index, ReviewState::Accepted, "Ada", &meta)?;
+move_annotation(&mut doc, page, index, dx, dy, &meta)?;
+set_style(&mut doc, page, index, Some(rgb), Some(0.5), Some(2.0), &meta)?;
+delete_annotation(&mut doc, page, index)?;
+```
+
+A comment is addressed by `(page, index in /Annots)`, the same pair
+`printcraft_render::Annotation` reports. `Meta` carries the date and the `/NM` id so edits stay
+deterministic; the engine supplies them.
+
+## Fidelity rules
+
+- Unknown keys are kept. Inline annotation dictionaries are promoted to indirect objects only
+ when an edit needs a reference to them.
+- `set_style` refuses (and changes nothing) when it cannot redraw the comment, e.g. stamps,
+ cloudy borders or callouts, instead of leaving a stale appearance.
+- Replies get the parent's `/Rect` and an empty appearance: they appear in comment lists but
+ never paint a second icon.
+
+## Not yet
+
+Callouts, polygons and polylines, clouds, carets (insert/replace text), stamps, file
+attachments, rich text (`/RC`, `/DS`), and the shared named-appearance cache Acrobat writes.
diff --git a/crates/annot/src/appearance.rs b/crates/annot/src/appearance.rs
new file mode 100644
index 000000000..6509c0a07
--- /dev/null
+++ b/crates/annot/src/appearance.rs
@@ -0,0 +1,455 @@
+//! Appearance streams (§12.5.5) for the comment types PrintCraft creates, execution plan M5.2.
+//!
+//! [`build`] draws a normal appearance (`/AP /N`) from the annotation dictionary alone, so the
+//! same code serves new comments and restyled ones. Drawings are in page space with
+//! `/BBox = /Rect` (identity matrix), except note icons, which are drawn in a 20 × 20 box.
+//! It returns `None` for anything it cannot draw faithfully (cloudy borders, unknown line
+//! endings, indirect geometry), so callers never replace an appearance with a worse one.
+//!
+//! The note icons are PrintCraft's own drawings (AGENTS.md §1). Text boxes use the standard
+//! Helvetica font with WinAnsi encoding; line breaking uses [`text_width`], an approximation of
+//! Helvetica's proportions by character class (no font program or metrics file is bundled).
+
+use printcraft_cos::{Dict, Object, PdfString, Stream};
+
+use crate::{NOTE_SIZE, Rgb, n};
+
+/// Length of an arrowhead for a line of width `w`.
+pub fn arrow_size(w: f64) -> f64 {
+ 6.0 + 3.0 * w.max(0.0)
+}
+
+fn nums(d: &Dict, key: &[u8]) -> Option<Vec<f64>> {
+ d.get(key)?.as_array()?.iter().map(|o| o.as_f64()).collect()
+}
+
+/// `/C`-style colour arrays: none (transparent), gray, RGB or CMYK.
+fn color(d: &Dict, key: &[u8]) -> Option<Option<Rgb>> {
+ let c = match d.get(key) {
+ None => return Some(None),
+ Some(o) => o.as_array()?.iter().map(|o| o.as_f64()).collect::<Option<Vec<f64>>>()?,
+ };
+ Some(match c.as_slice() {
+ [] => None,
+ [g] => Some([*g; 3]),
+ [r, g, b] => Some([*r, *g, *b]),
+ [c, m, y, k] => Some([(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]),
+ _ => return None,
+ })
+}
+
+fn border_width(d: &Dict) -> f64 {
+ if let Some(w) = d.get(b"BS").and_then(|b| b.as_dict()).and_then(|b| b.get(b"W")).and_then(|w| w.as_f64()) {
+ return w.max(0.0);
+ }
+ match nums(d, b"Border") {
+ Some(b) if b.len() >= 3 => b[2].max(0.0),
+ _ => 1.0,
+ }
+}
+
+/// Dash pattern operator for a dashed border, if any.
+fn dash(d: &Dict) -> String {
+ let Some(bs) = d.get(b"BS").and_then(|b| b.as_dict()) else { return String::new() };
+ if bs.name(b"S") != Some(b"D") {
+ return String::new();
+ }
+ let arr = nums(bs, b"D").filter(|a| !a.is_empty() && a.iter().all(|x| *x >= 0.0)).unwrap_or_else(|| vec![3.0]);
+ format!("[{}] 0 d\n", arr.iter().map(|x| n(*x)).collect::<Vec<_>>().join(" "))
+}
+
+fn rg(c: Rgb) -> String {
+ format!("{} {} {} rg\n", n(c[0]), n(c[1]), n(c[2]))
+}
+
+fn rg_stroke(c: Rgb) -> String {
+ format!("{} {} {} RG\n", n(c[0]), n(c[1]), n(c[2]))
+}
+
+/// `/DA` of a text box: (text colour, font size). Defaults to black 12 pt.
+pub fn parse_da(d: &Dict) -> (Rgb, f64) {
+ let da = d.get(b"DA").and_then(|o| o.as_string()).map(|s| String::from_utf8_lossy(&s.bytes).into_owned()).unwrap_or_default();
+ let toks: Vec<&str> = da.split_whitespace().collect();
+ let mut col = [0.0; 3];
+ let mut size = 12.0;
+ let num = |i: usize| toks.get(i).and_then(|t| t.parse::<f64>().ok());
+ for (i, t) in toks.iter().enumerate() {
+ match *t {
+ "rg" if i >= 3 => {
+ if let (Some(r), Some(g), Some(b)) = (num(i - 3), num(i - 2), num(i - 1)) {
+ col = [r, g, b];
+ }
+ }
+ "g" if i >= 1 => {
+ if let Some(g) = num(i - 1) {
+ col = [g; 3];
+ }
+ }
+ "Tf" if i >= 1 => {
+ if let Some(s) = num(i - 1).filter(|s| *s > 0.0) {
+ size = s;
+ }
+ }
+ _ => {}
+ }
+ }
+ (col.map(|x| x.clamp(0.0, 1.0)), size.min(400.0))
+}
+
+/// Approximate advance of `s` in Helvetica at `size` points.
+pub fn text_width(s: &str, size: f64) -> f64 {
+ let units: f64 = s
+ .chars()
+ .map(|c| match c {
+ ' ' | 'i' | 'j' | 'l' | '\'' | '!' | '|' | '.' | ',' | ':' | ';' | 'I' => 260.0,
+ 'f' | 't' | 'r' | '(' | ')' | '[' | ']' | '/' | '-' | '"' => 333.0,
+ 'm' => 833.0,
+ 'w' => 722.0,
+ 'M' => 833.0,
+ 'W' => 944.0,
+ 'J' | 'c' | 'k' | 's' | 'v' | 'x' | 'y' | 'z' => 500.0,
+ '0'..='9' | 'a'..='z' | '$' | '#' | '?' | '_' => 556.0,
+ 'A'..='Z' => 680.0,
+ '@' => 1015.0,
+ _ if c.is_whitespace() => 260.0,
+ _ => 584.0,
+ })
+ .sum();
+ units * size / 1000.0
+}
+
+/// WinAnsi-encode text for a literal string, escaping delimiters; unmappable characters → `?`.
+fn win_ansi(s: &str) -> Vec<u8> {
+ let mut out = Vec::new();
+ for c in s.chars() {
+ let b = match c {
+ '\u{20}'..='\u{7e}' => c as u8,
+ '\u{a0}'..='\u{ff}' => c as u32 as u8,
+ '€' => 0x80,
+ '‚' => 0x82,
+ '„' => 0x84,
+ '…' => 0x85,
+ '‘' => 0x91,
+ '’' => 0x92,
+ '“' => 0x93,
+ '”' => 0x94,
+ '•' => 0x95,
+ '–' => 0x96,
+ '—' => 0x97,
+ '™' => 0x99,
+ '\t' => b' ',
+ _ => b'?',
+ };
+ if matches!(b, b'(' | b')' | b'\\') {
+ out.push(b'\\');
+ }
+ out.push(b);
+ }
+ out
+}
+
+/// Greedy line breaking within `width` (paragraphs split on newlines; long words are split).
+pub fn wrap(text: &str, size: f64, width: f64) -> Vec<String> {
+ let mut lines = Vec::new();
+ for para in text.split(['\n', '\r']) {
+ let mut line = String::new();
+ for word in para.split(' ') {
+ let candidate = if line.is_empty() { word.to_string() } else { format!("{line} {word}") };
+ if text_width(&candidate, size) <= width || line.is_empty() && text_width(word, size) <= width {
+ line = candidate;
+ continue;
+ }
+ if !line.is_empty() {
+ lines.push(std::mem::take(&mut line));
+ }
+ // A word wider than the box: break it by characters.
+ for ch in word.chars() {
+ if !line.is_empty() && text_width(&format!("{line}{ch}"), size) > width {
+ lines.push(std::mem::take(&mut line));
+ }
+ line.push(ch);
+ }
+ }
+ lines.push(line);
+ }
+ lines
+}
+
+fn ext_gstate(opacity: f64, multiply: bool) -> Option<Dict> {
+ if opacity >= 1.0 && !multiply {
+ return None;
+ }
+ let mut gs = Dict::new();
+ gs.set(b"Type".to_vec(), Object::name("ExtGState"));
+ if multiply {
+ gs.set(b"BM".to_vec(), Object::name("Multiply"));
+ }
+ gs.set(b"CA".to_vec(), Object::Real(opacity));
+ gs.set(b"ca".to_vec(), Object::Real(opacity));
+ let mut res = Dict::new();
+ res.set(b"GS0".to_vec(), Object::Dict(gs));
+ Some(res)
+}
+
+fn form(bbox: [f64; 4], content: &[u8], resources: Dict) -> Stream {
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("XObject"));
+ d.set(b"Subtype".to_vec(), Object::name("Form"));
+ d.set(b"FormType".to_vec(), Object::Int(1));
+ d.set(b"BBox".to_vec(), Object::Array(bbox.iter().map(|x| Object::Real(*x)).collect()));
+ d.set(b"Resources".to_vec(), Object::Dict(resources));
+ Stream::flate(d, content)
+}
+
+/// Draw the normal appearance of an annotation, or `None` if this subtype/variant isn't supported.
+pub fn build(d: &Dict) -> Option<Stream> {
+ let subtype = d.name(b"Subtype")?.to_vec();
+ let rect = nums(d, b"Rect").filter(|r| r.len() == 4)?;
+ let rect = [rect[0].min(rect[2]), rect[1].min(rect[3]), rect[0].max(rect[2]), rect[1].max(rect[3])];
+ // Cloudy borders (§12.5.4) are not drawn yet.
+ if d.get(b"BE").and_then(|b| b.as_dict()).is_some_and(|b| b.name(b"S") == Some(b"C")) {
+ return None;
+ }
+ let opacity = d.get(b"CA").and_then(|o| o.as_f64()).unwrap_or(1.0).clamp(0.0, 1.0);
+ let stroke = color(d, b"C")?;
+ let w = border_width(d);
+ let mut res = Dict::new();
+ let mut c = String::new();
+ let markup = matches!(subtype.as_slice(), b"Highlight" | b"Underline" | b"StrikeOut" | b"Squiggly");
+ if let Some(gs) = ext_gstate(opacity, subtype == b"Highlight") {
+ res.set(b"ExtGState".to_vec(), Object::Dict(gs));
+ c.push_str("/GS0 gs\n");
+ }
+ match subtype.as_slice() {
+ b"Text" => {
+ let col = stroke.unwrap_or([1.0, 0.82, 0.0]);
+ let icon = d.name(b"Name").map(|n| String::from_utf8_lossy(n).into_owned()).unwrap_or_else(|| "Note".into());
+ c.push_str(&note_icon(&icon, col));
+ return Some(form([0.0, 0.0, NOTE_SIZE, NOTE_SIZE], c.as_bytes(), res));
+ }
+ _ if markup => {
+ let q = nums(d, b"QuadPoints").filter(|q| !q.is_empty() && q.len() % 8 == 0)?;
+ let col = stroke?;
+ for quad in q.chunks_exact(8) {
+ let p = |i: usize| (quad[2 * i], quad[2 * i + 1]);
+ let (p1, p2, p3, p4) = (p(0), p(1), p(2), p(3));
+ let h = (p1.0 - p3.0).hypot(p1.1 - p3.1);
+ // A point a fraction `t` of the way from the bottom edge to the top edge.
+ let at = |bottom: (f64, f64), top: (f64, f64), t: f64| (bottom.0 + (top.0 - bottom.0) * t, bottom.1 + (top.1 - bottom.1) * t);
+ match subtype.as_slice() {
+ b"Highlight" => {
+ c.push_str(&rg(col));
+ c.push_str(&format!(
+ "{} {} m {} {} l {} {} l {} {} l h f\n",
+ n(p1.0),
+ n(p1.1),
+ n(p2.0),
+ n(p2.1),
+ n(p4.0),
+ n(p4.1),
+ n(p3.0),
+ n(p3.1)
+ ));
+ }
+ b"Underline" | b"StrikeOut" => {
+ let lw = (h * 0.07).clamp(0.5, 3.0);
+ let t = if subtype == b"Underline" { 0.08 } else { 0.42 };
+ let (a, b) = (at(p3, p1, t), at(p4, p2, t));
+ c.push_str(&format!("{}{} w\n{} {} m {} {} l S\n", rg_stroke(col), n(lw), n(a.0), n(a.1), n(b.0), n(b.1)));
+ }
+ _ => {
+ // Squiggly: a zigzag along the bottom of the quad.
+ let lw = (h * 0.05).clamp(0.5, 2.0);
+ let amp = (h * 0.06).max(0.75);
+ let len = (p4.0 - p3.0).hypot(p4.1 - p3.1);
+ let step = (h / 4.0).max(1.5);
+ let steps = ((len / step).ceil() as usize).clamp(1, 10_000);
+ c.push_str(&format!("{}{} w 1 j\n", rg_stroke(col), n(lw)));
+ for i in 0..=steps {
+ let t = i as f64 / steps as f64;
+ let base = (p3.0 + (p4.0 - p3.0) * t, p3.1 + (p4.1 - p3.1) * t);
+ let up = if i % 2 == 0 { amp * 2.0 } else { 0.0 };
+ let (ux, uy) = if h > 0.0 { ((p1.0 - p3.0) / h, (p1.1 - p3.1) / h) } else { (0.0, 1.0) };
+ let (x, y) = (base.0 + ux * up, base.1 + uy * up);
+ c.push_str(&format!("{} {} {}\n", n(x), n(y), if i == 0 { "m" } else { "l" }));
+ }
+ c.push_str("S\n");
+ }
+ }
+ }
+ }
+ b"Square" | b"Circle" => {
+ let fill = color(d, b"IC")?;
+ if stroke.is_none() && fill.is_none() {
+ return Some(form(rect, c.as_bytes(), res));
+ }
+ let inset = w / 2.0;
+ let [x0, y0, x1, y1] = [rect[0] + inset, rect[1] + inset, rect[2] - inset, rect[3] - inset];
+ if let Some(f) = fill {
+ c.push_str(&rg(f));
+ }
+ if let Some(s) = stroke {
+ c.push_str(&format!("{}{} w\n{}", rg_stroke(s), n(w), dash(d)));
+ }
+ if subtype == b"Square" {
+ c.push_str(&format!("{} {} {} {} re\n", n(x0), n(y0), n(x1 - x0), n(y1 - y0)));
+ } else {
+ c.push_str(&ellipse(x0, y0, x1, y1));
+ }
+ c.push_str(match (fill.is_some(), stroke.is_some() && w > 0.0) {
+ (true, true) => "B\n",
+ (true, false) => "f\n",
+ (false, true) => "S\n",
+ (false, false) => "n\n",
+ });
+ }
+ b"Line" => {
+ let l = nums(d, b"L").filter(|l| l.len() == 4)?;
+ let col = stroke?;
+ let ends: Vec<Vec<u8>> = match d.get(b"LE") {
+ None => vec![b"None".to_vec(), b"None".to_vec()],
+ Some(o) => o.as_array()?.iter().map(|e| e.as_name().map(<[u8]>::to_vec)).collect::<Option<_>>()?,
+ };
+ if ends.len() != 2 || ends.iter().any(|e| !matches!(e.as_slice(), b"None" | b"OpenArrow" | b"ClosedArrow")) {
+ return None;
+ }
+ let fill = color(d, b"IC")?.unwrap_or(col);
+ c.push_str(&format!("{}{}{} w 1 J 1 j\n{}", rg_stroke(col), rg(fill), n(w), dash(d)));
+ c.push_str(&format!("{} {} m {} {} l S\n[] 0 d\n", n(l[0]), n(l[1]), n(l[2]), n(l[3])));
+ for (end, (tip, from)) in ends.iter().zip([((l[0], l[1]), (l[2], l[3])), ((l[2], l[3]), (l[0], l[1]))]) {
+ if end.as_slice() == b"None" {
+ continue;
+ }
+ let (dx, dy) = (from.0 - tip.0, from.1 - tip.1);
+ let len = dx.hypot(dy);
+ if len == 0.0 {
+ continue;
+ }
+ let (ux, uy) = (dx / len, dy / len);
+ let s = arrow_size(w);
+ let (cos, sin) = (30f64.to_radians().cos(), 30f64.to_radians().sin());
+ let a = (tip.0 + s * (ux * cos - uy * sin), tip.1 + s * (ux * sin + uy * cos));
+ let b = (tip.0 + s * (ux * cos + uy * sin), tip.1 + s * (-ux * sin + uy * cos));
+ let op = if end.as_slice() == b"ClosedArrow" { "h B" } else { "S" };
+ c.push_str(&format!("{} {} m {} {} l {} {} l {op}\n", n(a.0), n(a.1), n(tip.0), n(tip.1), n(b.0), n(b.1)));
+ }
+ }
+ b"Ink" => {
+ let col = stroke?;
+ let list = d.get(b"InkList")?.as_array()?;
+ c.push_str(&format!("{}{} w 1 J 1 j\n", rg_stroke(col), n(w)));
+ for s in list {
+ let pts: Vec<f64> = s.as_array()?.iter().map(|o| o.as_f64()).collect::<Option<_>>()?;
+ let pts: Vec<(f64, f64)> = pts.chunks_exact(2).map(|p| (p[0], p[1])).collect();
+ let Some(first) = pts.first() else { continue };
+ c.push_str(&format!("{} {} m\n", n(first.0), n(first.1)));
+ if pts.len() == 1 {
+ c.push_str(&format!("{} {} l\n", n(first.0 + 0.01), n(first.1)));
+ }
+ for p in &pts[1..] {
+ c.push_str(&format!("{} {} l\n", n(p.0), n(p.1)));
+ }
+ c.push_str("S\n");
+ }
+ }
+ b"FreeText" => {
+ // Callouts (`/CL`) and rich text without plain contents aren't drawn yet.
+ if d.contains(b"CL") {
+ return None;
+ }
+ let (text_color, size) = parse_da(d);
+ let bg = stroke;
+ let bw = if d.contains(b"BS") || d.contains(b"Border") { border_width(d) } else { 0.0 };
+ if let Some(bg) = bg {
+ c.push_str(&format!("{}{} {} {} {} re f\n", rg(bg), n(rect[0]), n(rect[1]), n(rect[2] - rect[0]), n(rect[3] - rect[1])));
+ }
+ if bw > 0.0 {
+ let h = bw / 2.0;
+ c.push_str(&format!(
+ "{}{} w\n{}{} {} {} {} re S\n[] 0 d\n",
+ rg_stroke(text_color),
+ n(bw),
+ dash(d),
+ n(rect[0] + h),
+ n(rect[1] + h),
+ n(rect[2] - rect[0] - bw),
+ n(rect[3] - rect[1] - bw)
+ ));
+ }
+ let text = d.get(b"Contents").and_then(|o| o.as_string()).map(PdfString::to_text).unwrap_or_default();
+ let pad = 2.0 + bw;
+ let width = (rect[2] - rect[0] - 2.0 * pad).max(1.0);
+ let q = d.int(b"Q").unwrap_or(0);
+ c.push_str(&format!(
+ "{} {} {} {} re W n\nBT\n/Helv {} Tf\n{}",
+ n(rect[0]),
+ n(rect[1]),
+ n(rect[2] - rect[0]),
+ n(rect[3] - rect[1]),
+ n(size),
+ rg(text_color)
+ ));
+ let mut out = c.into_bytes();
+ let mut y = rect[3] - pad - size * 0.9;
+ for line in wrap(&text, size, width) {
+ if y < rect[1] - size {
+ break;
+ }
+ let lw = text_width(&line, size);
+ let x = match q {
+ 1 => rect[0] + pad + (width - lw) / 2.0,
+ 2 => rect[2] - pad - lw,
+ _ => rect[0] + pad,
+ };
+ out.extend(format!("1 0 0 1 {} {} Tm (", n(x), n(y)).bytes());
+ out.extend(win_ansi(&line));
+ out.extend_from_slice(b") Tj\n");
+ y -= size * 1.2;
+ }
+ out.extend_from_slice(b"ET\n");
+ let mut font = Dict::new();
+ font.set(b"Type".to_vec(), Object::name("Font"));
+ font.set(b"Subtype".to_vec(), Object::name("Type1"));
+ font.set(b"BaseFont".to_vec(), Object::name("Helvetica"));
+ font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));
+ let mut fonts = Dict::new();
+ fonts.set(b"Helv".to_vec(), Object::Dict(font));
+ res.set(b"Font".to_vec(), Object::Dict(fonts));
+ return Some(form(rect, &out, res));
+ }
+ _ => return None,
+ }
+ Some(form(rect, c.as_bytes(), 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;
+ let (cx, cy, rx, ry) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0, (x1 - x0) / 2.0, (y1 - y0) / 2.0);
+ let (ox, oy) = (rx * k, ry * k);
+ let mut s = format!("{} {} m\n", n(cx + rx), n(cy));
+ for [a, b, c, d, e, f] in [
+ [cx + rx, cy + oy, cx + ox, cy + ry, cx, cy + ry],
+ [cx - ox, cy + ry, cx - rx, cy + oy, cx - rx, cy],
+ [cx - rx, cy - oy, cx - ox, cy - ry, cx, cy - ry],
+ [cx + ox, cy - ry, cx + rx, cy - oy, cx + rx, cy],
+ ] {
+ s.push_str(&format!("{} {} {} {} {} {} c\n", n(a), n(b), n(c), n(d), n(e), n(f)));
+ }
+ s.push_str("h\n");
+ s
+}
+
+/// PrintCraft's note icons, drawn in a 20 × 20 box: a speech bubble for `/Comment`, a page
+/// with a folded corner for everything else, both filled with the note colour.
+fn note_icon(name: &str, col: Rgb) -> String {
+ let mut s = format!("{}0.25 0.25 0.25 RG 0.8 w 1 j 1 J\n", rg(col));
+ if name == "Comment" {
+ s.push_str("3 18.5 m 17 18.5 l 18.5 18.5 18.5 17 18.5 17 c 18.5 8 l 18.5 6.5 17 6.5 17 6.5 c 9.5 6.5 l 5 2 l 5.5 6.5 l 3 6.5 l 1.5 6.5 1.5 8 1.5 8 c 1.5 17 l 1.5 18.5 3 18.5 3 18.5 c h B\n");
+ s.push_str("4.5 15 m 15.5 15 l 4.5 12.5 m 15.5 12.5 l 4.5 10 m 11.5 10 l S\n");
+ } else {
+ s.push_str("3 19 m 13 19 l 17 15 l 17 1 l 3 1 l h B\n13 19 m 13 15 l 17 15 l S\n");
+ s.push_str("5.5 12 m 14.5 12 l 5.5 9 m 14.5 9 l 5.5 6 m 11.5 6 l S\n");
+ }
+ s
+}
diff --git a/crates/annot/src/lib.rs b/crates/annot/src/lib.rs
new file mode 100644
index 000000000..cf6aff993
--- /dev/null
+++ b/crates/annot/src/lib.rs
@@ -0,0 +1,758 @@
+//! printcraft-annot — comments (annotations), ISO 32000-2 §12.5, execution plan M5.1–M5.3.
+//!
+//! Builders for the comment types Acrobat's commenting tools create (sticky note, highlight,
+//! underline, strikethrough, squiggly, rectangle, oval, line/arrow, freehand ink, text box),
+//! appearance streams for them ([`appearance`]), and the edits a comment goes through: reply,
+//! change its text, recolour, move, resize and delete.
+//!
+//! Addressing: a comment is `(page, index)`, its position in the page's `/Annots` array, which
+//! is what `printcraft_render::Annotation::index` reports. Inline annotation dictionaries are
+//! promoted to indirect objects when they are edited (replies need a reference to point at).
+//!
+//! Every edit mutates a `printcraft_cos::Document` (copy-on-write); callers snapshot it first
+//! for undo. Keys we do not understand are left alone.
+
+use printcraft_cos::{Dict, Document, ObjRef, Object, PdfString};
+
+pub mod appearance;
+
+#[cfg(test)]
+mod tests;
+
+#[derive(Debug, thiserror::Error, PartialEq)]
+pub enum AnnotError {
+ #[error("the document has no page tree")]
+ NoPageTree,
+ #[error("page {0} does not exist")]
+ NoSuchPage(usize),
+ #[error("there is no comment {index} on page {page}")]
+ NoSuchAnnotation { page: usize, index: usize },
+ #[error("{0}")]
+ Invalid(String),
+ #[error("{0} comments can't be restyled yet (their appearance can't be regenerated)")]
+ Unsupported(String),
+ #[error("{0}")]
+ Cos(#[from] printcraft_cos::CosError),
+}
+
+pub type Rgb = [f64; 3];
+
+/// Text markup kinds (§12.5.6.10).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Markup {
+ Highlight,
+ Underline,
+ StrikeOut,
+ Squiggly,
+}
+
+impl Markup {
+ fn subtype(self) -> &'static str {
+ match self {
+ Markup::Highlight => "Highlight",
+ Markup::Underline => "Underline",
+ Markup::StrikeOut => "StrikeOut",
+ Markup::Squiggly => "Squiggly",
+ }
+ }
+}
+
+/// The standard text-annotation icon names (§12.5.6.4, Table 175).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
+pub enum NoteIcon {
+ #[default]
+ Comment,
+ Note,
+ Help,
+ Insert,
+ Key,
+ NewParagraph,
+ Paragraph,
+}
+
+impl NoteIcon {
+ pub fn name(self) -> &'static str {
+ match self {
+ NoteIcon::Comment => "Comment",
+ NoteIcon::Note => "Note",
+ NoteIcon::Help => "Help",
+ NoteIcon::Insert => "Insert",
+ NoteIcon::Key => "Key",
+ NoteIcon::NewParagraph => "NewParagraph",
+ NoteIcon::Paragraph => "Paragraph",
+ }
+ }
+
+ pub fn from_name(n: &str) -> Option<Self> {
+ [Self::Comment, Self::Note, Self::Help, Self::Insert, Self::Key, Self::NewParagraph, Self::Paragraph].into_iter().find(|i| i.name() == n)
+ }
+}
+
+/// Geometry of a new comment, in PDF user space of its page.
+#[derive(Clone, Debug, PartialEq)]
+pub enum Shape {
+ /// A sticky note whose icon's top-left corner is at `at`.
+ Note {
+ at: [f64; 2],
+ icon: NoteIcon,
+ },
+ /// Text markup over quadrilaterals: `[x1 y1 x2 y2 x3 y3 x4 y4]` = top-left, top-right,
+ /// bottom-left, bottom-right (the order Acrobat writes, §12.5.6.10).
+ TextMarkup {
+ kind: Markup,
+ quads: Vec<[f64; 8]>,
+ },
+ Rectangle {
+ rect: [f64; 4],
+ },
+ Oval {
+ rect: [f64; 4],
+ },
+ /// A line, with an open arrowhead at `to` when `arrow` is set.
+ Line {
+ from: [f64; 2],
+ to: [f64; 2],
+ arrow: bool,
+ },
+ /// Freehand strokes (Draw tool).
+ Ink {
+ strokes: Vec<Vec<[f64; 2]>>,
+ },
+ /// A text box (FreeText) showing the comment's contents.
+ TextBox {
+ rect: [f64; 4],
+ font_size: f64,
+ },
+}
+
+impl Shape {
+ pub fn subtype(&self) -> &'static str {
+ match self {
+ Shape::Note { .. } => "Text",
+ Shape::TextMarkup { kind, .. } => kind.subtype(),
+ Shape::Rectangle { .. } => "Square",
+ Shape::Oval { .. } => "Circle",
+ Shape::Line { .. } => "Line",
+ Shape::Ink { .. } => "Ink",
+ Shape::TextBox { .. } => "FreeText",
+ }
+ }
+}
+
+/// How a comment looks.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Style {
+ /// Stroke colour (text colour for text boxes, icon colour for notes).
+ pub color: Rgb,
+ /// 0–1 (`/CA`).
+ pub opacity: f64,
+ /// Border / stroke width in points (0 = none).
+ pub width: f64,
+ /// Interior fill for rectangles and ovals (`/IC`), background for text boxes.
+ pub fill: Option<Rgb>,
+}
+
+impl Default for Style {
+ fn default() -> Self {
+ Self { color: [1.0, 0.82, 0.0], opacity: 1.0, width: 1.0, fill: None }
+ }
+}
+
+impl Style {
+ /// The default look of each commenting tool.
+ pub fn default_for(shape: &Shape) -> Self {
+ let (color, width) = match shape {
+ Shape::Note { .. } => ([1.0, 0.82, 0.0], 1.0),
+ Shape::TextMarkup { kind: Markup::Highlight, .. } => ([1.0, 0.94, 0.0], 1.0),
+ Shape::TextMarkup { kind: Markup::Underline, .. } => ([0.0, 0.47, 0.84], 1.0),
+ Shape::TextMarkup { kind: Markup::StrikeOut, .. } => ([0.89, 0.13, 0.13], 1.0),
+ Shape::TextMarkup { kind: Markup::Squiggly, .. } => ([0.18, 0.62, 0.36], 1.0),
+ Shape::Rectangle { .. } | Shape::Oval { .. } | Shape::Line { .. } => ([0.89, 0.13, 0.13], 2.0),
+ Shape::Ink { .. } => ([0.0, 0.4, 0.87], 2.0),
+ Shape::TextBox { .. } => ([0.0, 0.0, 0.0], 0.0),
+ };
+ Self { color, opacity: 1.0, width, fill: None }
+ }
+}
+
+/// A comment to add.
+#[derive(Clone, Debug, PartialEq)]
+pub struct NewAnnotation {
+ /// 0-based page index.
+ pub page: usize,
+ pub shape: Shape,
+ pub style: Style,
+ /// The comment text (`/Contents`); the text shown by a text box.
+ pub contents: String,
+ /// `/T` (shown as the comment's author).
+ pub author: String,
+}
+
+/// Values stamped onto what an edit creates or changes, supplied by the caller so edits stay
+/// deterministic: a PDF date (`D:…`) and a unique id for `/NM`.
+#[derive(Clone, Debug, PartialEq, Default)]
+pub struct Meta {
+ pub date: Option<String>,
+ pub id: String,
+}
+
+/// Review states a reply can set (§12.5.6.3, Table 172; Acrobat's "Set status").
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ReviewState {
+ None,
+ Accepted,
+ Rejected,
+ Cancelled,
+ Completed,
+}
+
+impl ReviewState {
+ pub fn name(self) -> &'static str {
+ match self {
+ ReviewState::None => "None",
+ ReviewState::Accepted => "Accepted",
+ ReviewState::Rejected => "Rejected",
+ ReviewState::Cancelled => "Cancelled",
+ ReviewState::Completed => "Completed",
+ }
+ }
+
+ pub fn from_name(n: &str) -> Option<Self> {
+ [Self::None, Self::Accepted, Self::Rejected, Self::Cancelled, Self::Completed].into_iter().find(|s| s.name().eq_ignore_ascii_case(n))
+ }
+}
+
+// ── pages and /Annots ───────────────────────────────────────────────────────────────────────
+
+/// The page object of each leaf page, in order.
+pub fn page_refs(doc: &Document) -> Result<Vec<ObjRef>, AnnotError> {
+ let root = doc.root().ok_or(AnnotError::NoPageTree)?;
+ let pages = doc.get(root).as_dict().and_then(|d| d.reference(b"Pages")).ok_or(AnnotError::NoPageTree)?;
+ let mut out = Vec::new();
+ let mut seen = std::collections::HashSet::new();
+ let mut stack = vec![pages];
+ while let Some(node) = stack.pop() {
+ if !seen.insert(node) || seen.len() > 1_000_000 {
+ continue;
+ }
+ let obj = doc.get(node);
+ let Some(d) = obj.as_dict() else { continue };
+ match d.get(b"Kids").map(|k| doc.resolve(k)) {
+ Some(kids) if d.name(b"Type") != Some(b"Page") => {
+ if let Some(a) = kids.as_array() {
+ stack.extend(a.iter().rev().filter_map(|k| k.as_ref()));
+ }
+ }
+ _ => out.push(node),
+ }
+ }
+ Ok(out)
+}
+
+fn page_ref(doc: &Document, page: usize) -> Result<ObjRef, AnnotError> {
+ page_refs(doc)?.get(page).copied().ok_or(AnnotError::NoSuchPage(page))
+}
+
+/// The entries of a page's `/Annots` (references or inline dictionaries).
+fn annots(doc: &Document, page: ObjRef) -> Vec<Object> {
+ let obj = doc.get(page);
+ let Some(a) = obj.as_dict().and_then(|d| d.get(b"Annots")) else { return Vec::new() };
+ doc.resolve(a).as_array().cloned().unwrap_or_default()
+}
+
+/// Replace a page's `/Annots`, writing into the shared array object when it is indirect.
+fn set_annots(doc: &mut Document, page: ObjRef, list: Vec<Object>) -> Result<(), AnnotError> {
+ let existing = doc.get(page).as_dict().and_then(|d| d.reference(b"Annots"));
+ match existing {
+ Some(r) if doc.get(r).as_array().is_some() => doc.set(r, Object::Array(list)),
+ _ => doc.update_dict(page, |d| {
+ if list.is_empty() {
+ d.remove(b"Annots");
+ } else {
+ d.set(b"Annots".to_vec(), Object::Array(list));
+ }
+ })?,
+ }
+ Ok(())
+}
+
+/// The annotation at `(page, index)` as an indirect object (inline dictionaries are promoted).
+fn annot_ref(doc: &mut Document, page: usize, index: usize) -> Result<(ObjRef, ObjRef), AnnotError> {
+ let p = page_ref(doc, page)?;
+ let mut list = annots(doc, p);
+ let entry = list.get(index).cloned().ok_or(AnnotError::NoSuchAnnotation { page, index })?;
+ let r = match entry {
+ Object::Ref(r) if doc.get(r).as_dict().is_some() => r,
+ Object::Dict(d) => {
+ let r = doc.add(Object::Dict(d));
+ list[index] = Object::Ref(r);
+ set_annots(doc, p, list)?;
+ r
+ }
+ _ => return Err(AnnotError::NoSuchAnnotation { page, index }),
+ };
+ Ok((p, r))
+}
+
+fn annot_dict(doc: &Document, r: ObjRef) -> Dict {
+ doc.get(r).as_dict().cloned().unwrap_or_default()
+}
+
+// ── building ────────────────────────────────────────────────────────────────────────────────
+
+/// Annotation flags (§12.5.3).
+const FLAG_PRINT: i64 = 4;
+const FLAG_NO_ZOOM: i64 = 8;
+const FLAG_NO_ROTATE: i64 = 16;
+
+/// Size of a note icon (points, unscaled by zoom).
+pub const NOTE_SIZE: f64 = 20.0;
+
+fn num_array(v: &[f64]) -> Object {
+ Object::Array(v.iter().map(|x| Object::Real(*x)).collect())
+}
+
+fn rgb(c: Rgb) -> Object {
+ num_array(&c.map(|x| x.clamp(0.0, 1.0)))
+}
+
+fn finite(v: &[f64]) -> bool {
+ v.iter().all(|x| x.is_finite() && x.abs() < 1e7)
+}
+
+fn normalize(r: [f64; 4]) -> [f64; 4] {
+ [r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])]
+}
+
+fn bounds(points: impl Iterator<Item = [f64; 2]>) -> Option<[f64; 4]> {
+ points.fold(None, |acc, [x, y]| match acc {
+ None => Some([x, y, x, y]),
+ Some([a, b, c, d]) => Some([a.min(x), b.min(y), c.max(x), d.max(y)]),
+ })
+}
+
+fn grow(r: [f64; 4], by: f64) -> [f64; 4] {
+ [r[0] - by, r[1] - by, r[2] + by, r[3] + by]
+}
+
+/// Validate and compute `/Rect` for a new comment.
+fn rect_for(shape: &Shape, style: &Style) -> Result<[f64; 4], AnnotError> {
+ let bad = |what: &str| AnnotError::Invalid(format!("invalid {what}"));
+ let half = style.width.max(0.0) / 2.0;
+ let r = match shape {
+ Shape::Note { at, .. } => {
+ if !finite(at) {
+ return Err(bad("position"));
+ }
+ [at[0], at[1] - NOTE_SIZE, at[0] + NOTE_SIZE, at[1]]
+ }
+ Shape::TextMarkup { quads, .. } => {
+ if quads.is_empty() || !quads.iter().all(|q| finite(q)) {
+ return Err(bad("text area (no quadrilaterals)"));
+ }
+ bounds(quads.iter().flat_map(|q| q.chunks_exact(2).map(|p| [p[0], p[1]]).collect::<Vec<_>>())).ok_or_else(|| bad("text area"))?
+ }
+ Shape::Rectangle { rect } | Shape::Oval { rect } | Shape::TextBox { rect, .. } => {
+ let r = normalize(*rect);
+ if !finite(rect) || r[2] - r[0] < 1.0 || r[3] - r[1] < 1.0 {
+ return Err(bad("rectangle (too small)"));
+ }
+ r
+ }
+ Shape::Line { from, to, arrow } => {
+ if !finite(from) || !finite(to) || (from[0] - to[0]).hypot(from[1] - to[1]) < 1.0 {
+ return Err(bad("line (too short)"));
+ }
+ let pad = half + if *arrow { appearance::arrow_size(style.width) } else { 0.0 };
+ grow(bounds([*from, *to].into_iter()).unwrap_or_default(), pad + 1.0)
+ }
+ Shape::Ink { strokes } => {
+ if strokes.iter().all(|s| s.is_empty()) || !strokes.iter().flatten().all(|p| finite(p)) {
+ return Err(bad("drawing (no points)"));
+ }
+ grow(bounds(strokes.iter().flatten().copied()).unwrap_or_default(), half + 1.0)
+ }
+ };
+ Ok(r)
+}
+
+fn base_dict(subtype: &str, rect: [f64; 4], page: ObjRef, contents: &str, author: &str, meta: &Meta) -> Dict {
+ let mut d = Dict::new();
+ d.set(b"Type".to_vec(), Object::name("Annot"));
+ d.set(b"Subtype".to_vec(), Object::name(subtype));
+ d.set(b"Rect".to_vec(), num_array(&rect));
+ d.set(b"Contents".to_vec(), PdfString::text(contents));
+ if !author.is_empty() {
+ d.set(b"T".to_vec(), PdfString::text(author));
+ }
+ if let Some(date) = &meta.date {
+ d.set(b"M".to_vec(), PdfString::literal(date.as_bytes().to_vec()));
+ d.set(b"CreationDate".to_vec(), PdfString::literal(date.as_bytes().to_vec()));
+ }
+ if !meta.id.is_empty() {
+ d.set(b"NM".to_vec(), PdfString::text(&meta.id));
+ }
+ d.set(b"P".to_vec(), Object::Ref(page));
+ d.set(b"F".to_vec(), Object::Int(FLAG_PRINT));
+ d
+}
+
+/// Acrobat's `/Subj` for each tool (shown as the comment type in other viewers).
+fn subject(shape: &Shape) -> &'static str {
+ match shape {
+ Shape::Note { .. } => "Sticky Note",
+ Shape::TextMarkup { kind: Markup::Highlight, .. } => "Highlight",
+ Shape::TextMarkup { kind: Markup::Underline, .. } => "Underline",
+ Shape::TextMarkup { kind: Markup::StrikeOut, .. } => "Strikethrough",
+ Shape::TextMarkup { kind: Markup::Squiggly, .. } => "Squiggly",
+ Shape::Rectangle { .. } => "Rectangle",
+ Shape::Oval { .. } => "Oval",
+ Shape::Line { arrow: true, .. } => "Arrow",
+ Shape::Line { .. } => "Line",
+ Shape::Ink { .. } => "Pencil",
+ Shape::TextBox { .. } => "Text Box",
+ }
+}
+
+/// Add a comment; returns its index in the page's `/Annots`.
+pub fn add_annotation(doc: &mut Document, new: &NewAnnotation, meta: &Meta) -> Result<usize, AnnotError> {
+ let page = page_ref(doc, new.page)?;
+ let style = &new.style;
+ if !finite(&style.color) || !style.opacity.is_finite() || !style.width.is_finite() {
+ return Err(AnnotError::Invalid("invalid style".into()));
+ }
+ let rect = rect_for(&new.shape, style)?;
+ let mut d = base_dict(new.shape.subtype(), rect, page, &new.contents, &new.author, meta);
+ d.set(b"Subj".to_vec(), PdfString::text(subject(&new.shape)));
+ let opacity = style.opacity.clamp(0.0, 1.0);
+ if opacity < 1.0 {
+ d.set(b"CA".to_vec(), Object::Real(opacity));
+ }
+ let border = |d: &mut Dict| {
+ let mut bs = Dict::new();
+ bs.set(b"W".to_vec(), Object::Real(style.width.max(0.0)));
+ bs.set(b"S".to_vec(), Object::name("S"));
+ d.set(b"BS".to_vec(), Object::Dict(bs));
+ };
+ let mut popup = None;
+ match &new.shape {
+ Shape::Note { icon, .. } => {
+ d.set(b"C".to_vec(), rgb(style.color));
+ d.set(b"Name".to_vec(), Object::name(icon.name()));
+ d.set(b"F".to_vec(), Object::Int(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE));
+ d.set(b"Open".to_vec(), Object::Bool(false));
+ popup = Some([rect[2] + 10.0, rect[3] - 120.0, rect[2] + 210.0, rect[3]]);
+ }
+ Shape::TextMarkup { quads, .. } => {
+ d.set(b"C".to_vec(), rgb(style.color));
+ d.set(b"QuadPoints".to_vec(), num_array(&quads.concat()));
+ }
+ Shape::Rectangle { .. } | Shape::Oval { .. } => {
+ d.set(b"C".to_vec(), rgb(style.color));
+ if let Some(f) = style.fill {
+ d.set(b"IC".to_vec(), rgb(f));
+ }
+ border(&mut d);
+ }
+ Shape::Line { from, to, arrow } => {
+ d.set(b"C".to_vec(), rgb(style.color));
+ d.set(b"L".to_vec(), num_array(&[from[0], from[1], to[0], to[1]]));
+ if *arrow {
+ d.set(b"LE".to_vec(), Object::Array(vec![Object::name("None"), Object::name("OpenArrow")]));
+ }
+ border(&mut d);
+ }
+ Shape::Ink { 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();
+ d.set(b"InkList".to_vec(), Object::Array(list));
+ border(&mut d);
+ }
+ Shape::TextBox { font_size, .. } => {
+ let size = if font_size.is_finite() && *font_size > 0.0 { font_size.clamp(1.0, 400.0) } else { 12.0 };
+ let [r, g, b] = style.color.map(|x| x.clamp(0.0, 1.0));
+ d.set(b"DA".to_vec(), PdfString::literal(format!("{} {} {} rg /Helv {} Tf", n(r), n(g), n(b), n(size)).into_bytes()));
+ d.set(b"Q".to_vec(), Object::Int(0));
+ if let Some(f) = style.fill {
+ d.set(b"C".to_vec(), rgb(f));
+ }
+ border(&mut d);
+ }
+ }
+ let r = doc.add(Object::Dict(d.clone()));
+ set_appearance(doc, r)?;
+ let mut list = annots(doc, page);
+ let index = list.len();
+ list.push(Object::Ref(r));
+ if let Some(pr) = popup {
+ let mut p = Dict::new();
+ p.set(b"Type".to_vec(), Object::name("Annot"));
+ p.set(b"Subtype".to_vec(), Object::name("Popup"));
+ p.set(b"Rect".to_vec(), num_array(&pr));
+ p.set(b"Parent".to_vec(), Object::Ref(r));
+ p.set(b"Open".to_vec(), Object::Bool(false));
+ p.set(b"F".to_vec(), Object::Int(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE));
+ let pref = doc.add(Object::Dict(p));
+ doc.update_dict(r, |d| d.set(b"Popup".to_vec(), Object::Ref(pref)))?;
+ list.push(Object::Ref(pref));
+ }
+ set_annots(doc, page, list)?;
+ Ok(index)
+}
+
+/// (Re)generate `/AP /N` for the annotation `r` from its dictionary.
+fn set_appearance(doc: &mut Document, r: ObjRef) -> Result<(), AnnotError> {
+ let d = annot_dict(doc, r);
+ let subtype = String::from_utf8_lossy(d.name(b"Subtype").unwrap_or_default()).into_owned();
+ let Some(stream) = appearance::build(&d) else { return Err(AnnotError::Unsupported(subtype)) };
+ let ap = doc.add(Object::Stream(stream));
+ let mut apd = Dict::new();
+ apd.set(b"N".to_vec(), Object::Ref(ap));
+ doc.update_dict(r, |d| {
+ d.set(b"AP".to_vec(), Object::Dict(apd));
+ d.remove(b"AS");
+ })?;
+ Ok(())
+}
+
+/// Format a number for content streams and DA strings.
+pub(crate) fn n(v: f64) -> String {
+ let s = format!("{:.3}", if v.abs() < 5e-4 { 0.0 } else { v });
+ let s = s.trim_end_matches('0').trim_end_matches('.');
+ if s == "-0" { "0".into() } else { s.into() }
+}
+
+// ── edits ───────────────────────────────────────────────────────────────────────────────────
+
+fn touch(d: &mut Dict, meta: &Meta) {
+ if let Some(date) = &meta.date {
+ d.set(b"M".to_vec(), PdfString::literal(date.as_bytes().to_vec()));
+ }
+}
+
+/// Delete a comment together with its pop-up and its replies (and theirs), as Acrobat does.
+pub fn delete_annotation(doc: &mut Document, page: usize, index: usize) -> Result<(), AnnotError> {
+ let p = page_ref(doc, page)?;
+ let list = annots(doc, p);
+ let target = list.get(index).cloned().ok_or(AnnotError::NoSuchAnnotation { page, index })?;
+ let mut doomed: Vec<ObjRef> = target.as_ref().into_iter().collect();
+ // Replies (`/IRT`) and pop-ups (`/Parent`) of anything doomed, to a fixpoint.
+ loop {
+ let before = doomed.len();
+ for e in &list {
+ let Some(r) = e.as_ref() else { continue };
+ if doomed.contains(&r) {
+ continue;
+ }
+ let obj = doc.get(r);
+ let Some(d) = obj.as_dict() else { continue };
+ let points_at = |k: &[u8]| d.reference(k).is_some_and(|t| doomed.contains(&t));
+ if points_at(b"IRT") || points_at(b"Parent") {
+ doomed.push(r);
+ }
+ }
+ for r in doomed.clone() {
+ if let Some(pop) = doc.get(r).as_dict().and_then(|d| d.reference(b"Popup"))
+ && !doomed.contains(&pop)
+ {
+ doomed.push(pop);
+ }
+ }
+ if doomed.len() == before {
+ break;
+ }
+ }
+ let kept: Vec<Object> =
+ list.into_iter().enumerate().filter(|(i, e)| *i != index && !e.as_ref().is_some_and(|r| doomed.contains(&r))).map(|(_, e)| e).collect();
+ set_annots(doc, p, kept)
+}
+
+/// Change a comment's text. Text boxes are redrawn to show it.
+pub fn set_contents(doc: &mut Document, page: usize, index: usize, text: &str, meta: &Meta) -> Result<(), AnnotError> {
+ let (_, r) = annot_ref(doc, page, index)?;
+ let free_text = annot_dict(doc, r).name(b"Subtype") == Some(b"FreeText");
+ doc.update_dict(r, |d| {
+ d.set(b"Contents".to_vec(), PdfString::text(text));
+ // The rich-text version would contradict the new plain text.
+ d.remove(b"RC");
+ touch(d, meta);
+ })?;
+ if free_text {
+ set_appearance(doc, r)?;
+ }
+ Ok(())
+}
+
+/// Reply to a comment; returns the reply's index in the page's `/Annots`.
+///
+/// A reply is a text annotation with `/IRT` pointing at its parent (§12.5.6.2). It gets the
+/// parent's rectangle and an empty appearance, so it shows in comment lists but never paints a
+/// second icon on the page.
+pub fn add_reply(doc: &mut Document, page: usize, index: usize, text: &str, author: &str, meta: &Meta) -> Result<usize, AnnotError> {
+ reply(doc, page, index, text, author, meta, None)
+}
+
+/// Set a comment's review status (Acrobat: "Set status ▸ Accepted"…). Like Acrobat this adds a
+/// state reply (`/State`, `/StateModel /Review`) by `author`; the latest one wins.
+pub fn set_review_state(doc: &mut Document, page: usize, index: usize, state: ReviewState, author: &str, meta: &Meta) -> Result<usize, AnnotError> {
+ let text = format!("{} set by {}", state.name(), if author.is_empty() { "unknown" } else { author });
+ reply(doc, page, index, &text, author, meta, Some(state))
+}
+
+fn reply(
+ doc: &mut Document,
+ page: usize,
+ index: usize,
+ text: &str,
+ author: &str,
+ meta: &Meta,
+ state: Option<ReviewState>,
+) -> Result<usize, AnnotError> {
+ let (p, parent) = annot_ref(doc, page, index)?;
+ let pd = annot_dict(doc, parent);
+ if pd.name(b"Subtype") == Some(b"Popup") {
+ return Err(AnnotError::Invalid("pop-ups can't be replied to".into()));
+ }
+ let rect = pd.get(b"Rect").cloned().unwrap_or_else(|| num_array(&[0.0, 0.0, 0.0, 0.0]));
+ let mut d = base_dict("Text", [0.0; 4], p, text, author, meta);
+ d.set(b"Rect".to_vec(), rect);
+ d.set(b"IRT".to_vec(), Object::Ref(parent));
+ d.set(b"F".to_vec(), Object::Int(FLAG_PRINT | FLAG_NO_ZOOM | FLAG_NO_ROTATE));
+ d.set(b"Name".to_vec(), Object::name("Comment"));
+ if let Some(c) = pd.get(b"C") {
+ d.set(b"C".to_vec(), c.clone());
+ }
+ if let Some(s) = state {
+ d.set(b"State".to_vec(), PdfString::text(s.name()));
+ d.set(b"StateModel".to_vec(), PdfString::text("Review"));
+ d.set(b"Subj".to_vec(), PdfString::text("Status"));
+ }
+ // An empty form: nothing is drawn for the reply itself.
+ let mut fd = Dict::new();
+ fd.set(b"Type".to_vec(), Object::name("XObject"));
+ fd.set(b"Subtype".to_vec(), Object::name("Form"));
+ fd.set(b"BBox".to_vec(), num_array(&[0.0, 0.0, 0.0, 0.0]));
+ let ap = doc.add(Object::Stream(printcraft_cos::Stream::from_raw(fd, Vec::new())));
+ let mut apd = Dict::new();
+ apd.set(b"N".to_vec(), Object::Ref(ap));
+ d.set(b"AP".to_vec(), Object::Dict(apd));
+ let r = doc.add(Object::Dict(d));
+ let mut list = annots(doc, p);
+ list.push(Object::Ref(r));
+ let i = list.len() - 1;
+ set_annots(doc, p, list)?;
+ Ok(i)
+}
+
+/// Move a comment (and its pop-up) by `(dx, dy)` points. The appearance moves with `/Rect`.
+pub fn move_annotation(doc: &mut Document, page: usize, index: usize, dx: f64, dy: f64, meta: &Meta) -> Result<(), AnnotError> {
+ if !finite(&[dx, dy]) {
+ return Err(AnnotError::Invalid("invalid offset".into()));
+ }
+ let (_, r) = annot_ref(doc, page, index)?;
+ let shift = |o: &Object, every: bool| -> Option<Object> {
+ let a = o.as_array()?;
+ Some(Object::Array(
+ a.iter()
+ .enumerate()
+ .map(|(i, v)| match v.as_f64() {
+ Some(x) if every || i < 4 => Object::Real(x + if i % 2 == 0 { dx } else { dy }),
+ _ => v.clone(),
+ })
+ .collect(),
+ ))
+ };
+ let popup = annot_dict(doc, r).reference(b"Popup");
+ doc.update_dict(r, |d| {
+ for (k, every) in [(&b"Rect"[..], false), (b"QuadPoints", true), (b"L", false), (b"CL", true), (b"Vertices", true)] {
+ if let Some(v) = d.get(k).and_then(|o| shift(o, every)) {
+ d.set(k.to_vec(), v);
+ }
+ }
+ if let Some(Object::Array(list)) = d.get(b"InkList").cloned() {
+ let moved = list.iter().map(|s| shift(s, true).unwrap_or_else(|| s.clone())).collect();
+ d.set(b"InkList".to_vec(), Object::Array(moved));
+ }
+ touch(d, meta);
+ })?;
+ if let Some(p) = popup
+ && doc.get(p).as_dict().is_some()
+ {
+ doc.update_dict(p, |d| {
+ if let Some(v) = d.get(b"Rect").and_then(|o| shift(o, false)) {
+ d.set(b"Rect".to_vec(), v);
+ }
+ })?;
+ }
+ Ok(())
+}
+
+/// Resize a rectangle, oval or text box to `rect`; its appearance is redrawn.
+pub fn set_rect(doc: &mut Document, page: usize, index: usize, rect: [f64; 4], meta: &Meta) -> Result<(), AnnotError> {
+ let (_, r) = annot_ref(doc, page, index)?;
+ let d = annot_dict(doc, r);
+ let subtype = String::from_utf8_lossy(d.name(b"Subtype").unwrap_or_default()).into_owned();
+ if !matches!(subtype.as_str(), "Square" | "Circle" | "FreeText") {
+ return Err(AnnotError::Invalid(format!("{subtype} comments can't be resized")));
+ }
+ let rect = normalize(rect);
+ if !finite(&rect) || rect[2] - rect[0] < 1.0 || rect[3] - rect[1] < 1.0 {
+ return Err(AnnotError::Invalid("invalid rectangle (too small)".into()));
+ }
+ doc.update_dict(r, |d| {
+ d.set(b"Rect".to_vec(), num_array(&rect));
+ d.remove(b"RD");
+ touch(d, meta);
+ })?;
+ set_appearance(doc, r)
+}
+
+/// Change a comment's colour, opacity and/or line width, and redraw it.
+pub fn set_style(
+ doc: &mut Document,
+ page: usize,
+ index: usize,
+ color: Option<Rgb>,
+ opacity: Option<f64>,
+ width: Option<f64>,
+ meta: &Meta,
+) -> Result<(), AnnotError> {
+ let (_, r) = annot_ref(doc, page, index)?;
+ let d = annot_dict(doc, r);
+ let subtype = String::from_utf8_lossy(d.name(b"Subtype").unwrap_or_default()).into_owned();
+ // Check before changing anything: a stale appearance would contradict the new style.
+ if appearance::build(&d).is_none() {
+ return Err(AnnotError::Unsupported(subtype));
+ }
+ if color.is_some_and(|c| !finite(&c)) || opacity.is_some_and(|o| !o.is_finite()) || width.is_some_and(|w| !w.is_finite()) {
+ return Err(AnnotError::Invalid("invalid style".into()));
+ }
+ let free_text = subtype == "FreeText";
+ doc.update_dict(r, |d| {
+ if let Some(c) = color {
+ if free_text {
+ let (_, size) = appearance::parse_da(d);
+ let [r, g, b] = c.map(|x| x.clamp(0.0, 1.0));
+ d.set(b"DA".to_vec(), PdfString::literal(format!("{} {} {} rg /Helv {} Tf", n(r), n(g), n(b), n(size)).into_bytes()));
+ } else {
+ d.set(b"C".to_vec(), rgb(c));
+ }
+ }
+ if let Some(o) = opacity {
+ let o = o.clamp(0.0, 1.0);
+ if o < 1.0 {
+ d.set(b"CA".to_vec(), Object::Real(o));
+ } else {
+ d.remove(b"CA");
+ }
+ }
+ if let Some(w) = width {
+ let mut bs = d.get(b"BS").and_then(|b| b.as_dict()).cloned().unwrap_or_default();
+ bs.set(b"W".to_vec(), Object::Real(w.max(0.0)));
+ d.set(b"BS".to_vec(), Object::Dict(bs));
+ d.remove(b"Border");
+ }
+ touch(d, meta);
+ })?;
+ set_appearance(doc, r)
+}
diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rs
new file mode 100644
index 000000000..944096fc6
--- /dev/null
+++ b/crates/annot/src/tests.rs
@@ -0,0 +1,303 @@
+use std::sync::Arc;
+
+use printcraft_cos::{Document, ObjRef, Object, SaveOptions, write_incremental};
+
+use super::*;
+
+/// Two pages. Page 1 has an inline Square annotation in a direct /Annots array; page 2 has an
+/// indirect /Annots array holding a Stamp (a type we cannot redraw).
+fn fixture() -> Document {
+ let objs: Vec<&[u8]> = vec![
+ b"<< /Type /Catalog /Pages 2 0 R >>", // 1
+ b"<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 /MediaBox [0 0 612 792] >>", // 2
+ b"<< /Type /Page /Parent 2 0 R /Annots [<< /Type /Annot /Subtype /Square /Rect [10 10 50 50] /C [1 0 0] >>] >>", // 3
+ b"<< /Type /Page /Parent 2 0 R /Annots 5 0 R >>", // 4
+ b"[6 0 R]", // 5
+ b"<< /Type /Annot /Subtype /Stamp /Rect [100 100 200 150] /Name /Approved /Foo (kept) >>", // 6
+ ];
+ let mut out = b"%PDF-1.7\n".to_vec();
+ let mut offsets = Vec::new();
+ for (i, o) in objs.iter().enumerate() {
+ offsets.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes());
+ out.extend_from_slice(o);
+ out.extend_from_slice(b"\nendobj\n");
+ }
+ let xref = out.len();
+ out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
+ for o in offsets {
+ out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
+ }
+ out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
+ Document::open(Arc::new(out)).expect("opens")
+}
+
+fn meta(id: &str) -> Meta {
+ Meta { date: Some("D:20261001120000Z".into()), id: id.into() }
+}
+
+fn new(page: usize, shape: Shape) -> NewAnnotation {
+ NewAnnotation {
+ page,
+ shape,
+ style: Style { color: [0.0, 0.4, 1.0], opacity: 1.0, width: 2.0, fill: None },
+ contents: "hello".into(),
+ author: "Ada".into(),
+ }
+}
+
+/// Save incrementally and reopen, so every check runs against what a reader would see.
+fn reopen(doc: &Document) -> Document {
+ let bytes = write_incremental(doc, &SaveOptions::default()).expect("writes");
+ // A second, independent parser must accept the result too.
+ hayro_syntax::Pdf::new(bytes.clone()).expect("hayro-syntax parses the output");
+ Document::open(Arc::new(bytes)).expect("reopens")
+}
+
+fn list(doc: &Document, page: usize) -> Vec<Dict> {
+ let p = page_refs(doc).unwrap()[page];
+ annots(doc, p).iter().map(|o| doc.resolve(o).as_dict().cloned().unwrap()).collect()
+}
+
+fn ap_content(doc: &Document, d: &Dict) -> String {
+ let n = d.get(b"AP").and_then(|a| a.as_dict()).and_then(|a| a.reference(b"N")).expect("has /AP /N");
+ let obj = doc.get(n);
+ let Object::Stream(s) = &*obj else { panic!("AP is not a stream") };
+ String::from_utf8_lossy(&s.decoded().unwrap()).into_owned()
+}
+
+fn text(d: &Dict, k: &[u8]) -> String {
+ d.get(k).and_then(|o| o.as_string()).map(|s| s.to_text()).unwrap_or_default()
+}
+
+fn rect(d: &Dict) -> Vec<f64> {
+ d.get(b"Rect").unwrap().as_array().unwrap().iter().map(|o| o.as_f64().unwrap()).collect()
+}
+
+#[test]
+fn every_tool_creates_a_drawable_comment() {
+ let shapes = [
+ Shape::Note { at: [100.0, 700.0], icon: NoteIcon::Comment },
+ Shape::TextMarkup { kind: Markup::Highlight, quads: vec![[72.0, 712.0, 200.0, 712.0, 72.0, 700.0, 200.0, 700.0]] },
+ Shape::TextMarkup { kind: Markup::Underline, quads: vec![[72.0, 612.0, 200.0, 612.0, 72.0, 600.0, 200.0, 600.0]] },
+ Shape::TextMarkup { kind: Markup::StrikeOut, quads: vec![[72.0, 512.0, 200.0, 512.0, 72.0, 500.0, 200.0, 500.0]] },
+ Shape::TextMarkup { kind: Markup::Squiggly, quads: vec![[72.0, 412.0, 200.0, 412.0, 72.0, 400.0, 200.0, 400.0]] },
+ Shape::Rectangle { rect: [300.0, 300.0, 200.0, 200.0] },
+ Shape::Oval { rect: [300.0, 300.0, 400.0, 350.0] },
+ Shape::Line { from: [50.0, 50.0], to: [150.0, 100.0], arrow: true },
+ Shape::Ink { strokes: vec![vec![[10.0, 10.0], [20.0, 30.0], [30.0, 10.0]], vec![[40.0, 40.0]]] },
+ Shape::TextBox { rect: [300.0, 600.0, 500.0, 650.0], font_size: 14.0 },
+ ];
+ let mut doc = fixture();
+ for (i, s) in shapes.iter().enumerate() {
+ let idx = add_annotation(&mut doc, &new(0, s.clone()), &meta(&format!("id-{i}"))).expect("adds");
+ assert!(idx >= 1, "appended after the existing inline annotation");
+ }
+ let doc = reopen(&doc);
+ let all = list(&doc, 0);
+ // The inline square, 10 comments and the sticky note's pop-up.
+ assert_eq!(all.len(), 12);
+ let subtypes: Vec<&[u8]> = all.iter().map(|d| d.name(b"Subtype").unwrap()).collect();
+ assert_eq!(
+ subtypes,
+ [
+ &b"Square"[..],
+ b"Text",
+ b"Popup",
+ b"Highlight",
+ b"Underline",
+ b"StrikeOut",
+ b"Squiggly",
+ b"Square",
+ b"Circle",
+ b"Line",
+ b"Ink",
+ b"FreeText"
+ ]
+ );
+ for d in all.iter().filter(|d| d.contains(b"NM")) {
+ assert_eq!(text(d, b"T"), "Ada");
+ assert_eq!(text(d, b"Contents"), "hello");
+ assert!(d.reference(b"P").is_some(), "/P points at the page");
+ assert!(!ap_content(&doc, d).is_empty(), "{:?} has an appearance", d.name(b"Subtype"));
+ }
+ // Highlight multiplies; the rectangle was normalized.
+ let hl = &all[3];
+ let ap = hl.get(b"AP").unwrap().as_dict().unwrap().reference(b"N").unwrap();
+ let res = doc.get(ap).as_dict().unwrap().get(b"Resources").cloned().unwrap();
+ let gs = res.as_dict().unwrap().get(b"ExtGState").unwrap().as_dict().unwrap().get(b"GS0").unwrap().as_dict().unwrap().clone();
+ assert_eq!(gs.name(b"BM"), Some(&b"Multiply"[..]));
+ assert_eq!(rect(&all[7]), [200.0, 200.0, 300.0, 300.0]);
+ // The arrow's rectangle includes the arrowhead and the stroke.
+ let r = rect(&all[9]);
+ assert!(r[0] < 50.0 && r[2] > 150.0 + 1.0);
+ // The text box draws its contents in Helvetica.
+ assert!(ap_content(&doc, &all[11]).contains("(hello) Tj"));
+ assert!(ap_content(&doc, &all[11]).contains("/Helv 14 Tf"));
+ // The note is a fixed-size icon with a closed pop-up.
+ assert_eq!(all[1].int(b"F"), Some(28));
+ let entries = annots(&doc, page_refs(&doc).unwrap()[0]);
+ assert_eq!(all[2].reference(b"Parent"), entries[1].as_ref());
+ assert_eq!(all[1].reference(b"Popup"), entries[2].as_ref());
+}
+
+#[test]
+fn indirect_annots_array_is_updated_in_place() {
+ let mut doc = fixture();
+ add_annotation(&mut doc, &new(1, Shape::Rectangle { rect: [0.0, 0.0, 10.0, 10.0] }), &meta("x")).unwrap();
+ let doc = reopen(&doc);
+ let page = doc.get(page_refs(&doc).unwrap()[1]);
+ assert_eq!(page.as_dict().unwrap().reference(b"Annots"), Some(ObjRef::new(5, 0)));
+ assert_eq!(doc.get(ObjRef::new(5, 0)).as_array().unwrap().len(), 2);
+}
+
+#[test]
+fn invalid_geometry_is_rejected() {
+ let mut doc = fixture();
+ let bad = [
+ Shape::TextMarkup { kind: Markup::Highlight, quads: vec![] },
+ Shape::Rectangle { rect: [0.0, 0.0, 0.5, 10.0] },
+ Shape::Line { from: [1.0, 1.0], to: [1.0, 1.0], arrow: false },
+ Shape::Ink { strokes: vec![vec![]] },
+ Shape::Note { at: [f64::NAN, 0.0], icon: NoteIcon::Note },
+ ];
+ for s in bad {
+ assert!(matches!(add_annotation(&mut doc, &new(0, s.clone()), &meta("x")), Err(AnnotError::Invalid(_))), "{s:?}");
+ }
+ assert_eq!(add_annotation(&mut doc, &new(5, Shape::Rectangle { rect: [0.0, 0.0, 10.0, 10.0] }), &meta("x")), Err(AnnotError::NoSuchPage(5)));
+ assert!(!doc.is_modified(), "failed adds change nothing");
+}
+
+#[test]
+fn replies_and_status_thread_onto_the_parent() {
+ let mut doc = fixture();
+ // Replying to the inline square promotes it to an indirect object.
+ let r = add_reply(&mut doc, 0, 0, "Agreed", "Bob", &meta("r1")).unwrap();
+ let s = set_review_state(&mut doc, 0, 0, ReviewState::Accepted, "Bob", &meta("r2")).unwrap();
+ assert_eq!((r, s), (1, 2));
+ let doc = reopen(&doc);
+ let p = page_refs(&doc).unwrap()[0];
+ let entries = annots(&doc, p);
+ let parent = entries[0].as_ref().expect("promoted to an indirect object");
+ let all = list(&doc, 0);
+ assert_eq!(all[1].reference(b"IRT"), Some(parent));
+ assert_eq!(text(&all[1], b"Contents"), "Agreed");
+ assert_eq!(rect(&all[1]), [10.0, 10.0, 50.0, 50.0]);
+ assert_eq!(ap_content(&doc, &all[1]), "", "replies draw nothing");
+ assert_eq!(text(&all[2], b"State"), "Accepted");
+ assert_eq!(text(&all[2], b"StateModel"), "Review");
+ assert_eq!(text(&all[2], b"Contents"), "Accepted set by Bob");
+}
+
+#[test]
+fn delete_takes_popup_and_reply_chain() {
+ let mut doc = fixture();
+ let note = add_annotation(&mut doc, &new(0, Shape::Note { at: [100.0, 100.0], icon: NoteIcon::Comment }), &meta("n")).unwrap();
+ let reply = add_reply(&mut doc, 0, note, "first", "Bob", &meta("r1")).unwrap();
+ add_reply(&mut doc, 0, reply, "reply to reply", "Ada", &meta("r2")).unwrap();
+ add_reply(&mut doc, 0, 0, "on the square", "Ada", &meta("r3")).unwrap();
+ assert_eq!(list(&doc, 0).len(), 6);
+ delete_annotation(&mut doc, 0, note).unwrap();
+ let doc = reopen(&doc);
+ let left: Vec<String> =
+ list(&doc, 0).iter().map(|d| format!("{}:{}", String::from_utf8_lossy(d.name(b"Subtype").unwrap()), text(d, b"Contents"))).collect();
+ assert_eq!(left, ["Square:", "Text:on the square"]);
+ let mut doc = doc;
+ assert_eq!(delete_annotation(&mut doc, 0, 9), Err(AnnotError::NoSuchAnnotation { page: 0, index: 9 }));
+}
+
+#[test]
+fn deleting_the_last_comment_removes_annots() {
+ let mut doc = fixture();
+ delete_annotation(&mut doc, 0, 0).unwrap();
+ let doc = reopen(&doc);
+ assert!(!doc.get(page_refs(&doc).unwrap()[0]).as_dict().unwrap().contains(b"Annots"));
+}
+
+#[test]
+fn move_shifts_all_geometry_and_the_popup() {
+ let mut doc = fixture();
+ let q = [72.0, 712.0, 200.0, 712.0, 72.0, 700.0, 200.0, 700.0];
+ let h = add_annotation(&mut doc, &new(0, Shape::TextMarkup { kind: Markup::Highlight, quads: vec![q] }), &meta("h")).unwrap();
+ let i = add_annotation(&mut doc, &new(0, Shape::Ink { strokes: vec![vec![[10.0, 10.0], [20.0, 20.0]]] }), &meta("i")).unwrap();
+ let n = add_annotation(&mut doc, &new(0, Shape::Note { at: [100.0, 100.0], icon: NoteIcon::Note }), &meta("n")).unwrap();
+ for idx in [h, i, n] {
+ move_annotation(&mut doc, 0, idx, 10.0, -5.0, &meta("")).unwrap();
+ }
+ let doc = reopen(&doc);
+ let all = list(&doc, 0);
+ let qp: Vec<f64> = all[h].get(b"QuadPoints").unwrap().as_array().unwrap().iter().map(|o| o.as_f64().unwrap()).collect();
+ assert_eq!(qp, [82.0, 707.0, 210.0, 707.0, 82.0, 695.0, 210.0, 695.0]);
+ let ink = all[i].get(b"InkList").unwrap().as_array().unwrap()[0].as_array().unwrap().iter().map(|o| o.as_f64().unwrap()).collect::<Vec<_>>();
+ assert_eq!(ink, [20.0, 5.0, 30.0, 15.0]);
+ assert_eq!(rect(&all[n]), [110.0, 75.0, 130.0, 95.0]);
+ let popup = &all[n + 1];
+ assert_eq!(rect(popup)[0], 140.0);
+}
+
+#[test]
+fn restyle_and_resize_redraw_the_appearance() {
+ let mut doc = fixture();
+ let r = add_annotation(&mut doc, &new(0, Shape::Rectangle { rect: [10.0, 10.0, 110.0, 60.0] }), &meta("r")).unwrap();
+ set_style(&mut doc, 0, r, Some([1.0, 0.0, 0.0]), Some(0.5), Some(4.0), &meta("")).unwrap();
+ set_rect(&mut doc, 0, r, [0.0, 0.0, 200.0, 100.0], &meta("")).unwrap();
+ let doc2 = reopen(&doc);
+ let d = &list(&doc2, 0)[r];
+ let ap = ap_content(&doc2, d);
+ assert!(ap.contains("1 0 0 RG") && ap.contains("4 w") && ap.contains("/GS0 gs"), "{ap}");
+ assert!(ap.contains("2 2 196 96 re"), "inset by half the border: {ap}");
+ assert_eq!(d.get(b"CA").and_then(|o| o.as_f64()), Some(0.5));
+ // A stamp's appearance can't be regenerated, so restyling it changes nothing.
+ let before = list(&doc, 1)[0].clone();
+ assert_eq!(set_style(&mut doc, 1, 0, Some([0.0; 3]), None, None, &meta("")), Err(AnnotError::Unsupported("Stamp".into())));
+ assert_eq!(list(&doc, 1)[0], before);
+ // Lines can't be resized as rectangles.
+ let l = add_annotation(&mut doc, &new(0, Shape::Line { from: [0.0, 0.0], to: [10.0, 10.0], arrow: false }), &meta("l")).unwrap();
+ assert!(matches!(set_rect(&mut doc, 0, l, [0.0, 0.0, 5.0, 5.0], &meta("")), Err(AnnotError::Invalid(_))));
+}
+
+#[test]
+fn text_box_text_and_colour_changes_are_drawn() {
+ let mut doc = fixture();
+ let t = add_annotation(&mut doc, &new(0, Shape::TextBox { rect: [0.0, 0.0, 300.0, 100.0], font_size: 12.0 }), &meta("t")).unwrap();
+ set_contents(&mut doc, 0, t, "Caf\u{e9} (draft) \u{2014} 100%", &meta("")).unwrap();
+ set_style(&mut doc, 0, t, Some([1.0, 0.0, 0.0]), None, None, &meta("")).unwrap();
+ let doc = reopen(&doc);
+ let d = &list(&doc, 0)[t];
+ assert_eq!(text(d, b"Contents"), "Caf\u{e9} (draft) \u{2014} 100%");
+ assert_eq!(text(d, b"DA"), "1 0 0 rg /Helv 12 Tf");
+ let n = d.get(b"AP").unwrap().as_dict().unwrap().reference(b"N").unwrap();
+ let Object::Stream(s) = &*doc.get(n) else { panic!() };
+ let raw = s.decoded().unwrap();
+ // WinAnsi bytes, with the parentheses escaped.
+ let needle = b"(Caf\xe9 \\(draft\\) \x97 100%) Tj";
+ assert!(raw.windows(needle.len()).any(|w| w == needle), "{}", String::from_utf8_lossy(&raw));
+ assert!(String::from_utf8_lossy(&raw).contains("1 0 0 rg"));
+}
+
+#[test]
+fn unknown_keys_survive_edits() {
+ let mut doc = fixture();
+ move_annotation(&mut doc, 1, 0, 1.0, 1.0, &meta("")).unwrap();
+ set_contents(&mut doc, 1, 0, "note", &meta("")).unwrap();
+ let doc = reopen(&doc);
+ let d = &list(&doc, 1)[0];
+ assert_eq!(text(d, b"Foo"), "kept");
+ assert_eq!(d.name(b"Name"), Some(&b"Approved"[..]));
+ assert_eq!(rect(d), [101.0, 101.0, 201.0, 151.0]);
+}
+
+#[test]
+fn wrapping_and_widths() {
+ assert!(appearance::text_width("MMMM", 10.0) > appearance::text_width("iiii", 10.0) * 2.0);
+ let lines = appearance::wrap("the quick brown fox jumps over the lazy dog", 12.0, 80.0);
+ assert!(lines.len() > 2);
+ assert!(lines.iter().all(|l| appearance::text_width(l, 12.0) <= 80.0));
+ assert_eq!(appearance::wrap("a\nb", 12.0, 100.0), ["a", "b"]);
+ // A word longer than the line is broken.
+ let long = appearance::wrap("Supercalifragilisticexpialidocious", 12.0, 40.0);
+ assert!(long.len() > 3 && long.concat() == "Supercalifragilisticexpialidocious");
+ assert_eq!(n(1.0), "1");
+ assert_eq!(n(-0.0001), "0");
+ assert_eq!(n(2.50), "2.5");
+}
diff --git a/crates/automation/src/comments.rs b/crates/automation/src/comments.rs
new file mode 100644
index 000000000..3f4a5e5f3
--- /dev/null
+++ b/crates/automation/src/comments.rs
@@ -0,0 +1,308 @@
+//! Comment tools: list, add, reply, set status, edit and delete (execution plan M5, AGENTS.md §3).
+//!
+//! 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_render::{Annotation, PageInfo};
+use serde_json::{Value, json};
+
+use crate::{Args, Automation, Result, ToolError, failed};
+
+/// Author used when a tool call names none.
+const DEFAULT_AUTHOR: &str = "PrintCraft";
+
+pub(crate) fn parse_color(s: &str) -> Result<Rgb> {
+ let named = match s.to_ascii_lowercase().as_str() {
+ "yellow" => Some("#FFEF00"),
+ "red" => Some("#E32222"),
+ "orange" => Some("#FF8A00"),
+ "green" => Some("#2E9E5C"),
+ "blue" => Some("#0078D6"),
+ "purple" => Some("#8A3FD1"),
+ "pink" => Some("#FF5FA2"),
+ "black" => Some("#000000"),
+ "gray" | "grey" => Some("#808080"),
+ "white" => Some("#FFFFFF"),
+ _ => None,
+ };
+ let hex = named.unwrap_or(s).trim_start_matches('#');
+ if hex.len() != 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
+ return Err(ToolError::InvalidArgs(format!("{s:?} is not a colour (use #RRGGBB or a name)")));
+ }
+ let c = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).map(|v| v as f64 / 255.0).unwrap_or(0.0);
+ Ok([c(0), c(2), c(4)])
+}
+
+fn hex(c: [f32; 3]) -> String {
+ let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
+ format!("#{:02X}{:02X}{:02X}", b(c[0]), b(c[1]), b(c[2]))
+}
+
+fn to_user(p: &PageInfo, x: f64, y: f64) -> [f64; 2] {
+ let [ux, uy] = p.view_to_user(x as f32, y as f32);
+ [ux as f64, uy as f64]
+}
+
+fn rect_to_user(p: &PageInfo, r: [f64; 4]) -> [f64; 4] {
+ let (a, b) = (to_user(p, r[0], r[1]), to_user(p, r[2], r[3]));
+ [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])]
+}
+
+fn rect_to_view(p: &PageInfo, r: [f32; 4]) -> [f32; 4] {
+ let (a, b) = (p.user_to_view(r[0], r[1]), p.user_to_view(r[2], r[3]));
+ let round = |v: f32| (v * 100.0).round() / 100.0;
+ [round(a[0].min(b[0])), round(a[1].min(b[1])), round(a[0].max(b[0])), round(a[1].max(b[1]))]
+}
+
+impl Args<'_> {
+ fn nums<const N: usize>(&self, key: &str) -> Result<Option<[f64; N]>> {
+ let Some(v) = self.get(key) else { return Ok(None) };
+ let wrong = || Self::wrong(key, &format!("an array of {N} numbers"));
+ let arr = v.as_array().ok_or_else(wrong)?;
+ let nums: Vec<f64> = arr.iter().map(|x| x.as_f64().filter(|f| f.is_finite())).collect::<Option<_>>().ok_or_else(wrong)?;
+ <[f64; N]>::try_from(nums).map(Some).map_err(|_| wrong())
+ }
+
+ fn need<const N: usize>(&self, key: &str, why: &str) -> Result<[f64; N]> {
+ self.nums(key)?.ok_or_else(|| ToolError::InvalidArgs(format!("{why} needs `{key}`")))
+ }
+
+ fn color(&self, key: &str) -> Result<Option<Rgb>> {
+ self.opt_str(key)?.map(parse_color).transpose()
+ }
+}
+
+impl Automation {
+ /// Comments of a document, optionally only of one 0-based page.
+ fn comments(&self, a: &Args) -> Result<Vec<Annotation>> {
+ let doc = self.doc(a)?;
+ Ok(doc.info.annotations.iter().filter(|x| x.subtype != "Popup").cloned().collect())
+ }
+
+ /// The (0-based page, index) a comment tool call refers to: `id`, or `page` + `index`.
+ fn comment_target(&self, a: &Args) -> Result<(usize, usize)> {
+ let all = self.comments(a)?;
+ if let Some(id) = a.opt_str("id")? {
+ let c =
+ all.iter().find(|c| c.name.as_deref() == Some(id)).ok_or_else(|| failed(format!("no comment with id {id:?} (see comment_list)")))?;
+ return Ok((c.page, c.index));
+ }
+ let (Some(page), Some(index)) = (a.opt_int("page")?, a.opt_int("index")?) else {
+ return Err(ToolError::InvalidArgs("pass the comment's id, or page and index".into()));
+ };
+ let (page, index) = ((page.max(1) - 1) as usize, (index.max(1) - 1) as usize);
+ if !all.iter().any(|c| c.page == page && c.index == index) {
+ return Err(failed(format!("there is no comment {} on page {} (see comment_list)", index + 1, page + 1)));
+ }
+ Ok((page, index))
+ }
+
+ pub(crate) fn comment_list(&self, a: &Args) -> Result<Value> {
+ let doc = self.doc(a)?;
+ let only = a.opt_int("page")?.map(|p| (p.max(1) - 1) as usize);
+ let all = self.comments(a)?;
+ let view = |c: &Annotation| -> Value {
+ let p = &doc.info.pages[c.page.min(doc.info.pages.len().saturating_sub(1))];
+ json!({
+ "id": c.name,
+ "page": c.page + 1,
+ "index": c.index + 1,
+ "type": c.subtype,
+ "author": c.author,
+ "contents": c.contents,
+ "modified": c.modified,
+ "rect": rect_to_view(p, c.rect),
+ "color": c.color.map(hex),
+ })
+ };
+ let roots: Vec<Value> = all
+ .iter()
+ .filter(|c| c.in_reply_to.is_none() && only.is_none_or(|p| c.page == p))
+ .map(|c| {
+ let mut v = view(c);
+ let thread: Vec<&Annotation> = match &c.name {
+ Some(nm) => all.iter().filter(|r| r.in_reply_to.as_deref() == Some(nm.as_str())).collect(),
+ None => Vec::new(),
+ };
+ let status = thread.iter().rev().find_map(|r| r.state.clone());
+ v["status"] = json!(status);
+ v["replies"] = thread.iter().filter(|r| r.state.is_none()).map(|r| view(r)).collect();
+ v
+ })
+ .collect();
+ Ok(json!({ "count": roots.len(), "comments": roots }))
+ }
+
+ pub(crate) fn comment_add(&mut self, a: &Args) -> Result<Value> {
+ let page = self.page(a)?;
+ let info = self.doc(a)?.info.pages[page].clone();
+ let kind = a.str("type")?;
+ let markup = match kind {
+ "highlight" => Some(Markup::Highlight),
+ "underline" => Some(Markup::Underline),
+ "strikeout" => Some(Markup::StrikeOut),
+ "squiggly" => Some(Markup::Squiggly),
+ _ => None,
+ };
+ let shape = if let Some(markup) = markup {
+ let quads = match (a.opt_str("find")?, a.get("quads")) {
+ (Some(needle), _) => {
+ let id = self.doc(a)?.id;
+ let text = self.page_texts(id, &[page])?.remove(0);
+ let mut hits = text.find(needle);
+ if hits.is_empty() {
+ return Err(failed(format!("{needle:?} was not found on page {}", page + 1)));
+ }
+ if !a.opt_bool("all")?.unwrap_or(false) {
+ hits.truncate(1);
+ }
+ hits.into_iter().flat_map(|r| text.line_rects(r)).map(|r| info.view_rect_to_quad(r)).collect()
+ }
+ (None, Some(q)) => {
+ let wrong = || ToolError::InvalidArgs("quads must be arrays of 8 numbers".into());
+ let quads = q.as_array().ok_or_else(wrong)?;
+ quads
+ .iter()
+ .map(|q| {
+ let v: Vec<f64> = q.as_array().ok_or_else(wrong)?.iter().map(|x| x.as_f64()).collect::<Option<_>>().ok_or_else(wrong)?;
+ let v: [f64; 8] = v.try_into().map_err(|_| wrong())?;
+ let mut out = [0.0; 8];
+ for i in 0..4 {
+ let [x, y] = to_user(&info, v[2 * i], v[2 * i + 1]);
+ (out[2 * i], out[2 * i + 1]) = (x, y);
+ }
+ Ok(out)
+ })
+ .collect::<Result<Vec<_>>>()?
+ }
+ (None, None) => return Err(ToolError::InvalidArgs(format!("{kind} needs `find` (text to mark) or `quads`"))),
+ };
+ Shape::TextMarkup { kind: markup, quads }
+ } else {
+ match kind {
+ "note" => {
+ let [x, y] = a.need::<2>("at", "a note")?;
+ let icon = match a.opt_str("icon")? {
+ Some(n) => NoteIcon::from_name(n).ok_or_else(|| ToolError::InvalidArgs(format!("unknown icon {n:?}")))?,
+ None => NoteIcon::Comment,
+ };
+ Shape::Note { at: to_user(&info, x, y), icon }
+ }
+ "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" => {
+ let font_size = a.opt_num("font_size")?.unwrap_or(12.0);
+ Shape::TextBox { rect: rect_to_user(&info, a.need::<4>("rect", "a text box")?), font_size }
+ }
+ "line" | "arrow" => {
+ let (f, t) = (a.need::<2>("from", "a line")?, a.need::<2>("to", "a line")?);
+ Shape::Line { from: to_user(&info, f[0], f[1]), to: to_user(&info, t[0], t[1]), arrow: kind == "arrow" }
+ }
+ "ink" => {
+ let wrong = || ToolError::InvalidArgs("strokes must be an array of arrays of [x, y] points".into());
+ let strokes = a.get("strokes").ok_or_else(|| ToolError::InvalidArgs("ink needs `strokes`".into()))?;
+ let strokes = strokes
+ .as_array()
+ .ok_or_else(wrong)?
+ .iter()
+ .map(|s| {
+ s.as_array()
+ .ok_or_else(wrong)?
+ .iter()
+ .map(|p| match p.as_array().map(|p| p.iter().map(|v| v.as_f64()).collect::<Vec<_>>()).as_deref() {
+ Some([Some(x), Some(y)]) => Ok(to_user(&info, *x, *y)),
+ _ => Err(wrong()),
+ })
+ .collect::<Result<Vec<_>>>()
+ })
+ .collect::<Result<Vec<_>>>()?;
+ Shape::Ink { strokes }
+ }
+ other => return Err(ToolError::InvalidArgs(format!("unknown comment type {other:?}"))),
+ }
+ };
+ let mut style = Style::default_for(&shape);
+ if let Some(c) = a.color("color")? {
+ style.color = c;
+ }
+ style.fill = a.color("fill")?;
+ if let Some(o) = a.opt_num("opacity")? {
+ style.opacity = o.clamp(0.0, 1.0);
+ }
+ if let Some(w) = a.opt_num("width")? {
+ style.width = w.max(0.0);
+ }
+ let contents = a.opt_str("contents")?.unwrap_or_default().to_string();
+ let author = a.opt_str("author")?.unwrap_or(DEFAULT_AUTHOR).to_string();
+ let marked = match &shape {
+ Shape::TextMarkup { quads, .. } => Some(quads.len()),
+ _ => None,
+ };
+ let before: Vec<Option<String>> = self.doc(a)?.info.annotations.iter().map(|c| c.name.clone()).collect();
+ let mut out = self.apply(a, Edit::AddAnnotation(NewAnnotation { page, shape, style, contents, author }))?;
+ let added = self.doc(a)?.info.annotations.iter().find(|c| c.page == page && c.subtype != "Popup" && !before.contains(&c.name));
+ out["comment"] = json!({ "id": added.and_then(|c| c.name.clone()), "page": page + 1, "index": added.map(|c| c.index + 1) });
+ if let Some(n) = marked {
+ out["comment"]["lines"] = json!(n);
+ }
+ Ok(out)
+ }
+
+ pub(crate) fn comment_reply(&mut self, a: &Args) -> Result<Value> {
+ let (page, index) = self.comment_target(a)?;
+ let author = a.opt_str("author")?.unwrap_or(DEFAULT_AUTHOR).to_string();
+ self.apply(a, Edit::ReplyToAnnotation { page, index, text: a.str("text")?.to_string(), author })
+ }
+
+ pub(crate) fn comment_set_status(&mut self, a: &Args) -> Result<Value> {
+ let (page, index) = self.comment_target(a)?;
+ let status = a.str("status")?;
+ let state = ReviewState::from_name(status).ok_or_else(|| ToolError::InvalidArgs(format!("unknown status {status:?}")))?;
+ let author = a.opt_str("author")?.unwrap_or(DEFAULT_AUTHOR).to_string();
+ self.apply(a, Edit::SetAnnotationStatus { page, index, state, author })
+ }
+
+ pub(crate) fn comment_edit(&mut self, a: &Args) -> Result<Value> {
+ let (page, index) = self.comment_target(a)?;
+ let info = self.doc(a)?.info.pages[page].clone();
+ let mut edits = Vec::new();
+ if let Some(text) = a.opt_str("contents")? {
+ edits.push(Edit::SetAnnotationContents { page, index, text: text.to_string() });
+ }
+ let (color, opacity, width) = (a.color("color")?, a.opt_num("opacity")?, a.opt_num("width")?);
+ if color.is_some() || opacity.is_some() || width.is_some() {
+ edits.push(Edit::StyleAnnotation { page, index, color, opacity, width });
+ }
+ if let Some(r) = a.nums::<4>("rect")? {
+ edits.push(Edit::ResizeAnnotation { page, index, rect: rect_to_user(&info, r) });
+ }
+ if let Some([dx, dy]) = a.nums::<2>("move")? {
+ let (o, d) = (to_user(&info, 0.0, 0.0), to_user(&info, dx, dy));
+ edits.push(Edit::MoveAnnotation { page, index, dx: d[0] - o[0], dy: d[1] - o[1] });
+ }
+ if edits.is_empty() {
+ return Err(ToolError::InvalidArgs("nothing to change: pass contents, color, opacity, width, rect or move".into()));
+ }
+ let edit = if edits.len() == 1 { edits.remove(0) } else { Edit::Batch { label: "Edit comment".into(), edits } };
+ self.apply(a, edit)
+ }
+
+ pub(crate) fn comment_delete(&mut self, a: &Args) -> Result<Value> {
+ let (page, index) = self.comment_target(a)?;
+ self.apply(a, Edit::DeleteAnnotation { page, index })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn colours_parse_by_hex_and_name() {
+ assert_eq!(parse_color("#FF0000").unwrap(), [1.0, 0.0, 0.0]);
+ assert_eq!(parse_color("black").unwrap(), [0.0, 0.0, 0.0]);
+ assert!(parse_color("#12").is_err() && parse_color("chartreuse").is_err());
+ assert_eq!(hex([1.0, 0.5, 0.0]), "#FF8000");
+ }
+}
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
index ea2200e21..8ab056e29 100644
--- a/crates/automation/src/lib.rs
+++ b/crates/automation/src/lib.rs
@@ -9,6 +9,7 @@
//! with the origin at the top-left of the displayed page.
//! - An optional root directory confines every path a tool reads or writes.
+mod comments;
#[cfg(feature = "mcp")]
pub mod mcp;
mod tools;
@@ -208,6 +209,12 @@ impl Automation {
let (path, page) = (a.path("path")?, self.page(&a)?);
self.apply(&a, Edit::SetBookmarkPage { path, page })?
}
+ "comment_list" => self.comment_list(&a)?,
+ "comment_add" => self.comment_add(&a)?,
+ "comment_reply" => self.comment_reply(&a)?,
+ "comment_set_status" => self.comment_set_status(&a)?,
+ "comment_edit" => self.comment_edit(&a)?,
+ "comment_delete" => self.comment_delete(&a)?,
other => return Err(ToolError::UnknownTool(other.into())),
};
Ok(vec![Content::Json(out)])
diff --git a/crates/automation/src/tools.rs b/crates/automation/src/tools.rs
index 401d2c76b..db487d857 100644
--- a/crates/automation/src/tools.rs
+++ b/crates/automation/src/tools.rs
@@ -34,6 +34,24 @@ fn path(what: &str) -> Value {
json!({ "type": "array", "items": { "type": "integer", "minimum": 1 }, "description": format!("{what}: 1-based positions from the top level, e.g. [2, 1] = the first child of the second bookmark.") })
}
+fn point() -> Value {
+ json!({ "type": "array", "items": { "type": "number" }, "minItems": 2, "maxItems": 2, "description": "[x, y] in points from the top-left of the displayed page." })
+}
+
+fn color() -> Value {
+ json!({ "type": "string", "description": "#RRGGBB or a name: yellow, red, orange, green, blue, purple, pink, black, gray, white." })
+}
+
+/// Properties that pick one comment: its `id` (from comment_list), or `page` + `index`.
+fn comment_ref(mut extra: Value) -> Value {
+ let props = extra.as_object_mut().expect("an object");
+ props.insert("doc".into(), doc());
+ props.insert("id".into(), json!({ "type": "string", "description": "The comment's id (from comment_list)." }));
+ props.insert("page".into(), json!({ "type": "integer", "minimum": 1, "description": "With `index`, instead of `id`." }));
+ props.insert("index".into(), json!({ "type": "integer", "minimum": 1, "description": "1-based position on the page, as comment_list reports." }));
+ extra
+}
+
fn schema(props: Value, required: &[&str]) -> Value {
json!({ "type": "object", "properties": props, "required": required, "additionalProperties": false })
}
@@ -177,6 +195,60 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["doc", "from", "to"],
)),
+ t("comment_list", "List comments", "Every comment (annotation other than links, form widgets and pop-ups) with its page, index, id, type, author, text, date, rectangle, colour, review status and replies.")
+ .ro()
+ .with(schema(json!({ "doc": doc(), "page": { "type": "integer", "minimum": 1, "description": "Only this page." } }), &["doc"])),
+ t(
+ "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`. \
+ 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"] },
+ "contents": { "type": "string", "description": "The comment text (what a text box shows)." },
+ "author": { "type": "string" },
+ "at": point(),
+ "rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
+ "from": point(),
+ "to": point(),
+ "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 } },
+ "strokes": { "type": "array", "items": { "type": "array", "items": point() } },
+ "icon": { "type": "string", "enum": ["Comment", "Note", "Help", "Insert", "Key", "NewParagraph", "Paragraph"] },
+ "color": color(),
+ "fill": color(),
+ "opacity": { "type": "number", "minimum": 0, "maximum": 1 },
+ "width": { "type": "number", "minimum": 0, "description": "Line width in points." },
+ "font_size": { "type": "number", "exclusiveMinimum": 0 },
+ }),
+ &["doc", "page", "type"],
+ )),
+ t("comment_reply", "Reply to a comment", "Add a reply to a comment's thread. Undoable.").with(schema(
+ comment_ref(json!({ "text": { "type": "string", "minLength": 1 }, "author": { "type": "string" } })),
+ &["doc", "text"],
+ )),
+ t("comment_set_status", "Set a comment's status", "Set a comment's review status (Acrobat: Set status), recorded as a status reply. Undoable.").with(schema(
+ comment_ref(json!({ "status": { "type": "string", "enum": ["none", "accepted", "rejected", "cancelled", "completed"] }, "author": { "type": "string" } })),
+ &["doc", "status"],
+ )),
+ t("comment_edit", "Edit a comment", "Change a comment's text, colour, opacity, line width, rectangle (rectangle/oval/text box) or position (`move` [dx, dy] in points). One undo step.").with(schema(
+ comment_ref(json!({
+ "contents": { "type": "string" },
+ "color": color(),
+ "opacity": { "type": "number", "minimum": 0, "maximum": 1 },
+ "width": { "type": "number", "minimum": 0 },
+ "rect": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
+ "move": point(),
+ })),
+ &["doc"],
+ )),
+ t("comment_delete", "Delete a comment", "Delete a comment with its pop-up and replies. Undoable.").destructive().with(schema(comment_ref(json!({})), &["doc"])),
t("edit_undo", "Undo", "Undo the last edit of a document.").cmd("edit.undo").with(schema(json!({ "doc": doc() }), &["doc"])),
t("edit_redo", "Redo", "Redo the last undone edit of a document.").cmd("edit.redo").with(schema(json!({ "doc": doc() }), &["doc"])),
t("command_list", "List commands", "Every registered PrintCraft command with its menu, shortcut, whether it is enabled now, and the tool that automates it.")
diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs
index 00aab952e..8f5a95ca3 100644
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@ -340,3 +340,69 @@ fn numbering_pages_through_tools() {
assert!(matches!(a.call("page_number", &json!({ "doc": doc, "from": 2, "to": 4 })), Err(ToolError::InvalidArgs(_))));
assert!(matches!(a.call("page_number", &json!({ "doc": doc, "from": 1, "to": 1, "style": "klingon" })), Err(ToolError::InvalidArgs(_))));
}
+
+#[test]
+fn comments_through_tools() {
+ let dir = workdir("comments");
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+ // "Page 2" sits at y = 150 (user space) = 150 from the top of the 300 pt page.
+ let hl = ok(&mut a, "comment_add", json!({ "doc": doc, "page": 2, "type": "highlight", "find": "page 2", "contents": "check", "author": "Ada" }));
+ assert_eq!(hl["comment"]["lines"], 1);
+ let id = hl["comment"]["id"].as_str().unwrap().to_string();
+ ok(&mut a, "comment_add", json!({ "doc": doc, "page": 2, "type": "note", "at": [150, 20], "contents": "Sticky" }));
+ ok(&mut a, "comment_add", json!({ "doc": doc, "page": 1, "type": "rectangle", "rect": [10, 10, 60, 40], "color": "blue", "width": 3 }));
+ ok(&mut a, "comment_add", json!({ "doc": doc, "page": 1, "type": "textbox", "rect": [10, 200, 190, 240], "contents": "Hello", "font_size": 10 }));
+ ok(&mut a, "comment_add", json!({ "doc": doc, "page": 1, "type": "ink", "strokes": [[[10, 280], [50, 260], [90, 285]]] }));
+ ok(&mut a, "comment_add", json!({ "doc": doc, "page": 3, "type": "arrow", "from": [10, 10], "to": [100, 100] }));
+ ok(&mut a, "comment_reply", json!({ "doc": doc, "id": id, "text": "Looks right", "author": "Bob" }));
+ ok(&mut a, "comment_set_status", json!({ "doc": doc, "id": id, "status": "accepted", "author": "Bob" }));
+
+ let list = ok(&mut a, "comment_list", json!({ "doc": doc }));
+ assert_eq!(list["count"], 6, "{list}");
+ let c = list["comments"].as_array().unwrap().iter().find(|c| c["id"] == id.as_str()).unwrap().clone();
+ assert_eq!((c["type"].as_str(), c["author"].as_str(), c["contents"].as_str()), (Some("Highlight"), Some("Ada"), Some("check")));
+ assert_eq!(c["status"], "Accepted");
+ assert_eq!(c["replies"].as_array().unwrap().len(), 1);
+ assert_eq!(c["replies"][0]["contents"], "Looks right");
+ // The highlight covers the found text, reported in top-left-origin points.
+ let r: Vec<f64> = c["rect"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect();
+ assert!(r[0] >= 15.0 && r[0] <= 25.0 && r[1] > 120.0 && r[3] < 160.0, "{r:?}");
+ let rect = list["comments"].as_array().unwrap().iter().find(|c| c["type"] == "Square").unwrap().clone();
+ assert_eq!(rect["color"], "#0078D6");
+ assert_eq!(rect["rect"], json!([10.0, 10.0, 60.0, 40.0]));
+ let note = list["comments"].as_array().unwrap().iter().find(|c| c["type"] == "Text").unwrap().clone();
+ assert_eq!(note["rect"], json!([150.0, 20.0, 170.0, 40.0]), "note icon hangs from its top-left point");
+
+ // Edit by page + index; several changes are one undo step.
+ let (page, index) = (rect["page"].as_u64().unwrap(), rect["index"].as_u64().unwrap());
+ ok(&mut a, "comment_edit", json!({ "doc": doc, "page": page, "index": index, "color": "#FF0000", "move": [5, 5], "contents": "moved" }));
+ let list = ok(&mut a, "comment_list", json!({ "doc": doc, "page": 1 }));
+ let rect = list["comments"].as_array().unwrap().iter().find(|c| c["type"] == "Square").unwrap().clone();
+ assert_eq!((rect["color"].as_str(), rect["contents"].as_str()), (Some("#FF0000"), Some("moved")));
+ assert_eq!(rect["rect"], json!([15.0, 15.0, 65.0, 45.0]));
+ let undo = ok(&mut a, "edit_undo", json!({ "doc": doc }));
+ assert_eq!(undo["undone"], "Edit comment");
+ ok(&mut a, "edit_redo", json!({ "doc": doc }));
+
+ // The rendered page shows the rectangle's border.
+ let png = a.call("page_render", &json!({ "doc": doc, "page": 1, "dpi": 72 })).unwrap();
+ assert!(matches!(png[0], Content::Png { .. }));
+
+ ok(&mut a, "comment_delete", json!({ "doc": doc, "id": id }));
+ assert_eq!(ok(&mut a, "comment_list", json!({ "doc": doc }))["count"], 5);
+ assert!(matches!(a.call("comment_delete", &json!({ "doc": doc, "id": id })), Err(ToolError::Failed(_))));
+ assert!(matches!(a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "highlight", "find": "nowhere" })), Err(ToolError::Failed(_))));
+ assert!(matches!(a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "rectangle" })), Err(ToolError::InvalidArgs(_))));
+ assert!(matches!(
+ a.call("comment_add", &json!({ "doc": doc, "page": 1, "type": "note", "at": [1, 1], "color": "mauve" })),
+ Err(ToolError::InvalidArgs(_))
+ ));
+ assert!(matches!(a.call("comment_edit", &json!({ "doc": doc, "page": 1, "index": 1 })), Err(ToolError::InvalidArgs(_))));
+
+ // Comments survive a save and reopen.
+ ok(&mut a, "doc_save", json!({ "doc": doc, "path": "commented.pdf" }));
+ let mut b = auto(&dir);
+ let re = ok(&mut b, "doc_open", json!({ "path": "commented.pdf" }))["doc"].as_u64().unwrap();
+ assert_eq!(ok(&mut b, "comment_list", json!({ "doc": re }))["count"], 5);
+}
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index fe70e6980..2d14be6a4 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -12,4 +12,5 @@ workspace = true
printcraft-render = { workspace = true }
printcraft-cos = { workspace = true }
printcraft-organize = { workspace = true }
+printcraft-annot = { workspace = true }
thiserror = { workspace = true }
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 45799aff7..e9ae8c6f4 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -19,6 +19,10 @@ pub use printcraft_organize::{SplitBy, split_ranges};
/// One file produced by a split: (1-based first page, last page, PDF bytes).
pub use printcraft_organize::LabelStyle;
+/// Comment geometry helpers (text-box line breaking) for frontends.
+pub use printcraft_annot::appearance as annot_text;
+pub use printcraft_annot::{Markup, NewAnnotation, NoteIcon, ReviewState, Rgb, Shape, Style};
+
pub type SplitPart = (usize, usize, Arc<Vec<u8>>);
use std::sync::Arc;
@@ -91,6 +95,11 @@ impl Document {
self.editable() && self.permissions().is_none_or(|p| p.modify())
}
+ /// Adding and changing comments is allowed (Table 22, bit 6).
+ pub fn allows_annotation(&self) -> bool {
+ self.editable() && self.permissions().is_none_or(|p| p.annotate())
+ }
+
/// A summary of the document's security for Document Properties ▸ Security.
pub fn security_summary(&self) -> Option<SecuritySummary> {
let editor = self.editor.as_ref()?;
@@ -207,6 +216,50 @@ pub enum Edit {
prefix: String,
first: u32,
},
+ /// Add a comment (sticky note, highlight, shape, drawing, text box…).
+ AddAnnotation(NewAnnotation),
+ /// 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,
+ },
+ MoveAnnotation {
+ page: usize,
+ index: usize,
+ dx: f64,
+ dy: f64,
+ },
+ /// 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>,
+ },
/// Several edits applied as one undoable step (all or nothing).
Batch {
label: String,
@@ -230,11 +283,36 @@ impl Edit {
Edit::MoveBookmark { .. } => "Move bookmark".into(),
Edit::SetBookmarkPage { .. } => "Set bookmark destination".into(),
Edit::NumberPages { .. } => "Number pages".into(),
+ Edit::AddAnnotation(a) => format!("Add {}", annotation_noun(&a.shape)),
+ Edit::DeleteAnnotation { .. } => "Delete comment".into(),
+ Edit::SetAnnotationContents { .. } => "Edit comment".into(),
+ Edit::ReplyToAnnotation { .. } => "Reply".into(),
+ Edit::SetAnnotationStatus { state, .. } => format!("Set status {}", state.name()),
+ Edit::MoveAnnotation { .. } => "Move comment".into(),
+ Edit::ResizeAnnotation { .. } => "Resize comment".into(),
+ Edit::StyleAnnotation { .. } => "Change comment properties".into(),
Edit::Batch { label, .. } => label.clone(),
}
}
}
+/// What the Edit menu calls a new comment ("Undo Add highlight").
+fn annotation_noun(s: &Shape) -> &'static str {
+ match s {
+ Shape::Note { .. } => "sticky note",
+ Shape::TextMarkup { kind: Markup::Highlight, .. } => "highlight",
+ Shape::TextMarkup { kind: Markup::Underline, .. } => "underline",
+ Shape::TextMarkup { kind: Markup::StrikeOut, .. } => "strikethrough",
+ Shape::TextMarkup { kind: Markup::Squiggly, .. } => "squiggly underline",
+ Shape::Rectangle { .. } => "rectangle",
+ Shape::Oval { .. } => "oval",
+ Shape::Line { arrow: true, .. } => "arrow",
+ Shape::Line { .. } => "line",
+ Shape::Ink { .. } => "drawing",
+ Shape::TextBox { .. } => "text box",
+ }
+}
+
/// Whether the opening password allows an edit (§7.6.4.2, Table 22).
fn check_permission(edit: &Edit, p: &printcraft_cos::Permissions) -> Result<(), EditError> {
match edit {
@@ -256,6 +334,20 @@ fn check_permission(edit: &Edit, p: &printcraft_cos::Permissions) -> Result<(),
Err(EditError::NotPermitted("page changes"))
}
}
+ Edit::AddAnnotation(_)
+ | Edit::DeleteAnnotation { .. }
+ | Edit::SetAnnotationContents { .. }
+ | Edit::ReplyToAnnotation { .. }
+ | Edit::SetAnnotationStatus { .. }
+ | Edit::MoveAnnotation { .. }
+ | Edit::ResizeAnnotation { .. }
+ | Edit::StyleAnnotation { .. } => {
+ if p.annotate() {
+ Ok(())
+ } else {
+ Err(EditError::NotPermitted("comments"))
+ }
+ }
Edit::SetInfo { .. } => {
if p.modify() {
Ok(())
@@ -267,8 +359,51 @@ fn check_permission(edit: &Edit, p: &printcraft_cos::Permissions) -> Result<(),
}
}
+/// Dates and unique ids stamped onto what an edit creates.
+struct EditCtx {
+ date: Option<String>,
+ seed: u64,
+ count: u64,
+}
+
+impl EditCtx {
+ 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 { date: now.map(printcraft_cos::pdf_date), seed, count: 0 }
+ }
+
+ /// A fresh `/NM`: a random-looking UUID (version 4 layout) from a splitmix64 stream.
+ fn meta(&mut self) -> printcraft_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
+ );
+ printcraft_annot::Meta { date: self.date.clone(), id }
+ }
+}
+
/// Perform an edit on a working copy (the caller discards it on error).
-fn run_edit(doc: &mut printcraft_cos::Document, edit: &Edit) -> Result<(), EditError> {
+fn run_edit(doc: &mut printcraft_cos::Document, edit: &Edit, cx: &mut EditCtx) -> Result<(), EditError> {
match edit {
Edit::RotatePages { pages, degrees } => printcraft_organize::rotate_pages(doc, pages, *degrees)?,
Edit::DeletePages { pages } => printcraft_organize::delete_pages(doc, pages)?,
@@ -295,9 +430,25 @@ fn run_edit(doc: &mut printcraft_cos::Document, edit: &Edit) -> Result<(), EditE
}
Edit::SetBookmarkPage { path, page } => printcraft_organize::set_bookmark_page(doc, path, *page)?,
Edit::NumberPages { from, to, style, prefix, first } => printcraft_organize::number_pages(doc, *from, *to, *style, prefix, *first)?,
+ Edit::AddAnnotation(a) => {
+ printcraft_annot::add_annotation(doc, a, &cx.meta())?;
+ }
+ Edit::DeleteAnnotation { page, index } => printcraft_annot::delete_annotation(doc, *page, *index)?,
+ Edit::SetAnnotationContents { page, index, text } => printcraft_annot::set_contents(doc, *page, *index, text, &cx.meta())?,
+ Edit::ReplyToAnnotation { page, index, text, author } => {
+ printcraft_annot::add_reply(doc, *page, *index, text, author, &cx.meta())?;
+ }
+ Edit::SetAnnotationStatus { page, index, state, author } => {
+ printcraft_annot::set_review_state(doc, *page, *index, *state, author, &cx.meta())?;
+ }
+ Edit::MoveAnnotation { page, index, dx, dy } => printcraft_annot::move_annotation(doc, *page, *index, *dx, *dy, &cx.meta())?,
+ Edit::ResizeAnnotation { page, index, rect } => printcraft_annot::set_rect(doc, *page, *index, *rect, &cx.meta())?,
+ Edit::StyleAnnotation { page, index, color, opacity, width } => {
+ printcraft_annot::set_style(doc, *page, *index, *color, *opacity, *width, &cx.meta())?;
+ }
Edit::Batch { edits, .. } => {
for e in edits {
- run_edit(doc, e)?;
+ run_edit(doc, e, cx)?;
}
}
}
@@ -333,6 +484,8 @@ pub enum EditError {
Organize(#[from] printcraft_organize::OrganizeError),
#[error("{0}")]
Bookmark(#[from] printcraft_organize::OutlineError),
+ #[error("{0}")]
+ Comment(#[from] printcraft_annot::AnnotError),
#[error("the edited document could not be written: {0}")]
Write(String),
#[error("the edited document could not be reopened: {0}")]
@@ -426,14 +579,16 @@ impl Session {
/// Apply an edit. On success the previous state is undoable and the view data is refreshed.
pub fn apply(&mut self, id: DocId, edit: Edit) -> Result<(), EditError> {
+ let now = self.now();
let doc = self.doc_mut(id)?;
+ let mut cx = EditCtx::new(now, doc.generation ^ (id.0 << 48));
let reason = doc.read_only_reason.clone().unwrap_or_default();
let editor = doc.editor.as_mut().ok_or(EditError::ReadOnly(reason))?;
if let Some(p) = editor.cos.permissions() {
check_permission(&edit, &p)?;
}
let mut next = editor.cos.clone();
- run_edit(&mut next, &edit)?;
+ run_edit(&mut next, &edit, &mut cx)?;
let previous = std::mem::replace(&mut editor.cos, next);
editor.undo.push((edit.label(), previous));
if editor.undo.len() > MAX_UNDO {
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index e890499c3..974e225da 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -382,3 +382,105 @@ fn number_pages_shows_in_the_viewer_and_undoes() {
assert_eq!(labels(&s), ["i", "ii", "3", "4", "5"]);
assert!(s.apply(id, Edit::NumberPages { from: 3, to: 9, style: LabelStyle::Decimal, prefix: String::new(), first: 1 }).is_err());
}
+
+/// RGBA of the pixel at PDF point (x, y) on `page`, rendered at 1 px/pt (page height 300).
+fn pixel(s: &Session, id: DocId, page: usize, x: u32, y: u32) -> [u8; 4] {
+ let doc = s.get(id).unwrap();
+ let mut r = printcraft_render::PageRenderer::new(doc.bytes.clone(), printcraft_render::RenderConfig::default());
+ let out = r.render(printcraft_render::RenderRequest { page, scale: 1.0, ..Default::default() });
+ assert!(out.error.is_none(), "{:?}", out.error);
+ let i = (((300 - y) * out.width + x) * 4) as usize;
+ out.rgba[i..i + 4].try_into().unwrap()
+}
+
+fn rect_comment(page: usize, rect: [f64; 4]) -> Edit {
+ Edit::AddAnnotation(NewAnnotation {
+ page,
+ shape: Shape::Rectangle { rect },
+ style: Style { color: [1.0, 0.0, 0.0], opacity: 1.0, width: 2.0, fill: Some([1.0, 0.0, 0.0]) },
+ contents: "Look here".into(),
+ author: "Reviewer".into(),
+ })
+}
+
+#[test]
+fn comments_are_added_drawn_threaded_and_undone() {
+ let (mut s, id) = session_with(2);
+ assert_eq!(pixel(&s, id, 1, 100, 100), [255, 255, 255, 255]);
+ s.apply(id, rect_comment(1, [80.0, 80.0, 120.0, 120.0])).unwrap();
+ assert_eq!(s.get(id).unwrap().can_undo(), Some("Add rectangle"));
+ let px = pixel(&s, id, 1, 100, 100);
+ assert!(px[0] > 200 && px[1] < 40 && px[2] < 40, "the rectangle is drawn: {px:?}");
+ let a = &s.get(id).unwrap().info.annotations;
+ assert_eq!(a.len(), 1);
+ assert_eq!((a[0].page, a[0].index, a[0].author.as_deref(), a[0].contents.as_deref()), (1, 0, Some("Reviewer"), Some("Look here")));
+ assert_eq!(a[0].modified.as_deref().map(|m| m.contains("2023")), Some(true), "dated by the session clock");
+ let nm = a[0].name.clone().expect("has an /NM");
+ assert_eq!(nm.len(), 36);
+
+ s.apply(id, Edit::ReplyToAnnotation { page: 1, index: 0, text: "Done".into(), author: "Ada".into() }).unwrap();
+ s.apply(id, Edit::SetAnnotationStatus { page: 1, index: 0, state: ReviewState::Completed, author: "Ada".into() }).unwrap();
+ let a = &s.get(id).unwrap().info.annotations;
+ assert_eq!(a.len(), 3);
+ assert!(a.iter().filter(|r| r.in_reply_to.as_deref() == Some(nm.as_str())).count() == 2);
+ assert!(a.iter().any(|r| r.state.as_deref() == Some("Completed")));
+ assert_ne!(a[1].name, a[2].name, "every comment gets its own id");
+
+ s.apply(id, Edit::MoveAnnotation { page: 1, index: 0, dx: 50.0, dy: 0.0 }).unwrap();
+ assert_eq!(pixel(&s, id, 1, 100, 100), [255, 255, 255, 255]);
+ let px = pixel(&s, id, 1, 150, 100);
+ assert!(px[0] > 200 && px[1] < 40, "moved: {px:?}");
+
+ s.apply(id, Edit::DeleteAnnotation { page: 1, index: 0 }).unwrap();
+ assert!(s.get(id).unwrap().info.annotations.is_empty(), "replies go with their parent");
+ for _ in 0..4 {
+ s.undo(id).unwrap();
+ }
+ assert_eq!(s.get(id).unwrap().info.annotations.len(), 1);
+ let px = pixel(&s, id, 1, 100, 100);
+ assert!(px[0] > 200 && px[1] < 40, "back where it was: {px:?}");
+}
+
+#[test]
+fn highlight_multiplies_over_text() {
+ let (mut s, id) = session_with(1);
+ // "Page 1" is drawn at 20,150 in 24 pt Helvetica.
+ let quad = [18.0, 172.0, 100.0, 172.0, 18.0, 145.0, 100.0, 145.0];
+ s.apply(
+ id,
+ Edit::AddAnnotation(NewAnnotation {
+ page: 0,
+ shape: Shape::TextMarkup { kind: Markup::Highlight, quads: vec![quad] },
+ style: Style { color: [1.0, 1.0, 0.0], ..Style::default() },
+ contents: String::new(),
+ author: String::new(),
+ }),
+ )
+ .unwrap();
+ let a = &s.get(id).unwrap().info.annotations[0];
+ assert_eq!(a.subtype, "Highlight");
+ assert_eq!(a.quads, vec![quad.map(|v| v as f32)]);
+ // Background inside the quad turns yellow; text stays dark (multiply).
+ let bg = pixel(&s, id, 0, 19, 170);
+ assert!(bg[0] > 240 && bg[1] > 240 && bg[2] < 30, "{bg:?}");
+}
+
+#[test]
+fn comment_permission_is_enforced() {
+ let mut cos = printcraft_cos::Document::open(Arc::new(fixture(1))).unwrap();
+ // Owner "own", empty user password, everything allowed except commenting (bit 6).
+ let params = printcraft_cos::NewEncryption {
+ algorithm: printcraft_cos::Algorithm::Aes256,
+ user_password: "",
+ owner_password: "own",
+ permissions: !(1 << 5),
+ encrypt_metadata: true,
+ seed: [7; 32],
+ };
+ cos.set_encryption(&params).unwrap();
+ let bytes = printcraft_cos::write_full(&cos, &printcraft_cos::SaveOptions::default()).unwrap();
+ let mut s = Session::new();
+ let id = s.open("locked.pdf", None, Arc::new(bytes), None).unwrap();
+ let err = s.apply(id, rect_comment(0, [10.0, 10.0, 50.0, 50.0])).unwrap_err();
+ assert_eq!(err, EditError::NotPermitted("comments"));
+}
diff --git a/crates/render/src/inspect.rs b/crates/render/src/inspect.rs
index e247091b7..a9376320e 100644
--- a/crates/render/src/inspect.rs
+++ b/crates/render/src/inspect.rs
@@ -53,6 +53,47 @@ pub struct PageInfo {
pub rotation: u16,
}
+impl PageInfo {
+ /// A point in view space (points, y down, after `/Rotate`; what the text layer uses) →
+ /// PDF user space.
+ pub fn view_to_user(&self, x: f32, y: f32) -> [f32; 2] {
+ let [cx0, cy0, cx1, cy1] = self.crop;
+ let (a, b) = (x / self.width.max(1e-3), y / self.height.max(1e-3));
+ let (u, v) = match self.rotation {
+ 90 => (b, 1.0 - a),
+ 180 => (1.0 - a, 1.0 - b),
+ 270 => (1.0 - b, a),
+ _ => (a, b),
+ };
+ [cx0 + u * (cx1 - cx0), cy1 - v * (cy1 - cy0)]
+ }
+
+ /// PDF user space → view space (the inverse of [`Self::view_to_user`]).
+ pub fn user_to_view(&self, x: f32, y: f32) -> [f32; 2] {
+ let [cx0, cy0, cx1, cy1] = self.crop;
+ let (u, v) = ((x - cx0) / (cx1 - cx0).max(1e-3), (cy1 - y) / (cy1 - cy0).max(1e-3));
+ let (a, b) = match self.rotation {
+ 90 => (1.0 - v, u),
+ 180 => (1.0 - u, 1.0 - v),
+ 270 => (v, 1.0 - u),
+ _ => (u, v),
+ };
+ [a * self.width, b * self.height]
+ }
+
+ /// A view-space rectangle as a text-markup quad in user space: top-left, top-right,
+ /// bottom-left, bottom-right as read on screen.
+ pub fn view_rect_to_quad(&self, r: [f32; 4]) -> [f64; 8] {
+ let mut q = [0.0; 8];
+ for (i, (x, y)) in [(r[0], r[1]), (r[2], r[1]), (r[0], r[3]), (r[2], r[3])].into_iter().enumerate() {
+ let [ux, uy] = self.view_to_user(x, y);
+ q[2 * i] = ux as f64;
+ q[2 * i + 1] = uy as f64;
+ }
+ q
+ }
+}
+
/// A clickable link annotation.
#[derive(Clone, Debug)]
pub struct Link {
@@ -89,6 +130,12 @@ pub struct Annotation {
/// Rect in PDF user space: [x0, y0, x1, y1].
pub rect: [f32; 4],
pub color: Option<[f32; 3]>,
+ /// Position in the page's `/Annots` (how edits address the comment).
+ pub index: usize,
+ /// For a status reply (`/State`, Acrobat's "Set status"): the state it sets.
+ pub state: Option<String>,
+ /// Text markup quadrilaterals (`/QuadPoints`), 8 numbers each.
+ pub quads: Vec<[f32; 8]>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -471,13 +518,32 @@ impl<'a> Inspector<'a> {
continue;
}
let rect = rect4(self.resolve(d.get(b"Rect").unwrap_or(&Object::Null)));
- let color = match d.get(b"C").map(|o| self.resolve(o)) {
+ let mut color = match d.get(b"C").map(|o| self.resolve(o)) {
Ok(Object::Array(c)) if c.len() == 3 => {
let f = |i: usize| c[i].as_float().unwrap_or(0.0);
Some([f(0), f(1), f(2)])
}
_ => None,
};
+ // A text box's /C is its background; its text colour is in /DA.
+ if subtype == "FreeText"
+ && let Some(da) = self.text(d, b"DA")
+ {
+ let t: Vec<&str> = da.split_whitespace().collect();
+ if let Some(i) = t.iter().position(|x| *x == "rg")
+ && i >= 3
+ {
+ let f = |k: usize| t[k].parse::<f32>().unwrap_or(0.0);
+ color = Some([f(i - 3), f(i - 2), f(i - 1)]);
+ }
+ }
+ let quads = match d.get(b"QuadPoints").map(|o| self.resolve(o)) {
+ Ok(Object::Array(q)) => {
+ let v: Vec<f32> = q.iter().map(|o| o.as_float().unwrap_or(0.0)).collect();
+ v.chunks_exact(8).map(|c| <[f32; 8]>::try_from(c).unwrap_or_default()).collect()
+ }
+ _ => Vec::new(),
+ };
let in_reply_to = d.get(b"IRT").ok().and_then(|o| self.dict(o)).and_then(|p| self.text(p, b"NM"));
info.annotations.push(Annotation {
page,
@@ -489,6 +555,9 @@ impl<'a> Inspector<'a> {
in_reply_to,
rect,
color,
+ index,
+ state: self.text(d, b"State"),
+ quads,
});
}
}
@@ -775,6 +844,23 @@ pub fn attachment_data(bytes: &[u8], password: Option<&str>, att: &Attachment) -
#[cfg(test)]
mod tests {
+ #[test]
+ fn view_and_user_space_round_trip_for_every_rotation() {
+ for rotation in [0u16, 90, 180, 270] {
+ let (w, h) = if rotation % 180 == 0 { (200.0, 300.0) } else { (300.0, 200.0) };
+ let p = super::PageInfo { width: w, height: h, label: String::new(), crop: [10.0, 20.0, 210.0, 320.0], rotation };
+ for (x, y) in [(0.0, 0.0), (15.0, 40.0), (w, h)] {
+ let [ux, uy] = p.view_to_user(x, y);
+ let [vx, vy] = p.user_to_view(ux, uy);
+ assert!((vx - x).abs() < 1e-3 && (vy - y).abs() < 1e-3, "{rotation}: {x},{y} → {ux},{uy} → {vx},{vy}");
+ }
+ }
+ // Unrotated: the view's top-left is the crop box's top-left.
+ let p = super::PageInfo { width: 200.0, height: 300.0, label: String::new(), crop: [10.0, 20.0, 210.0, 320.0], rotation: 0 };
+ assert_eq!(p.view_to_user(0.0, 0.0), [10.0, 320.0]);
+ assert_eq!(p.view_rect_to_quad([0.0, 0.0, 10.0, 5.0]), [10.0, 320.0, 20.0, 320.0, 10.0, 315.0, 20.0, 315.0]);
+ }
+
use super::*;
#[test]