Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / pdf / src / main / rust / src / annotations.rs

annotations.rs449 lines · 19.3 KiBRaw
1use crate::*;
2
3/// The §12.5.5 appearance algorithm's matrix **A**: it maps the `/Matrix`-
4/// transformed `/BBox` onto the annotation `/Rect`, and does NOT itself include
5/// `/Matrix`.
6///
7/// This is the matrix to concatenate before invoking the appearance with `Do`,
8/// because §8.10.2 makes `Do` concatenate the form's own `/Matrix` with the CTM.
9/// Using the full `AA` there applies `/Matrix` twice. Callers that play the
10/// appearance's operators directly want `appearance_matrix` instead.
11pub(crate) fn appearance_fit_matrix(rect: [f64; 4], bbox: [f64; 4], matrix: Mat) -> Mat {
12 let corners = [
13 (bbox[0], bbox[1]),
14 (bbox[2], bbox[1]),
15 (bbox[2], bbox[3]),
16 (bbox[0], bbox[3]),
17 ];
18 let mut tx0 = f64::INFINITY;
19 let mut ty0 = f64::INFINITY;
20 let mut tx1 = f64::NEG_INFINITY;
21 let mut ty1 = f64::NEG_INFINITY;
22 for (x, y) in corners {
23 let (px, py) = transform(&matrix, x, y);
24 tx0 = tx0.min(px);
25 ty0 = ty0.min(py);
26 tx1 = tx1.max(px);
27 ty1 = ty1.max(py);
28 }
29 let rx0 = rect[0].min(rect[2]);
30 let ry0 = rect[1].min(rect[3]);
31 let rx1 = rect[0].max(rect[2]);
32 let ry1 = rect[1].max(rect[3]);
33 let bw = tx1 - tx0;
34 let bh = ty1 - ty0;
35 let sx = if bw.abs() > 1e-6 { (rx1 - rx0) / bw } else { 1.0 };
36 let sy = if bh.abs() > 1e-6 { (ry1 - ry0) / bh } else { 1.0 };
37 [sx, 0.0, 0.0, sy, rx0 - sx * tx0, ry0 - sy * ty0]
38}
39
40/// The §12.5.5 appearance algorithm's matrix **AA** = `Matrix` × **A**: maps the
41/// appearance stream's form space straight to page space.
42///
43/// For a caller that interprets the appearance's operator list itself (which
44/// therefore never sees a `Do` to apply `/Matrix` for it). A caller that emits
45/// `Do` must use `appearance_fit_matrix`.
46pub(crate) fn appearance_matrix(rect: [f64; 4], bbox: [f64; 4], matrix: Mat) -> Mat {
47 mat_mul(&matrix, &appearance_fit_matrix(rect, bbox, matrix))
48}
49
50/// Whether an annotation should be painted on screen. Shared by the renderer and
51/// by `flatten_document`, which must not bake in anything invisible.
52///
53/// Per §12.5.3 Table 165 the `/F` flags are tested by VALUE: Hidden is bit
54/// position 2 (value 2), NoView is bit position 6 (value 32). Also honors
55/// optional content (§8.11.2) and skips `/Popup`, whose appearance is shown only
56/// via its parent's open state (§12.5.6.14).
57///
58/// The `OcConfig` is a PARAMETER, deliberately. There was a `annot_visible_on_screen(doc,
59/// dict)` convenience wrapper that called `OcConfig::from_doc` itself, and both callers
60/// walk an `/Annots` array — so it rebuilt the catalog's whole membership configuration
61/// once per annotation. It is deleted rather than left for the next caller to reach for,
62/// because that shape is what silently undid a measured 8.8x win twice: once in the
63/// renderer's `Do` arm and once here in `flatten_document`. Resolve the config once, at
64/// the outermost point that has the document, and pass it down.
65pub(crate) fn annot_visible_on_screen_with(
66 oc: &OcConfig,
67 doc: &Document,
68 dict: &lopdf::Dictionary,
69) -> bool {
70 let flags = dict
71 .get(b"F")
72 .ok()
73 .and_then(|o| deref(doc, o).or(Some(o)))
74 .and_then(num)
75 .unwrap_or(0.0) as i64;
76 if flags & 0b10 != 0 || flags & 0b10_0000 != 0 {
77 return false;
78 }
79 if dict.get(b"OC").ok().map(|o| oc.object_hidden(doc, o)).unwrap_or(false) {
80 return false;
81 }
82 dict.get(b"Subtype")
83 .ok()
84 .and_then(|o| deref(doc, o).or(Some(o)))
85 .and_then(|o| o.as_name().ok())
86 != Some(b"Popup")
87}
88
89/// Render each visible page annotation's normal appearance (`/AP /N`) into
90/// primitives, mapping the appearance BBox into the annotation Rect, then
91/// through `base` (page rotation / origin) into displayed space.
92pub(crate) fn render_annotations(doc: &Document, page_id: ObjectId, base: &Mat, prims: &mut Vec<Prim>) {
93 let annots = match doc
94 .get_dictionary(page_id)
95 .ok()
96 .and_then(|d| d.get(b"Annots").ok())
97 .and_then(|o| deref(doc, o))
98 {
99 Some(Object::Array(a)) => a.clone(),
100 _ => return,
101 };
102
103 let oc = OcConfig::from_doc(doc);
104 for a in annots.iter().take(MAX_ANNOTATIONS) {
105 let dict = match deref(doc, a).and_then(|o| o.as_dict().ok()) {
106 Some(d) => d,
107 None => continue,
108 };
109 if !annot_visible_on_screen_with(&oc, doc, dict) {
110 continue;
111 }
112 render_annotation(doc, dict, base, prims);
113 }
114 if annots.len() > MAX_ANNOTATIONS {
115 // Each annotation can emit an appearance stream's worth of primitives, so an
116 // /Annots array with a hostile number of entries is an unbounded amount of work
117 // even though the array itself is bounded by the file size.
118 if cfg!(debug_assertions) {
119 eprintln!(
120 "[pdf_render/annotations] page has {} annotations - only the first {} are rendered",
121 annots.len(),
122 MAX_ANNOTATIONS
123 );
124 }
125 }
126}
127
128pub(crate) fn render_annotation(doc: &Document, dict: &lopdf::Dictionary, base: &Mat, prims: &mut Vec<Prim>) {
129 let rect = match dict.get(b"Rect").ok().and_then(|o| read_rect(doc, o)) {
130 Some(r) => r,
131 None => return,
132 };
133
134 // §12.7.2 Table 218: when the AcroForm sets /NeedAppearances the consumer
135 // SHALL construct field appearances from /V and /DA, so the flag wins over a
136 // /AP that is present but stale. Without the flag a real /AP wins, and a
137 // Widget reaches the same synthesis only through
138 // `synthesize_annotation_appearance` below — i.e. when there is no usable
139 // /AP at all.
140 if dict.get(b"Subtype").ok().and_then(|o| deref(doc, o).or(Some(o))).and_then(|o| o.as_name().ok())
141 == Some(b"Widget".as_ref())
142 && crate::forms::need_appearances(doc)
143 && render_widget_value(doc, dict, rect, base, prims)
144 {
145 return;
146 }
147
148 // Resolve the normal appearance: /AP /N is either a stream or a subdictionary
149 // of appearance states selected by /AS. When absent, synthesize a basic
150 // appearance for common markup/shape annotation types.
151 let ap = match dict.get(b"AP").ok().and_then(|o| deref(doc, o)) {
152 Some(Object::Dictionary(d)) => d,
153 _ => {
154 synthesize_annotation_appearance(doc, dict, rect, base, prims);
155 return;
156 }
157 };
158 // Fix P0 early return without fallback — if /AP present but N malformed, synthesize fallback
159 let normal = match ap.get(b"N").ok().and_then(|o| deref(doc, o)) {
160 Some(Object::Stream(s)) => s,
161 Some(Object::Dictionary(states)) => {
162 // §7.3.10 lets any object be indirect. An indirect /AS read as a
163 // plain name yields None, which falls into the no-/AS branch below
164 // and renders a checkbox whose state was set indirectly as unchecked
165 // — or draws nothing at all. /F, /Subtype, /C and /CA are all
166 // dereferenced in this file; /AS was the outlier.
167 let as_name = dict
168 .get(b"AS")
169 .ok()
170 .and_then(|o| deref(doc, o).or(Some(o)))
171 .and_then(|o| o.as_name().ok());
172 let picked = match as_name {
173 // §12.5.5 defines no fallback for an /AS that names a state the
174 // /N dictionary does not hold, so this is a judgement about
175 // malformed input. The name itself decides the direction:
176 //
177 // /AS = /Off, absent — blank IS the off appearance, and
178 // omitting the /Off entry is a normal way to encode it. Draw
179 // nothing, which the synthesis fallback below does.
180 //
181 // /AS = anything else, absent — the file is asserting this
182 // widget is ON. Falling back to /Off then renders a checked
183 // box as unchecked, and if /Off is absent too it renders
184 // NOTHING at all. When exactly one non-Off state exists it is
185 // unambiguously the on-art under a different export name
186 // (/Yes vs /On vs /1), so use it. That is not the
187 // "nondeterministic arbitrary entry" this used to warn about:
188 // it is taken only when /AS has explicitly said not-Off, so it
189 // cannot turn an unchecked box into a checked one.
190 Some(n) => states.get(n).ok().or_else(|| {
191 if n == b"Off" {
192 return None;
193 }
194 let mut on: Vec<&Object> =
195 states.iter().filter(|(k, _)| k.as_slice() != b"Off").map(|(_, v)| v).collect();
196 match on.len() {
197 1 => Some(on.remove(0)),
198 _ => states.get(b"Off").ok(),
199 }
200 }),
201 // /AS absent is malformed (§12.5.5, Table 168 requires it when /N
202 // is a subdictionary). Prefer "Off"; failing that, a single entry
203 // is unambiguous, so use the real appearance rather than
204 // synthesizing a crude one over the top of it.
205 None => states.get(b"Off").ok().or_else(|| {
206 if states.len() == 1 {
207 states.iter().next().map(|(_, v)| v)
208 } else {
209 None
210 }
211 }),
212 };
213 match picked.and_then(|o| deref(doc, o)) {
214 Some(Object::Stream(s)) => s,
215 _ => {
216 synthesize_annotation_appearance(doc, dict, rect, base, prims);
217 return;
218 }
219 }
220 }
221 _ => {
222 synthesize_annotation_appearance(doc, dict, rect, base, prims);
223 return;
224 }
225 };
226
227 let bbox_raw = normal
228 .dict
229 .get(b"BBox")
230 .ok()
231 .and_then(|o| read_rect(doc, o));
232 let bbox = bbox_raw.unwrap_or([0.0, 0.0, 1.0, 1.0]);
233 let matrix = normal
234 .dict
235 .get(b"Matrix")
236 .ok()
237 .and_then(read_matrix_obj)
238 .unwrap_or(IDENTITY);
239 let res = normal
240 .dict
241 .get(b"Resources")
242 .ok()
243 .and_then(|o| deref(doc, o))
244 .and_then(|o| o.as_dict().ok())
245 .cloned();
246
247 let ops = crate::content::stream_operations(doc, normal);
248 if ops.is_empty() {
249 // `objects.rs` returns an empty operation list for a stream it could not
250 // decode at all (unknown filter, /Crypt, broken filter chain), which is
251 // indistinguishable here from a genuinely empty appearance. Every other
252 // unusable-/AP branch above falls back to the synthesized shape; this one
253 // returned, so the annotation vanished outright.
254 synthesize_annotation_appearance(doc, dict, rect, base, prims);
255 return;
256 }
257
258 let ctm = mat_mul(&appearance_matrix(rect, bbox, matrix), base);
259
260 // §8.10.2: a form XObject's /BBox "shall be used to clip" its contents, and
261 // §12.5.5 defines an appearance stream as a form XObject. Without this an
262 // appearance paints outside its own Rect. Clip to the /Matrix-transformed
263 // BBox QUAD rather than the axis-aligned box §12.5.5 derives for the /Rect
264 // fit — the latter is too loose and lets a rotated appearance spill. The
265 // same `ctm` is reused for the clip and the content, so the form's /Matrix
266 // (already folded into it by appearance_matrix) cannot be applied twice.
267 //
268 // A degenerate BBox cannot clip — a collapsed quad would swallow the whole
269 // annotation, turning a spill into a vanish — but emitting NO clip is not safe
270 // either: `sh` fills the whole of the current clip region (§8.7.4.3), so an
271 // appearance stream containing one floods the entire page. Fall back to the
272 // annotation's own /Rect, which bounds it per §12.5.5 regardless of the /BBox.
273 // /Rect is in default user space, so it maps through `base`, not `ctm`.
274 let (clip, clip_ctm) = match bbox_raw
275 .map(normalize_rect)
276 .filter(|b| b[2] - b[0] > 0.0 && b[3] - b[1] > 0.0)
277 {
278 Some(b) => (Some(b), ctm),
279 None => {
280 let r = normalize_rect(rect);
281 let usable = (r[2] - r[0] > 0.0 && r[3] - r[1] > 0.0).then_some(r);
282 (usable, *base)
283 }
284 };
285 let mut clip_bbox_device: Option<[f64; 4]> = None;
286 if let Some(b) = clip {
287 let dev: Vec<(f64, f64)> = [(b[0], b[1]), (b[2], b[1]), (b[2], b[3]), (b[0], b[3])]
288 .iter()
289 .map(|&(x, y)| transform(&clip_ctm, x, y))
290 .collect();
291 let xs = dev.iter().map(|p| p.0);
292 let ys = dev.iter().map(|p| p.1);
293 let bb = [
294 xs.clone().fold(f64::INFINITY, f64::min),
295 ys.clone().fold(f64::INFINITY, f64::min),
296 xs.fold(f64::NEG_INFINITY, f64::max),
297 ys.fold(f64::NEG_INFINITY, f64::max),
298 ];
299 if bb.iter().all(|v| v.is_finite()) && bb[2] > bb[0] && bb[3] > bb[1] {
300 clip_bbox_device = Some(bb);
301 }
302 let pts: Vec<(f32, f32)> = dev.iter().map(|&(x, y)| (x as f32, y as f32)).collect();
303 let mut path_ops = vec![PathOp::Move(pts[0].0, pts[0].1)];
304 path_ops.extend(pts[1..].iter().map(|&(x, y)| PathOp::Line(x, y)));
305 path_ops.push(PathOp::Close);
306 prims.push(Prim::ClipPush { even_odd: false, pts, path_ops: Some(path_ops) });
307 }
308
309 let gs = GraphicsState {
310 ctm,
311 ..Default::default()
312 };
313 let start = prims.len();
314 // Seed the device clip extent rather than using `interpret_content`, which passes
315 // `None`. §8.7.4.1 requires `sh` to cover the entire clipping region, so when a
316 // shading has no `/BBox` of its own `rasterize_shading` needs that extent to know
317 // what to cover — and with `None` it returns `None` and pushes no prim at all, so a
318 // gradient painted with `sh` inside an appearance stream was INVISIBLE. The comment
319 // on that early return assumed the page-level caller always seeds it; an annotation
320 // appearance is the caller that does not. The extent is the same BBox-or-Rect quad
321 // clipped above, which is exactly the region such an `sh` may cover.
322 interpret_content_seeded(
323 doc,
324 &ops,
325 res.as_ref(),
326 gs,
327 prims,
328 1,
329 false,
330 clip_bbox_device,
331 );
332
333 // §12.5.2: /CA is the constant opacity the WHOLE annotation is painted with, so
334 // §11.6.6 applies it once to the composited appearance — exactly what a
335 // GroupPush/GroupPop layer does, and the same mechanism the `Do` arm uses for /ca on
336 // a form XObject.
337 //
338 // This used to walk `prims[start..]` calling `scale_prim_alpha` on each, which
339 // conflicts with two other fixes:
340 // * a transparency group inside the appearance already carries its alpha on
341 // `GroupPush`, and the loop scaled BOTH the GroupPush and every prim inside it,
342 // so /CA landed twice (CA² on the group's contents);
343 // * `wrap_with_soft_mask` appends the mask group's own prims after
344 // `SoftMaskContent`, inside this same range, so the loop faded the MASK rather
345 // than the content — for a luminosity mask that changes the mask's shape, not
346 // its opacity.
347 // Wrapping instead of scaling cannot reach either: the layer's alpha is applied to
348 // the composite, and nothing inside is rewritten.
349 let ca = dict.get(b"CA").ok().and_then(|o| deref(doc, o).or(Some(o))).and_then(num).unwrap_or(1.0);
350 if ca < 1.0 && prims.len() > start {
351 prims.insert(
352 start,
353 Prim::GroupPush {
354 isolated: true,
355 knockout: false,
356 alpha: ca.clamp(0.0, 1.0) as f32,
357 blend: BlendMode::Normal,
358 },
359 );
360 prims.push(Prim::GroupPop);
361 }
362 // Unconditional pop (mirrors the `Do` arm): interpret_content always returns
363 // with a balanced clip depth, so this keeps the canvas clip stack balanced
364 // even if the content hit the primitive cap.
365 if clip.is_some() {
366 prims.push(Prim::ClipPop);
367 }
368}
369
370/// Read an annotation color array (`/C`, `/IC`) as ARGB, or `None` when the
371/// array is empty (meaning "no color" / transparent) or absent.
372///
373/// The array is dereferenced: §7.3.10 lets any object be indirect, and an
374/// indirect `/C` previously read as "no colour", silently substituting the
375/// default instead of the author's.
376fn markup_color(doc: &Document, dict: &lopdf::Dictionary, key: &[u8]) -> Option<u32> {
377 let arr = dict
378 .get(key)
379 .ok()
380 .and_then(|o| deref(doc, o).or(Some(o)))?
381 .as_array()
382 .ok()?;
383 let c: Vec<f64> = arr.iter().filter_map(num).collect();
384 match c.len() {
385 1 => Some(gray_to_argb(c[0])),
386 3 => Some(rgb_to_argb(c[0], c[1], c[2])),
387 4 => Some(cmyk_to_argb(c[0], c[1], c[2], c[3])),
388 _ => None,
389 }
390}
391
392/// Border width from `/BS /W` (preferred) or the legacy `/Border` array [_,_,W].
393fn annot_border_width(doc: &Document, dict: &lopdf::Dictionary) -> f64 {
394 if let Some(w) = dict.get(b"BS").ok().and_then(|o| deref(doc, o))
395 .and_then(|o| o.as_dict().ok())
396 .and_then(|bs| bs.get(b"W").ok()).and_then(num) {
397 return w;
398 }
399 if let Some(Object::Array(b)) = dict.get(b"Border").ok().and_then(|o| deref(doc, o)) {
400 if let Some(w) = b.get(2).and_then(num) { return w; }
401 }
402 1.0
403}
404
405/// Border dash array from ExGState `/D` or `/BS /D` or `/Border` dash [3rd?].
406fn annot_border_dash(doc: &Document, dict: &lopdf::Dictionary) -> Vec<f64> {
407 const MAX_D: usize = 32;
408 if let Some(b) = dict.get(b"BS").ok().and_then(|o| deref(doc, o)).and_then(|o| o.as_dict().ok()) {
409 if let Some(db) = b.get(b"D").ok().and_then(|o| deref(doc, o).or(Some(o))) {
410 let (d, _phase) = parse_dash_extgstate(doc, db);
411 if !d.is_empty() {
412 return d.into_iter().take(MAX_D).collect();
413 }
414 }
415 }
416 if let Some(Object::Array(b)) = dict.get(b"Border").ok().and_then(|o| deref(doc, o)) {
417 if b.len() >= 4 {
418 if let Some(Object::Array(dash_arr)) = b.get(3) {
419 return dash_arr.iter().filter_map(num).filter(|v| *v >= 0.0).take(MAX_D).collect();
420 }
421 }
422 }
423 Vec::new()
424}
425
426/// Numbers of an annotation's coordinate array (`/QuadPoints`, `/L`,
427/// `/Vertices`, one `/InkList` path), or `None` when any of them is non-finite.
428///
429/// §7.3.3 numbers are finite, but a real with more digits than `f32` can hold
430/// parses to an infinity, and one poisoned coordinate propagates through every
431/// primitive derived from it — the rasterizer drops a path containing a
432/// non-finite point silently, so the annotation vanishes with no error
433/// anywhere. Rejecting the whole array matches `read_rect`'s treatment of a
434/// non-finite `/Rect`, and matches this function's rule for missing geometry:
435/// draw nothing rather than a shape the file did not actually give.
436fn finite_coords(doc: &Document, obj: &Object) -> Option<Vec<f64>> {
437 let v: Vec<f64> = deref(doc, obj)?.as_array().ok()?.iter().filter_map(num).collect();
438 v.iter().all(|n| n.is_finite()).then_some(v)
439}
440
441include!("annotations_part1.rs");
442include!("annotations_part2.rs");
443include!("annotations_part3.rs");
444include!("annotations_part4.rs");
445include!("annotations_part5.rs");
446include!("annotations_part6.rs");
447include!("annotations_part7.rs");
448include!("annotations_part8.rs");
449include!("annotations_part9.rs");