rpdfium-doc 7676.6.4

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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
// Derived from PDFium's cpdf_interactiveform.cpp
// Original: Copyright 2014 The PDFium Authors
// Licensed under BSD-3-Clause / Apache-2.0
// See pdfium-upstream/LICENSE for the original license.

//! Interactive forms (AcroForm) — read-only field parsing and value extraction.
//!
//! Parses the `/AcroForm` dictionary from the document catalog into a flat
//! and hierarchical view of form fields (ISO 32000-2 section 12.7).

use std::collections::HashMap;

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

use crate::error::{DocError, DocResult};
use crate::form_field::{FormField, FormFieldFlags, FormFieldType};
use crate::variable_text::Alignment;

/// Maximum number of fields to parse (security limit).
const MAX_FIELDS: usize = 10_000;

/// A parsed interactive form (AcroForm).
#[derive(Debug, Clone)]
pub struct InteractiveForm {
    /// Top-level form fields (may contain children for hierarchical fields).
    pub fields: Vec<FormField>,
    /// Calculation order — field names in the order they should be calculated.
    pub calculation_order: Vec<String>,
    /// Default appearance string (`/DA`) from the AcroForm dictionary.
    pub default_appearance: Option<String>,
    /// Default quadding/alignment (`/Q`) — 0=Left, 1=Center, 2=Right.
    pub default_alignment: Alignment,
}

impl InteractiveForm {
    /// Parse the interactive form from the document catalog.
    ///
    /// Returns `None` if no `/AcroForm` dictionary is present.
    /// Field trees are traversed **iteratively** for WASM safety.
    pub fn from_catalog<S: PdfSource>(
        catalog: &Object,
        store: &ObjectStore<S>,
    ) -> DocResult<Option<Self>> {
        let catalog_dict = store
            .deep_resolve(catalog)
            .map_err(|e| DocError::Parser(e.to_string()))?
            .as_dict()
            .ok_or(DocError::UnexpectedType)?;

        let acroform_obj = match catalog_dict.get(&Name::acro_form()) {
            Some(obj) => store
                .deep_resolve(obj)
                .map_err(|e| DocError::Parser(e.to_string()))?,
            None => return Ok(None),
        };

        let acroform_dict = match acroform_obj.as_dict() {
            Some(d) => d,
            None => return Ok(None),
        };

        // Parse /CO (calculation order)
        let calculation_order = parse_calculation_order(acroform_dict, store);

        // Parse /DA (default appearance)
        let default_appearance = acroform_dict
            .get(&Name::da())
            .and_then(|o| store.deep_resolve(o).ok())
            .and_then(|o| o.as_string().map(|s| s.to_string_lossy()));

        // Parse /Q (default quadding/alignment)
        let default_alignment = acroform_dict
            .get(&Name::q())
            .and_then(|o| store.deep_resolve(o).ok())
            .and_then(|o| o.as_i64())
            .map(|v| Alignment::from_value(v as i32))
            .unwrap_or(Alignment::Left);

        let fields_obj = match acroform_dict.get(&Name::fields()) {
            Some(obj) => store
                .deep_resolve(obj)
                .map_err(|e| DocError::Parser(e.to_string()))?,
            None => {
                return Ok(Some(InteractiveForm {
                    fields: Vec::new(),
                    calculation_order,
                    default_appearance: default_appearance.clone(),
                    default_alignment,
                }));
            }
        };

        let fields_arr = match fields_obj.as_array() {
            Some(a) => a,
            None => {
                return Ok(Some(InteractiveForm {
                    fields: Vec::new(),
                    calculation_order,
                    default_appearance: default_appearance.clone(),
                    default_alignment,
                }));
            }
        };

        // Iterative tree traversal using a Vec stack.
        // Each stack item records: (dict, parent_ft, parent_name, depth_index path).
        let mut result_fields: Vec<FormField> = Vec::new();
        let mut total_count: usize = 0;

        struct StackItem {
            dict: HashMap<Name, Object>,
            parent_ft: Option<String>,
            parent_name: String,
            /// Path of indices for inserting into the result tree.
            path: Vec<usize>,
        }

        let mut stack: Vec<StackItem> = Vec::new();

        // Push top-level fields in reverse order so we process them in forward order
        for field_obj in fields_arr.iter().rev() {
            let resolved = match store.deep_resolve(field_obj).ok() {
                Some(o) => o,
                None => continue,
            };
            if let Some(d) = resolved.as_dict() {
                stack.push(StackItem {
                    dict: d.clone(),
                    parent_ft: None,
                    parent_name: String::new(),
                    path: Vec::new(),
                });
            }
        }

        while let Some(item) = stack.pop() {
            if total_count >= MAX_FIELDS {
                break;
            }

            // Determine the /FT for this node (for inheritance to children)
            let ft_str = item
                .dict
                .get(&Name::ft())
                .and_then(|o| store.deep_resolve(o).ok())
                .and_then(|o| o.as_name().map(|n| n.as_str().into_owned()));
            let effective_ft = ft_str.as_deref().or(item.parent_ft.as_deref());

            // Determine the partial name for this node
            let partial_name = item
                .dict
                .get(&Name::t())
                .and_then(|o| store.deep_resolve(o).ok())
                .and_then(|o| o.as_string().map(|s| s.to_string_lossy()));
            let current_name = match (&partial_name, item.parent_name.is_empty()) {
                (Some(pn), true) => pn.clone(),
                (Some(pn), false) => format!("{}.{pn}", item.parent_name),
                (None, _) => item.parent_name.clone(),
            };

            // Check for /Kids — if present, this is a non-terminal node
            let kids = item
                .dict
                .get(&Name::kids())
                .and_then(|o| store.deep_resolve(o).ok())
                .and_then(|o| o.as_array().map(|a| a.to_vec()));

            if let Some(kids_arr) = kids {
                // Try to parse as a field first (some fields have both /FT and /Kids)
                let field = FormField::from_dict(
                    &item.dict,
                    store,
                    item.parent_ft.as_deref(),
                    &item.parent_name,
                );

                if let Some(mut f) = field {
                    // This is a field with children — insert it and
                    // push kids to populate its children
                    let idx = insert_at_path(&mut result_fields, &item.path, &mut f);
                    total_count += 1;

                    let mut child_path = item.path.clone();
                    child_path.push(idx);

                    for kid_obj in kids_arr.iter().rev() {
                        let resolved = match store.deep_resolve(kid_obj).ok() {
                            Some(o) => o,
                            None => continue,
                        };
                        if let Some(d) = resolved.as_dict() {
                            stack.push(StackItem {
                                dict: d.clone(),
                                parent_ft: effective_ft.map(|s| s.to_string()),
                                parent_name: current_name.clone(),
                                path: child_path.clone(),
                            });
                        }
                    }
                } else {
                    // Non-terminal node without /FT — just pass name/FT down to kids
                    for kid_obj in kids_arr.iter().rev() {
                        let resolved = match store.deep_resolve(kid_obj).ok() {
                            Some(o) => o,
                            None => continue,
                        };
                        if let Some(d) = resolved.as_dict() {
                            stack.push(StackItem {
                                dict: d.clone(),
                                parent_ft: effective_ft.map(|s| s.to_string()),
                                parent_name: current_name.clone(),
                                path: item.path.clone(),
                            });
                        }
                    }
                }
            } else {
                // Leaf field
                let field = FormField::from_dict(
                    &item.dict,
                    store,
                    item.parent_ft.as_deref(),
                    &item.parent_name,
                );
                if let Some(mut f) = field {
                    insert_at_path(&mut result_fields, &item.path, &mut f);
                    total_count += 1;
                }
            }
        }

        Ok(Some(InteractiveForm {
            fields: result_fields,
            calculation_order,
            default_appearance,
            default_alignment,
        }))
    }

    /// Returns the calculation order field names.
    pub fn calculation_order(&self) -> &[String] {
        &self.calculation_order
    }

    /// Return a flat iterator over all fields (depth-first).
    pub fn all_fields(&self) -> Vec<&FormField> {
        let mut result = Vec::new();
        let mut stack: Vec<&FormField> = self.fields.iter().rev().collect();
        while let Some(field) = stack.pop() {
            result.push(field);
            for child in field.children.iter().rev() {
                stack.push(child);
            }
        }
        result
    }

    /// Find a field by its fully qualified name.
    pub fn field_by_name(&self, name: &str) -> Option<&FormField> {
        let mut stack: Vec<&FormField> = self.fields.iter().rev().collect();
        while let Some(field) = stack.pop() {
            if field.name == name {
                return Some(field);
            }
            for child in field.children.iter().rev() {
                stack.push(child);
            }
        }
        None
    }

    /// Find a field by its fully qualified name (mutable).
    pub fn field_by_name_mut(&mut self, name: &str) -> Option<&mut FormField> {
        let mut stack: Vec<&mut FormField> = self.fields.iter_mut().rev().collect();
        while let Some(field) = stack.pop() {
            if field.name == name {
                return Some(field);
            }
            for child in field.children.iter_mut().rev() {
                stack.push(child);
            }
        }
        None
    }

    /// Collect all field names in depth-first order.
    ///
    /// This can be combined with [`Self::field_by_name_mut`] to iterate mutably.
    pub fn all_field_names(&self) -> Vec<String> {
        self.all_fields().iter().map(|f| f.name.clone()).collect()
    }

    /// Return the default appearance string (`/DA`) from the AcroForm dictionary.
    pub fn default_appearance(&self) -> Option<&str> {
        self.default_appearance.as_deref()
    }

    /// ADR-019 alias for [`default_appearance()`](Self::default_appearance).
    ///
    /// Corresponds to `CPDF_InteractiveForm::GetDefaultAppearance()` in PDFium.
    #[inline]
    pub fn get_default_appearance(&self) -> Option<&str> {
        self.default_appearance()
    }

    /// Return the default alignment (`/Q`) from the AcroForm dictionary.
    pub fn default_alignment(&self) -> Alignment {
        self.default_alignment
    }

    /// ADR-019 alias for [`default_alignment()`](Self::default_alignment).
    ///
    /// Corresponds to `CPDF_InteractiveForm::GetFormAlignment()` in PDFium.
    #[inline]
    pub fn get_form_alignment(&self) -> Alignment {
        self.default_alignment()
    }

    /// Check which required fields have empty values.
    ///
    /// Returns the names of fields that have the Required flag (bit 2) set
    /// but have no value.
    pub fn check_required_fields(&self) -> Vec<&str> {
        let mut missing = Vec::new();
        let all = self.all_fields();
        for field in &all {
            if field.flags.is_required() && field.value.is_none() {
                missing.push(field.name.as_str());
            }
        }
        missing
    }

    /// Find a form control (widget) at the given point.
    ///
    /// Returns the field name and control index if a control's rect contains (x, y).
    ///
    /// Corresponds to `CPDF_InteractiveForm::GetControlAtPoint()` in PDFium.
    pub fn control_at_point(&self, x: f64, y: f64) -> Option<(&str, usize)> {
        let all = self.all_fields();
        for field in &all {
            for (i, control) in field.controls.iter().enumerate() {
                let r = &control.rect;
                if x >= r.left && x <= r.right && y >= r.bottom && y <= r.top {
                    return Some((&field.name, i));
                }
            }
        }
        None
    }

    /// ADR-019 alias for [`control_at_point()`](Self::control_at_point).
    ///
    /// Corresponds to `CPDF_InteractiveForm::GetControlAtPoint()` in PDFium.
    #[inline]
    pub fn get_control_at_point(&self, x: f64, y: f64) -> Option<(&str, usize)> {
        self.control_at_point(x, y)
    }
}

/// Parse the `/CO` (calculation order) array from an AcroForm dictionary.
///
/// Each element in the array is a reference to a field dict. We resolve each
/// reference and extract its `/T` (partial name) to build the order list.
fn parse_calculation_order<S: PdfSource>(
    acroform_dict: &HashMap<Name, Object>,
    store: &ObjectStore<S>,
) -> Vec<String> {
    let co_obj = match acroform_dict.get(&Name::co()) {
        Some(o) => o,
        None => return Vec::new(),
    };
    let resolved = match store.deep_resolve(co_obj).ok() {
        Some(o) => o,
        None => return Vec::new(),
    };
    let arr = match resolved.as_array() {
        Some(a) => a,
        None => return Vec::new(),
    };

    let mut order = Vec::new();
    for item in arr {
        let field_obj = match store.deep_resolve(item).ok() {
            Some(o) => o,
            None => continue,
        };
        if let Some(dict) = field_obj.as_dict() {
            if let Some(t_obj) = dict.get(&Name::t()) {
                if let Ok(resolved_t) = store.deep_resolve(t_obj) {
                    if let Some(s) = resolved_t.as_string() {
                        order.push(s.to_string_lossy());
                    }
                }
            }
        }
    }
    order
}

/// Insert a field at the given path in the tree, returning its index in the parent container.
fn insert_at_path(root: &mut Vec<FormField>, path: &[usize], field: &mut FormField) -> usize {
    let container = get_children_at_path(root, path);
    let idx = container.len();
    // Take ownership by swapping with an empty placeholder
    let owned = std::mem::replace(
        field,
        FormField {
            name: String::new(),
            field_type: FormFieldType::Text,
            value: None,
            default_value: None,
            flags: FormFieldFlags::from_bits(0),
            tooltip: None,
            alternate_name: None,
            mapping_name: None,
            max_len: None,
            options: Vec::new(),
            appearance_state: None,
            children: Vec::new(),
            controls: Vec::new(),
            dirty: false,
            selected_indices: Vec::new(),
            additional_actions: None,
        },
    );
    container.push(owned);
    idx
}

/// Navigate to the children vec at the given index path (iterative).
fn get_children_at_path<'a>(
    root: &'a mut Vec<FormField>,
    path: &[usize],
) -> &'a mut Vec<FormField> {
    let mut current = root;
    for &idx in path {
        current = &mut current[idx].children;
    }
    current
}

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

    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
    }

    fn str_obj(s: &str) -> Object {
        Object::String(PdfString::from_bytes(s.as_bytes().to_vec()))
    }

    fn make_field_dict(ft: &str, name: &str) -> HashMap<Name, Object> {
        let mut dict = HashMap::new();
        dict.insert(Name::ft(), Object::Name(Name::from(ft)));
        dict.insert(Name::t(), str_obj(name));
        dict
    }

    #[test]
    fn test_no_acroform_returns_none() {
        let store = build_store();
        let mut catalog = HashMap::new();
        catalog.insert(Name::r#type(), Object::Name(Name::from("Catalog")));
        let obj = Object::Dictionary(catalog);
        let result = InteractiveForm::from_catalog(&obj, &store).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_empty_fields_array() {
        let store = build_store();
        let mut acroform = HashMap::new();
        acroform.insert(Name::fields(), Object::Array(Vec::new()));

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();
        assert!(form.fields.is_empty());
    }

    #[test]
    fn test_single_text_field() {
        let store = build_store();

        let mut field_dict = make_field_dict("Tx", "username");
        field_dict.insert(Name::v(), str_obj("alice"));

        let mut acroform = HashMap::new();
        acroform.insert(
            Name::fields(),
            Object::Array(vec![Object::Dictionary(field_dict)]),
        );

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();
        assert_eq!(form.fields.len(), 1);
        assert_eq!(form.fields[0].name, "username");
        assert_eq!(form.fields[0].value.as_deref(), Some("alice"));
    }

    #[test]
    fn test_hierarchical_fields_with_inherited_ft() {
        let store = build_store();

        // Parent node with /FT Tx and /T "address", /Kids with two children
        let child1 = {
            let mut d = HashMap::new();
            d.insert(Name::t(), str_obj("city"));
            d.insert(Name::v(), str_obj("Tokyo"));
            Object::Dictionary(d)
        };
        let child2 = {
            let mut d = HashMap::new();
            d.insert(Name::t(), str_obj("zip"));
            d.insert(Name::v(), str_obj("100-0001"));
            Object::Dictionary(d)
        };

        let mut parent = HashMap::new();
        parent.insert(Name::ft(), Object::Name(Name::from("Tx")));
        parent.insert(Name::t(), str_obj("address"));
        parent.insert(Name::kids(), Object::Array(vec![child1, child2]));

        let mut acroform = HashMap::new();
        acroform.insert(
            Name::fields(),
            Object::Array(vec![Object::Dictionary(parent)]),
        );

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();

        // The children should inherit /FT from parent
        let all = form.all_fields();
        // There should be 2 leaf fields with inherited Tx type
        let leaf_fields: Vec<_> = all
            .iter()
            .filter(|f| f.field_type == FormFieldType::Text && f.value.is_some())
            .collect();
        assert_eq!(leaf_fields.len(), 2);

        // Check field_by_name
        let city = form.field_by_name("address.city");
        assert!(city.is_some());
        assert_eq!(city.unwrap().value.as_deref(), Some("Tokyo"));

        let zip = form.field_by_name("address.zip");
        assert!(zip.is_some());
        assert_eq!(zip.unwrap().value.as_deref(), Some("100-0001"));
    }

    #[test]
    fn test_multiple_top_level_fields() {
        let store = build_store();

        let field1 = make_field_dict("Tx", "name");
        let field2 = make_field_dict("Btn", "submit");
        let field3 = make_field_dict("Ch", "color");

        let mut acroform = HashMap::new();
        acroform.insert(
            Name::fields(),
            Object::Array(vec![
                Object::Dictionary(field1),
                Object::Dictionary(field2),
                Object::Dictionary(field3),
            ]),
        );

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();
        assert_eq!(form.fields.len(), 3);
        assert_eq!(form.fields[0].field_type, FormFieldType::Text);
        assert_eq!(form.fields[1].field_type, FormFieldType::Button);
        assert_eq!(form.fields[2].field_type, FormFieldType::Choice);
    }

    #[test]
    fn test_all_fields_flat() {
        let store = build_store();

        // Parent with one child
        let child = {
            let mut d = HashMap::new();
            d.insert(Name::ft(), Object::Name(Name::from("Tx")));
            d.insert(Name::t(), str_obj("child"));
            Object::Dictionary(d)
        };
        let mut parent = make_field_dict("Tx", "parent");
        parent.insert(Name::kids(), Object::Array(vec![child]));

        // Another standalone field
        let standalone = make_field_dict("Btn", "btn1");

        let mut acroform = HashMap::new();
        acroform.insert(
            Name::fields(),
            Object::Array(vec![
                Object::Dictionary(parent),
                Object::Dictionary(standalone),
            ]),
        );

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();
        let all = form.all_fields();
        // parent + child + btn1 = 3
        assert_eq!(all.len(), 3);
    }

    #[test]
    fn test_field_by_name_not_found() {
        let store = build_store();

        let field = make_field_dict("Tx", "exists");

        let mut acroform = HashMap::new();
        acroform.insert(
            Name::fields(),
            Object::Array(vec![Object::Dictionary(field)]),
        );

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();
        assert!(form.field_by_name("nonexistent").is_none());
    }

    #[test]
    fn test_from_catalog_with_programmatic_pdf() {
        // Build a minimal PDF with an AcroForm baked in
        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 /AcroForm << /Fields [ << /FT /Tx /T (email) /V (test@example.com) >> ] >> >>\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());

        let store = ObjectStore::open(pdf, rpdfium_core::ParsingMode::Lenient).unwrap();

        // Get catalog from store via trailer root
        let root_id = store.trailer().root;
        let catalog = store.resolve(root_id).unwrap();
        let form = InteractiveForm::from_catalog(catalog, &store)
            .unwrap()
            .unwrap();
        assert_eq!(form.fields.len(), 1);
        assert_eq!(form.fields[0].name, "email");
        assert_eq!(form.fields[0].value.as_deref(), Some("test@example.com"));
    }

    #[test]
    fn test_calculation_order_parsed() {
        let store = build_store();

        let field_a = {
            let mut d = make_field_dict("Tx", "total");
            d.insert(Name::v(), str_obj("100"));
            Object::Dictionary(d)
        };
        let field_b = {
            let mut d = make_field_dict("Tx", "tax");
            d.insert(Name::v(), str_obj("10"));
            Object::Dictionary(d)
        };

        // CO array references field dicts directly
        let co_a = {
            let mut d = HashMap::new();
            d.insert(Name::t(), str_obj("tax"));
            Object::Dictionary(d)
        };
        let co_b = {
            let mut d = HashMap::new();
            d.insert(Name::t(), str_obj("total"));
            Object::Dictionary(d)
        };

        let mut acroform = HashMap::new();
        acroform.insert(Name::fields(), Object::Array(vec![field_a, field_b]));
        acroform.insert(Name::co(), Object::Array(vec![co_a, co_b]));

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();
        assert_eq!(form.calculation_order(), &["tax", "total"]);
    }

    #[test]
    fn test_calculation_order_empty_when_absent() {
        let store = build_store();

        let mut acroform = HashMap::new();
        acroform.insert(Name::fields(), Object::Array(Vec::new()));
        // No /CO key

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();
        assert!(form.calculation_order().is_empty());
    }

    #[test]
    fn test_default_appearance_parsed() {
        let store = build_store();

        let mut acroform = HashMap::new();
        acroform.insert(Name::fields(), Object::Array(Vec::new()));
        acroform.insert(Name::da(), str_obj("0 g /Helv 12 Tf"));
        acroform.insert(Name::q(), Object::Integer(1));

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();
        assert_eq!(form.default_appearance(), Some("0 g /Helv 12 Tf"));
        assert_eq!(form.default_alignment(), Alignment::Center);
    }

    #[test]
    fn test_default_alignment_defaults_to_left() {
        let store = build_store();

        let mut acroform = HashMap::new();
        acroform.insert(Name::fields(), Object::Array(Vec::new()));

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();
        assert!(form.default_appearance().is_none());
        assert_eq!(form.default_alignment(), Alignment::Left);
    }

    #[test]
    fn test_check_required_fields_empty() {
        let store = build_store();

        let field = make_field_dict("Tx", "name");

        let mut acroform = HashMap::new();
        acroform.insert(
            Name::fields(),
            Object::Array(vec![Object::Dictionary(field)]),
        );

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();
        assert!(form.check_required_fields().is_empty());
    }

    #[test]
    fn test_check_required_fields_finds_missing() {
        let store = build_store();

        let mut field = make_field_dict("Tx", "required_field");
        field.insert(Name::ff(), Object::Integer(2)); // Required flag

        let mut acroform = HashMap::new();
        acroform.insert(
            Name::fields(),
            Object::Array(vec![Object::Dictionary(field)]),
        );

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();
        let missing = form.check_required_fields();
        assert_eq!(missing.len(), 1);
        assert_eq!(missing[0], "required_field");
    }

    #[test]
    fn test_check_required_fields_skips_filled() {
        let store = build_store();

        let mut field = make_field_dict("Tx", "required_field");
        field.insert(Name::ff(), Object::Integer(2)); // Required flag
        field.insert(Name::v(), str_obj("filled"));

        let mut acroform = HashMap::new();
        acroform.insert(
            Name::fields(),
            Object::Array(vec![Object::Dictionary(field)]),
        );

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();
        assert!(form.check_required_fields().is_empty());
    }

    /// Upstream: TEST_F(CPDFInteractiveFormTest, LoadFieldsWithReferencedNames)
    ///
    /// The upstream test creates fields where /T is an indirect reference to:
    /// 1. A CPDF_String ("good_string") — should resolve as a valid field name
    /// 2. A CPDF_Name ("bad_name") — should NOT resolve as a string, so no name
    /// 3. A CPDF_Stream ("bad_stream") — should NOT resolve as a string, so no name
    ///
    /// In rpdfium, from_catalog resolves /T via deep_resolve + as_string().
    /// A Name object returns None from as_string(), and a Stream also returns None.
    /// So only the String-based /T produces a valid partial name.
    #[test]
    fn test_cpdf_interactive_form_load_fields_with_referenced_names() {
        let store = build_store();

        // Field 1: /T is a PDF String → should parse as field name "good_string"
        let mut field1 = HashMap::new();
        field1.insert(Name::ft(), Object::Name(Name::from("Btn")));
        field1.insert(Name::t(), str_obj("good_string"));

        // Field 2: /T is a Name object → as_string() returns None, no partial name
        let mut field2 = HashMap::new();
        field2.insert(Name::ft(), Object::Name(Name::from("Btn")));
        field2.insert(Name::t(), Object::Name(Name::from("bad_name")));

        // Field 3: /T is a Stream object → as_string() returns None, no partial name
        let mut field3 = HashMap::new();
        field3.insert(Name::ft(), Object::Name(Name::from("Btn")));
        field3.insert(
            Name::t(),
            Object::Stream {
                dict: HashMap::new(),
                data: rpdfium_parser::StreamData::Decoded {
                    data: b"bad_stream".to_vec(),
                },
            },
        );

        let mut acroform = HashMap::new();
        acroform.insert(
            Name::fields(),
            Object::Array(vec![
                Object::Dictionary(field1),
                Object::Dictionary(field2),
                Object::Dictionary(field3),
            ]),
        );

        let mut catalog = HashMap::new();
        catalog.insert(Name::acro_form(), Object::Dictionary(acroform));
        let obj = Object::Dictionary(catalog);

        let form = InteractiveForm::from_catalog(&obj, &store)
            .unwrap()
            .unwrap();

        // The good_string field should be found by name
        let good = form.field_by_name("good_string");
        assert!(
            good.is_some(),
            "String-based /T should produce a valid field name"
        );

        // The bad_name and bad_stream fields have no valid /T string,
        // so their partial name is empty. They still exist as fields
        // but with an empty name (inherited from empty parent_name).
        let all = form.all_fields();

        // We expect all 3 fields to be parsed (they all have /FT)
        assert_eq!(all.len(), 3);

        // The first field should have name "good_string"
        let good_field = all.iter().find(|f| f.name == "good_string");
        assert!(good_field.is_some());

        // The other two fields should have empty names (Name and Stream
        // don't produce valid partial names via as_string())
        let empty_name_fields: Vec<_> = all.iter().filter(|f| f.name.is_empty()).collect();
        assert_eq!(
            empty_name_fields.len(),
            2,
            "Name and Stream /T values should result in empty field names"
        );
    }
}