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
//! Whether optional content is off as the document opens (ISO 32000-2 §8.11): an optional
//! content group against the default configuration's `/BaseState`, `/ON` and `/OFF`
//! (§8.11.4.3), and a membership dictionary by its visibility expression (`/VE`) or, without
//! one, its `/OCGs` and `/P` policy (§8.11.2.2).
//!
//! What can't be read or decided is [`Visibility::Unknown`]: a group the configuration's intent
//! ignores, one `/OCGs` doesn't list, one a usage application (`/AS`) names (a viewer may turn
//! it on or off for viewing, printing or exporting), one both `/ON` and `/OFF` list, a policy or expression no standard defines, an expression
//! longer than [`MAX_EXPRESSION`] items or nested deeper than [`MAX_DEPTH`]. A caller that
//! removes hidden content keeps unknown content and says so; [`Document::optional_content_off`]
//! counts it as on.
use std::collections::BTreeSet;
use laminapdf_cos::{Dict, Object, Result};
use crate::document::Document;
/// The most groups and operators one visibility expression or membership may hold before it
/// counts as [`Visibility::Unknown`].
const MAX_EXPRESSION: usize = 1_024;
/// How deep a visibility expression may nest before it counts as [`Visibility::Unknown`].
const MAX_DEPTH: usize = 32;
/// Whether content an `/OC` entry marks shows as the document opens (ISO 32000-2 §8.11).
///
/// Added in 0.7.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Visibility {
/// It shows.
Visible,
/// The default configuration hides it.
Hidden,
/// Its state can't be decided: something it names is missing, malformed, outside the
/// configuration's intent or beyond the evaluation's bounds.
Unknown,
}
impl Visibility {
/// Kleene's `and`: hidden when either is, visible when both are.
const fn and(self, other: Self) -> Self {
match (self, other) {
(Self::Hidden, _) | (_, Self::Hidden) => Self::Hidden,
(Self::Visible, Self::Visible) => Self::Visible,
_ => Self::Unknown,
}
}
/// Kleene's `or`: visible when either is, hidden when both are.
const fn or(self, other: Self) -> Self {
match (self, other) {
(Self::Visible, _) | (_, Self::Visible) => Self::Visible,
(Self::Hidden, Self::Hidden) => Self::Hidden,
_ => Self::Unknown,
}
}
const fn not(self) -> Self {
match self {
Self::Visible => Self::Hidden,
Self::Hidden => Self::Visible,
Self::Unknown => Self::Unknown,
}
}
}
/// The document's default optional content configuration (`/OCProperties /D`, §8.11.4.3), read
/// once: which groups exist and which are on.
///
/// Added in 0.7.0.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct OptionalContent {
/// The groups `/OCGs` lists, by object number.
groups: BTreeSet<u32>,
base_off: bool,
on: BTreeSet<u32>,
off: BTreeSet<u32>,
/// The groups a usage application (`/AS`) names: a viewer may turn them on or off for
/// viewing, printing or exporting, so the default state alone doesn't decide them.
usage: BTreeSet<u32>,
/// The configuration's `/Intent` names; `None` for `All`.
intents: Option<BTreeSet<Vec<u8>>>,
}
impl OptionalContent {
/// The groups `/OCProperties /OCGs` lists, by object number.
///
/// Added in 0.7.0.
#[must_use]
pub const fn groups(&self) -> &BTreeSet<u32> {
&self.groups
}
/// The listed groups the default configuration turns off, whatever their intent.
///
/// Added in 0.7.0.
#[must_use]
pub fn off_groups(&self) -> BTreeSet<u32> {
self.groups
.iter()
.copied()
.filter(|g| !self.on(*g) || (self.on.contains(g) && self.off.contains(g)))
.collect()
}
fn on(&self, group: u32) -> bool {
if self.base_off {
self.on.contains(&group)
} else {
!self.off.contains(&group)
}
}
/// Whether the content that the `/OC` value `oc` marks (a group or a membership dictionary,
/// by reference or direct) shows as the document opens. Its work is bounded: a membership
/// or expression of more than 1,024 items, or nested more than 32 deep, is
/// [`Visibility::Unknown`].
///
/// # Errors
/// Only what must propagate (strict mode, pending data, a source error).
///
/// Added in 0.7.0.
pub fn visibility(&self, doc: &Document, oc: &Object) -> Result<Visibility> {
let mut left = MAX_EXPRESSION;
let Some(dict) = doc.read(oc)?.and_then(|o| o.as_dict().cloned()) else {
return Ok(Visibility::Unknown);
};
match name(doc, &dict, "Type")?.as_deref() {
Some(b"OCG") => self.group(doc, oc, &dict),
Some(b"OCMD") => self.membership(doc, &dict, &mut left),
_ => Ok(Visibility::Unknown),
}
}
/// A group, by reference: only a listed group within the configuration's intent counts.
fn group(&self, doc: &Document, oc: &Object, dict: &Dict) -> Result<Visibility> {
let Some(num) = oc.as_ref().map(|r| r.num) else {
return Ok(Visibility::Unknown);
};
// A group in both `/ON` and `/OFF` is read either way by different viewers.
let contradicted = self.on.contains(&num) && self.off.contains(&num);
if !self.groups.contains(&num) || contradicted || self.usage.contains(&num) || !self.in_intent(doc, dict)? {
return Ok(Visibility::Unknown);
}
Ok(if self.on(num) {
Visibility::Visible
} else {
Visibility::Hidden
})
}
/// Whether the group's `/Intent` (default `View`) meets the configuration's.
fn in_intent(&self, doc: &Document, dict: &Dict) -> Result<bool> {
let Some(config) = &self.intents else {
return Ok(true);
};
let own = match dict.get("Intent") {
Some(value) => names(doc, value)?,
None => Some(BTreeSet::from([b"View".to_vec()])),
};
Ok(own.is_some_and(|own| !own.is_disjoint(config)))
}
/// A membership dictionary: its `/VE` when it has one, else `/OCGs` under `/P`.
fn membership(&self, doc: &Document, dict: &Dict, left: &mut usize) -> Result<Visibility> {
if let Some(ve) = dict.get("VE") {
return self.expression(doc, ve, 0, left);
}
let members: Vec<Object> = match dict.get("OCGs") {
None => Vec::new(),
Some(value) => match doc.read(value)?.as_deref() {
Some(Object::Array(items)) => items.clone(),
Some(Object::Dict(_)) => vec![value.clone()],
Some(Object::Null) | None => Vec::new(),
Some(_) => return Ok(Visibility::Unknown),
},
};
let mut states = Vec::with_capacity(members.len().min(MAX_EXPRESSION));
for member in members.iter().filter(|m| !matches!(m, Object::Null)) {
if !charge(left) {
return Ok(Visibility::Unknown);
}
let state = match doc.read(member)?.and_then(|o| o.as_dict().cloned()) {
Some(group) if name(doc, &group, "Type")?.as_deref() == Some(b"OCG") => {
self.group(doc, member, &group)?
}
_ => Visibility::Unknown,
};
states.push(state);
}
// No groups: the dictionary has no effect on visibility (§8.11.2.2).
if states.is_empty() {
return Ok(Visibility::Visible);
}
let all =
|f: fn(Visibility) -> Visibility| states.iter().map(|s| f(*s)).fold(Visibility::Visible, Visibility::and);
let any =
|f: fn(Visibility) -> Visibility| states.iter().map(|s| f(*s)).fold(Visibility::Hidden, Visibility::or);
let same = |s: Visibility| s;
Ok(match name(doc, dict, "P")?.as_deref() {
None | Some(b"AnyOn") => any(same),
Some(b"AllOn") => all(same),
Some(b"AnyOff") => any(Visibility::not),
Some(b"AllOff") => all(Visibility::not),
Some(_) => Visibility::Unknown,
})
}
/// A visibility expression (§8.11.2.2, Table 98): a group, or `[/And …]`, `[/Or …]` or
/// `[/Not e]`.
fn expression(&self, doc: &Document, value: &Object, depth: usize, left: &mut usize) -> Result<Visibility> {
if depth > MAX_DEPTH || !charge(left) {
return Ok(Visibility::Unknown);
}
let Some(resolved) = doc.read(value)? else {
return Ok(Visibility::Unknown);
};
match &*resolved {
Object::Dict(group) if name(doc, group, "Type")?.as_deref() == Some(b"OCG") => {
self.group(doc, value, group)
}
Object::Array(items) => {
let Some((operator, operands)) = items.split_first() else {
return Ok(Visibility::Unknown);
};
let operator = match doc.read(operator)?.as_deref() {
Some(Object::Name(n)) => n.as_bytes().to_vec(),
_ => return Ok(Visibility::Unknown),
};
match (operator.as_slice(), operands) {
(b"Not", [only]) => Ok(self.expression(doc, only, depth + 1, left)?.not()),
(b"And" | b"Or", [_, ..]) => {
let and = operator == b"And";
let mut out = if and { Visibility::Visible } else { Visibility::Hidden };
for operand in operands {
let state = self.expression(doc, operand, depth + 1, left)?;
out = if and { out.and(state) } else { out.or(state) };
}
Ok(out)
}
_ => Ok(Visibility::Unknown),
}
}
_ => Ok(Visibility::Unknown),
}
}
}
/// Takes one step of the bound; `false` when none is left.
fn charge(left: &mut usize) -> bool {
match left.checked_sub(1) {
Some(rest) => {
*left = rest;
true
}
None => false,
}
}
/// The name at `key`, read through a reference.
fn name(doc: &Document, dict: &Dict, key: &str) -> Result<Option<Vec<u8>>> {
Ok(match dict.get(key) {
Some(value) => match doc.read(value)?.as_deref() {
Some(Object::Name(n)) => Some(n.as_bytes().to_vec()),
_ => None,
},
None => None,
})
}
/// A name or an array of names, read through references; `None` when it is neither.
fn names(doc: &Document, value: &Object) -> Result<Option<BTreeSet<Vec<u8>>>> {
Ok(match doc.read(value)?.as_deref() {
Some(Object::Name(n)) => Some(BTreeSet::from([n.as_bytes().to_vec()])),
Some(Object::Array(items)) => {
let mut out = BTreeSet::new();
for item in items.iter().take(MAX_EXPRESSION) {
match doc.read(item)?.as_deref() {
Some(Object::Name(n)) => {
out.insert(n.as_bytes().to_vec());
}
_ => return Ok(None),
}
}
Some(out)
}
_ => None,
})
}
impl Document {
/// The default optional content configuration (`/OCProperties /D`), read once; `None` for a
/// document without one, whose `/OC` entries a viewer ignores. A group is named by its
/// object number.
///
/// # Errors
/// Only what must propagate (strict mode, pending data, a source error).
///
/// Added in 0.7.0.
pub fn optional_content(&self) -> Result<Option<OptionalContent>> {
let catalog = self.catalog()?;
let Some(properties) = self.dict_of(catalog.get("OCProperties"))? else {
return Ok(None);
};
let Some(d) = self.dict_of(properties.get("D"))? else {
return Ok(None);
};
let refs = |value: Option<&Object>| -> Result<BTreeSet<u32>> {
Ok(match value {
Some(value) => self
.read(value)?
.as_deref()
.and_then(Object::as_array)
.map(|items| items.iter().filter_map(|i| i.as_ref().map(|r| r.num)).collect())
.unwrap_or_default(),
None => BTreeSet::new(),
})
};
let intents = match d.get("Intent") {
None => Some(BTreeSet::from([b"View".to_vec()])),
Some(value) => match names(self, value)? {
Some(set) if set.contains(b"All".as_slice()) => None,
Some(set) => Some(set),
// An intent no one can read: no group meets it, so every group is unknown.
None => Some(BTreeSet::new()),
},
};
let mut usage = BTreeSet::new();
if let Some(applications) = d.get("AS") {
let applications = self.read(applications)?;
for application in applications
.as_deref()
.and_then(Object::as_array)
.unwrap_or_default()
.iter()
.take(MAX_EXPRESSION)
{
if let Some(app) = self.dict_of(Some(application))? {
usage.extend(refs(app.get("OCGs"))?);
}
}
}
Ok(Some(OptionalContent {
usage,
groups: refs(properties.get("OCGs"))?,
base_off: name(self, &d, "BaseState")?.as_deref() == Some(b"OFF".as_slice()),
on: refs(d.get("ON"))?,
off: refs(d.get("OFF"))?,
intents,
}))
}
/// Whether the content that the `/OC` value `oc` marks (an optional content group or a
/// membership dictionary, by reference) is hidden in the default configuration, as the
/// document opens: [`OptionalContent::visibility`] is [`Visibility::Hidden`]. `false` for a
/// document without optional content and for anything that can't be decided.
///
/// # Errors
/// Only what must propagate (strict mode, pending data, a source error).
///
/// Added in 0.6.0.
pub fn optional_content_off(&self, oc: &Object) -> Result<bool> {
let Some(config) = self.optional_content()? else {
return Ok(false);
};
Ok(config.visibility(self, oc)? == Visibility::Hidden)
}
fn dict_of(&self, value: Option<&Object>) -> Result<Option<Dict>> {
Ok(match value {
Some(value) => self.read(value)?.and_then(|o| o.as_dict().cloned()),
None => None,
})
}
}
#[cfg(test)]
#[path = "optional_content_tests.rs"]
mod tests;