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

//! Appearance stream generation for interactive form fields.
//!
//! Generates PDF content streams that visually represent the current value
//! of a form field (ISO 32000-2 section 12.7.4.3).

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

/// Generate a text-field appearance stream.
///
/// Produces a minimal content stream that renders `value` using Helvetica
/// at the given `font_size`, positioned 2 units inward from the lower-left
/// corner of the annotation rectangle.
///
/// The caller is responsible for wrapping this into a proper Form XObject.
pub fn generate_text_appearance(
    value: &str,
    font_size: f32,
    _rect_width: f32,
    _rect_height: f32,
) -> Vec<u8> {
    // Escape parentheses and backslashes in the value for PDF string literal
    let escaped = escape_pdf_string(value);

    format!("BT\n/Helv {font_size:.1} Tf\n2 2 Td\n({escaped}) Tj\nET\n").into_bytes()
}

/// Generate a checkbox appearance stream.
///
/// When `checked` is `true`, produces a check mark (ZapfDingbats character 4).
/// When `false`, produces an empty stream.
pub fn generate_checkbox_appearance(checked: bool, size: f32) -> Vec<u8> {
    if !checked {
        return Vec::new();
    }

    // Draw a simple check mark path scaled to the given size
    let scale = size / 12.0;
    let mut buf = Vec::new();
    buf.extend_from_slice(
        format!(
            "q\n{scale:.4} 0 0 {scale:.4} 0 0 cm\n\
             1.5 4.5 m\n5 9 l\n10.5 1.5 l\nS\nQ\n"
        )
        .as_bytes(),
    );
    buf
}

/// Generate an appearance stream for the given form field.
///
/// Dispatches to the appropriate generator based on the field type.
/// Returns an error for Signature fields (which require cryptographic data).
pub fn generate_for_field(field: &FormField) -> DocResult<Vec<u8>> {
    match field.field_type {
        FormFieldType::Text => {
            let value = field.value.as_deref().unwrap_or("");
            Ok(generate_text_appearance(value, 12.0, 200.0, 20.0))
        }
        FormFieldType::Button => {
            let checked = field
                .appearance_state
                .as_deref()
                .is_some_and(|s| s != "Off");
            Ok(generate_checkbox_appearance(checked, 12.0))
        }
        FormFieldType::Choice => {
            // Choice fields display the selected value as text
            let value = field.value.as_deref().unwrap_or("");
            Ok(generate_text_appearance(value, 12.0, 200.0, 20.0))
        }
        FormFieldType::Signature => Err(DocError::TypeMismatch {
            expected: "Text, Button, or Choice".to_string(),
            got: "Signature".to_string(),
        }),
    }
}

/// A parsed default appearance (`/DA`) string.
#[derive(Debug, Clone)]
pub struct ParsedDefaultAppearance {
    /// Font name from `Tf` operator (e.g., "Helv").
    pub font_name: Option<String>,
    /// Font size from `Tf` operator.
    pub font_size: f64,
    /// Color operands preceding a color operator (`g`, `rg`, `k`).
    pub color: Option<Vec<f64>>,
}

/// Parse a default appearance (`/DA`) string.
///
/// DA strings contain a subset of content stream operators, typically:
/// - `/FontName size Tf` — set font and size
/// - `gray g` or `r g b rg` or `c m y k k` — set color
pub fn parse_default_appearance(da: &str) -> ParsedDefaultAppearance {
    let mut font_name = None;
    let mut font_size = 0.0;
    let mut color = None;
    let mut num_stack: Vec<f64> = Vec::new();

    let tokens: Vec<&str> = da.split_whitespace().collect();
    for token in &tokens {
        if let Ok(n) = token.parse::<f64>() {
            num_stack.push(n);
        } else if let Some(stripped) = token.strip_prefix('/') {
            // Font name — push as string token
            num_stack.clear();
            font_name = Some(stripped.to_string());
        } else {
            match *token {
                "Tf" => {
                    if let Some(size) = num_stack.pop() {
                        font_size = size;
                    }
                    // font_name already set from the /Name token above
                    num_stack.clear();
                }
                "g" => {
                    if !num_stack.is_empty() {
                        color = Some(std::mem::take(&mut num_stack));
                    }
                }
                "rg" => {
                    if num_stack.len() >= 3 {
                        color = Some(std::mem::take(&mut num_stack));
                    }
                }
                "k" => {
                    if num_stack.len() >= 4 {
                        color = Some(std::mem::take(&mut num_stack));
                    }
                }
                _ => {
                    num_stack.clear();
                }
            }
        }
    }

    ParsedDefaultAppearance {
        font_name,
        font_size,
        color,
    }
}

/// Alignment for text fields (from `/Q` key).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextAlignment {
    /// Left-aligned (Q=0, default).
    Left,
    /// Center-aligned (Q=1).
    Center,
    /// Right-aligned (Q=2).
    Right,
}

/// Generate a text-field appearance stream with word wrapping and alignment.
///
/// `da` is the parsed default appearance, `value` is the field's text,
/// `rect_width`/`rect_height` define the annotation rectangle dimensions,
/// and `alignment` controls horizontal text positioning.
pub fn generate_text_appearance_rich(
    da: &ParsedDefaultAppearance,
    value: &str,
    rect_width: f32,
    rect_height: f32,
    alignment: TextAlignment,
) -> Vec<u8> {
    let font_name = da.font_name.as_deref().unwrap_or("Helv");
    let font_size = if da.font_size > 0.0 {
        da.font_size as f32
    } else {
        12.0
    };

    // Approximate character width as 0.5 * font_size (for monospace-like estimation)
    let char_width = font_size * 0.5;
    let margin = 2.0;
    let usable_width = (rect_width - 2.0 * margin).max(0.0);
    let leading = font_size * 1.2;

    // Word wrap
    let lines = word_wrap(value, usable_width, char_width);

    // Build content stream
    let mut buf = String::new();
    buf.push_str("BT\n");

    // Set font
    buf.push_str(&format!("/{font_name} {font_size:.1} Tf\n"));

    // Set color if present
    if let Some(ref c) = da.color {
        match c.len() {
            1 => buf.push_str(&format!("{:.3} g\n", c[0])),
            3 => buf.push_str(&format!("{:.3} {:.3} {:.3} rg\n", c[0], c[1], c[2])),
            4 => buf.push_str(&format!(
                "{:.3} {:.3} {:.3} {:.3} k\n",
                c[0], c[1], c[2], c[3]
            )),
            _ => {}
        }
    }

    // Calculate starting Y position (top-down)
    let total_text_height = lines.len() as f32 * leading;
    let start_y = if total_text_height < rect_height - 2.0 * margin {
        // Vertically center if text fits
        rect_height - margin - (rect_height - total_text_height) / 2.0 - font_size
    } else {
        rect_height - margin - font_size
    };

    for (i, line) in lines.iter().enumerate() {
        let escaped = escape_pdf_string(line);
        let line_width = line.len() as f32 * char_width;

        let x = match alignment {
            TextAlignment::Left => margin,
            TextAlignment::Center => margin + (usable_width - line_width).max(0.0) / 2.0,
            TextAlignment::Right => margin + (usable_width - line_width).max(0.0),
        };

        let y = start_y - (i as f32 * leading);
        buf.push_str(&format!("{x:.1} {y:.1} Td\n"));
        buf.push_str(&format!("({escaped}) Tj\n"));
    }

    buf.push_str("ET\n");
    buf.into_bytes()
}

/// Simple word-wrap: split text into lines that fit within `max_width`.
fn word_wrap(text: &str, max_width: f32, char_width: f32) -> Vec<String> {
    if text.is_empty() {
        return vec![String::new()];
    }

    let max_chars = if char_width > 0.0 {
        (max_width / char_width).floor() as usize
    } else {
        usize::MAX
    };

    if max_chars == 0 {
        return vec![text.to_string()];
    }

    let mut lines = Vec::new();
    let mut current_line = String::new();
    let mut current_len: usize = 0;

    for word in text.split(' ') {
        if current_line.is_empty() {
            current_line.push_str(word);
            current_len = word.len();
        } else if current_len + 1 + word.len() <= max_chars {
            current_line.push(' ');
            current_line.push_str(word);
            current_len += 1 + word.len();
        } else {
            lines.push(current_line);
            current_line = word.to_string();
            current_len = word.len();
        }
    }

    if !current_line.is_empty() {
        lines.push(current_line);
    }

    if lines.is_empty() {
        lines.push(String::new());
    }

    lines
}

/// Escape a string for use inside a PDF literal string `(...)`.
fn escape_pdf_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '(' => out.push_str("\\("),
            ')' => out.push_str("\\)"),
            _ => out.push(ch),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::form_field::{ChoiceOption, FieldValue, FormFieldFlags};

    fn make_text_field(name: &str, value: Option<&str>, max_len: Option<u32>) -> FormField {
        FormField {
            name: name.to_string(),
            field_type: FormFieldType::Text,
            value: value.map(|s| s.to_string()),
            default_value: None,
            flags: FormFieldFlags::from_bits(0),
            tooltip: None,
            alternate_name: None,
            mapping_name: None,
            max_len,
            options: Vec::new(),
            appearance_state: None,
            children: Vec::new(),
            controls: Vec::new(),
            dirty: false,
            selected_indices: Vec::new(),
            additional_actions: None,
        }
    }

    fn make_button_field(name: &str, state: Option<&str>) -> FormField {
        FormField {
            name: name.to_string(),
            field_type: FormFieldType::Button,
            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: state.map(|s| s.to_string()),
            children: Vec::new(),
            controls: Vec::new(),
            dirty: false,
            selected_indices: Vec::new(),
            additional_actions: None,
        }
    }

    #[test]
    fn test_text_appearance_contains_value() {
        let bytes = generate_text_appearance("Hello World", 12.0, 200.0, 20.0);
        let content = String::from_utf8(bytes).unwrap();
        assert!(content.contains("BT"));
        assert!(content.contains("/Helv 12.0 Tf"));
        assert!(content.contains("(Hello World) Tj"));
        assert!(content.contains("ET"));
    }

    #[test]
    fn test_text_appearance_escapes_parens() {
        let bytes = generate_text_appearance("a(b)c\\d", 10.0, 100.0, 20.0);
        let content = String::from_utf8(bytes).unwrap();
        assert!(content.contains("(a\\(b\\)c\\\\d) Tj"));
    }

    #[test]
    fn test_checkbox_checked_produces_path() {
        let bytes = generate_checkbox_appearance(true, 12.0);
        let content = String::from_utf8(bytes).unwrap();
        assert!(content.contains("m\n"));
        assert!(content.contains("l\n"));
        assert!(content.contains("S\n"));
    }

    #[test]
    fn test_checkbox_unchecked_is_empty() {
        let bytes = generate_checkbox_appearance(false, 12.0);
        assert!(bytes.is_empty());
    }

    #[test]
    fn test_generate_for_text_field() {
        let field = make_text_field("name", Some("Alice"), None);
        let bytes = generate_for_field(&field).unwrap();
        let content = String::from_utf8(bytes).unwrap();
        assert!(content.contains("(Alice) Tj"));
    }

    #[test]
    fn test_generate_for_checked_button() {
        let field = make_button_field("agree", Some("Yes"));
        let bytes = generate_for_field(&field).unwrap();
        assert!(!bytes.is_empty());
    }

    #[test]
    fn test_generate_for_unchecked_button() {
        let field = make_button_field("agree", Some("Off"));
        let bytes = generate_for_field(&field).unwrap();
        assert!(bytes.is_empty());
    }

    #[test]
    fn test_generate_for_choice_field() {
        let mut field = FormField {
            name: "color".to_string(),
            field_type: FormFieldType::Choice,
            value: None,
            default_value: None,
            flags: FormFieldFlags::from_bits(0),
            tooltip: None,
            alternate_name: None,
            mapping_name: None,
            max_len: None,
            options: vec![
                ChoiceOption {
                    export_value: "R".to_string(),
                    display_value: "Red".to_string(),
                },
                ChoiceOption {
                    export_value: "G".to_string(),
                    display_value: "Green".to_string(),
                },
            ],
            appearance_state: None,
            children: Vec::new(),
            controls: Vec::new(),
            dirty: false,
            selected_indices: Vec::new(),
            additional_actions: None,
        };
        field.set_value(FieldValue::Choice(1)).unwrap();
        let bytes = generate_for_field(&field).unwrap();
        let content = String::from_utf8(bytes).unwrap();
        assert!(content.contains("(G) Tj"));
    }

    #[test]
    fn test_generate_for_signature_errors() {
        let field = FormField {
            name: "sig".to_string(),
            field_type: FormFieldType::Signature,
            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,
        };
        assert!(generate_for_field(&field).is_err());
    }

    // ---- ParsedDefaultAppearance tests ----

    #[test]
    fn test_parse_da_basic() {
        let da = parse_default_appearance("/Helv 12 Tf 0 0 0 rg");
        assert_eq!(da.font_name.as_deref(), Some("Helv"));
        assert_eq!(da.font_size, 12.0);
        assert_eq!(da.color, Some(vec![0.0, 0.0, 0.0]));
    }

    #[test]
    fn test_parse_da_gray_color() {
        let da = parse_default_appearance("/Cour 10 Tf 0.5 g");
        assert_eq!(da.font_name.as_deref(), Some("Cour"));
        assert_eq!(da.font_size, 10.0);
        assert_eq!(da.color, Some(vec![0.5]));
    }

    #[test]
    fn test_parse_da_cmyk_color() {
        let da = parse_default_appearance("/Helv 8 Tf 0 0 0 1 k");
        assert_eq!(da.font_size, 8.0);
        assert_eq!(da.color, Some(vec![0.0, 0.0, 0.0, 1.0]));
    }

    #[test]
    fn test_parse_da_no_color() {
        let da = parse_default_appearance("/Helv 14 Tf");
        assert_eq!(da.font_name.as_deref(), Some("Helv"));
        assert_eq!(da.font_size, 14.0);
        assert!(da.color.is_none());
    }

    #[test]
    fn test_parse_da_empty() {
        let da = parse_default_appearance("");
        assert!(da.font_name.is_none());
        assert_eq!(da.font_size, 0.0);
        assert!(da.color.is_none());
    }

    // ---- Word wrap tests ----

    #[test]
    fn test_word_wrap_single_line() {
        let lines = word_wrap("Hello World", 100.0, 6.0);
        assert_eq!(lines, vec!["Hello World"]);
    }

    #[test]
    fn test_word_wrap_multiple_lines() {
        // max_width=30, char_width=6 => max 5 chars per line
        let lines = word_wrap("Hello World Test", 30.0, 6.0);
        assert_eq!(lines, vec!["Hello", "World", "Test"]);
    }

    #[test]
    fn test_word_wrap_empty_string() {
        let lines = word_wrap("", 100.0, 6.0);
        assert_eq!(lines, vec![""]);
    }

    // ---- Rich text appearance tests ----

    #[test]
    fn test_generate_rich_left_aligned() {
        let da = ParsedDefaultAppearance {
            font_name: Some("Helv".to_string()),
            font_size: 12.0,
            color: Some(vec![0.0, 0.0, 0.0]),
        };
        let bytes = generate_text_appearance_rich(&da, "Test", 200.0, 20.0, TextAlignment::Left);
        let content = String::from_utf8(bytes).unwrap();
        assert!(content.contains("BT"));
        assert!(content.contains("/Helv 12.0 Tf"));
        assert!(content.contains("(Test) Tj"));
        assert!(content.contains("ET"));
    }

    #[test]
    fn test_generate_rich_center_aligned() {
        let da = ParsedDefaultAppearance {
            font_name: Some("Helv".to_string()),
            font_size: 12.0,
            color: None,
        };
        let bytes = generate_text_appearance_rich(&da, "Hi", 200.0, 20.0, TextAlignment::Center);
        let content = String::from_utf8(bytes).unwrap();
        assert!(content.contains("(Hi) Tj"));
    }

    /// Upstream: TEST(CPDFDefaultAppearanceTest, FindTagParamFromStart)
    #[test]
    #[ignore = "FindTagParamFromStart not yet implemented"]
    fn test_cpdf_default_appearance_find_tag_param_from_start() {
        // The upstream test verifies that FindTagParamFromStart correctly
        // locates operator tokens (like "Tj", "cm") in a content stream
        // byte sequence, positioning the parser at the start of the
        // operator's parameters. Cases tested:
        //
        // - Empty input with token "Tj" → not found, position 0
        // - Empty input with empty token → not found, position 0
        // - Input "  T j" with empty token → not found, position 5
        // - "Tj" with token "Tj" and 1 param → not found (no param), position 2
        // - "(Tj" with token "Tj" and 1 param → not found, position 3
        // - "\r12\t34  56 78Tj" with 1 param → not found (partial match), position 15
        // - "\r\0abd Tj" with 1 param → found, position 0
        // - "12 4 Tj 3 46 Tj" with 1 param → found, position 2
        // - "er^ 2 (34) (5667) Tj" with 2 params → found, position 5
        // - "<344> (232)\t343.4\n12 45 Tj" with 3 params → found, position 11
        // - "1 2 3 4 5 6 7 8 cm" with 6 params → found, position 3
        //
        // Once FindTagParamFromStart is ported, this test should exercise
        // the function with each of these cases and assert both the boolean
        // result and the parser's final position.
        todo!("Port FindTagParamFromStart and its test data");
    }

    #[test]
    fn test_generate_rich_uses_default_font() {
        let da = ParsedDefaultAppearance {
            font_name: None,
            font_size: 0.0,
            color: None,
        };
        let bytes = generate_text_appearance_rich(&da, "Text", 200.0, 20.0, TextAlignment::Left);
        let content = String::from_utf8(bytes).unwrap();
        // Should fall back to Helv and 12.0
        assert!(content.contains("/Helv 12.0 Tf"));
    }
}