oxidize-pdf 5.5.3

Pure Rust toolkit for PDF generation, parsing, manipulation, text extraction, AI/RAG pipelines, signatures, and PDF/A validation.
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
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
//! Provider-neutral two-phase incremental PDF signing.

use super::{
    ensure_modification_allowed, IncrementalModification, SignatureError, SignatureResult,
};
use crate::parser::objects::{PdfArray, PdfDictionary, PdfName, PdfObject, PdfStream, PdfString};
use crate::parser::{PdfDocument, PdfReader};
use crate::text::fonts::get_standard_font_metrics;
use crate::text::{escape_pdf_string_literal, Font, TextEncoding};
use crate::writer::IncrementalUpdate;
use std::collections::HashSet;
use std::io::Cursor;
use std::ops::Range;

const BYTE_RANGE_SENTINEL: i64 = i64::MAX;
const BYTE_RANGE_WIDTH: usize = 19;
const MIN_PLACEHOLDER_BYTES: usize = 256;
const MAX_PLACEHOLDER_BYTES: usize = 16 * 1024 * 1024;
const MAX_WATERMARK_PIXELS: usize = 16 * 1024 * 1024;

/// Rectangle for a visible signature widget.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SignatureRect {
    pub left: f64,
    pub bottom: f64,
    pub right: f64,
    pub top: f64,
}

/// RGB raster image drawn as a watermark in a visible signature appearance.
///
/// `rgb` contains exactly `width * height * 3` bytes in row-major RGB order.
/// The image is embedded in the signature appearance before the detached
/// signature's byte range is computed. It is centered behind the text while
/// preserving its aspect ratio and never reserves text space.
#[derive(Debug, Clone, PartialEq)]
pub struct SignatureWatermark {
    pub width: u32,
    pub height: u32,
    pub rgb: Vec<u8>,
    /// Opacity in the inclusive range `0.0..=1.0`.
    pub opacity: f32,
}

/// Content for a generated visible signature appearance.
///
/// The appearance is rendered in widget-local coordinates. Consequently the
/// page's crop box and rotation are applied by the PDF viewer together with
/// the widget annotation, rather than being baked into the artwork.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct SignatureAppearance {
    pub signer_name: Option<String>,
    pub signing_date: Option<String>,
    /// Additional paragraphs shown below the signer and date. Long paragraphs
    /// wrap to the available width; explicit line breaks are preserved.
    pub text: Vec<String>,
    pub watermark: Option<SignatureWatermark>,
}

/// Validated Helvetica text layout in widget-local coordinates, in PDF points.
/// Produced by [`SignatureAppearance::layout`] and used by signature generation.
#[derive(Debug, Clone, PartialEq)]
pub struct SignatureAppearanceLayout {
    /// Wrapped lines, including explicit empty lines.
    pub lines: Vec<String>,
    /// Selected font size, between 6 and 12 points in quarter-point steps.
    pub font_size: f64,
    /// Inset from each edge of the widget.
    pub margin: f64,
    /// Baseline of the first line, measured from the bottom of the widget.
    pub first_baseline: f64,
    /// Baseline spacing, including room for descenders.
    pub line_height: f64,
}

impl SignatureAppearance {
    /// Validate and fit all appearance text before invoking an external signer.
    ///
    /// This is the same calculation used by signature preparation. The watermark
    /// never changes the text layout. Lines wrap at spaces where possible and
    /// otherwise between characters. CRLF/CR become LF and tabs become spaces;
    /// explicit line breaks and all printable characters are preserved.
    /// Helvetica/WinAnsi advances determine width. Each line reserves 1 em
    /// above its baseline and 0.25 em below, including accented glyphs.
    ///
    /// ```
    /// use oxidize_pdf::signatures::{SignatureAppearance, SignatureRect};
    /// let appearance = SignatureAppearance {
    ///     signer_name: Some("MARIA DEL CARMEN FERNANDEZ".into()),
    ///     ..Default::default()
    /// };
    /// let rect = SignatureRect { left: 0.0, bottom: 0.0, right: 300.0, top: 100.0 };
    /// let layout = appearance.layout(rect)?;
    /// assert!(layout.font_size >= 6.0);
    /// # Ok::<(), oxidize_pdf::signatures::SignatureError>(())
    /// ```
    ///
    /// # Errors
    /// Returns [`SignatureError::InvalidSignatureDict`] for invalid geometry,
    /// text or watermark, or an explicit layout error if all text cannot fit at
    /// the minimum readable size of 6 points. No text is clipped or discarded.
    pub fn layout(&self, rect: SignatureRect) -> SignatureResult<SignatureAppearanceLayout> {
        rect.validate()?;
        validate_appearance(self)?;
        let width = rect.right - rect.left;
        let height = rect.top - rect.bottom;
        let margin = (width.min(height) * 0.08).clamp(3.0, 10.0);
        // Borrow the static AFM table once; measuring through `measure_char`
        // would clone its character map for every glyph.
        let metrics = get_standard_font_metrics(&Font::Helvetica)
            .ok_or_else(|| invalid("Helvetica metrics are unavailable"))?;
        let paragraphs: Vec<Vec<(char, f64)>> = self
            .signer_name
            .iter()
            .chain(self.signing_date.iter())
            .chain(self.text.iter())
            .flat_map(|value| {
                value
                    .replace("\r\n", "\n")
                    .replace('\r', "\n")
                    .replace('\t', " ")
                    .split('\n')
                    .map(|line| {
                        line.chars()
                            .map(|c| (c, metrics.char_width_unicode(c) as f64 / 1000.0))
                            .collect::<Vec<_>>()
                    })
                    .collect::<Vec<_>>()
            })
            .collect();
        for quarter_points in (24..=48).rev() {
            let font_size = quarter_points as f64 / 4.0;
            let line_height = font_size * 1.25;
            let available_height = height - 2.0 * margin;
            let max_lines = (available_height / line_height).max(0.0).floor() as usize;
            if let Some(lines) =
                wrap_appearance_lines(&paragraphs, (width - 2.0 * margin) / font_size, max_lines)
            {
                return Ok(SignatureAppearanceLayout {
                    lines,
                    font_size,
                    margin,
                    first_baseline: height - margin - font_size,
                    line_height,
                });
            }
        }
        Err(invalid(
            "signature appearance layout: complete text does not fit at the minimum font size of 6 points; enlarge the rectangle or shorten the text",
        ))
    }
}

/// Greedy wrapping in em units. Reject as soon as the height budget is spent.
fn wrap_appearance_lines(
    paragraphs: &[Vec<(char, f64)>],
    available_width: f64,
    max_lines: usize,
) -> Option<Vec<String>> {
    let mut lines = Vec::new();
    for paragraph in paragraphs {
        if lines.len() >= max_lines {
            return None;
        }
        if paragraph.is_empty() {
            lines.push(String::new());
            continue;
        }
        let mut start = 0;
        while start < paragraph.len() {
            if lines.len() >= max_lines {
                return None;
            }
            let mut end = start;
            let mut width = 0.0;
            let mut last_space = None;
            while end < paragraph.len() && width + paragraph[end].1 <= available_width {
                width += paragraph[end].1;
                if paragraph[end].0 == ' ' {
                    last_space = Some(end + 1);
                }
                end += 1;
            }
            if end == start {
                return None;
            }
            if end < paragraph.len() {
                end = last_space.unwrap_or(end);
            }
            lines.push(paragraph[start..end].iter().map(|&(c, _)| c).collect());
            start = end;
        }
    }
    Some(lines)
}

impl SignatureRect {
    pub(super) fn validate(self) -> SignatureResult<()> {
        let values = [self.left, self.bottom, self.right, self.top];
        if values.iter().any(|value| !value.is_finite())
            || !(self.right - self.left).is_finite()
            || !(self.top - self.bottom).is_finite()
            || self.right <= self.left
            || self.top <= self.bottom
        {
            return Err(invalid("signature rectangle must be finite and non-empty"));
        }
        Ok(())
    }

    pub(super) fn object(self) -> PdfObject {
        PdfObject::Array(PdfArray(vec![
            PdfObject::Real(self.left),
            PdfObject::Real(self.bottom),
            PdfObject::Real(self.right),
            PdfObject::Real(self.top),
        ]))
    }
}

/// Select an empty signature field or create a new widget.
#[derive(Debug, Clone, PartialEq)]
pub enum SignatureTarget {
    Existing {
        field_name: String,
        /// Child widget to update. `None` selects a combined field/widget.
        widget_index: Option<usize>,
        /// Optional replacement rectangle and generated normal appearance.
        rect: Option<SignatureRect>,
    },
    New {
        field_name: String,
        page_index: usize,
        rect: Option<SignatureRect>,
    },
}

/// Generic DocMDP permission written by a certification signature.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CertificationPermission {
    NoChanges = 1,
    FormFillAndSign = 2,
    FormFillSignAndAnnotate = 3,
}

/// Generic FieldMDP field selection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FieldLock {
    All,
    Include(Vec<String>),
    Exclude(Vec<String>),
}

/// Input for the prepare phase. No key or signer handle is accepted.
#[derive(Debug, Clone, PartialEq)]
pub struct SignaturePreparationOptions {
    pub target: SignatureTarget,
    pub placeholder_bytes: usize,
    /// PDF signature handler name, normally `Adobe.PPKLite`.
    pub filter: String,
    /// Signature container profile, for example `adbe.pkcs7.detached`.
    pub sub_filter: String,
    pub reason: Option<String>,
    pub location: Option<String>,
    pub contact_info: Option<String>,
    pub signing_time: Option<String>,
    pub certification: Option<CertificationPermission>,
    pub field_lock: Option<FieldLock>,
    /// Profile-specific signature dictionary entries.
    ///
    /// Structural entries owned by the signing engine cannot be overridden.
    pub additional_signature_entries: PdfDictionary,
}

impl SignaturePreparationOptions {
    pub fn invisible(field_name: impl Into<String>) -> Self {
        Self {
            target: SignatureTarget::New {
                field_name: field_name.into(),
                page_index: 0,
                rect: None,
            },
            placeholder_bytes: 16_384,
            filter: "Adobe.PPKLite".to_string(),
            sub_filter: "adbe.pkcs7.detached".to_string(),
            reason: None,
            location: None,
            contact_info: None,
            signing_time: None,
            certification: None,
            field_lock: None,
            additional_signature_entries: PdfDictionary::new(),
        }
    }

    /// Select an existing signature field without changing its widget appearance.
    pub fn existing(field_name: impl Into<String>) -> Self {
        let mut options = Self::invisible(field_name);
        let field_name = match options.target {
            SignatureTarget::New { field_name, .. } => field_name,
            SignatureTarget::Existing { .. } => unreachable!(),
        };
        options.target = SignatureTarget::Existing {
            field_name,
            widget_index: None,
            rect: None,
        };
        options
    }
}

/// Prepared PDF and exact detached-signature coverage.
#[derive(Debug, Clone)]
pub struct PreparedSignature {
    pdf: Vec<u8>,
    byte_range: super::ByteRange,
    contents_hex: Range<usize>,
    placeholder_bytes: usize,
}

impl PreparedSignature {
    pub fn prepared_pdf(&self) -> &[u8] {
        &self.pdf
    }

    pub fn byte_range(&self) -> &super::ByteRange {
        &self.byte_range
    }

    /// Concatenate the exact bytes that an external signer must digest.
    pub fn bytes_to_digest(&self) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(self.byte_range.total_bytes() as usize);
        for &(offset, length) in self.byte_range.ranges() {
            let start = offset as usize;
            bytes.extend_from_slice(&self.pdf[start..start + length as usize]);
        }
        bytes
    }

    /// Embed a caller-produced DER CMS container without rewriting prior bytes.
    pub fn finalize(mut self, cms: &[u8]) -> SignatureResult<Vec<u8>> {
        validate_cms_container(cms)?;
        if cms.len() > self.placeholder_bytes {
            return Err(SignatureError::ContentsExtractionFailed {
                details: format!(
                    "CMS container needs {} bytes but the placeholder reserves {}",
                    cms.len(),
                    self.placeholder_bytes
                ),
            });
        }
        let slot = &mut self.pdf[self.contents_hex.clone()];
        slot.fill(b'0');
        for (index, byte) in cms.iter().enumerate() {
            let encoded = format!("{byte:02X}");
            slot[index * 2..index * 2 + 2].copy_from_slice(encoded.as_bytes());
        }
        Ok(self.pdf)
    }
}

/// Options for an external RFC 3161 document timestamp. The caller owns token
/// acquisition, message-imprint validation, trust and renewal policy.
#[derive(Debug, Clone, PartialEq)]
pub struct DocumentTimestampOptions {
    /// Existing empty signature field or a new invisible field.
    pub target: SignatureTarget,
    /// Reserved DER token capacity in bytes (same bounds as CMS signing).
    pub placeholder_bytes: usize,
}

impl DocumentTimestampOptions {
    /// Prepare a new invisible field on the first page.
    pub fn invisible(field_name: impl Into<String>) -> Self {
        let options = SignaturePreparationOptions::invisible(field_name);
        Self {
            target: options.target,
            placeholder_bytes: options.placeholder_bytes,
        }
    }

    /// Use an existing empty signature field whose widgets all have zero rectangles.
    pub fn existing(field_name: impl Into<String>) -> Self {
        let options = SignaturePreparationOptions::existing(field_name);
        Self {
            target: options.target,
            placeholder_bytes: options.placeholder_bytes,
        }
    }
}

/// Prepare `/Type /DocTimeStamp`, `/SubFilter /ETSI.RFC3161` with engine-owned
/// ByteRange/Contents. Digest [`PreparedSignature::bytes_to_digest`] externally,
/// obtain a timestamp token for that digest and pass its DER ContentInfo to
/// [`PreparedSignature::finalize`]. Finalization checks only envelope/capacity,
/// not RFC 3161 semantics, message imprint, trust or cryptographic validity.
///
/// Encryption, DocMDP P=1 and applicable FieldMDP locks are rejected. P=2/P=3
/// use the existing signing permission boundary; this is no exemption for
/// arbitrary content or catalog edits. Every existing widget must have a valid
/// zero rectangle, including widgets other than the selected one.
pub fn prepare_document_timestamp(
    base: &[u8],
    options: &DocumentTimestampOptions,
) -> SignatureResult<PreparedSignature> {
    let rect = match &options.target {
        SignatureTarget::New { rect, .. } | SignatureTarget::Existing { rect, .. } => rect,
    };
    if rect.is_some() {
        return Err(invalid("document timestamps must be invisible"));
    }
    let mut signing = SignaturePreparationOptions::invisible("timestamp");
    signing.target = options.target.clone();
    signing.placeholder_bytes = options.placeholder_bytes;
    signing.sub_filter = "ETSI.RFC3161".into();
    prepare_incremental_signature_inner(base, &signing, None, true)
}

/// Prepare an incremental revision for an external CMS signer.
pub fn prepare_incremental_signature(
    base: &[u8],
    options: &SignaturePreparationOptions,
) -> SignatureResult<PreparedSignature> {
    prepare_incremental_signature_inner(base, options, None, false)
}

/// Prepare an incremental revision with generated visible signature artwork.
///
/// A visible target rectangle is required. The artwork, including its font and
/// optional image resource, is part of the prepared revision and is therefore
/// covered by the caller-produced CMS signature.
pub fn prepare_incremental_signature_with_appearance(
    base: &[u8],
    options: &SignaturePreparationOptions,
    appearance: &SignatureAppearance,
) -> SignatureResult<PreparedSignature> {
    prepare_incremental_signature_inner(base, options, Some(appearance), false)
}

fn prepare_incremental_signature_inner(
    base: &[u8],
    options: &SignaturePreparationOptions,
    appearance: Option<&SignatureAppearance>,
    document_timestamp: bool,
) -> SignatureResult<PreparedSignature> {
    let layout = validate_options(options, appearance)?;
    let mut reader =
        PdfReader::new(Cursor::new(base)).map_err(|error| invalid(error.to_string()))?;
    if reader.is_encrypted() {
        return Err(invalid(
            "incremental signing does not support encrypted PDFs",
        ));
    }
    let mut catalog = reader
        .catalog()
        .map_err(|error| invalid(error.to_string()))?
        .clone();
    ensure_modification_allowed(&mut reader, &catalog, IncrementalModification::AddSignature)?;
    let target = &options.target;
    let target_field_name = match target {
        SignatureTarget::Existing { field_name, .. } | SignatureTarget::New { field_name, .. } => {
            field_name
        }
    };
    ensure_fieldmdp_allows_signature(&mut reader, target_field_name)?;
    let mut update = IncrementalUpdate::from_base(base)?;
    let signature_id = update.allocate_id()?;
    let mut signature = signature_dictionary(options);
    if document_timestamp {
        signature.insert("Type".into(), name("DocTimeStamp"));
    }
    signature.insert(
        "ByteRange".to_string(),
        PdfObject::Array(PdfArray(vec![
            PdfObject::Integer(0),
            PdfObject::Integer(BYTE_RANGE_SENTINEL),
            PdfObject::Integer(BYTE_RANGE_SENTINEL),
            PdfObject::Integer(BYTE_RANGE_SENTINEL),
        ])),
    );
    signature.insert(
        "Contents".to_string(),
        PdfObject::String(PdfString::new(vec![0xA5; options.placeholder_bytes])),
    );
    update.replace(signature_id, PdfObject::Dictionary(signature))?;

    match target {
        SignatureTarget::Existing {
            field_name,
            widget_index,
            rect,
        } => {
            let field = find_signature_field(&mut reader, &catalog, field_name)?;
            let mut dictionary = reader
                .get_object(field.0, field.1)
                .map_err(|error| invalid(format!("resolve signature field: {error}")))?
                .as_dict()
                .cloned()
                .ok_or_else(|| invalid("signature field is not a dictionary"))?;
            if dictionary.contains_key("V") {
                return Err(invalid("selected signature field is already signed"));
            }
            if document_timestamp {
                ensure_timestamp_widgets_invisible(&mut reader, field, *widget_index)?;
            }
            dictionary.insert("V".to_string(), reference(signature_id));
            if rect.is_some() {
                let widget = select_widget(&mut reader, field, *widget_index)?;
                let appearance_id = update.allocate_id()?;
                let rect = (*rect).ok_or_else(|| invalid("visible widget requires a rectangle"))?;
                let watermark_id = appearance
                    .and_then(|appearance| appearance.watermark.as_ref())
                    .map(|_| update.allocate_id())
                    .transpose()?;
                let mut appearance_entry = PdfDictionary::new();
                appearance_entry.insert("N".to_string(), reference(appearance_id));
                if widget == field {
                    // A combined field/widget is one indirect object.  Its value and
                    // appearance must be emitted as one incremental replacement.
                    dictionary.insert("Rect".to_string(), rect.object());
                    dictionary.insert("AP".to_string(), PdfObject::Dictionary(appearance_entry));
                    update.replace(field, PdfObject::Dictionary(dictionary))?;
                } else {
                    update.replace(field, PdfObject::Dictionary(dictionary))?;
                    let mut widget_dictionary = reader
                        .get_object(widget.0, widget.1)
                        .map_err(|error| invalid(format!("resolve signature widget: {error}")))?
                        .as_dict()
                        .cloned()
                        .ok_or_else(|| invalid("signature widget is not a dictionary"))?;
                    widget_dictionary.insert("Rect".to_string(), rect.object());
                    widget_dictionary
                        .insert("AP".to_string(), PdfObject::Dictionary(appearance_entry));
                    update.replace(widget, PdfObject::Dictionary(widget_dictionary))?;
                }
                if let (Some(watermark), Some(watermark_id)) = (
                    appearance.and_then(|appearance| appearance.watermark.as_ref()),
                    watermark_id,
                ) {
                    update.replace(watermark_id, watermark_object(watermark))?;
                }
                update.replace(
                    appearance_id,
                    visible_appearance(rect, appearance, watermark_id, layout.as_ref()),
                )?;
            } else if widget_index.is_some() {
                select_widget(&mut reader, field, *widget_index)?;
                update.replace(field, PdfObject::Dictionary(dictionary))?;
            } else {
                update.replace(field, PdfObject::Dictionary(dictionary))?;
            }
        }
        SignatureTarget::New {
            field_name,
            page_index,
            rect,
        } => {
            ensure_field_name_available(&mut reader, &catalog, field_name)?;
            let page_reader = PdfReader::new(Cursor::new(base))
                .map_err(|error| invalid(format!("open signature page snapshot: {error}")))?;
            let page_document = PdfDocument::new(page_reader);
            let page = page_document
                .get_page(*page_index as u32)
                .map_err(|error| invalid(format!("select signature page: {error}")))?;
            let field_id = update.allocate_id()?;
            let appearance_id = rect.map(|_| update.allocate_id()).transpose()?;
            let watermark_id = if rect.is_some() {
                appearance
                    .and_then(|appearance| appearance.watermark.as_ref())
                    .map(|_| update.allocate_id())
                    .transpose()?
            } else {
                None
            };
            let mut field = PdfDictionary::new();
            field.insert("Type".to_string(), name("Annot"));
            field.insert("Subtype".to_string(), name("Widget"));
            field.insert("FT".to_string(), name("Sig"));
            field.insert("T".to_string(), text(field_name));
            field.insert("F".to_string(), PdfObject::Integer(4));
            field.insert("P".to_string(), reference(page.obj_ref));
            field.insert("V".to_string(), reference(signature_id));
            field.insert(
                "Rect".to_string(),
                rect.map(SignatureRect::object)
                    .unwrap_or_else(|| PdfObject::Array(PdfArray(vec![PdfObject::Integer(0); 4]))),
            );
            if let (Some(rect), Some(appearance_id)) = (rect, appearance_id) {
                field.insert("AP".to_string(), {
                    let mut ap = PdfDictionary::new();
                    ap.insert("N".to_string(), reference(appearance_id));
                    PdfObject::Dictionary(ap)
                });
                if let (Some(watermark), Some(watermark_id)) = (
                    appearance.and_then(|appearance| appearance.watermark.as_ref()),
                    watermark_id,
                ) {
                    update.replace(watermark_id, watermark_object(watermark))?;
                }
                update.replace(
                    appearance_id,
                    visible_appearance(*rect, appearance, watermark_id, layout.as_ref()),
                )?;
            }
            update.replace(field_id, PdfObject::Dictionary(field))?;
            append_page_annotation(&mut reader, &mut update, page.obj_ref, &page.dict, field_id)?;
            append_acroform_field(&mut reader, &mut update, &mut catalog, field_id)?;
        }
    }

    if options.certification.is_some() {
        if catalog.contains_key("Perms") {
            return Err(invalid(
                "catalog already contains certification permissions",
            ));
        }
        let mut perms = PdfDictionary::new();
        perms.insert("DocMDP".to_string(), reference(signature_id));
        catalog.insert("Perms".to_string(), PdfObject::Dictionary(perms));
    }
    let root = reader
        .trailer()
        .root()
        .map_err(|error| invalid(error.to_string()))?;
    update.replace(root, PdfObject::Dictionary(catalog))?;
    let prepared = update.finish()?;
    locate_and_patch_placeholders(prepared, base.len(), options.placeholder_bytes)
}

fn validate_options(
    options: &SignaturePreparationOptions,
    appearance: Option<&SignatureAppearance>,
) -> SignatureResult<Option<SignatureAppearanceLayout>> {
    if !(MIN_PLACEHOLDER_BYTES..=MAX_PLACEHOLDER_BYTES).contains(&options.placeholder_bytes) {
        return Err(invalid(format!(
            "placeholder_bytes must be between {MIN_PLACEHOLDER_BYTES} and {MAX_PLACEHOLDER_BYTES}"
        )));
    }
    let name = match &options.target {
        SignatureTarget::Existing { field_name, .. } | SignatureTarget::New { field_name, .. } => {
            field_name
        }
    };
    if name.is_empty() || name.as_bytes().contains(&0) {
        return Err(invalid("signature field name is empty or contains NUL"));
    }
    validate_pdf_name(&options.filter, "filter")?;
    validate_pdf_name(&options.sub_filter, "sub_filter")?;
    const RESERVED: [&str; 7] = [
        "Type",
        "Filter",
        "SubFilter",
        "ByteRange",
        "Contents",
        "Reference",
        "M",
    ];
    if let Some(key) = RESERVED
        .iter()
        .find(|key| options.additional_signature_entries.contains_key(**key))
    {
        return Err(invalid(format!(
            "additional signature entry {key:?} is owned by the signing engine"
        )));
    }
    let rect = match &options.target {
        SignatureTarget::Existing { rect, .. } | SignatureTarget::New { rect, .. } => rect,
    };
    if let Some(rect) = rect {
        rect.validate()?;
    }
    appearance
        .map(|appearance| {
            let rect = rect.ok_or_else(|| {
                invalid("a custom signature appearance requires a visible target rectangle")
            })?;
            appearance.layout(rect)
        })
        .transpose()
}

fn validate_appearance(appearance: &SignatureAppearance) -> SignatureResult<()> {
    for value in appearance
        .signer_name
        .iter()
        .chain(appearance.signing_date.iter())
        .chain(appearance.text.iter())
    {
        if value.is_empty()
            || value
                .chars()
                .any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t'))
            || TextEncoding::WinAnsiEncoding.encode_strict(value).is_err()
        {
            return Err(invalid(
                "signature appearance text must be non-empty and representable in WinAnsiEncoding",
            ));
        }
    }
    if let Some(watermark) = &appearance.watermark {
        let pixels = (watermark.width as usize)
            .checked_mul(watermark.height as usize)
            .ok_or_else(|| invalid("signature watermark dimensions overflow"))?;
        let bytes = pixels
            .checked_mul(3)
            .ok_or_else(|| invalid("signature watermark byte count overflows"))?;
        if watermark.width == 0
            || watermark.height == 0
            || pixels > MAX_WATERMARK_PIXELS
            || watermark.rgb.len() != bytes
        {
            return Err(invalid(
                "signature watermark must be a bounded non-empty RGB raster",
            ));
        }
        if !watermark.opacity.is_finite() || !(0.0..=1.0).contains(&watermark.opacity) {
            return Err(invalid(
                "signature watermark opacity must be finite and between zero and one",
            ));
        }
    }
    Ok(())
}

fn signature_dictionary(options: &SignaturePreparationOptions) -> PdfDictionary {
    let mut dictionary = PdfDictionary::new();
    dictionary.insert("Type".to_string(), name("Sig"));
    dictionary.insert("Filter".to_string(), name(&options.filter));
    dictionary.insert("SubFilter".to_string(), name(&options.sub_filter));
    dictionary
        .0
        .extend(options.additional_signature_entries.0.clone());
    for (key, value) in [
        ("Reason", &options.reason),
        ("Location", &options.location),
        ("ContactInfo", &options.contact_info),
        ("M", &options.signing_time),
    ] {
        if let Some(value) = value {
            dictionary.insert(key.to_string(), text(value));
        }
    }
    let mut transforms = Vec::new();
    if let Some(permission) = options.certification {
        let mut params = PdfDictionary::new();
        params.insert("Type".to_string(), name("TransformParams"));
        params.insert("P".to_string(), PdfObject::Integer(permission as i64));
        params.insert("V".to_string(), name("1.2"));
        transforms.push(transform("DocMDP", params));
    }
    if let Some(lock) = &options.field_lock {
        let mut params = PdfDictionary::new();
        params.insert("Type".to_string(), name("TransformParams"));
        params.insert("V".to_string(), name("1.2"));
        match lock {
            FieldLock::All => {
                params.insert("Action".to_string(), name("All"));
            }
            FieldLock::Include(fields) | FieldLock::Exclude(fields) => {
                params.insert(
                    "Action".to_string(),
                    name(if matches!(lock, FieldLock::Include(_)) {
                        "Include"
                    } else {
                        "Exclude"
                    }),
                );
                params.insert(
                    "Fields".to_string(),
                    PdfObject::Array(PdfArray(fields.iter().map(|field| text(field)).collect())),
                );
            }
        }
        transforms.push(transform("FieldMDP", params));
    }
    if !transforms.is_empty() {
        dictionary.insert(
            "Reference".to_string(),
            PdfObject::Array(PdfArray(transforms)),
        );
    }
    dictionary
}

fn transform(method: &str, params: PdfDictionary) -> PdfObject {
    let mut dictionary = PdfDictionary::new();
    dictionary.insert("Type".to_string(), name("SigRef"));
    dictionary.insert("TransformMethod".to_string(), name(method));
    dictionary.insert("TransformParams".to_string(), PdfObject::Dictionary(params));
    PdfObject::Dictionary(dictionary)
}

pub(super) fn append_page_annotation(
    reader: &mut PdfReader<Cursor<&[u8]>>,
    update: &mut IncrementalUpdate<'_>,
    page_id: (u32, u16),
    original: &PdfDictionary,
    field_id: (u32, u16),
) -> SignatureResult<()> {
    let mut page = original.clone();
    let mut annotations = match page.get("Annots") {
        None => Vec::new(),
        Some(PdfObject::Array(array)) => array.0.clone(),
        Some(PdfObject::Reference(n, g)) => reader
            .get_object(*n, *g)
            .map_err(|error| invalid(error.to_string()))?
            .as_array()
            .ok_or_else(|| invalid("page /Annots reference is not an array"))?
            .0
            .clone(),
        _ => return Err(invalid("page /Annots is not an array")),
    };
    annotations.push(reference(field_id));
    page.insert(
        "Annots".to_string(),
        PdfObject::Array(PdfArray(annotations)),
    );
    update.replace(page_id, PdfObject::Dictionary(page))?;
    Ok(())
}

pub(super) fn append_acroform_field(
    reader: &mut PdfReader<Cursor<&[u8]>>,
    update: &mut IncrementalUpdate<'_>,
    catalog: &mut PdfDictionary,
    field_id: (u32, u16),
) -> SignatureResult<()> {
    let mut form = match catalog.get("AcroForm") {
        None => PdfDictionary::new(),
        Some(PdfObject::Dictionary(dictionary)) => dictionary.clone(),
        Some(PdfObject::Reference(n, g)) => {
            let id = (*n, *g);
            let mut dictionary = reader
                .get_object(*n, *g)
                .map_err(|error| invalid(error.to_string()))?
                .as_dict()
                .cloned()
                .ok_or_else(|| invalid("/AcroForm reference is not a dictionary"))?;
            append_field_array(reader, &mut dictionary, field_id)?;
            update.replace(id, PdfObject::Dictionary(dictionary))?;
            return Ok(());
        }
        _ => return Err(invalid("catalog /AcroForm is not a dictionary")),
    };
    append_field_array(reader, &mut form, field_id)?;
    form.insert("SigFlags".to_string(), PdfObject::Integer(3));
    catalog.insert("AcroForm".to_string(), PdfObject::Dictionary(form));
    Ok(())
}

fn append_field_array(
    reader: &mut PdfReader<Cursor<&[u8]>>,
    form: &mut PdfDictionary,
    field_id: (u32, u16),
) -> SignatureResult<()> {
    let mut fields = match form.get("Fields") {
        None => Vec::new(),
        Some(PdfObject::Array(array)) => array.0.clone(),
        Some(PdfObject::Reference(n, g)) => reader
            .get_object(*n, *g)
            .map_err(|error| invalid(error.to_string()))?
            .as_array()
            .ok_or_else(|| invalid("/AcroForm /Fields reference is not an array"))?
            .0
            .clone(),
        _ => return Err(invalid("/AcroForm /Fields is not an array")),
    };
    fields.push(reference(field_id));
    form.insert("Fields".to_string(), PdfObject::Array(PdfArray(fields)));
    form.insert("SigFlags".to_string(), PdfObject::Integer(3));
    Ok(())
}

pub(super) fn root_field_references(
    reader: &mut PdfReader<Cursor<&[u8]>>,
    catalog: &PdfDictionary,
) -> SignatureResult<Vec<(u32, u16)>> {
    let Some(form) = catalog.get("AcroForm") else {
        return Ok(Vec::new());
    };
    let form = match form {
        PdfObject::Dictionary(d) => d.clone(),
        PdfObject::Reference(n, g) => reader
            .get_object(*n, *g)
            .map_err(|e| invalid(e.to_string()))?
            .as_dict()
            .cloned()
            .ok_or_else(|| invalid("/AcroForm is not a dictionary"))?,
        _ => return Err(invalid("/AcroForm is not a dictionary")),
    };
    let Some(fields) = form.get("Fields") else {
        return Ok(Vec::new());
    };
    Ok(resolve_array(reader, fields, "/AcroForm /Fields")?
        .iter()
        .map(|field| {
            field
                .as_reference()
                .ok_or_else(|| invalid("/AcroForm /Fields entries must be indirect references"))
        })
        .collect::<SignatureResult<Vec<_>>>()?)
}

pub(super) fn ensure_field_name_available(
    reader: &mut PdfReader<Cursor<&[u8]>>,
    catalog: &PdfDictionary,
    name: &str,
) -> SignatureResult<()> {
    if find_named_field(reader, catalog, name)?.is_some() {
        return Err(invalid(format!("field name {name:?} already exists")));
    }
    Ok(())
}

pub(super) fn find_signature_field(
    reader: &mut PdfReader<Cursor<&[u8]>>,
    catalog: &PdfDictionary,
    name: &str,
) -> SignatureResult<(u32, u16)> {
    let field = find_named_field(reader, catalog, name)?
        .ok_or_else(|| invalid(format!("signature field {name:?} was not found")))?;
    if field.field_type.as_deref() != Some("Sig") {
        return Err(invalid("selected field is not a signature field"));
    }
    Ok(field.id)
}

fn select_widget(
    reader: &mut PdfReader<Cursor<&[u8]>>,
    field: (u32, u16),
    widget_index: Option<usize>,
) -> SignatureResult<(u32, u16)> {
    let dictionary = reader
        .get_object(field.0, field.1)
        .map_err(|error| invalid(format!("resolve signature field widgets: {error}")))?
        .as_dict()
        .cloned()
        .ok_or_else(|| invalid("signature field is not a dictionary"))?;
    let Some(index) = widget_index else {
        if dictionary
            .get("Subtype")
            .and_then(PdfObject::as_name)
            .is_some_and(|subtype| subtype.0 == "Widget")
        {
            return Ok(field);
        }
        return Err(invalid(
            "existing field is not a combined widget; specify widget_index",
        ));
    };
    let kids = dictionary
        .get("Kids")
        .ok_or_else(|| invalid("existing field has no child widgets"))?;
    let kids = resolve_array(reader, kids, "signature field /Kids")?;
    let widget = kids
        .get(index)
        .and_then(PdfObject::as_reference)
        .ok_or_else(|| invalid(format!("signature widget index {index} is out of bounds")))?;
    let widget_dictionary = reader
        .get_object(widget.0, widget.1)
        .map_err(|error| invalid(format!("resolve signature widget: {error}")))?
        .as_dict()
        .ok_or_else(|| invalid("signature widget is not a dictionary"))?;
    if widget_dictionary
        .get("Subtype")
        .and_then(PdfObject::as_name)
        .is_none_or(|subtype| subtype.0 != "Widget")
    {
        return Err(invalid("selected child is not a widget annotation"));
    }
    Ok(widget)
}

/// The timestamp value belongs to the field, so every associated widget must
/// remain invisible regardless of which widget the caller selected.
fn ensure_timestamp_widgets_invisible(
    reader: &mut PdfReader<Cursor<&[u8]>>,
    field: (u32, u16),
    widget_index: Option<usize>,
) -> SignatureResult<()> {
    // Preserve the target-selection contract, including out-of-range indices.
    let selected = select_widget(reader, field, widget_index)?;
    let dictionary = resolve_dictionary(reader, &reference(field), "timestamp field")?;
    let mut widgets = vec![selected];
    if dictionary
        .get("Subtype")
        .and_then(PdfObject::as_name)
        .is_some_and(|name| name.0 == "Widget")
        && selected != field
    {
        widgets.push(field);
    }
    if let Some(kids) = dictionary.get("Kids") {
        for child in resolve_array(reader, kids, "timestamp field /Kids")? {
            let child = child
                .as_reference()
                .ok_or_else(|| invalid("timestamp widgets must be indirect references"))?;
            if child != selected {
                widgets.push(child);
            }
        }
    }
    for widget in widgets {
        let widget = resolve_dictionary(reader, &reference(widget), "timestamp widget")?;
        if widget
            .get("Subtype")
            .and_then(PdfObject::as_name)
            .is_none_or(|name| name.0 != "Widget")
            || widget.contains_key("Kids")
        {
            return Err(invalid(
                "timestamp field children must be widget annotations",
            ));
        }
        let rect = widget
            .get("Rect")
            .ok_or_else(|| invalid("timestamp widget requires a zero rectangle"))?;
        let rect = resolve_array(reader, rect, "timestamp widget /Rect")?;
        if rect.len() != 4 || rect.iter().any(|value| value.as_real() != Some(0.0)) {
            return Err(invalid("every timestamp widget must have a zero rectangle"));
        }
    }
    Ok(())
}

#[derive(Clone, Debug)]
struct NamedField {
    id: (u32, u16),
    field_type: Option<String>,
}

fn find_named_field(
    reader: &mut PdfReader<Cursor<&[u8]>>,
    catalog: &PdfDictionary,
    wanted: &str,
) -> SignatureResult<Option<NamedField>> {
    let mut stack: Vec<_> = root_field_references(reader, catalog)?
        .into_iter()
        .map(|id| (id, String::new(), None::<String>))
        .collect();
    let mut visited = HashSet::new();
    let mut found = None;
    while let Some((id, parent_name, inherited_type)) = stack.pop() {
        if !visited.insert(id) || visited.len() > 100_000 {
            continue;
        }
        let dictionary = reader
            .get_object(id.0, id.1)
            .map_err(|e| invalid(e.to_string()))?
            .as_dict()
            .cloned()
            .ok_or_else(|| invalid("field tree node is not a dictionary"))?;
        let partial_name = dictionary
            .get("T")
            .and_then(PdfObject::as_string)
            .map(|value| value.to_text());
        let qualified_name = match (parent_name.as_str(), partial_name.as_deref()) {
            ("", Some(partial)) => partial.to_string(),
            (_, Some(partial)) => format!("{parent_name}.{partial}"),
            (_, None) => parent_name.clone(),
        };
        let field_type = dictionary
            .get("FT")
            .and_then(PdfObject::as_name)
            .map(|value| value.0.clone())
            .or(inherited_type);
        if partial_name.is_some() && qualified_name == wanted {
            if found
                .replace(NamedField {
                    id,
                    field_type: field_type.clone(),
                })
                .is_some()
            {
                return Err(invalid(format!("field identity {wanted:?} is ambiguous")));
            }
        }
        if let Some(kids) = dictionary.get("Kids") {
            for kid in resolve_array(reader, kids, "field /Kids")? {
                let kid = kid
                    .as_reference()
                    .ok_or_else(|| invalid("field /Kids entries must be indirect references"))?;
                stack.push((kid, qualified_name.clone(), field_type.clone()));
            }
        }
    }
    Ok(found)
}

pub(super) fn ensure_fieldmdp_allows_signature(
    reader: &mut PdfReader<Cursor<&[u8]>>,
    target: &str,
) -> SignatureResult<()> {
    super::permissions::ensure_field_modifications_allowed(reader, &[target])
        .map_err(|error| invalid(error.to_string()))
}

fn resolve_dictionary(
    reader: &mut PdfReader<Cursor<&[u8]>>,
    value: &PdfObject,
    role: &str,
) -> SignatureResult<PdfDictionary> {
    let value = resolve_object(reader, value, role)?;
    value
        .as_dict()
        .cloned()
        .ok_or_else(|| invalid(format!("{role} is not a dictionary")))
}

fn resolve_array(
    reader: &mut PdfReader<Cursor<&[u8]>>,
    value: &PdfObject,
    role: &str,
) -> SignatureResult<Vec<PdfObject>> {
    let value = resolve_object(reader, value, role)?;
    value
        .as_array()
        .map(|array| array.0.clone())
        .ok_or_else(|| invalid(format!("{role} is not an array")))
}

fn resolve_object(
    reader: &mut PdfReader<Cursor<&[u8]>>,
    value: &PdfObject,
    role: &str,
) -> SignatureResult<PdfObject> {
    match value {
        PdfObject::Reference(number, generation) => reader
            .get_object(*number, *generation)
            .cloned()
            .map_err(|error| invalid(format!("resolve {role}: {error}"))),
        value => Ok(value.clone()),
    }
}

fn visible_appearance(
    rect: SignatureRect,
    appearance: Option<&SignatureAppearance>,
    watermark_id: Option<(u32, u16)>,
    layout: Option<&SignatureAppearanceLayout>,
) -> PdfObject {
    let width = rect.right - rect.left;
    let height = rect.top - rect.bottom;
    let mut data = format!("q 0 0 {width} {height} re S Q\n");
    if let Some(appearance) = appearance {
        if let (Some(watermark), Some(_)) = (&appearance.watermark, watermark_id) {
            let image_width = width * 0.84;
            let image_height = height * 0.76;
            let scale =
                (image_width / watermark.width as f64).min(image_height / watermark.height as f64);
            let draw_width = watermark.width as f64 * scale;
            let draw_height = watermark.height as f64 * scale;
            let x = (width - draw_width) / 2.0;
            let y = (height - draw_height) / 2.0;
            data.push_str(&format!(
                "q /GS1 gs {draw_width} 0 0 {draw_height} {x} {y} cm /Im0 Do Q\n"
            ));
        }
        if let Some(layout) = layout {
            for (index, line) in layout.lines.iter().enumerate() {
                let y = layout.first_baseline - index as f64 * layout.line_height;
                data.push_str(&format!(
                    "BT /F1 {} Tf 0 g {} {y} Td ({}) Tj ET\n",
                    layout.font_size,
                    layout.margin,
                    appearance_text_literal(line)
                ));
            }
        }
    }

    let mut dictionary = PdfDictionary::new();
    dictionary.insert("Type".to_string(), name("XObject"));
    dictionary.insert("Subtype".to_string(), name("Form"));
    dictionary.insert(
        "BBox".to_string(),
        PdfObject::Array(PdfArray(vec![
            PdfObject::Integer(0),
            PdfObject::Integer(0),
            PdfObject::Real(width),
            PdfObject::Real(height),
        ])),
    );
    let mut resources = PdfDictionary::new();
    if appearance.is_some() {
        let mut font = PdfDictionary::new();
        font.insert("Type".to_string(), name("Font"));
        font.insert("Subtype".to_string(), name("Type1"));
        font.insert("BaseFont".to_string(), name("Helvetica"));
        font.insert("Encoding".to_string(), name("WinAnsiEncoding"));
        let mut fonts = PdfDictionary::new();
        fonts.insert("F1".to_string(), PdfObject::Dictionary(font));
        resources.insert("Font".to_string(), PdfObject::Dictionary(fonts));
    }
    if let (Some(appearance), Some(watermark_id)) = (appearance, watermark_id) {
        if appearance.watermark.is_some() {
            let mut xobjects = PdfDictionary::new();
            xobjects.insert("Im0".to_string(), reference(watermark_id));
            resources.insert("XObject".to_string(), PdfObject::Dictionary(xobjects));
            let mut state = PdfDictionary::new();
            let opacity = appearance.watermark.as_ref().unwrap().opacity as f64;
            state.insert("Type".to_string(), name("ExtGState"));
            state.insert("ca".to_string(), PdfObject::Real(opacity));
            state.insert("CA".to_string(), PdfObject::Real(opacity));
            let mut states = PdfDictionary::new();
            states.insert("GS1".to_string(), PdfObject::Dictionary(state));
            resources.insert("ExtGState".to_string(), PdfObject::Dictionary(states));
        }
    }
    dictionary.insert("Resources".to_string(), PdfObject::Dictionary(resources));
    PdfObject::Stream(PdfStream {
        dict: dictionary,
        data: data.into_bytes(),
    })
}

fn watermark_object(watermark: &SignatureWatermark) -> PdfObject {
    let mut dictionary = PdfDictionary::new();
    dictionary.insert("Type".to_string(), name("XObject"));
    dictionary.insert("Subtype".to_string(), name("Image"));
    dictionary.insert(
        "Width".to_string(),
        PdfObject::Integer(watermark.width as i64),
    );
    dictionary.insert(
        "Height".to_string(),
        PdfObject::Integer(watermark.height as i64),
    );
    dictionary.insert("ColorSpace".to_string(), name("DeviceRGB"));
    dictionary.insert("BitsPerComponent".to_string(), PdfObject::Integer(8));
    PdfObject::Stream(PdfStream {
        dict: dictionary,
        data: watermark.rgb.clone(),
    })
}

fn appearance_text_literal(value: &str) -> String {
    let encoded = TextEncoding::WinAnsiEncoding
        .encode_strict(value)
        .expect("appearance text was validated before rendering");
    escape_pdf_string_literal(&encoded)
}

fn locate_and_patch_placeholders(
    mut pdf: Vec<u8>,
    base_len: usize,
    placeholder_bytes: usize,
) -> SignatureResult<PreparedSignature> {
    let marker = format!("<{}>", "A5".repeat(placeholder_bytes));
    let appended = pdf
        .get(base_len..)
        .ok_or_else(|| invalid("incremental revision is shorter than its source"))?;
    let contents_start =
        base_len + find_unique(appended, marker.as_bytes(), "/Contents placeholder")?;
    let contents_end = contents_start + marker.len();
    let ranges = [
        0u64,
        contents_start as u64,
        contents_end as u64,
        (pdf.len() - contents_end) as u64,
    ];
    let sentinel = BYTE_RANGE_SENTINEL.to_string();
    let locations: Vec<_> = find_all(&pdf[base_len..], sentinel.as_bytes())
        .into_iter()
        .map(|location| base_len + location)
        .collect();
    if locations.len() != 3 {
        return Err(invalid(
            "could not locate the three ByteRange placeholders uniquely",
        ));
    }
    for (location, value) in locations.into_iter().zip(ranges[1..].iter()) {
        let encoded = format!("{value:0BYTE_RANGE_WIDTH$}");
        if encoded.len() != BYTE_RANGE_WIDTH {
            return Err(invalid("PDF offsets exceed the reserved ByteRange width"));
        }
        pdf[location..location + BYTE_RANGE_WIDTH].copy_from_slice(encoded.as_bytes());
    }
    Ok(PreparedSignature {
        pdf,
        byte_range: super::ByteRange::new(vec![(0, ranges[1]), (ranges[2], ranges[3])]),
        contents_hex: contents_start + 1..contents_end - 1,
        placeholder_bytes,
    })
}

fn validate_cms_container(cms: &[u8]) -> SignatureResult<()> {
    if cms.len() < 2 || cms[0] != 0x30 {
        return Err(SignatureError::CmsParsingFailed {
            details: "CMS must be a non-empty DER SEQUENCE".to_string(),
        });
    }
    let (header, content_len) = if cms[1] & 0x80 == 0 {
        (2, cms[1] as usize)
    } else {
        let count = (cms[1] & 0x7f) as usize;
        if count == 0 || count > 8 || cms.len() < 2 + count {
            return Err(SignatureError::CmsParsingFailed {
                details: "invalid DER length".to_string(),
            });
        }
        let mut length = 0usize;
        for byte in &cms[2..2 + count] {
            length = length
                .checked_mul(256)
                .and_then(|v| v.checked_add(*byte as usize))
                .ok_or_else(|| SignatureError::CmsParsingFailed {
                    details: "DER length overflow".to_string(),
                })?;
        }
        (2 + count, length)
    };
    if header.checked_add(content_len) != Some(cms.len()) {
        return Err(SignatureError::CmsParsingFailed {
            details: "DER sequence length does not match CMS size".to_string(),
        });
    }
    Ok(())
}

fn find_unique(haystack: &[u8], needle: &[u8], role: &str) -> SignatureResult<usize> {
    let matches = find_all(haystack, needle);
    if matches.len() != 1 {
        return Err(invalid(format!("{role} occurs {} times", matches.len())));
    }
    Ok(matches[0])
}
fn find_all(haystack: &[u8], needle: &[u8]) -> Vec<usize> {
    haystack
        .windows(needle.len())
        .enumerate()
        .filter_map(|(index, value)| (value == needle).then_some(index))
        .collect()
}
pub(super) fn reference(id: (u32, u16)) -> PdfObject {
    PdfObject::Reference(id.0, id.1)
}
pub(super) fn name(value: &str) -> PdfObject {
    PdfObject::Name(PdfName::new(value.to_string()))
}
pub(super) fn text(value: &str) -> PdfObject {
    PdfObject::String(PdfString::new(value.as_bytes().to_vec()))
}
pub(super) fn invalid(details: impl Into<String>) -> SignatureError {
    SignatureError::InvalidSignatureDict {
        details: details.into(),
    }
}

fn validate_pdf_name(value: &str, role: &str) -> SignatureResult<()> {
    if value.is_empty()
        || value.bytes().any(|byte| {
            byte.is_ascii_whitespace()
                || matches!(
                    byte,
                    b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%' | b'#'
                )
        })
    {
        return Err(invalid(format!("{role} is not a safe PDF name")));
    }
    Ok(())
}

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

    fn pdf_with_unused_zero_offset_entry(in_use: bool, docmdp_points_to_entry: bool) -> Vec<u8> {
        let catalog = if docmdp_points_to_entry {
            "<< /Type /Catalog /Pages 2 0 R /Perms << /DocMDP 4 0 R >> >>"
        } else {
            "<< /Type /Catalog /Pages 2 0 R >>"
        };
        let mut pdf = b"%PDF-1.7\n".to_vec();
        let mut offsets = Vec::new();
        for (index, body) in [
            catalog,
            "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
            "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> >>",
        ]
        .iter()
        .enumerate()
        {
            offsets.push(pdf.len());
            pdf.extend_from_slice(format!("{} 0 obj\n{}\nendobj\n", index + 1, body).as_bytes());
        }
        let xref = pdf.len();
        pdf.extend_from_slice(b"xref\n0 5\n0000000000 65535 f \n");
        for offset in offsets {
            pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
        }
        pdf.extend_from_slice(if in_use {
            b"0000000000 00000 n \n"
        } else {
            b"0000000000 00000 f \n"
        });
        pdf.extend_from_slice(
            format!("trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n").as_bytes(),
        );
        pdf
    }

    #[test]
    fn incremental_signature_ignores_unreferenced_in_use_zero_offset_entry() {
        let options = SignaturePreparationOptions::invisible("Signature");
        assert!(prepare_incremental_signature(
            &pdf_with_unused_zero_offset_entry(true, false),
            &options,
        )
        .is_ok());
    }

    #[test]
    fn incremental_signature_accepts_free_zero_offset_entry_control() {
        let options = SignaturePreparationOptions::invisible("Signature");
        assert!(prepare_incremental_signature(
            &pdf_with_unused_zero_offset_entry(false, false),
            &options,
        )
        .is_ok());
    }

    #[test]
    fn incremental_signature_rejects_docmdp_reference_to_zero_offset_entry() {
        let options = SignaturePreparationOptions::invisible("Signature");
        let error =
            prepare_incremental_signature(&pdf_with_unused_zero_offset_entry(true, true), &options)
                .expect_err("a DocMDP reference to a zero-offset entry must be rejected");
        assert!(error
            .to_string()
            .contains("resolve certification signature"));
    }
}