use super::create::finite; use super::draw::set_appearance; use super::lookup::{annot_dict, annot_ref, annotation_flags, annots, drawn_upright, is_fill_sign, page_ref, page_refs}; use super::modify::{callout_line, callout_text_box, fillable, touch, unlocked}; use super::text_style; use super::types::{BorderShape, FLAG_LOCKED, LineEnding, Meta, NoteIcon, Rgb}; use super::{AnnotError, Dict, Document, ObjRef, Object, PdfString, appearance}; // ── reading ───────────────────────────────────────────────────────────────────────────────── /// One comment as the viewer lists it (the same fields and rules as /// `pdfcraft_render::Annotation`), read straight from the object graph. The engine uses it to /// refresh the comment list after a comment edit without re-inspecting the whole document. #[derive(Clone, Debug, PartialEq)] pub struct Summary { pub page: usize, pub index: usize, pub subtype: String, pub author: Option, pub contents: Option, /// `/M` as written (a PDF date string). pub modified: Option, pub name: Option, pub in_reply_to: Option, /// The page and `/Annots` position `/IRT` points at, by reference (`/NM` need not be unique). pub parent: Option<(usize, usize)>, /// `/RT /Group`: with an `/IRT` reference, a subordinate of the group whose primary that is /// ([`is_group_subordinate`]), not a reply to it. pub grouped: bool, pub rect: [f32; 4], pub color: Option<[f32; 3]>, pub state: Option, pub quads: Vec<[f32; 8]>, pub locked: bool, pub intent: Option, /// A Fill & Sign mark ([`is_fill_sign`]). pub fill_sign: bool, /// The NoRotate flag (`/F` bit 5), as `pdfcraft_render::Annotation::no_rotate`. pub no_rotate: bool, /// A line's two ends (`/L`), the corners of connected lines, a polygon or a cloud /// (`/Vertices`), or a callout's arrow point and knee (`/CL` without its end, which follows /// the text box), in user space; empty for other comments. pub points: Vec<[f32; 2]>, /// A callout's text box (`/Rect` inset by `/RD`), in user space; `None` for other comments. pub text_box: Option<[f32; 4]>, /// The comment's pop-up window (`/Popup`), when it has one. pub popup: Option, } impl Summary { /// A subordinate of a group (`/RT /Group` with an `/IRT` to a listed comment, ISO 32000-2 /// §12.5.6.2): part of its primary's comment, not a reply. As /// `pdfcraft_render::Annotation::is_group_member`, which also drops a looping `/IRT`. pub fn is_group_member(&self) -> bool { self.grouped && self.parent.is_some() } } /// A comment's pop-up window (ISO 32000-2 §12.5.6.14): where it sits on the page and whether it /// is shown open. #[derive(Clone, Copy, Debug, PartialEq)] pub struct PopupInfo { /// `/Rect` of the `/Popup` annotation, in user space. pub rect: [f32; 4], /// `/Open` of the `/Popup` annotation. pub open: bool, } /// The pop-up the comment `annot` (the object `own`, when it is one of its own) names in /// `/Popup`, when it is the comment's: a pop-up annotation whose `/Parent`, if it has one, is a /// reference to the comment. A `/Popup` naming another annotation, or a pop-up of another /// comment, isn't. ISO 32000-2:2020 §12.5.6.14, Table 186: `/Parent` is "(Optional; shall be /// an indirect reference)". pub(crate) fn own_popup(doc: &Document, own: Option, annot: &Dict) -> Option { let pr = annot.reference(b"Popup")?; let is_own = doc.get(pr).as_dict().is_some_and(|pd| { pd.name(b"Subtype") == Some(b"Popup") && pd .get(b"Parent") .is_none_or(|parent| parent.as_ref().is_some_and(|parent| own.is_some_and(|own| final_ref(doc, parent) == final_ref(doc, own)))) }); is_own.then_some(pr) } /// The comment's own pop-up (see [`own_popup`]), as [`PopupInfo`]: `None` when it has none or it /// is unreadable. pub(crate) fn popup_info(doc: &Document, own: Option, annot: &Dict) -> Option { // Another annotation's rectangle and open state aren't this comment's (review on #2137). let r = own_popup(doc, own, annot)?; let p = doc.get(r); let p = p.as_dict()?; let rect: Vec = doc.resolve(p.get(b"Rect")?).as_array()?.iter().filter_map(|v| doc.resolve(v).as_f64().map(|x| x as f32)).collect(); // Four numbers that are finite as `f32` (a huge one becomes infinite), corners in any order. let [x0, y0, x1, y1] = rect[..] else { return None }; if !rect.iter().all(|v| v.is_finite()) { return None; } let open = p.get(b"Open").map(|o| doc.resolve(o)).is_some_and(|o| matches!(&*o, Object::Bool(true))); Some(PopupInfo { rect: [x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)], open }) } pub(crate) fn text_value(doc: &Document, d: &Dict, key: &[u8]) -> Option { let o = doc.resolve(d.get(key)?); let s = match &*o { Object::String(s) => s.to_text(), Object::Name(n) => String::from_utf8_lossy(n).into_owned(), _ => return None, }; let s = s.trim_matches('\0'); // Typewriter outer whitespace belongs to the text (keep in step with render's inspector). let name_is = |key: &[u8], expected: &[u8]| d.get(key).is_some_and(|o| doc.resolve(o).as_name() == Some(expected)); let keep_breaks = key == b"Contents" && name_is(b"Subtype", b"FreeText") && name_is(b"IT", b"FreeTextTypeWriter"); let s = if keep_breaks { s } else { s.trim() }; (!s.trim().is_empty()).then(|| s.to_owned()) } /// Whether an annotation subtype is a comment. Links, form widgets, pop-ups and the non-markup /// multimedia and print-production annotations (ISO 32000-2 §12.5.6: Screen, Movie, RichMedia, /// 3D, PrinterMark, TrapNet, Watermark) are not. pub fn is_comment_subtype(subtype: &str) -> bool { !matches!(subtype, "Link" | "Widget" | "Popup" | "Screen" | "Movie" | "RichMedia" | "3D" | "PrinterMark" | "TrapNet" | "Watermark") } /// Where a reference to a reference (`5 0 obj 6 0 R endobj`) ends, as `pdfcraft_render::inspect` /// follows it, within a few steps (a cycle stops there). pub(crate) fn final_ref(doc: &Document, mut r: ObjRef) -> ObjRef { for _ in 0..8 { match &*doc.get(r) { Object::Ref(next) => r = *next, _ => break, } } r } /// Whether an annotation is a subordinate of a group rather than a reply: `/RT /Group` with an /// `/IRT` reference (ISO 32000-2 §12.5.6.2, Table 172). The group's primary is the `/IRT` /// annotation, and the subordinate's own text, author, colour, dates and pop-up are ignored. /// `/RT` is `R` by default, and a value other than `Group` reads as `R` too. Keep in step with /// `pdfcraft_render::inspect`. pub fn is_group_subordinate(d: &Dict) -> bool { d.name(b"RT") == Some(b"Group") && d.reference(b"IRT").is_some() } /// Every comment (see [`is_comment_subtype`]), ordered by page and then top edge. pub fn summaries(doc: &Document) -> Vec { let mut out = Vec::new(); let Ok(pages) = page_refs(doc) else { return out }; let lists: Vec> = pages.iter().map(|p| annots(doc, *p)).collect(); // Where each annotation is first listed, so a reply's `/IRT` finds its parent by reference. let mut slots: std::collections::HashMap = std::collections::HashMap::new(); for (page, list) in lists.iter().enumerate() { for (index, entry) in list.iter().enumerate() { if let Some(r) = entry.as_ref() { slots.entry(final_ref(doc, r)).or_insert((page, index)); } } } for (page, list) in lists.iter().enumerate() { for (index, entry) in list.iter().enumerate() { let obj = entry.as_ref().map_or_else(|| doc.resolve(entry), |r| doc.get(final_ref(doc, r))); let Some(d) = obj.as_dict() else { continue }; let Some(subtype) = d.name(b"Subtype").map(|s| String::from_utf8_lossy(s).into_owned()) else { continue }; if !is_comment_subtype(&subtype) { continue; } let nums = |k: &[u8]| -> Vec { d.get(k) .map(|o| doc.resolve(o)) .and_then(|o| o.as_array().map(|a| a.iter().map(|x| doc.resolve(x).as_f64().unwrap_or(0.0) as f32).collect())) .unwrap_or_default() }; let r = nums(b"Rect"); let rect = if r.len() == 4 { [r[0].min(r[2]), r[1].min(r[3]), r[0].max(r[2]), r[1].max(r[3])] } else { [0.0; 4] }; let c = nums(b"C"); let rgb = (c.len() == 3).then(|| [c[0], c[1], c[2]]); // Other comments report the stroke colour as it is drawn (grey, CMYK, a null entry // read as 0), like `props`; three numbers, some given by reference, are still read. let mut color = if subtype == "FreeText" { rgb } else { summary_color(doc, d).or(rgb) }; if subtype == "FreeText" && let Some(da) = text_value(doc, 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::().unwrap_or(0.0); color = Some([f(i - 3), f(i - 2), f(i - 1)]); } } // Only usable quads, by the rule redaction apply reads them with, so a mark's outline // is the area apply removes (and with none, the `/Rect` both fall back to). let quads: Vec<[f32; 8]> = d .get(b"QuadPoints") .map(|o| doc.resolve(o)) .map(|a| { let entries = a.as_array().into_iter().flatten().map(|x| doc.resolve(x).as_f64()); pdfcraft_geom::quad_points::usable_quads(entries).into_iter().map(|q| q.map(|v| v as f32)).collect() }) .unwrap_or_default(); // Keep in step with `pdfcraft_render::inspect`: a callout gives its points only with a // readable text box, without which they can't be changed either. let callout = (subtype == "FreeText").then(|| callout_line(doc, d).zip(callout_text_box(doc, d))).flatten(); let points = match subtype.as_str() { "Line" => Some(nums(b"L")).filter(|l| l.len() == 4).map(|l| l.as_chunks::<2>().0.to_vec()).unwrap_or_default(), "PolyLine" | "Polygon" => nums(b"Vertices").as_chunks::<2>().0.to_vec(), "FreeText" => callout .as_ref() .and_then(|(line, _)| line.split_last()) .map(|(_, lead)| lead.iter().map(|p| [p[0] as f32, p[1] as f32]).collect()) .unwrap_or_default(), _ => Vec::new(), }; let text_box = callout.map(|(_, t)| t.map(|v| v as f32)); let irt = d.get(b"IRT").map(|o| o.as_ref().map_or_else(|| doc.resolve(o), |r| doc.get(final_ref(doc, r)))); let in_reply_to = irt.and_then(|o| o.as_dict().cloned()).and_then(|p| text_value(doc, &p, b"NM")); let parent = d.get(b"IRT").and_then(Object::as_ref).and_then(|r| slots.get(&final_ref(doc, r)).copied()); // A group is one page's, as Acrobat reads it: a subordinate whose primary is on // another page is a comment of its own (keep in step with // `pdfcraft_render::link_replies`). let grouped = d.name(b"RT") == Some(b"Group"); let cross_page = grouped && parent.is_some_and(|(p, _)| p != page); let (parent, in_reply_to) = if cross_page { (None, None) } else { (parent, in_reply_to) }; out.push(Summary { page, index, subtype, author: text_value(doc, d, b"T"), // Acrobat ends lines with CR, which the interface would draw as nothing (keep in // step with `pdfcraft_render::inspect`). contents: text_value(doc, d, b"Contents").map(|s| s.replace("\r\n", "\n").replace('\r', "\n")), modified: text_value(doc, d, b"M"), name: text_value(doc, d, b"NM"), in_reply_to, parent, grouped, rect, color, // A reply that gives only `/StateModel` has the model's default state (ISO 32000-2 // Table 175), as `last_state_reply` and the inspector read it. state: text_value(doc, d, b"State").or_else(|| match text_value(doc, d, b"StateModel").as_deref() { Some("Marked") => Some("Unmarked".into()), Some("Review") => Some("None".into()), _ => None, }), quads, locked: annotation_flags(doc, d) & FLAG_LOCKED != 0, intent: d.get(b"IT").and_then(|o| doc.resolve(o).as_name().map(|n| String::from_utf8_lossy(n).into_owned())), fill_sign: is_fill_sign(doc, d), no_rotate: drawn_upright(doc, d), points, text_box, popup: popup_info(doc, entry.as_ref().map(|r| final_ref(doc, r)), d), }); } } out.sort_by(|a, b| a.page.cmp(&b.page).then(b.rect[3].total_cmp(&a.rect[3]))); out } /// Change a comment's author (`/T`), subject (`/Subj`) and, for notes, icon (`/Name`, redrawn). /// `None` leaves a value as it is. pub fn set_info( doc: &mut Document, page: usize, index: usize, author: Option<&str>, subject: Option<&str>, icon: Option, meta: &Meta, ) -> Result<(), AnnotError> { let (_, r) = annot_ref(doc, page, index)?; unlocked(doc, r)?; let is_note = annot_dict(doc, r).name(b"Subtype") == Some(b"Text"); if icon.is_some() && !is_note { return Err(AnnotError::Invalid("only sticky notes have an icon".into())); } doc.update_dict(r, |d| { if let Some(a) = author { d.set(b"T".to_vec(), PdfString::text(a)); } if let Some(s) = subject { d.set(b"Subj".to_vec(), PdfString::text(s)); } if let Some(i) = icon { d.set(b"Name".to_vec(), Object::name(i.name())); } touch(d, meta); })?; if icon.is_some() { set_appearance(doc, r)?; } Ok(()) } /// What Comment properties shows for one comment. #[derive(Clone, Debug, PartialEq)] pub struct Props { pub subtype: String, pub author: String, pub subject: String, pub color: Option, pub opacity: f64, /// Border / line width, for shapes, lines, drawings and text boxes. pub width: Option, /// Notes only. pub icon: Option, /// `/M`, as written. pub modified: Option, /// The appearance can be redrawn (so colour, opacity and width can change). pub restylable: bool, /// The Locked flag. pub locked: bool, /// `/LE`: two names for a line or polyline (`None` when unset), one for a callout. pub endings: Option>, /// Whether the comment has a fill control (see [`fillable`]). pub fillable: bool, /// The interior colour (`None`: no fill). pub fill: Option, /// Text boxes, typewriter text and callouts: the `/DA` font size in points. pub font_size: Option, /// Text boxes, typewriter text and callouts: the border's own colour (`None`: the text's). pub border_color: Option, /// Text boxes and typewriter text: the border's shape (callouts have none to choose). pub border_shape: Option, /// How opaque the fill is drawn, for a comment with a fill control (`opacity` is then its /// line's or border's). pub fill_opacity: Option, /// How opaque a text box's, typewriter text's or callout's text is drawn. pub text_opacity: Option, } /// The current properties of the comment at `(page, index)`. pub fn props(doc: &Document, page: usize, index: usize) -> Option { let p = page_ref(doc, page).ok()?; let entry = annots(doc, p).get(index).cloned()?; let obj = doc.resolve(&entry); // Values given by reference (`/C 7 0 R`, `/BS 5 0 R`, ISO 32000-2 §7.3.10) read as the display draws them. let raw = obj.as_dict()?; let direct = crate::draw::with_direct_values(doc, raw); let d = direct.as_ref(); let subtype = String::from_utf8_lossy(d.name(b"Subtype")?).into_owned(); if !is_comment_subtype(&subtype) { return None; } // A text box reports the colour and size it is drawn in (`/DA`, or `/DS` where it sets one). let style = (subtype == "FreeText").then(|| text_style::text_style(d, None)); let color = match &style { Some(s) => Some(s.color), None => drawn_color(d, b"C"), }; let width = matches!(subtype.as_str(), "Square" | "Circle" | "Line" | "Ink" | "Polygon" | "PolyLine" | "FreeText").then(|| { if subtype == "FreeText" { appearance::border_width(d) } else { d.get(b"BS").and_then(|b| b.as_dict()).and_then(|b| b.get(b"W")).and_then(|w| w.as_f64()).unwrap_or(1.0) } }); Some(Props { author: text_value(doc, d, b"T").unwrap_or_default(), subject: text_value(doc, d, b"Subj").unwrap_or_default(), color, opacity: appearance::part_opacity(d).line, width, icon: (subtype == "Text").then(|| d.name(b"Name").and_then(|n| NoteIcon::from_name(&String::from_utf8_lossy(n))).unwrap_or(NoteIcon::Note)), modified: text_value(doc, d, b"M"), restylable: crate::draw::can_draw(doc, raw), locked: annotation_flags(doc, d) & FLAG_LOCKED != 0, fillable: fillable(&subtype), fill: fill_of(d), font_size: style.map(|s| s.size), border_color: (subtype == "FreeText").then(|| appearance::da_border(d)).flatten(), border_shape: (subtype == "FreeText" && !d.contains(b"CL")).then(|| BorderShape::of(d)), fill_opacity: fillable(&subtype).then(|| appearance::part_opacity(d).fill), text_opacity: (subtype == "FreeText").then(|| appearance::part_opacity(d).text), subtype, endings: line_endings_of(d), }) } /// A shape’s `/IC` or FreeText `/C` as RGB, read as it is drawn. Grey and CMYK fills are converted. fn fill_of(d: &Dict) -> Option { let key: &[u8] = if d.name(b"Subtype") == Some(b"FreeText") { b"C" } else { b"IC" }; drawn_color(d, key) } /// `/C` as [`drawn_color`] reads it, the array itself followed when it is given by reference. /// Only an array of at most four entries is copied out of the reference. fn summary_color(doc: &Document, d: &Dict) -> Option<[f32; 3]> { let rgb = match d.get(b"C") { Some(o @ Object::Ref(_)) => { let held = doc.resolve(o); let entries = held.as_array().filter(|a| a.len() <= 4)?; let mut direct = Dict::new(); direct.set(b"C".to_vec(), Object::Array(entries.clone())); drawn_color(&direct, b"C") } _ => drawn_color(d, b"C"), }?; Some(rgb.map(|x| x as f32)) } /// The colour array at `key` as RGB, read as the appearance builder draws it: grey and CMYK are /// converted, and a four-entry array with a non-number in it is CMYK with that entry 0. fn drawn_color(d: &Dict, key: &[u8]) -> Option { let rgb = appearance::color(d, key).flatten()?; finite(&rgb).then(|| rgb.map(|x| x.clamp(0.0, 1.0))) } /// `/LE` for a line, polyline or callout. Unknown names yield `None` so the control stays hidden. pub(crate) fn line_endings_of(d: &Dict) -> Option> { let parse = |name: &[u8]| std::str::from_utf8(name).ok().and_then(LineEnding::parse); match d.name(b"Subtype")? { b"Line" | b"PolyLine" => match d.get(b"LE") { None => Some(vec![LineEnding::None, LineEnding::None]), Some(o) => o.as_array().filter(|a| a.len() == 2)?.iter().map(|e| parse(e.as_name()?)).collect(), }, b"FreeText" if d.contains(b"CL") => Some(vec![parse(d.name(b"LE").unwrap_or(b"None"))?]), _ => None, } }