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
//! The form-field widgets a page shows (ISO 32000-2 §12.5.6.19, §12.7.4): the widget
//! annotations in its `/Annots`, each with the field it belongs to; and fields' fully qualified
//! names (§12.7.4.2), with the `<partial>#<n>` rule that keeps a copied field's name unique.
use std::collections::{BTreeMap, BTreeSet};
use laminapdf_cos::{Dict, ObjRef, Object, Result, tolerant};
use laminapdf_syntax::text::decode_text_string;
use crate::document::Document;
use crate::id::PageId;
use crate::values::{array_items, dict_at};
/// A widget annotation on a page and the field it belongs to.
///
/// Added in 0.3.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub struct PageWidget {
/// The widget annotation.
pub widget: ObjRef,
/// The field it belongs to: the widget itself when it has a `/T` or a `/V` (a merged field
/// and widget), else the first field up its `/Parent` chain that has one, since a field in
/// between may have no partial name (§12.7.4.2).
pub field: ObjRef,
}
impl Document {
/// The widgets `page` lists in its `/Annots`, in that order. Reading is tolerant (ADR
/// 0003): an annotation or field object that doesn't parse is skipped, and a `/Parent`
/// chain that ends, loops or passes `Limits::max_tree_depth` before a named field gives
/// the widget's immediate parent.
///
/// # Errors
/// Unavailable input and hard limits.
///
/// Added in 0.3.0.
pub fn page_widgets(&self, page: &PageId) -> Result<Vec<PageWidget>> {
let Some(r) = page.as_lamina_id().obj_ref() else {
return Ok(Vec::new());
};
let Some(page) = dict_at(self, r)? else {
return Ok(Vec::new());
};
let annots = match page.get("Annots") {
Some(value) => tolerant(self.deref(value))?.and_then(|v| v.as_array().map(<[Object]>::to_vec)),
None => None,
};
let mut out = Vec::new();
for annot in annots.unwrap_or_default().iter().filter_map(Object::as_ref) {
let Some(widget) = dict_at(self, annot)? else { continue };
if is_widget(&widget) {
out.push(PageWidget {
widget: annot,
field: field_of(self, annot, &widget)?,
});
}
}
Ok(out)
}
}
/// A widget annotation: `/Subtype /Widget`, or, as some writers leave the subtype out, an
/// annotation without one that carries a field key.
///
/// Added in 0.3.0.
#[must_use]
pub fn is_widget(dict: &Dict) -> bool {
dict.get_name("Subtype").map_or_else(
|| dict.contains_key("FT") || dict.contains_key("Parent"),
|s| s == b"Widget",
)
}
/// The field widget `widget` (dictionary `dict`) belongs to ([`PageWidget::field`]).
fn field_of(doc: &Document, widget: ObjRef, dict: &Dict) -> Result<ObjRef> {
let names = |d: &Dict| d.contains_key("T") || d.contains_key("V");
if names(dict) {
return Ok(widget);
}
let Some(parent) = dict.get("Parent").and_then(Object::as_ref) else {
return Ok(widget);
};
let mut seen = BTreeSet::from([widget.num]);
let mut next = Some(parent);
while let Some(r) = next {
if seen.len() > doc.limits().max_tree_depth() || !seen.insert(r.num) {
break;
}
let Some(d) = dict_at(doc, r)? else { break };
if names(&d) {
return Ok(r);
}
next = d.get("Parent").and_then(Object::as_ref);
}
Ok(parent)
}
/// Every form field's fully qualified name (ISO 32000-2 §12.7.4.2), and the rule that picks a
/// name no field has: a copy of field `<partial>` is named `<partial>#<n>`, `n` the smallest
/// number from 2 that makes its fully qualified name unique (E2 plan §11). `#` may appear in a
/// partial name; only a period may not.
///
/// Added in 0.3.0.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FieldNames {
names: BTreeSet<String>,
}
impl FieldNames {
/// Whether some field has the fully qualified name `name`.
///
/// Added in 0.3.0.
#[must_use]
pub fn contains(&self, name: &str) -> bool {
self.names.contains(name)
}
/// Whether a field named `name` would clash with one already here: a field of that name,
/// one below it (`name.x`) or one it would sit below (`name` starting `x.` for a field
/// `x`): fully qualified names must be unique (ISO 32000-2 §12.7.4.2), and a terminal field
/// can't hold kids.
///
/// Added in 0.3.0.
#[must_use]
pub fn clashes(&self, name: &str) -> bool {
let below = format!("{name}.");
self.names.contains(name)
|| self
.names
.range(below.clone()..)
.next()
.is_some_and(|n| n.starts_with(&below))
|| name
.match_indices('.')
.any(|(at, _)| name.get(..at).is_some_and(|prefix| self.names.contains(prefix)))
}
/// Records `name`, a fully qualified name in use that [`Document::field_names`] doesn't
/// list (a field the form's `/Fields` doesn't reach, for one).
///
/// Added in 0.3.0.
pub fn insert(&mut self, name: String) {
self.names.insert(name);
}
/// The partial name for a copy of field `partial` under the field whose fully qualified
/// name is `parent` (`None` for a top-level field): `<partial>#<n>`, `n` the smallest number
/// from 2 that no field uses. A copy of a copy continues the series: the copy of `total#2`
/// is `total#3`, not `total#2#2`. The new name is recorded, so the next call picks another.
///
/// Added in 0.3.0.
pub fn unique_partial(&mut self, parent: Option<&str>, partial: &str) -> String {
let full = |p: &str| parent.map_or_else(|| p.to_owned(), |parent| format!("{parent}.{p}"));
let partial = match partial.rsplit_once('#') {
Some((base, n)) if !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) => base,
_ => partial,
};
let mut n: u64 = 2;
loop {
let candidate = format!("{partial}#{n}");
if self.names.insert(full(&candidate)) {
return candidate;
}
n += 1;
}
}
}
impl Document {
/// `field`'s fully qualified name: the partial names (`/T`) from the root field down,
/// joined by periods (ISO 32000-2 §12.7.4.2); a field without a `/T` adds nothing. `None`
/// when the `/Parent` chain can't be followed to its end: deeper than
/// `Limits::max_tree_depth`, a loop, or an object that can't be read.
///
/// # Errors
/// Unavailable input and hard limits.
///
/// Added in 0.3.0.
pub fn field_name(&self, field: ObjRef) -> Result<Option<String>> {
let max_depth = self.limits().max_tree_depth();
let mut parts = Vec::new();
let mut seen = BTreeSet::new();
let mut next = Some(field);
while let Some(r) = next {
if seen.len() >= max_depth || !seen.insert(r.num) {
return Ok(None);
}
let Some(d) = dict_at(self, r)? else { return Ok(None) };
if let Some(t) = d.get("T") {
match tolerant(self.deref(t))?.as_deref() {
Some(Object::String(t)) => parts.push(decode_text_string(&t.bytes)),
_ => return Ok(None),
}
}
next = d.get("Parent").and_then(Object::as_ref);
}
parts.reverse();
Ok(Some(parts.join(".")))
}
/// The fully qualified names of every field the form lists: `/AcroForm /Fields` and their
/// `/Kids`, down to `Limits::max_tree_depth`, each node once. A node that can't be read
/// is skipped (ADR 0003).
///
/// # Errors
/// Unavailable input and hard limits.
///
/// Added in 0.3.0.
pub fn field_names(&self) -> Result<FieldNames> {
Ok(FieldNames {
names: self.named_fields()?.into_keys().collect(),
})
}
/// The field whose fully qualified name is `name`, among those the form lists (as
/// [`Document::field_names`] reads them); the first found when two share it.
///
/// # Errors
/// Unavailable input and hard limits.
///
/// Added in 0.3.0.
pub fn field_by_name(&self, name: &str) -> Result<Option<ObjRef>> {
Ok(self.named_fields()?.get(name).copied())
}
/// Every named field the form lists, by fully qualified name (the first one reached for a
/// name two fields share).
fn named_fields(&self) -> Result<BTreeMap<String, ObjRef>> {
let mut names = BTreeMap::new();
let Some(form) = self.catalog()?.get("AcroForm").cloned() else {
return Ok(names);
};
let Some(form) = tolerant(self.deref(&form))?.and_then(|o| o.as_dict().cloned()) else {
return Ok(names);
};
let max_depth = self.limits().max_tree_depth();
let mut seen = BTreeSet::new();
let mut stack: Vec<(Object, Option<String>, usize)> = array_items(self, form.get("Fields"))?
.into_iter()
.rev()
.map(|k| (k, None, 0))
.collect();
while let Some((node, prefix, depth)) = stack.pop() {
let Some(r) = node.as_ref() else { continue };
if depth >= max_depth || !seen.insert(r.num) {
continue;
}
let Some(d) = dict_at(self, r)? else { continue };
let name = match d
.get("T")
.map(|t| tolerant(self.deref(t)))
.transpose()?
.flatten()
.as_deref()
{
Some(Object::String(t)) => {
let partial = decode_text_string(&t.bytes);
let full = prefix.map_or_else(|| partial.clone(), |p| format!("{p}.{partial}"));
names.entry(full.clone()).or_insert(r);
Some(full)
}
_ => prefix,
};
for kid in array_items(self, d.get("Kids"))?.into_iter().rev() {
stack.push((kid, name.clone(), depth + 1));
}
}
Ok(names)
}
}