rpdfium-doc 7676.6.2

Document-level features for rpdfium
Documentation
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
// Derived from PDFium's cpdf_iconfit.h/cpp
// Original: Copyright 2014 The PDFium Authors
// Licensed under BSD-3-Clause / Apache-2.0
// See pdfium-upstream/LICENSE for the original license.

//! Icon fit parameters for widget annotation buttons (`/IF` dictionary).
//!
//! Controls how a button icon is scaled and positioned within the annotation
//! rectangle (ISO 32000-2 section 12.5.6.19, Table 196).
//! Corresponds to upstream `CPDF_IconFit`.

use std::collections::HashMap;

use rpdfium_core::{Name, PdfSource};
use rpdfium_parser::{Object, ObjectStore};

/// Icon fit parameters parsed from an `/IF` dictionary inside `/MK`.
///
/// Controls how a button icon is scaled and positioned within the annotation
/// rectangle (ISO 32000-2 section 12.5.6.19).
#[derive(Debug, Clone)]
pub struct IconFit {
    /// How the icon should be scaled.
    pub scale_method: ScaleMethod,
    /// If `true`, scale proportionally; if `false`, scale anamorphically.
    pub proportional: bool,
    /// Horizontal position fraction (0.0 = left, 0.5 = center, 1.0 = right).
    pub position_x: f32,
    /// Vertical position fraction (0.0 = bottom, 0.5 = center, 1.0 = top).
    pub position_y: f32,
    /// If `true`, the button appearance is clipped to the annotation rectangle.
    pub fitting_bounds: bool,
}

/// Icon scale method (from `/SW` key in IconFit dictionary).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScaleMethod {
    /// Always scale to fit (`A`, default).
    Always,
    /// Scale only if the icon is bigger than the annotation (`B`).
    Bigger,
    /// Scale only if the icon is smaller than the annotation (`S`).
    Smaller,
    /// Never scale (`N`).
    Never,
}

impl IconFit {
    /// Returns how the icon should be scaled.
    ///
    /// Corresponds to `CPDF_IconFit::GetScaleMethod()` in PDFium.
    pub fn scale_method(&self) -> ScaleMethod {
        self.scale_method
    }

    /// Upstream-aligned alias for [`scale_method()`](Self::scale_method).
    ///
    /// Corresponds to `CPDF_IconFit::GetScaleMethod()` in PDFium.
    #[inline]
    pub fn get_scale_method(&self) -> ScaleMethod {
        self.scale_method()
    }

    /// Returns whether the icon is scaled proportionally.
    ///
    /// Corresponds to `CPDF_IconFit::IsProportionalScale()` in PDFium.
    pub fn is_proportional_scale(&self) -> bool {
        self.proportional
    }

    /// Returns whether the button appearance is clipped to the annotation rectangle.
    ///
    /// Corresponds to `CPDF_IconFit::GetFittingBounds()` in PDFium.
    pub fn fitting_bounds(&self) -> bool {
        self.fitting_bounds
    }

    /// Upstream-aligned alias for [`fitting_bounds()`](Self::fitting_bounds).
    ///
    /// Corresponds to `CPDF_IconFit::GetFittingBounds()` in PDFium.
    #[inline]
    pub fn get_fitting_bounds(&self) -> bool {
        self.fitting_bounds()
    }

    /// Returns the icon bottom-left position fraction as `(x, y)`.
    ///
    /// `x` is 0.0 (left) to 1.0 (right); `y` is 0.0 (bottom) to 1.0 (top).
    /// Corresponds to `CPDF_IconFit::GetIconBottomLeftPosition()` in PDFium.
    pub fn icon_bottom_left_position(&self) -> (f32, f32) {
        (self.position_x, self.position_y)
    }

    /// Upstream-aligned alias for [`icon_bottom_left_position()`](Self::icon_bottom_left_position).
    ///
    /// Corresponds to `CPDF_IconFit::GetIconBottomLeftPosition()` in PDFium.
    #[inline]
    pub fn get_icon_bottom_left_position(&self) -> (f32, f32) {
        self.icon_bottom_left_position()
    }

    /// Compute scale factors for an icon of `image_width` x `image_height`
    /// within a plate (annotation rect) of `plate_width` x `plate_height`.
    pub fn compute_scale(
        &self,
        image_width: f32,
        image_height: f32,
        plate_width: f32,
        plate_height: f32,
    ) -> (f32, f32) {
        let iw = image_width.max(1.0);
        let ih = image_height.max(1.0);
        let mut h_scale = match self.scale_method {
            ScaleMethod::Always => plate_width / iw,
            ScaleMethod::Bigger => {
                if plate_width < image_width {
                    plate_width / iw
                } else {
                    1.0
                }
            }
            ScaleMethod::Smaller => {
                if plate_width > image_width {
                    plate_width / iw
                } else {
                    1.0
                }
            }
            ScaleMethod::Never => 1.0,
        };
        let mut v_scale = match self.scale_method {
            ScaleMethod::Always => plate_height / ih,
            ScaleMethod::Bigger => {
                if plate_height < image_height {
                    plate_height / ih
                } else {
                    1.0
                }
            }
            ScaleMethod::Smaller => {
                if plate_height > image_height {
                    plate_height / ih
                } else {
                    1.0
                }
            }
            ScaleMethod::Never => 1.0,
        };
        if self.proportional {
            let min_scale = h_scale.min(v_scale);
            h_scale = min_scale;
            v_scale = min_scale;
        }
        (h_scale, v_scale)
    }

    /// Compute the offset for positioning the icon within the plate.
    pub fn compute_offset(
        &self,
        image_width: f32,
        image_height: f32,
        h_scale: f32,
        v_scale: f32,
        plate_width: f32,
        plate_height: f32,
    ) -> (f32, f32) {
        let scaled_w = image_width * h_scale;
        let scaled_h = image_height * v_scale;
        (
            (plate_width - scaled_w) * self.position_x,
            (plate_height - scaled_h) * self.position_y,
        )
    }
}

/// Parse an IconFit dictionary from the `/IF` sub-key of an MK dictionary.
pub fn parse_icon_fit<S: PdfSource>(
    mk_dict: &HashMap<Name, Object>,
    store: &ObjectStore<S>,
) -> Option<IconFit> {
    let if_obj = mk_dict.get(&Name::if_dict())?;
    let resolved = store.deep_resolve(if_obj).ok()?;
    let if_dict = resolved.as_dict()?;

    let scale_method = if_dict
        .get(&Name::sw())
        .and_then(|o| o.as_name())
        .map(|n| match n.as_str().as_ref() {
            "B" => ScaleMethod::Bigger,
            "S" => ScaleMethod::Smaller,
            "N" => ScaleMethod::Never,
            _ => ScaleMethod::Always,
        })
        .unwrap_or(ScaleMethod::Always);

    let proportional = if_dict
        .get(&Name::s())
        .and_then(|o| o.as_name())
        .map(|n| n.as_str().as_ref() != "A")
        .unwrap_or(true);

    let (position_x, position_y) = if_dict
        .get(&Name::a())
        .and_then(|o| store.deep_resolve(o).ok())
        .and_then(|o| {
            let arr = o.as_array()?;
            let x = arr.first()?.as_f64().map(|f| f as f32).unwrap_or(0.5);
            let y = arr.get(1)?.as_f64().map(|f| f as f32).unwrap_or(0.5);
            Some((x, y))
        })
        .unwrap_or((0.5, 0.5));

    let fitting_bounds = if_dict
        .get(&Name::fb())
        .and_then(|o| match o {
            Object::Boolean(b) => Some(*b),
            _ => None,
        })
        .unwrap_or(false);

    Some(IconFit {
        scale_method,
        proportional,
        position_x,
        position_y,
        fitting_bounds,
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn build_store() -> ObjectStore<Vec<u8>> {
        let pdf = build_minimal_pdf();
        ObjectStore::open(pdf, rpdfium_core::ParsingMode::Lenient).unwrap()
    }

    fn build_minimal_pdf() -> Vec<u8> {
        let mut pdf = Vec::new();
        pdf.extend_from_slice(b"%PDF-1.4\n");
        let obj1_offset = pdf.len();
        pdf.extend_from_slice(b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n");
        let obj2_offset = pdf.len();
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n");
        let xref_offset = pdf.len();
        pdf.extend_from_slice(b"xref\n0 3\n");
        pdf.extend_from_slice(b"0000000000 65535 f \r\n");
        pdf.extend_from_slice(format!("{:010} 00000 n \r\n", obj1_offset).as_bytes());
        pdf.extend_from_slice(format!("{:010} 00000 n \r\n", obj2_offset).as_bytes());
        pdf.extend_from_slice(b"trailer\n<< /Size 3 /Root 1 0 R >>\n");
        pdf.extend_from_slice(format!("startxref\n{}\n%%EOF", xref_offset).as_bytes());
        pdf
    }

    #[test]
    fn test_parse_icon_fit_defaults() {
        let store = build_store();
        let mut mk = HashMap::new();
        mk.insert(Name::if_dict(), Object::Dictionary(HashMap::new()));
        let result = parse_icon_fit(&mk, &store).unwrap();
        assert_eq!(result.scale_method, ScaleMethod::Always);
        assert!(result.proportional);
        assert!((result.position_x - 0.5).abs() < 0.001);
        assert!((result.position_y - 0.5).abs() < 0.001);
        assert!(!result.fitting_bounds);
    }

    #[test]
    fn test_parse_icon_fit_with_values() {
        let store = build_store();
        let mut if_dict = HashMap::new();
        if_dict.insert(Name::sw(), Object::Name(Name::from("B")));
        if_dict.insert(Name::s(), Object::Name(Name::from("A"))); // anamorphic
        if_dict.insert(
            Name::a(),
            Object::Array(vec![Object::Real(0.0), Object::Real(1.0)]),
        );
        if_dict.insert(Name::fb(), Object::Boolean(true));

        let mut mk = HashMap::new();
        mk.insert(Name::if_dict(), Object::Dictionary(if_dict));
        let result = parse_icon_fit(&mk, &store).unwrap();
        assert_eq!(result.scale_method, ScaleMethod::Bigger);
        assert!(!result.proportional); // "A" = anamorphic
        assert!((result.position_x - 0.0).abs() < 0.001);
        assert!((result.position_y - 1.0).abs() < 0.001);
        assert!(result.fitting_bounds);
    }

    #[test]
    fn test_parse_icon_fit_never_scale() {
        let store = build_store();
        let mut if_dict = HashMap::new();
        if_dict.insert(Name::sw(), Object::Name(Name::from("N")));

        let mut mk = HashMap::new();
        mk.insert(Name::if_dict(), Object::Dictionary(if_dict));
        let result = parse_icon_fit(&mk, &store).unwrap();
        assert_eq!(result.scale_method, ScaleMethod::Never);
    }

    #[test]
    fn test_parse_icon_fit_smaller_scale() {
        let store = build_store();
        let mut if_dict = HashMap::new();
        if_dict.insert(Name::sw(), Object::Name(Name::from("S")));

        let mut mk = HashMap::new();
        mk.insert(Name::if_dict(), Object::Dictionary(if_dict));
        let result = parse_icon_fit(&mk, &store).unwrap();
        assert_eq!(result.scale_method, ScaleMethod::Smaller);
    }

    #[test]
    fn test_parse_icon_fit_absent() {
        let store = build_store();
        let mk = HashMap::new();
        assert!(parse_icon_fit(&mk, &store).is_none());
    }

    #[test]
    fn test_icon_fit_always_scale() {
        let fit = IconFit {
            scale_method: ScaleMethod::Always,
            proportional: false,
            position_x: 0.5,
            position_y: 0.5,
            fitting_bounds: false,
        };
        let (h, v) = fit.compute_scale(100.0, 50.0, 200.0, 100.0);
        assert!((h - 2.0).abs() < 0.001);
        assert!((v - 2.0).abs() < 0.001);
    }

    #[test]
    fn test_icon_fit_always_proportional() {
        let fit = IconFit {
            scale_method: ScaleMethod::Always,
            proportional: true,
            position_x: 0.5,
            position_y: 0.5,
            fitting_bounds: false,
        };
        let (h, v) = fit.compute_scale(100.0, 200.0, 200.0, 200.0);
        // h_scale = 2.0, v_scale = 1.0, min = 1.0
        assert!((h - 1.0).abs() < 0.001);
        assert!((v - 1.0).abs() < 0.001);
    }

    #[test]
    fn test_icon_fit_never_scale() {
        let fit = IconFit {
            scale_method: ScaleMethod::Never,
            proportional: false,
            position_x: 0.5,
            position_y: 0.5,
            fitting_bounds: false,
        };
        let (h, v) = fit.compute_scale(100.0, 50.0, 200.0, 100.0);
        assert!((h - 1.0).abs() < 0.001);
        assert!((v - 1.0).abs() < 0.001);
    }

    #[test]
    fn test_icon_fit_bigger_icon_bigger() {
        let fit = IconFit {
            scale_method: ScaleMethod::Bigger,
            proportional: false,
            position_x: 0.5,
            position_y: 0.5,
            fitting_bounds: false,
        };
        // Icon (200x100) bigger than plate (100x50) → scale down
        let (h, v) = fit.compute_scale(200.0, 100.0, 100.0, 50.0);
        assert!((h - 0.5).abs() < 0.001);
        assert!((v - 0.5).abs() < 0.001);
    }

    #[test]
    fn test_icon_fit_bigger_icon_smaller() {
        let fit = IconFit {
            scale_method: ScaleMethod::Bigger,
            proportional: false,
            position_x: 0.5,
            position_y: 0.5,
            fitting_bounds: false,
        };
        // Icon (50x25) smaller than plate (100x50) → no scale
        let (h, v) = fit.compute_scale(50.0, 25.0, 100.0, 50.0);
        assert!((h - 1.0).abs() < 0.001);
        assert!((v - 1.0).abs() < 0.001);
    }

    #[test]
    fn test_icon_fit_compute_offset() {
        let fit = IconFit {
            scale_method: ScaleMethod::Always,
            proportional: false,
            position_x: 0.5,
            position_y: 0.5,
            fitting_bounds: false,
        };
        // Image 50x30 at scale 1.0 in plate 100x60 → centered
        let (ox, oy) = fit.compute_offset(50.0, 30.0, 1.0, 1.0, 100.0, 60.0);
        assert!((ox - 25.0).abs() < 0.001);
        assert!((oy - 15.0).abs() < 0.001);
    }

    #[test]
    fn test_icon_fit_offset_bottom_left() {
        let fit = IconFit {
            scale_method: ScaleMethod::Always,
            proportional: false,
            position_x: 0.0,
            position_y: 0.0,
            fitting_bounds: false,
        };
        let (ox, oy) = fit.compute_offset(50.0, 30.0, 1.0, 1.0, 100.0, 60.0);
        assert!((ox - 0.0).abs() < 0.001);
        assert!((oy - 0.0).abs() < 0.001);
    }
}