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
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
//! Form controls (widgets) — visual representations of form fields on pages.
//!
//! A `FormControl` represents a single widget annotation (/Subtype /Widget)
//! associated with a form field, storing its position and appearance state.

use rpdfium_core::Rect;
use rpdfium_parser::ObjectId;

use crate::icon_fit::IconFit;

/// Highlighting mode for a widget annotation (ISO 32000-2 Table 188).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HighlightingMode {
    /// No highlighting (N).
    None,
    /// Invert the contents of the annotation rectangle (I, default).
    #[default]
    Invert,
    /// Invert the border of the annotation (O).
    Outline,
    /// Push effect (P).
    Push,
    /// Same as Invert (T, for toggle — used by checkboxes).
    Toggle,
}

impl HighlightingMode {
    /// Parse from a PDF name string (`/H` key).
    pub fn from_name(name: &str) -> Self {
        match name {
            "N" => Self::None,
            "I" => Self::Invert,
            "O" => Self::Outline,
            "P" => Self::Push,
            "T" => Self::Toggle,
            _ => Self::Invert,
        }
    }
}

/// Text/icon positioning mode for a widget annotation (ISO 32000-2 Table 189).
///
/// Determines the relative placement of the caption text and icon within
/// a button widget.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TextPosition {
    /// Caption only; no icon displayed (TP=0, default).
    #[default]
    CaptionOnly = 0,
    /// Icon only; no caption displayed (TP=1).
    IconOnly = 1,
    /// Caption below the icon (TP=2).
    CaptionBelow = 2,
    /// Caption above the icon (TP=3).
    CaptionAbove = 3,
    /// Caption to the right of the icon (TP=4).
    CaptionRight = 4,
    /// Caption to the left of the icon (TP=5).
    CaptionLeft = 5,
    /// Caption overlaid directly on the icon (TP=6).
    Overlaid = 6,
}

impl TextPosition {
    /// Parse from the `/TP` integer value in an MK dictionary.
    pub fn from_value(v: u32) -> Self {
        match v {
            0 => Self::CaptionOnly,
            1 => Self::IconOnly,
            2 => Self::CaptionBelow,
            3 => Self::CaptionAbove,
            4 => Self::CaptionRight,
            5 => Self::CaptionLeft,
            6 => Self::Overlaid,
            _ => Self::CaptionOnly,
        }
    }
}

/// A visual widget (control) for a form field.
#[derive(Debug, Clone)]
pub struct FormControl {
    /// The fully qualified name of the associated form field.
    pub field_name: String,
    /// The annotation rectangle on the page.
    pub rect: Rect,
    /// The current appearance state (e.g., "Yes", "Off").
    pub appearance_state: Option<String>,
    /// Zero-based page index, if known.
    pub page_index: Option<usize>,
    /// Highlighting mode (`/H`).
    pub highlighting_mode: HighlightingMode,
    /// Rotation in degrees from `/MK` → `/R` (0, 90, 180, 270).
    pub rotation: u32,
    /// Border color from `/MK` → `/BC`.
    pub border_color: Option<Vec<f32>>,
    /// Background color from `/MK` → `/BG`.
    pub background_color: Option<Vec<f32>>,
    /// Normal caption from `/MK` → `/CA`.
    pub caption: Option<String>,
    /// Rollover caption from `/MK` → `/RC`.
    pub rollover_caption: Option<String>,
    /// Alternate (down) caption from `/MK` → `/AC`.
    pub alt_caption: Option<String>,
    /// Default appearance string (`/DA`).
    pub default_appearance: Option<String>,
    /// Normal icon stream reference (`/MK` → `/I`).
    pub normal_icon: Option<ObjectId>,
    /// Rollover icon stream reference (`/MK` → `/RI`).
    pub rollover_icon: Option<ObjectId>,
    /// Down (alternate) icon stream reference (`/MK` → `/IX`).
    pub down_icon: Option<ObjectId>,
    /// Icon fit parameters (`/MK` → `/IF`).
    pub icon_fit: Option<IconFit>,
    /// Text/icon positioning (`/MK` → `/TP`).
    pub text_position: TextPosition,
}

impl FormControl {
    /// Returns the annotation rectangle on the page.
    ///
    /// Corresponds to `CPDF_FormControl::GetRect()` in PDFium.
    pub fn rect(&self) -> Rect {
        self.rect
    }

    /// Deprecated — use [`rect()`](Self::rect) — no public `FPDFFormControl_GetRect` API.
    #[deprecated(
        note = "use `rect()` — there is no public FPDF_* API (internal `CPDF_FormControl::GetRect`)"
    )]
    #[inline]
    pub fn get_rect(&self) -> Rect {
        self.rect()
    }

    /// Returns the current checked appearance state name (e.g., `"Yes"`, `"Off"`).
    ///
    /// Corresponds to `CPDF_FormControl::GetCheckedAPState()` in PDFium.
    pub fn checked_ap_state(&self) -> Option<&str> {
        self.appearance_state.as_deref()
    }

    /// Deprecated — use [`checked_ap_state()`](Self::checked_ap_state) — no public FPDF_* API.
    #[deprecated(
        note = "use `checked_ap_state()` — there is no public FPDF_* API (internal `CPDF_FormControl::GetCheckedAPState`)"
    )]
    #[inline]
    pub fn get_checked_ap_state(&self) -> Option<&str> {
        self.checked_ap_state()
    }

    /// Returns the export value for a radio/checkbox button option.
    ///
    /// For checkbox and radio button controls, returns the appearance state
    /// name used when the button is in its on state. Corresponds to
    /// `CPDF_FormControl::GetExportValue()` in PDFium.
    pub fn export_value(&self) -> Option<&str> {
        self.appearance_state.as_deref()
    }

    /// Deprecated — use [`export_value()`](Self::export_value) — no public FPDF_* API.
    #[deprecated(
        note = "use `export_value()` — there is no public FPDF_* API (internal `CPDF_FormControl::GetExportValue`)"
    )]
    #[inline]
    pub fn get_export_value(&self) -> Option<&str> {
        self.export_value()
    }

    /// Returns the highlighting mode for this widget.
    ///
    /// Corresponds to `CPDF_FormControl::GetHighlightingMode()` in PDFium.
    pub fn highlighting_mode(&self) -> HighlightingMode {
        self.highlighting_mode
    }

    /// Deprecated — use [`highlighting_mode()`](Self::highlighting_mode) — no public FPDF_* API.
    #[deprecated(
        note = "use `highlighting_mode()` — there is no public FPDF_* API (internal `CPDF_FormControl::GetHighlightingMode`)"
    )]
    #[inline]
    pub fn get_highlighting_mode(&self) -> HighlightingMode {
        self.highlighting_mode()
    }

    /// Returns the rotation angle in degrees (0, 90, 180, or 270).
    ///
    /// Corresponds to `CPDF_FormControl::GetRotation()` in PDFium.
    pub fn rotation(&self) -> u32 {
        self.rotation
    }

    /// Deprecated — use [`rotation()`](Self::rotation) — no public FPDF_* API.
    #[deprecated(
        note = "use `rotation()` — there is no public FPDF_* API (internal `CPDF_FormControl::GetRotation`)"
    )]
    #[inline]
    pub fn get_rotation(&self) -> u32 {
        self.rotation()
    }

    /// Returns the normal (default) caption string for this widget.
    ///
    /// Corresponds to `CPDF_FormControl::GetNormalCaption()` in PDFium.
    pub fn normal_caption(&self) -> Option<&str> {
        self.caption.as_deref()
    }

    /// Deprecated — use [`normal_caption()`](Self::normal_caption) — no public FPDF_* API.
    #[deprecated(
        note = "use `normal_caption()` — there is no public FPDF_* API (internal `CPDF_FormControl::GetNormalCaption`)"
    )]
    #[inline]
    pub fn get_normal_caption(&self) -> Option<&str> {
        self.normal_caption()
    }

    /// Returns the rollover (hover) caption string for this widget.
    ///
    /// Corresponds to `CPDF_FormControl::GetRolloverCaption()` in PDFium.
    pub fn rollover_caption(&self) -> Option<&str> {
        self.rollover_caption.as_deref()
    }

    /// Deprecated — use [`rollover_caption()`](Self::rollover_caption) — no public FPDF_* API.
    #[deprecated(
        note = "use `rollover_caption()` — there is no public FPDF_* API (internal `CPDF_FormControl::GetRolloverCaption`)"
    )]
    #[inline]
    pub fn get_rollover_caption(&self) -> Option<&str> {
        self.rollover_caption()
    }

    /// Returns the down (pressed) caption string for this widget.
    ///
    /// Corresponds to `CPDF_FormControl::GetDownCaption()` in PDFium.
    pub fn down_caption(&self) -> Option<&str> {
        self.alt_caption.as_deref()
    }

    /// Deprecated — use [`down_caption()`](Self::down_caption) — no public FPDF_* API.
    #[deprecated(
        note = "use `down_caption()` — there is no public FPDF_* API (internal `CPDF_FormControl::GetDownCaption`)"
    )]
    #[inline]
    pub fn get_down_caption(&self) -> Option<&str> {
        self.down_caption()
    }

    /// Returns the text/icon position for this widget (TP value, 0–6).
    ///
    /// Corresponds to `CPDF_FormControl::GetTextPosition()` in PDFium.
    pub fn text_position(&self) -> TextPosition {
        self.text_position
    }

    /// Deprecated — use [`text_position()`](Self::text_position) — no public FPDF_* API.
    #[deprecated(
        note = "use `text_position()` — there is no public FPDF_* API (internal `CPDF_FormControl::GetTextPosition`)"
    )]
    #[inline]
    pub fn get_text_position(&self) -> TextPosition {
        self.text_position()
    }

    /// Returns `true` if the control's appearance state is "Yes" (checked).
    pub fn is_checked(&self) -> bool {
        self.appearance_state.as_deref() == Some("Yes")
    }

    /// Returns `true` if the default appearance state is "Yes".
    ///
    /// Note: We use `/AS` for the current state. Default checked state
    /// would typically come from `/DV` on the parent field.
    ///
    /// Tier-1 primary: calls another rpdfium function (`is_checked()`), so
    /// `#[inline]` must not be applied.
    pub fn is_default_checked(&self) -> bool {
        // Upstream uses the /DV from the parent field; here we check /AS
        // which is the initial state parsed from the PDF.
        self.is_checked()
    }

    /// Returns the border color as a packed ARGB value (`0xAARRGGBB`), or `None`
    /// if no border color is defined.
    ///
    /// Supports grayscale (1 component) and RGB (3 component) color arrays.
    /// Returns `None` for CMYK (4 components) or an empty array.
    ///
    /// Corresponds to `CPDF_FormControl::GetColorARGB()` in PDFium (nIndex=0).
    pub fn border_color_argb(&self) -> Option<u32> {
        color_components_to_argb(self.border_color.as_deref())
    }

    /// Returns the background color as a packed ARGB value (`0xAARRGGBB`), or `None`
    /// if no background color is defined.
    ///
    /// Supports grayscale (1 component) and RGB (3 component) color arrays.
    /// Returns `None` for CMYK (4 components) or an empty array.
    ///
    /// Corresponds to `CPDF_FormControl::GetColorARGB()` in PDFium (nIndex=1).
    pub fn background_color_argb(&self) -> Option<u32> {
        color_components_to_argb(self.background_color.as_deref())
    }
}

/// Convert PDF color component array (0.0–1.0) to a packed ARGB `u32`.
///
/// Supports 1-component (grayscale) and 3-component (RGB). Returns `None`
/// for other component counts (e.g., 4-component CMYK or empty).
fn color_components_to_argb(components: Option<&[f32]>) -> Option<u32> {
    let c = components?;
    let to_byte = |f: f32| (f.clamp(0.0, 1.0) * 255.0).round() as u32;
    let argb = match c.len() {
        1 => {
            let g = to_byte(c[0]);
            0xFF00_0000 | (g << 16) | (g << 8) | g
        }
        3 => {
            let r = to_byte(c[0]);
            let g = to_byte(c[1]);
            let b = to_byte(c[2]);
            0xFF00_0000 | (r << 16) | (g << 8) | b
        }
        _ => return None,
    };
    Some(argb)
}

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

    fn make_control() -> FormControl {
        FormControl {
            field_name: "checkbox1".to_string(),
            rect: Rect {
                left: 10.0,
                bottom: 20.0,
                right: 30.0,
                top: 40.0,
            },
            appearance_state: Some("Yes".to_string()),
            page_index: Some(0),
            highlighting_mode: HighlightingMode::Invert,
            rotation: 0,
            border_color: None,
            background_color: None,
            caption: None,
            rollover_caption: None,
            alt_caption: None,
            default_appearance: None,
            normal_icon: None,
            rollover_icon: None,
            down_icon: None,
            icon_fit: None,
            text_position: TextPosition::default(),
        }
    }

    #[test]
    fn test_form_control_creation() {
        let ctrl = make_control();
        assert_eq!(ctrl.field_name, "checkbox1");
        assert_eq!(ctrl.rect.left, 10.0);
        assert_eq!(ctrl.appearance_state.as_deref(), Some("Yes"));
        assert_eq!(ctrl.page_index, Some(0));
    }

    #[test]
    fn test_form_control_no_page_index() {
        let mut ctrl = make_control();
        ctrl.field_name = "text1".to_string();
        ctrl.rect = Rect {
            left: 0.0,
            bottom: 0.0,
            right: 100.0,
            top: 20.0,
        };
        ctrl.appearance_state = None;
        ctrl.page_index = None;
        assert!(ctrl.page_index.is_none());
        assert!(ctrl.appearance_state.is_none());
    }

    #[test]
    fn test_is_checked() {
        let ctrl = make_control();
        assert!(ctrl.is_checked());
    }

    #[test]
    fn test_is_not_checked() {
        let mut ctrl = make_control();
        ctrl.appearance_state = Some("Off".to_string());
        assert!(!ctrl.is_checked());
    }

    #[test]
    fn test_is_checked_none() {
        let mut ctrl = make_control();
        ctrl.appearance_state = None;
        assert!(!ctrl.is_checked());
    }

    #[test]
    fn test_highlighting_mode_from_name() {
        assert_eq!(HighlightingMode::from_name("N"), HighlightingMode::None);
        assert_eq!(HighlightingMode::from_name("I"), HighlightingMode::Invert);
        assert_eq!(HighlightingMode::from_name("O"), HighlightingMode::Outline);
        assert_eq!(HighlightingMode::from_name("P"), HighlightingMode::Push);
        assert_eq!(HighlightingMode::from_name("T"), HighlightingMode::Toggle);
        assert_eq!(
            HighlightingMode::from_name("Unknown"),
            HighlightingMode::Invert
        );
    }

    #[test]
    fn test_form_control_with_mk_data() {
        let mut ctrl = make_control();
        ctrl.rotation = 90;
        ctrl.border_color = Some(vec![1.0, 0.0, 0.0]);
        ctrl.background_color = Some(vec![1.0, 1.0, 1.0]);
        ctrl.caption = Some("Click me".to_string());
        ctrl.rollover_caption = Some("Hover text".to_string());
        ctrl.alt_caption = Some("Down text".to_string());
        ctrl.highlighting_mode = HighlightingMode::Push;

        assert_eq!(ctrl.rotation, 90);
        assert_eq!(ctrl.border_color.as_ref().unwrap().len(), 3);
        assert_eq!(ctrl.caption.as_deref(), Some("Click me"));
        assert_eq!(ctrl.rollover_caption.as_deref(), Some("Hover text"));
        assert_eq!(ctrl.alt_caption.as_deref(), Some("Down text"));
        assert_eq!(ctrl.highlighting_mode, HighlightingMode::Push);
    }

    #[test]
    fn test_text_position_from_value() {
        assert_eq!(TextPosition::from_value(0), TextPosition::CaptionOnly);
        assert_eq!(TextPosition::from_value(1), TextPosition::IconOnly);
        assert_eq!(TextPosition::from_value(2), TextPosition::CaptionBelow);
        assert_eq!(TextPosition::from_value(3), TextPosition::CaptionAbove);
        assert_eq!(TextPosition::from_value(4), TextPosition::CaptionRight);
        assert_eq!(TextPosition::from_value(5), TextPosition::CaptionLeft);
        assert_eq!(TextPosition::from_value(6), TextPosition::Overlaid);
        assert_eq!(TextPosition::from_value(99), TextPosition::CaptionOnly);
    }

    #[test]
    fn test_text_position_default() {
        assert_eq!(TextPosition::default(), TextPosition::CaptionOnly);
    }

    #[test]
    fn test_form_control_with_icon_data() {
        let mut ctrl = make_control();
        ctrl.normal_icon = Some(ObjectId::new(10, 0));
        ctrl.rollover_icon = Some(ObjectId::new(11, 0));
        ctrl.down_icon = Some(ObjectId::new(12, 0));
        ctrl.text_position = TextPosition::IconOnly;

        assert_eq!(ctrl.normal_icon, Some(ObjectId::new(10, 0)));
        assert_eq!(ctrl.rollover_icon, Some(ObjectId::new(11, 0)));
        assert_eq!(ctrl.down_icon, Some(ObjectId::new(12, 0)));
        assert_eq!(ctrl.text_position, TextPosition::IconOnly);
    }

    #[test]
    fn test_border_color_argb_rgb_red() {
        let mut ctrl = make_control();
        ctrl.border_color = Some(vec![1.0, 0.0, 0.0]);
        assert_eq!(ctrl.border_color_argb(), Some(0xFFFF0000));
    }

    #[test]
    fn test_background_color_argb_grayscale() {
        let mut ctrl = make_control();
        ctrl.background_color = Some(vec![1.0]); // white
        assert_eq!(ctrl.background_color_argb(), Some(0xFFFFFFFF));
    }

    #[test]
    fn test_background_color_argb_black_grayscale() {
        let mut ctrl = make_control();
        ctrl.background_color = Some(vec![0.0]); // black
        assert_eq!(ctrl.background_color_argb(), Some(0xFF000000));
    }

    #[test]
    fn test_border_color_argb_none_for_cmyk() {
        let mut ctrl = make_control();
        ctrl.border_color = Some(vec![0.1, 0.2, 0.3, 0.4]); // CMYK — not supported
        assert_eq!(ctrl.border_color_argb(), None);
    }

    #[test]
    fn test_color_argb_none_when_absent() {
        let ctrl = make_control();
        // make_control sets border_color and background_color to None
        assert_eq!(ctrl.border_color_argb(), None);
        assert_eq!(ctrl.background_color_argb(), None);
    }

    #[test]
    fn test_border_color_argb_rgb_green() {
        let mut ctrl = make_control();
        ctrl.border_color = Some(vec![0.0, 1.0, 0.0]);
        assert_eq!(ctrl.border_color_argb(), Some(0xFF00FF00));
    }
}