1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! Annotations (ISO 32000-2 §12.5): a typed view of each entry of a page's `/Annots`, read
//! tolerantly (ADR 0003). The common entries of Table 166, the markup entries of Table 172
//! (§12.5.6.2), the Popup pairing (§12.5.6.14) and each subtype's geometry are read; every
//! other key stays in the dictionary, untouched, for the ops that edit it.
//!
//! An entry that isn't a dictionary is left out. An annotation stored as a direct dictionary
//! (Table 31 asks for indirect references) gets a path ID, which ops refuse to edit.
use std::collections::BTreeSet;
use laminapdf_cos::{Dict, DirectPath, ObjRef, Object, PathSegment, Result, Warning};
use crate::comments::AnnotState;
use crate::document::Document;
use crate::geometry::{UserSpacePoint, UserSpaceRect};
use crate::id::AnnotId;
use crate::link::quads;
use crate::page::{Page, number, read_rect};
use crate::values::read_name;
/// One annotation on a page.
///
/// Added in 0.3.0.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Annot {
/// Its ID: the annotation object's, or a path ID for a direct dictionary.
pub id: AnnotId,
/// Its position in the page's `/Annots` array.
pub index: usize,
/// `/Subtype`.
pub subtype: AnnotSubtype,
/// `/Rect` in user space; `None` when absent or malformed.
pub rect: Option<UserSpaceRect>,
/// `/Contents`, decoded (§7.9.2.2).
pub contents: Option<String>,
/// `/NM`, decoded: a name unique on its page, which is only a hint (ADR 0005 §5).
pub name: Option<String>,
/// `/M` as stored: a PDF date or, as some writers leave it, any text.
pub modified: Option<String>,
/// `/F`.
pub flags: AnnotFlags,
/// `/C`: no components (transparent), one (gray), three (RGB) or four (CMYK).
pub color: Vec<f64>,
/// `/CA`, the constant opacity (§12.5.6.2; any annotation in PDF 2.0).
pub opacity: Option<f64>,
/// `/T`: the author, for a markup annotation.
pub author: Option<String>,
/// `/Subj`.
pub subject: Option<String>,
/// `/CreationDate` as stored.
pub created: Option<String>,
/// `/IRT`: the annotation this one replies to or is grouped with.
pub in_reply_to: Option<AnnotId>,
/// `/RT`: how it relates to [`Annot::in_reply_to`]; `Reply` when absent (Table 172).
pub reply_type: ReplyType,
/// The Popup annotation that shows this one's text: `/Popup`, else a Popup on the page
/// whose `/Parent` names it.
pub popup: Option<AnnotId>,
/// For a Popup, its `/Parent`.
pub parent: Option<AnnotId>,
/// Whether `/AP` has a normal appearance (`/N`).
pub has_appearance: bool,
/// Whether it has `/RC`, rich-text contents (§12.7.4.4).
pub has_rich_text: bool,
/// The subtype's own geometry.
pub geometry: AnnotGeometry,
/// For a Text annotation that sets a review state on the one it replies to, that state
/// (`/StateModel` and `/State`, Table 175; §12.5.6.4).
pub state: Option<AnnotState>,
/// A stamp's name, a file attachment's file or a sound's format.
///
/// Added in 0.6.0.
pub details: crate::AnnotDetails,
}
/// What an annotation op needs of an annotation, read without its text or geometry: its ID and
/// place, subtype, flags, and its links to other annotations ([`Document::annotation_links`]).
///
/// Added in 0.3.0.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct AnnotLink {
/// Its ID, as [`Annot::id`].
pub id: AnnotId,
/// Its position in the page's `/Annots`.
pub index: usize,
/// `/Subtype`.
pub subtype: AnnotSubtype,
/// `/F`.
pub flags: AnnotFlags,
/// `/IRT`.
pub in_reply_to: Option<AnnotId>,
/// `/RT`.
pub reply_type: ReplyType,
/// Its Popup, as [`Annot::popup`].
pub popup: Option<AnnotId>,
/// For a Popup, its `/Parent`.
pub parent: Option<AnnotId>,
}
/// An annotation's `/Subtype` (Table 171).
///
/// Added in 0.3.0.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AnnotSubtype {
/// `Text`, a note.
Text,
/// `Link`.
Link,
/// `FreeText`.
FreeText,
/// `Line`.
Line,
/// `Square`.
Square,
/// `Circle`.
Circle,
/// `Polygon`.
Polygon,
/// `PolyLine`.
PolyLine,
/// `Highlight`.
Highlight,
/// `Underline`.
Underline,
/// `Squiggly`.
Squiggly,
/// `StrikeOut`.
StrikeOut,
/// `Caret`.
Caret,
/// `Stamp`.
Stamp,
/// `Ink`.
Ink,
/// `Popup`.
Popup,
/// `FileAttachment`.
FileAttachment,
/// `Sound`.
Sound,
/// `Widget`, a form field's.
Widget,
/// `Redact`.
Redact,
/// Any other subtype, by its name's bytes (empty when `/Subtype` is missing).
Other(Vec<u8>),
}
impl AnnotSubtype {
pub(crate) fn from_name(name: &[u8]) -> Self {
match name {
b"Text" => Self::Text,
b"Link" => Self::Link,
b"FreeText" => Self::FreeText,
b"Line" => Self::Line,
b"Square" => Self::Square,
b"Circle" => Self::Circle,
b"Polygon" => Self::Polygon,
b"PolyLine" => Self::PolyLine,
b"Highlight" => Self::Highlight,
b"Underline" => Self::Underline,
b"Squiggly" => Self::Squiggly,
b"StrikeOut" => Self::StrikeOut,
b"Caret" => Self::Caret,
b"Stamp" => Self::Stamp,
b"Ink" => Self::Ink,
b"Popup" => Self::Popup,
b"FileAttachment" => Self::FileAttachment,
b"Sound" => Self::Sound,
b"Widget" => Self::Widget,
b"Redact" => Self::Redact,
other => Self::Other(other.to_vec()),
}
}
/// Whether it is a markup annotation (ISO 32000-2 Table 171's markup column, §12.5.6.2): the
/// kind that can be a comment, answer one or have a review state.
///
/// Added in 0.4.1.
#[must_use]
pub const fn is_markup(&self) -> bool {
matches!(
self,
Self::Text
| Self::FreeText
| Self::Line
| Self::Square
| Self::Circle
| Self::Polygon
| Self::PolyLine
| Self::Highlight
| Self::Underline
| Self::Squiggly
| Self::StrikeOut
| Self::Caret
| Self::Stamp
| Self::Ink
| Self::FileAttachment
| Self::Sound
| Self::Redact
)
}
/// The subtype's name as written in `/Subtype`.
///
/// Added in 0.3.0.
#[must_use]
pub fn name(&self) -> &[u8] {
match self {
Self::Text => b"Text",
Self::Link => b"Link",
Self::FreeText => b"FreeText",
Self::Line => b"Line",
Self::Square => b"Square",
Self::Circle => b"Circle",
Self::Polygon => b"Polygon",
Self::PolyLine => b"PolyLine",
Self::Highlight => b"Highlight",
Self::Underline => b"Underline",
Self::Squiggly => b"Squiggly",
Self::StrikeOut => b"StrikeOut",
Self::Caret => b"Caret",
Self::Stamp => b"Stamp",
Self::Ink => b"Ink",
Self::Popup => b"Popup",
Self::FileAttachment => b"FileAttachment",
Self::Sound => b"Sound",
Self::Widget => b"Widget",
Self::Redact => b"Redact",
Self::Other(name) => name,
}
}
}
/// An annotation's `/F` flags (Table 167).
///
/// Added in 0.3.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct AnnotFlags(pub u32);
impl AnnotFlags {
/// Don't show an annotation of an unknown subtype.
///
/// Added in 0.3.0.
pub const INVISIBLE: u32 = 1;
/// Don't show or print it.
///
/// Added in 0.3.0.
pub const HIDDEN: u32 = 1 << 1;
/// Print it.
///
/// Added in 0.3.0.
pub const PRINT: u32 = 1 << 2;
/// Don't scale it with the page's zoom.
///
/// Added in 0.3.0.
pub const NO_ZOOM: u32 = 1 << 3;
/// Don't rotate it with the page.
///
/// Added in 0.3.0.
pub const NO_ROTATE: u32 = 1 << 4;
/// Print it but don't show it.
///
/// Added in 0.3.0.
pub const NO_VIEW: u32 = 1 << 5;
/// Don't let a user interact with it.
///
/// Added in 0.3.0.
pub const READ_ONLY: u32 = 1 << 6;
/// Don't let a user delete it or change its properties (its contents may change).
///
/// Added in 0.3.0.
pub const LOCKED: u32 = 1 << 7;
/// Invert `NO_VIEW` on hover or selection.
///
/// Added in 0.3.0.
pub const TOGGLE_NO_VIEW: u32 = 1 << 8;
/// Don't let a user change its contents.
///
/// Added in 0.3.0.
pub const LOCKED_CONTENTS: u32 = 1 << 9;
/// Whether every bit of `flag` is set.
///
/// Added in 0.3.0.
#[must_use]
pub const fn has(self, flag: u32) -> bool {
self.0 & flag == flag
}
}
/// How a markup annotation relates to its `/IRT` (Table 172).
///
/// Added in 0.3.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ReplyType {
/// `/R`: a reply.
#[default]
Reply,
/// `/Group`: grouped with it, as one unit.
Group,
}
/// Where a subtype's own geometry puts it, in user space.
///
/// Added in 0.3.0.
#[derive(Debug, Clone, PartialEq, Default)]
#[non_exhaustive]
pub enum AnnotGeometry {
/// Nothing besides `/Rect`.
#[default]
None,
/// `/QuadPoints` of text markup, four corners each, in the order stored: the standard's
/// counter-clockwise order or Acrobat's (upper-left, upper-right, lower-left, lower-right).
Quads(Vec<[UserSpacePoint; 4]>),
/// `/InkList`: one point list per stroke.
Ink(Vec<Vec<UserSpacePoint>>),
/// `/Vertices` of a `Polygon` or `PolyLine`.
Vertices(Vec<UserSpacePoint>),
/// `/L` of a Line: its two ends.
Line([UserSpacePoint; 2]),
/// `/CL` of a `FreeText` callout: two or three points.
Callout(Vec<UserSpacePoint>),
/// The box a `Square` or `Circle` runs along: `/Rect` less `/RD`, or `/Rect` when `/RD` is
/// missing, malformed or leaves no box.
Inner(UserSpaceRect),
}
impl Document {
/// The annotations of `page`, in the order of its `/Annots`.
///
/// Two annotations with the same `/NM` on the page raise `annot-name-duplicate` (on the
/// second); both are kept.
///
/// # Errors
/// Only errors that must propagate ([`laminapdf_cos::Error::must_propagate`]): an
/// unreadable entry is left out.
///
/// Added in 0.3.0.
pub fn annotations(&self, page: &Page<'_>) -> Result<Vec<Annot>> {
let found = self.annotations_unchecked(page)?;
self.check_names(&found)?;
Ok(found)
}
/// [`Document::annotations`] without its duplicate-name warning, for views that read every
/// page each call (the comment threads), so a duplicate name neither repeats its warning nor
/// stops them in strict mode.
pub(crate) fn annotations_unchecked(&self, page: &Page<'_>) -> Result<Vec<Annot>> {
let mut found = Vec::new();
self.each_annotation(page, |id, index, dict| {
let link = self.link(id, index, dict)?;
found.push(self.annotation(link, dict)?);
Ok(())
})?;
pair_popups(&mut found, |a| (&a.id, a.parent.as_ref(), &mut a.popup));
Ok(found)
}
/// The annotations of `page` as [`AnnotLink`]s: their IDs, subtypes, flags and links, without
/// their text or geometry, and without [`Document::annotations`]' warning. The annotation
/// ops read every page this way to find one, so a duplicate name elsewhere never stops an
/// edit, strict mode included.
///
/// # Errors
/// As [`Document::annotations`].
///
/// Added in 0.3.0.
pub fn annotation_links(&self, page: &Page<'_>) -> Result<Vec<AnnotLink>> {
let mut found = Vec::new();
self.each_annotation(page, |id, index, dict| {
found.push(self.link(id, index, dict)?);
Ok(())
})?;
pair_popups(&mut found, |a| (&a.id, a.parent.as_ref(), &mut a.popup));
Ok(found)
}
/// Calls `f` with each dictionary of the page's `/Annots`, its ID and its position.
pub(crate) fn each_annotation(
&self,
page: &Page<'_>,
mut f: impl FnMut(AnnotId, usize, &Dict) -> Result<()>,
) -> Result<()> {
let Some(value) = page.dict().get("Annots") else {
return Ok(());
};
let Some(array) = self.read(value)? else {
return Ok(());
};
let array_ref = value.as_ref();
for (index, entry) in array.as_array().unwrap_or_default().iter().enumerate() {
let Some(dict) = self.read(entry)? else { continue };
let Some(dict) = dict.as_dict() else { continue };
let id = match entry.as_ref() {
Some(r) => AnnotId::object(r),
None => AnnotId::path(&direct_path(page, array_ref, index)),
};
f(id, index, dict)?;
}
Ok(())
}
fn link(&self, id: AnnotId, index: usize, dict: &Dict) -> Result<AnnotLink> {
let subtype = AnnotSubtype::from_name(&read_name(self, dict.get("Subtype"))?.unwrap_or_default());
let flags = match dict.get("F") {
Some(f) => self.read(f)?.and_then(|f| f.as_int()).unwrap_or(0),
None => 0,
};
Ok(AnnotLink {
id,
index,
flags: AnnotFlags(u32::try_from(flags).unwrap_or(0)),
in_reply_to: dict.get("IRT").and_then(Object::as_ref).map(AnnotId::object),
reply_type: match read_name(self, dict.get("RT"))?.as_deref() {
Some(b"Group") => ReplyType::Group,
_ => ReplyType::Reply,
},
popup: dict.get("Popup").and_then(Object::as_ref).map(AnnotId::object),
parent: if subtype == AnnotSubtype::Popup {
dict.get("Parent").and_then(Object::as_ref).map(AnnotId::object)
} else {
None
},
subtype,
})
}
fn annotation(&self, link: AnnotLink, dict: &Dict) -> Result<Annot> {
let geometry = self.geometry(&link.subtype, dict)?;
let state = if link.subtype == AnnotSubtype::Text {
self.annot_state(dict)?
} else {
None
};
let details = self.annot_details(&link.subtype, dict)?;
Ok(Annot {
details,
state,
rect: match dict.get("Rect") {
Some(rect) => read_rect(self, rect)?,
None => None,
},
contents: self.text_entry(dict, "Contents")?,
name: self.text_entry(dict, "NM")?,
modified: self.text_entry(dict, "M")?,
color: self.numbers(dict.get("C"))?.unwrap_or_default(),
opacity: match dict.get("CA") {
Some(ca) => number(self, ca)?,
None => None,
},
author: self.text_entry(dict, "T")?,
subject: self.text_entry(dict, "Subj")?,
created: self.text_entry(dict, "CreationDate")?,
has_appearance: self.has_normal_appearance(dict)?,
has_rich_text: dict.get("RC").is_some(),
id: link.id,
index: link.index,
subtype: link.subtype,
flags: link.flags,
in_reply_to: link.in_reply_to,
reply_type: link.reply_type,
popup: link.popup,
parent: link.parent,
geometry,
})
}
fn geometry(&self, subtype: &AnnotSubtype, dict: &Dict) -> Result<AnnotGeometry> {
Ok(match subtype {
AnnotSubtype::Highlight
| AnnotSubtype::Underline
| AnnotSubtype::Squiggly
| AnnotSubtype::StrikeOut
| AnnotSubtype::Redact => AnnotGeometry::Quads(quads(self, dict.get("QuadPoints"))?),
AnnotSubtype::Ink => {
let mut strokes = Vec::new();
if let Some(list) = dict.get("InkList")
&& let Some(list) = self.read(list)?
{
for stroke in list.as_array().unwrap_or_default() {
strokes.push(self.points(Some(stroke))?.unwrap_or_default());
}
}
AnnotGeometry::Ink(strokes)
}
AnnotSubtype::Polygon | AnnotSubtype::PolyLine => {
AnnotGeometry::Vertices(self.points(dict.get("Vertices"))?.unwrap_or_default())
}
AnnotSubtype::Line => match self.points(dict.get("L"))?.as_deref() {
Some(&[a, b]) => AnnotGeometry::Line([a, b]),
_ => AnnotGeometry::None,
},
AnnotSubtype::FreeText => match self.points(dict.get("CL"))? {
Some(points) if points.len() >= 2 => AnnotGeometry::Callout(points),
_ => AnnotGeometry::None,
},
AnnotSubtype::Square | AnnotSubtype::Circle => {
let rect = match dict.get("Rect") {
Some(rect) => read_rect(self, rect)?,
None => None,
};
match rect {
Some(rect) => AnnotGeometry::Inner(self.inner(rect, dict.get("RD"))?),
None => AnnotGeometry::None,
}
}
_ => AnnotGeometry::None,
})
}
/// `rect` less the `/RD` gaps on each side, or `rect` itself when `/RD` isn't four
/// non-negative numbers or would leave no box.
fn inner(&self, rect: UserSpaceRect, rd: Option<&Object>) -> Result<UserSpaceRect> {
let gaps = self.numbers(rd)?;
let Some(&[left, bottom, right, top]) = gaps.as_deref() else {
return Ok(rect);
};
if [left, bottom, right, top].iter().any(|v| !v.is_finite() || *v < 0.0) {
return Ok(rect);
}
let (x0, y0) = (rect.x0.min(rect.x1), rect.y0.min(rect.y1));
let (x1, y1) = (rect.x0.max(rect.x1), rect.y0.max(rect.y1));
if x0 + left >= x1 - right || y0 + bottom >= y1 - top {
return Ok(rect);
}
Ok(UserSpaceRect::from_corners(
x0 + left,
y0 + bottom,
x1 - right,
y1 - top,
))
}
/// An array of numbers; `None` when absent or when any item isn't a number.
fn numbers(&self, value: Option<&Object>) -> Result<Option<Vec<f64>>> {
let Some(value) = value else { return Ok(None) };
let Some(array) = self.read(value)? else {
return Ok(None);
};
let Some(items) = array.as_array() else { return Ok(None) };
let mut out = Vec::with_capacity(items.len());
for item in items {
match number(self, item)? {
Some(v) => out.push(v),
None => return Ok(None),
}
}
Ok(Some(out))
}
/// An array of coordinate pairs; `None` unless it holds an even count of numbers.
fn points(&self, value: Option<&Object>) -> Result<Option<Vec<UserSpacePoint>>> {
Ok(self.numbers(value)?.filter(|n| n.len().is_multiple_of(2)).map(|n| {
let (pairs, _) = n.as_chunks::<2>();
pairs.iter().map(|&[x, y]| UserSpacePoint::new(x, y)).collect()
}))
}
fn has_normal_appearance(&self, dict: &Dict) -> Result<bool> {
let Some(ap) = dict.get("AP") else { return Ok(false) };
let Some(ap) = self.read(ap)? else { return Ok(false) };
Ok(ap.as_dict().and_then(|ap| ap.get("N")).is_some())
}
fn check_names(&self, found: &[Annot]) -> Result<()> {
let mut seen = BTreeSet::new();
for annot in found {
if let Some(name) = &annot.name
&& !seen.insert(name.as_str())
{
self.warn(Warning::AnnotNameDuplicate {
object: annot.id.as_lamina_id().obj_ref().map(|r: ObjRef| r.num),
})?;
}
}
Ok(())
}
}
/// The path of the direct annotation at `index`: inside the indirect `/Annots` array, else
/// inside the page's own dictionary.
pub(crate) fn direct_path(page: &Page<'_>, array: Option<ObjRef>, index: usize) -> DirectPath {
match array {
Some(array) => DirectPath::new(Some(array), vec![PathSegment::Index(index)]),
None => DirectPath::new(
page.obj_ref(),
vec![PathSegment::Key("Annots"), PathSegment::Index(index)],
),
}
}
/// Gives each annotation without a `/Popup` the Popup on the page whose `/Parent` names it.
fn pair_popups<T>(found: &mut [T], fields: impl Fn(&mut T) -> (&AnnotId, Option<&AnnotId>, &mut Option<AnnotId>)) {
let mut pairs = Vec::new();
for a in found.iter_mut() {
let (id, parent, _) = fields(a);
if let Some(parent) = parent {
pairs.push((parent.clone(), id.clone()));
}
}
for (parent, popup) in pairs {
for a in found.iter_mut() {
let (id, _, slot) = fields(a);
if *id == parent && slot.is_none() {
*slot = Some(popup);
break;
}
}
}
}