printwell-sys 0.1.3

Low-level FFI bindings for Printwell using cxx
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
//! Low-level FFI bindings for printwell.
//!
//! This crate provides the cxx bridge between Rust and the native C++ library
//! that wraps Chromium's rendering components (Blink, Skia, `PDFium`).

// Allow unsafe code warnings in this crate - the cxx bridge inherently uses unsafe FFI
#![allow(unsafe_code)]
// Allow clippy warnings that can't be fixed in cxx::bridge blocks
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::must_use_candidate)]
#![allow(clippy::derivable_impls)] // cxx structs can't derive Default
#![warn(missing_docs)]

pub use ffi::*;

/// FFI bridge module generated by cxx.
///
/// This module contains all the type definitions and function declarations
/// that bridge Rust and C++ code.
#[cxx::bridge(namespace = "printwell")]
pub mod ffi {
    // ========================================================================
    // Shared structs
    // ========================================================================

    /// PDF metadata for document properties
    #[derive(Debug, Clone)]
    pub struct PdfMetadata {
        /// Document title
        pub title: String,
        /// Document author
        pub author: String,
        /// Document subject
        pub subject: String,
        /// Document keywords (comma-separated)
        pub keywords: String,
        /// Creating application name
        pub creator: String,
        /// PDF producer name
        pub producer: String,
    }

    /// PDF generation options
    #[derive(Debug, Clone)]
    pub struct PdfOptions {
        /// Page width in millimeters
        pub page_width_mm: f64,
        /// Page height in millimeters
        pub page_height_mm: f64,
        /// Top margin in millimeters
        pub margin_top_mm: f64,
        /// Right margin in millimeters
        pub margin_right_mm: f64,
        /// Bottom margin in millimeters
        pub margin_bottom_mm: f64,
        /// Left margin in millimeters
        pub margin_left_mm: f64,
        /// Print background colors and images
        pub print_background: bool,
        /// Use landscape orientation
        pub landscape: bool,
        /// Scale factor (0.1 to 2.0)
        pub scale: f64,
        /// Prefer CSS @page size
        pub prefer_css_page_size: bool,
        /// Header HTML template
        pub header_template: String,
        /// Footer HTML template
        pub footer_template: String,
        /// Page ranges (e.g., "1-5,8")
        pub page_ranges: String,
        /// PDF document metadata
        pub metadata: PdfMetadata,
    }

    /// Render options
    #[derive(Debug, Clone)]
    pub struct RenderOptions {
        /// Base URL for resolving relative resources
        pub base_url: String,
        /// Enable JavaScript execution
        pub javascript_enabled: bool,
        /// Script execution timeout in milliseconds
        pub script_timeout_ms: u32,
        /// User stylesheets to inject
        pub user_stylesheets: Vec<String>,
        /// User scripts to inject
        pub user_scripts: Vec<String>,
        /// Viewport width in pixels
        pub viewport_width: u32,
        /// Viewport height in pixels
        pub viewport_height: u32,
        /// Device scale factor
        pub device_scale_factor: f64,
        /// Resource loading options
        pub resource_options: ResourceOptions,
        /// Font configuration
        pub font_config: FontConfig,
    }

    /// Resource loading options
    #[derive(Debug, Clone)]
    pub struct ResourceOptions {
        /// Allow loading remote resources (images, CSS, etc.)
        pub allow_remote_resources: bool,
        /// Timeout for resource loading in milliseconds
        pub resource_timeout_ms: u32,
        /// Maximum concurrent resource requests
        pub max_concurrent_requests: u32,
        /// Block resources from these domains
        pub blocked_domains: Vec<String>,
        /// Only allow resources from these domains (empty = all allowed)
        pub allowed_domains: Vec<String>,
        /// Block specific resource types
        pub block_images: bool,
        /// Block external stylesheets
        pub block_stylesheets: bool,
        /// Block external scripts
        pub block_scripts: bool,
        /// Block web fonts
        pub block_fonts: bool,
        /// Custom User-Agent header
        pub user_agent: String,
        /// Additional HTTP headers for resource requests
        pub extra_headers: Vec<HttpHeader>,
        /// Enable resource caching
        pub enable_cache: bool,
        /// Cache directory path (empty = memory cache only)
        pub cache_path: String,
    }

    /// HTTP header key-value pair
    #[derive(Debug, Clone)]
    pub struct HttpHeader {
        /// Header name
        pub name: String,
        /// Header value
        pub value: String,
    }

    /// Font configuration
    #[derive(Debug, Clone)]
    pub struct FontConfig {
        /// Custom font files to load (path -> family name mapping)
        pub custom_fonts: Vec<CustomFont>,
        /// Default font family for sans-serif
        pub default_sans_serif: String,
        /// Default font family for serif
        pub default_serif: String,
        /// Default font family for monospace
        pub default_monospace: String,
        /// Default font family for cursive
        pub default_cursive: String,
        /// Default font family for fantasy
        pub default_fantasy: String,
        /// Minimum font size in pixels
        pub minimum_font_size: u32,
        /// Default font size in pixels
        pub default_font_size: u32,
        /// Default fixed font size in pixels
        pub default_fixed_font_size: u32,
        /// Enable system fonts
        pub use_system_fonts: bool,
        /// Enable web fonts (@font-face)
        pub enable_web_fonts: bool,
        /// Embed fonts in PDF
        pub embed_fonts: bool,
        /// Subset fonts to reduce PDF size
        pub subset_fonts: bool,
    }

    /// Custom font definition
    #[derive(Debug, Clone)]
    pub struct CustomFont {
        /// Font family name to use in CSS
        pub family: String,
        /// Font file data (TTF/OTF/WOFF/WOFF2)
        pub data: Vec<u8>,
        /// Font weight (100-900, 0 = normal)
        pub weight: u32,
        /// Font style: normal, italic, oblique
        pub style: String,
    }

    /// Renderer information
    #[derive(Debug, Clone)]
    pub struct RendererInfo {
        /// Printwell version string
        pub printwell_version: String,
        /// Chromium version string
        pub chromium_version: String,
        /// Skia version string
        pub skia_version: String,
        /// Build configuration (debug/release)
        pub build_config: String,
    }

    /// Element boundary in rendered PDF
    #[derive(Debug, Clone)]
    pub struct Boundary {
        /// CSS selector that matched
        pub selector: String,
        /// Match index (0-based)
        pub index: u32,
        /// Page number (1-based)
        pub page: u32,
        /// X coordinate in PDF points
        pub x: f64,
        /// Y coordinate in PDF points
        pub y: f64,
        /// Width in PDF points
        pub width: f64,
        /// Height in PDF points
        pub height: f64,
    }

    /// Render result with boundaries
    #[derive(Debug)]
    pub struct RenderResult {
        /// PDF data
        pub pdf_data: Vec<u8>,
        /// Page count
        pub page_count: u32,
        /// Element boundaries
        pub boundaries: Vec<Boundary>,
    }

    // ========================================================================
    // Forms feature types
    // ========================================================================

    /// Text field definition
    #[derive(Debug, Clone)]
    pub struct TextFieldDef {
        /// Field name
        pub name: String,
        /// Page number (1-based)
        pub page: u32,
        /// X coordinate in points
        pub x: f64,
        /// Y coordinate in points
        pub y: f64,
        /// Width in points
        pub width: f64,
        /// Height in points
        pub height: f64,
        /// Default value
        pub default_value: String,
        /// Maximum character length (0 = unlimited)
        pub max_length: u32,
        /// Allow multiple lines
        pub multiline: bool,
        /// Password field
        pub password: bool,
        /// Required field
        pub required: bool,
        /// Read-only field
        pub read_only: bool,
        /// Font size in points
        pub font_size: f64,
        /// Font name
        pub font_name: String,
    }

    /// Checkbox definition
    #[derive(Debug, Clone)]
    pub struct CheckboxDef {
        /// Field name
        pub name: String,
        /// Page number (1-based)
        pub page: u32,
        /// X coordinate in points
        pub x: f64,
        /// Y coordinate in points
        pub y: f64,
        /// Size (width and height) in points
        pub size: f64,
        /// Initially checked
        pub checked: bool,
        /// Export value when checked
        pub export_value: String,
    }

    /// Dropdown definition
    #[derive(Debug, Clone)]
    pub struct DropdownDef {
        /// Field name
        pub name: String,
        /// Page number (1-based)
        pub page: u32,
        /// X coordinate in points
        pub x: f64,
        /// Y coordinate in points
        pub y: f64,
        /// Width in points
        pub width: f64,
        /// Height in points
        pub height: f64,
        /// Available options
        pub options: Vec<String>,
        /// Selected index (-1 for none)
        pub selected_index: i32,
        /// Allow custom text entry
        pub editable: bool,
    }

    /// Signature field definition
    #[derive(Debug, Clone)]
    pub struct SignatureFieldDef {
        /// Field name
        pub name: String,
        /// Page number (1-based)
        pub page: u32,
        /// X coordinate in points
        pub x: f64,
        /// Y coordinate in points
        pub y: f64,
        /// Width in points
        pub width: f64,
        /// Height in points
        pub height: f64,
    }

    /// Radio button definition
    #[derive(Debug, Clone)]
    pub struct RadioButtonDef {
        /// Field name
        pub name: String,
        /// Radio button group name
        pub group: String,
        /// Page number (1-based)
        pub page: u32,
        /// X coordinate in points
        pub x: f64,
        /// Y coordinate in points
        pub y: f64,
        /// Size (width and height) in points
        pub size: f64,
        /// Initially selected
        pub selected: bool,
        /// Export value when selected
        pub export_value: String,
        /// Required field
        pub required: bool,
        /// Read-only field
        pub read_only: bool,
    }

    /// Detected form element type
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    #[repr(i32)]
    pub enum FormElementType {
        /// Not a form element
        None = 0,
        /// Text input field
        TextField = 1,
        /// Checkbox
        Checkbox = 2,
        /// Radio button
        RadioButton = 3,
        /// Dropdown/select
        Dropdown = 4,
        /// Signature field
        Signature = 5,
    }

    /// Form element detected in HTML
    #[derive(Debug, Clone)]
    pub struct FormElementInfo {
        /// Element type
        pub element_type: i32,
        /// Element ID
        pub id: String,
        /// Element name
        pub name: String,
        /// Page number (1-based)
        pub page: u32,
        /// X coordinate in CSS pixels
        pub x: f64,
        /// Y coordinate in CSS pixels
        pub y: f64,
        /// Width in CSS pixels
        pub width: f64,
        /// Height in CSS pixels
        pub height: f64,
        /// Required attribute
        pub required: bool,
        /// Readonly attribute
        pub readonly: bool,
        /// Disabled attribute
        pub disabled: bool,
        /// Default value (text fields)
        pub default_value: String,
        /// Placeholder text
        pub placeholder: String,
        /// Max length (0 = unlimited)
        pub max_length: u32,
        /// Checked state (checkbox/radio)
        pub checked: bool,
        /// Export value (checkbox/radio)
        pub export_value: String,
        /// Radio group name
        pub radio_group: String,
        /// Dropdown options (comma-separated)
        pub options: String,
        /// Selected index (-1 = none)
        pub selected_index: i32,
        /// Multiline text field
        pub multiline: bool,
        /// Password field
        pub password: bool,
        /// Font size in points
        pub font_size: f64,
    }

    /// Render result with form elements
    #[derive(Debug)]
    pub struct RenderResultWithForms {
        /// PDF data
        pub pdf_data: Vec<u8>,
        /// Page count
        pub page_count: u32,
        /// Element boundaries
        pub boundaries: Vec<Boundary>,
        /// Detected form elements
        pub form_elements: Vec<FormElementInfo>,
    }

    // ========================================================================
    // Signing feature types
    // ========================================================================

    /// Signing options
    #[derive(Debug, Clone)]
    pub struct SigningOptions {
        /// Reason for signing
        pub reason: String,
        /// Location of signing
        pub location: String,
        /// Contact information
        pub contact_info: String,
        /// Signature level (B, T, LT, LTA)
        pub signature_level: String,
        /// Timestamp server URL (for T, LT, LTA)
        pub timestamp_url: String,
    }

    /// Visible signature appearance
    #[derive(Debug, Clone)]
    pub struct VisibleSignature {
        /// Signature field name
        pub field_name: String,
        /// Page number (1-based)
        pub page: u32,
        /// X coordinate in points
        pub x: f64,
        /// Y coordinate in points
        pub y: f64,
        /// Width in points
        pub width: f64,
        /// Height in points
        pub height: f64,
        /// Show signer name
        pub show_name: bool,
        /// Show signing date
        pub show_date: bool,
        /// Show reason
        pub show_reason: bool,
        /// Background image data (PNG/JPEG)
        pub background_image: Vec<u8>,
    }

    /// Signature verification information
    #[derive(Debug, Clone)]
    pub struct SignatureInfo {
        /// Signer name
        pub signer_name: String,
        /// Signing time
        pub signing_time: String,
        /// Reason for signing
        pub reason: String,
        /// Location
        pub location: String,
        /// Whether signature is valid
        pub is_valid: bool,
        /// Whether signature covers whole document
        pub covers_whole_document: bool,
    }

    /// Prepared PDF signature (result of preparing PDF for signing)
    #[derive(Debug, Clone)]
    pub struct PreparedSignature {
        /// PDF data with signature placeholder
        pub pdf_data: Vec<u8>,
        /// Byte range array [offset1, len1, offset2, len2]
        pub byte_range: Vec<i64>,
        /// Offset where signature contents should be written
        pub contents_offset: u64,
        /// Maximum length of signature contents (hex-encoded)
        pub contents_length: u64,
    }

    /// Signing field definition for preparing signature
    #[derive(Debug, Clone)]
    pub struct SigningFieldDef {
        /// Field name
        pub field_name: String,
        /// Reason for signing
        pub reason: String,
        /// Location of signing
        pub location: String,
        /// Contact info
        pub contact_info: String,
        /// Page number (1-based, 0 = last page)
        pub page: u32,
        /// X coordinate in points (for visible signature)
        pub x: f64,
        /// Y coordinate in points
        pub y: f64,
        /// Width in points (0 = invisible)
        pub width: f64,
        /// Height in points
        pub height: f64,
    }

    /// Existing signature data extracted from PDF
    #[derive(Debug, Clone)]
    pub struct PdfSignatureData {
        /// CMS/PKCS#7 signature contents (DER encoded)
        pub contents: Vec<u8>,
        /// Byte range [offset1, len1, offset2, len2]
        pub byte_range: Vec<i64>,
        /// SubFilter (e.g., "adbe.pkcs7.detached")
        pub sub_filter: String,
        /// Reason for signing
        pub reason: String,
        /// Location
        pub location: String,
        /// Signing time (PDF date format)
        pub signing_time: String,
        /// Signer name (from certificate, if extracted)
        pub signer_name: String,
    }

    /// Signature field information (for listing existing fields)
    #[derive(Debug, Clone)]
    pub struct SignatureFieldInfo {
        /// Field name
        pub name: String,
        /// Page number (1-based)
        pub page: u32,
        /// X coordinate in points
        pub x: f64,
        /// Y coordinate in points
        pub y: f64,
        /// Width in points
        pub width: f64,
        /// Height in points
        pub height: f64,
        /// Whether the field is already signed
        pub is_signed: bool,
    }

    // ========================================================================
    // Opaque C++ types
    // ========================================================================

    unsafe extern "C++" {
        include!("printwell/ffi.h");

        /// Opaque renderer type
        type Renderer;

        // --------------------------------------------------------------------
        // Renderer functions
        // --------------------------------------------------------------------

        /// Create a new renderer instance
        fn renderer_create() -> Result<UniquePtr<Renderer>>;

        /// Get renderer information
        fn renderer_info(renderer: &Renderer) -> RendererInfo;

        /// Render HTML to PDF
        fn renderer_render_html(
            renderer: Pin<&mut Renderer>,
            html: &str,
            render_options: &RenderOptions,
            pdf_options: &PdfOptions,
        ) -> Result<Vec<u8>>;

        /// Render HTML to PDF with boundary extraction
        fn renderer_render_html_with_boundaries(
            renderer: Pin<&mut Renderer>,
            html: &str,
            render_options: &RenderOptions,
            pdf_options: &PdfOptions,
            selectors: &Vec<String>,
        ) -> Result<RenderResult>;

        /// Render HTML to PDF with form element detection
        fn renderer_render_html_with_forms(
            renderer: Pin<&mut Renderer>,
            html: &str,
            render_options: &RenderOptions,
            pdf_options: &PdfOptions,
            selectors: &Vec<String>,
        ) -> Result<RenderResultWithForms>;

        /// Render URL to PDF
        fn renderer_render_url(
            renderer: Pin<&mut Renderer>,
            url: &str,
            render_options: &RenderOptions,
            pdf_options: &PdfOptions,
        ) -> Result<Vec<u8>>;

        /// Shutdown the renderer
        fn renderer_shutdown(renderer: Pin<&mut Renderer>);

        // --------------------------------------------------------------------
        // Resource cache functions (for Rust-delegated resource fetching)
        // --------------------------------------------------------------------

        /// Register a resource in the cache (call before rendering)
        fn resource_cache_register(url: &str, data: &[u8]);

        /// Clear all cached resources
        fn resource_cache_clear();

        /// Check if a URL is in the cache
        fn resource_cache_has(url: &str) -> bool;

        // --------------------------------------------------------------------
        // UA stylesheet (User Agent default styles)
        // --------------------------------------------------------------------

        /// Set the User Agent stylesheet CSS (must be called before renderer_create)
        fn set_ua_stylesheet(css: &str);
    }

    // ========================================================================
    // Resource fetching callback (Rust functions called from C++)
    // ========================================================================

    /// Resource fetch result returned from Rust to C++
    #[derive(Debug, Clone)]
    pub struct ResourceFetchResult {
        /// Whether the fetch was successful
        pub success: bool,
        /// Resource data (empty if failed)
        pub data: Vec<u8>,
        /// Content type (MIME type)
        pub content_type: String,
        /// Error message (if failed)
        pub error: String,
    }

    extern "Rust" {
        /// Fetch a resource from a URL.
        /// Called by C++ when Blink needs to load a resource.
        /// The Rust implementation handles the actual HTTP request.
        fn rust_fetch_resource(url: &str) -> ResourceFetchResult;
    }

    // ========================================================================
    // Encryption feature (conditionally compiled in C++)
    // ========================================================================

    #[cfg(feature = "encrypt")]
    unsafe extern "C++" {
        include!("printwell/ffi.h");

        /// Decrypt a password-protected PDF.
        /// Returns the decrypted PDF data without password protection.
        fn pdf_decrypt(pdf_data: &[u8], password: &str) -> Result<Vec<u8>>;
    }

    // ========================================================================
    // Watermark feature (conditionally compiled in C++)
    // ========================================================================

    /// Watermark definition for FFI
    #[derive(Debug, Clone)]
    pub struct WatermarkDef {
        /// Text content (empty if image watermark)
        pub text: String,
        /// Image data (empty if text watermark)
        pub image: Vec<u8>,
        /// X position (for custom position)
        pub x: f32,
        /// Y position (for custom position)
        pub y: f32,
        /// Rotation in degrees
        pub rotation: f32,
        /// Opacity (0.0 - 1.0)
        pub opacity: f32,
        /// Font size for text
        pub font_size: f32,
        /// Font name for text
        pub font_name: String,
        /// Color as ARGB u32
        pub color: u32,
        /// Whether to place behind content
        pub behind_content: bool,
        /// Pages to watermark (empty = all, special values: -1=odd, -2=even, -3=first, -4=last)
        pub pages: Vec<i32>,
        /// Position type (0=center, 1=top-left, etc., 9=custom)
        pub position_type: i32,
        /// Custom X position
        pub custom_x: f32,
        /// Custom Y position
        pub custom_y: f32,
        /// Scale factor
        pub scale: f32,
    }

    #[cfg(feature = "watermark")]
    unsafe extern "C++" {
        include!("printwell/ffi.h");

        /// Add a watermark to all (or selected) pages of a PDF.
        fn pdf_add_watermark(pdf_data: &[u8], watermark: &WatermarkDef) -> Result<Vec<u8>>;
    }

    // ========================================================================
    // Bookmarks feature (conditionally compiled in C++)
    // ========================================================================

    /// Bookmark definition for FFI
    #[derive(Debug, Clone)]
    pub struct BookmarkDef {
        /// Bookmark title
        pub title: String,
        /// Target page (1-indexed)
        pub page: i32,
        /// Y position on page (negative means top of page)
        pub y_position: f64,
        /// Parent bookmark index (-1 for root)
        pub parent_index: i32,
        /// Whether bookmark is initially open
        pub open: bool,
    }

    #[cfg(feature = "bookmarks")]
    unsafe extern "C++" {
        include!("printwell/ffi.h");

        /// Add bookmarks to a PDF document.
        fn pdf_add_bookmarks(pdf_data: &[u8], bookmarks: &[BookmarkDef]) -> Result<Vec<u8>>;

        /// Extract existing bookmarks from a PDF.
        fn pdf_get_bookmarks(pdf_data: &[u8]) -> Result<Vec<BookmarkDef>>;
    }

    // ========================================================================
    // Annotations feature (conditionally compiled in C++)
    // ========================================================================

    /// Annotation definition for FFI
    #[derive(Debug, Clone)]
    pub struct AnnotationDef {
        /// Annotation type (PDFium constant)
        pub annotation_type: i32,
        /// Target page (1-indexed)
        pub page: i32,
        /// X coordinate
        pub x: f32,
        /// Y coordinate
        pub y: f32,
        /// Width
        pub width: f32,
        /// Height
        pub height: f32,
        /// Color as RGBA u32
        pub color: u32,
        /// Opacity (0.0 - 1.0)
        pub opacity: f32,
        /// Note contents
        pub contents: String,
        /// Author
        pub author: String,
        /// Text (for FreeText annotations)
        pub text: String,
        /// Font size (for FreeText)
        pub font_size: f32,
    }

    #[cfg(feature = "annotations")]
    unsafe extern "C++" {
        include!("printwell/ffi.h");

        /// Add annotations to a PDF document.
        fn pdf_add_annotations(pdf_data: &[u8], annotations: &[AnnotationDef]) -> Result<Vec<u8>>;

        /// List existing annotations in a PDF.
        fn pdf_list_annotations(pdf_data: &[u8]) -> Result<Vec<AnnotationDef>>;

        /// Remove annotations from a PDF.
        fn pdf_remove_annotations(pdf_data: &[u8], page: i32, types: &[i32]) -> Result<Vec<u8>>;
    }

    // ========================================================================
    // PDF/A feature (conditionally compiled in C++)
    // ========================================================================

    /// PDF/A metadata definition for FFI
    #[derive(Debug, Clone)]
    pub struct PdfAMetadataDef {
        /// PDF/A level (1, 2, or 3)
        pub level: i32,
        /// Conformance (A, B, or U)
        pub conformance: String,
        /// Document title
        pub title: String,
        /// Document author
        pub author: String,
        /// XMP metadata string
        pub xmp_data: String,
    }

    #[cfg(feature = "pdfa")]
    unsafe extern "C++" {
        include!("printwell/ffi.h");

        /// Add PDF/A metadata to a PDF document.
        fn pdf_add_pdfa_metadata(pdf_data: &[u8], metadata: &PdfAMetadataDef) -> Result<Vec<u8>>;
    }

    // ========================================================================
    // PDF/UA feature (conditionally compiled in C++)
    // ========================================================================

    /// PDF/UA metadata definition for FFI
    #[derive(Debug, Clone)]
    pub struct PdfUAMetadataDef {
        /// PDF/UA part number (1 or 2)
        pub part: i32,
        /// Document language (BCP 47 format)
        pub language: String,
        /// Document title
        pub title: String,
        /// XMP metadata string
        pub xmp_data: String,
    }

    #[cfg(feature = "pdfua")]
    unsafe extern "C++" {
        include!("printwell/ffi.h");

        /// Add PDF/UA metadata to a PDF document.
        fn pdf_add_pdfua_metadata(pdf_data: &[u8], metadata: &PdfUAMetadataDef) -> Result<Vec<u8>>;
    }

    // ========================================================================
    // Forms feature (conditionally compiled in C++)
    // ========================================================================

    #[cfg(feature = "forms")]
    unsafe extern "C++" {
        include!("printwell/forms_ffi.h");

        /// Opaque PDF document type for forms
        type PdfDocument;

        /// Open a PDF document
        fn pdf_open(data: &[u8]) -> Result<UniquePtr<PdfDocument>>;

        /// Add a text field
        fn pdf_add_text_field(doc: Pin<&mut PdfDocument>, field: &TextFieldDef) -> Result<()>;

        /// Add a checkbox
        fn pdf_add_checkbox(doc: Pin<&mut PdfDocument>, field: &CheckboxDef) -> Result<()>;

        /// Add a dropdown
        fn pdf_add_dropdown(doc: Pin<&mut PdfDocument>, field: &DropdownDef) -> Result<()>;

        /// Add a signature field
        fn pdf_add_signature_field(
            doc: Pin<&mut PdfDocument>,
            field: &SignatureFieldDef,
        ) -> Result<()>;

        /// Add a radio button
        fn pdf_add_radio_button(doc: Pin<&mut PdfDocument>, field: &RadioButtonDef) -> Result<()>;

        /// Apply detected form elements to PDF
        fn pdf_apply_form_elements(
            doc: Pin<&mut PdfDocument>,
            elements: &Vec<FormElementInfo>,
        ) -> Result<u32>;

        /// Save the PDF document
        fn pdf_save(doc: &PdfDocument) -> Result<Vec<u8>>;

        /// Get page count
        fn pdf_page_count(doc: &PdfDocument) -> u32;
    }

    // ========================================================================
    // Signing feature (conditionally compiled in C++)
    // ========================================================================

    #[cfg(feature = "signing")]
    unsafe extern "C++" {
        include!("printwell/signing_ffi.h");

        // --------------------------------------------------------------------
        // New PDF-centric signing API (crypto in Rust, PDF ops in C++)
        // --------------------------------------------------------------------

        /// Prepare a PDF for signing by adding a signature placeholder.
        /// Returns the modified PDF with byte range info for hashing.
        fn pdf_prepare_signature(
            pdf_data: &[u8],
            field: &SigningFieldDef,
            estimated_sig_size: u32,
        ) -> Result<PreparedSignature>;

        /// Get the data to be signed based on byte ranges.
        /// This extracts the bytes that need to be hashed for signing.
        fn pdf_get_data_to_sign(pdf_data: &[u8], byte_range: &[i64]) -> Result<Vec<u8>>;

        /// Embed a pre-computed signature (CMS blob) into the PDF.
        /// The signature is hex-encoded and placed at contents_offset.
        fn pdf_embed_signature(
            pdf_data: &[u8],
            signature: &[u8],
            contents_offset: u64,
            contents_length: u64,
        ) -> Result<Vec<u8>>;

        /// Extract existing signatures from a PDF for verification.
        fn pdf_get_signature_data(pdf_data: &[u8]) -> Result<Vec<PdfSignatureData>>;

        /// List existing signature fields in a PDF (including unsigned ones).
        fn pdf_list_signature_fields(pdf_data: &[u8]) -> Result<Vec<SignatureFieldInfo>>;

        /// Sign into an existing signature field.
        fn pdf_prepare_signature_in_field(
            pdf_data: &[u8],
            field_name: &str,
            estimated_sig_size: u32,
        ) -> Result<PreparedSignature>;

        /// Prepare a certification signature with MDP permissions.
        /// mdp_permissions: 1 = no changes, 2 = form fill/sign, 3 = annotations too
        fn pdf_prepare_certification_signature(
            pdf_data: &[u8],
            field: &SigningFieldDef,
            estimated_sig_size: u32,
            mdp_permissions: u32,
        ) -> Result<PreparedSignature>;
    }
}

// ============================================================================
// Helper implementations
// ============================================================================

impl Default for PdfMetadata {
    fn default() -> Self {
        Self {
            title: String::new(),
            author: String::new(),
            subject: String::new(),
            keywords: String::new(),
            creator: "printwell".to_string(),
            producer: "printwell".to_string(),
        }
    }
}

impl Default for PdfOptions {
    fn default() -> Self {
        Self {
            page_width_mm: 210.0, // A4
            page_height_mm: 297.0,
            margin_top_mm: 10.0,
            margin_right_mm: 10.0,
            margin_bottom_mm: 10.0,
            margin_left_mm: 10.0,
            print_background: true,
            landscape: false,
            scale: 1.0,
            prefer_css_page_size: false,
            header_template: String::new(),
            footer_template: String::new(),
            page_ranges: String::new(),
            metadata: PdfMetadata::default(),
        }
    }
}

impl Default for RenderOptions {
    fn default() -> Self {
        Self {
            base_url: String::new(),
            javascript_enabled: true,
            script_timeout_ms: 30000,
            user_stylesheets: Vec::new(),
            user_scripts: Vec::new(),
            viewport_width: 1280,
            viewport_height: 720,
            device_scale_factor: 1.0,
            resource_options: ResourceOptions::default(),
            font_config: FontConfig::default(),
        }
    }
}

impl Default for ResourceOptions {
    fn default() -> Self {
        Self {
            allow_remote_resources: true,
            resource_timeout_ms: 30000,
            max_concurrent_requests: 6,
            blocked_domains: Vec::new(),
            allowed_domains: Vec::new(),
            block_images: false,
            block_stylesheets: false,
            block_scripts: false,
            block_fonts: false,
            user_agent: String::new(),
            extra_headers: Vec::new(),
            enable_cache: true,
            cache_path: String::new(),
        }
    }
}

impl Default for HttpHeader {
    fn default() -> Self {
        Self {
            name: String::new(),
            value: String::new(),
        }
    }
}

impl Default for FontConfig {
    fn default() -> Self {
        Self {
            custom_fonts: Vec::new(),
            default_sans_serif: "Arial".to_string(),
            default_serif: "Times New Roman".to_string(),
            default_monospace: "Courier New".to_string(),
            default_cursive: "Comic Sans MS".to_string(),
            default_fantasy: "Impact".to_string(),
            minimum_font_size: 0,
            default_font_size: 16,
            default_fixed_font_size: 13,
            use_system_fonts: true,
            enable_web_fonts: true,
            embed_fonts: true,
            subset_fonts: true,
        }
    }
}

impl Default for CustomFont {
    fn default() -> Self {
        Self {
            family: String::new(),
            data: Vec::new(),
            weight: 400,
            style: "normal".to_string(),
        }
    }
}

impl Default for TextFieldDef {
    fn default() -> Self {
        Self {
            name: String::new(),
            page: 1,
            x: 0.0,
            y: 0.0,
            width: 100.0,
            height: 20.0,
            default_value: String::new(),
            max_length: 0,
            multiline: false,
            password: false,
            required: false,
            read_only: false,
            font_size: 12.0,
            font_name: "Helvetica".to_string(),
        }
    }
}

impl Default for CheckboxDef {
    fn default() -> Self {
        Self {
            name: String::new(),
            page: 1,
            x: 0.0,
            y: 0.0,
            size: 12.0,
            checked: false,
            export_value: "Yes".to_string(),
        }
    }
}

impl Default for DropdownDef {
    fn default() -> Self {
        Self {
            name: String::new(),
            page: 1,
            x: 0.0,
            y: 0.0,
            width: 100.0,
            height: 20.0,
            options: Vec::new(),
            selected_index: -1,
            editable: false,
        }
    }
}

impl Default for SignatureFieldDef {
    fn default() -> Self {
        Self {
            name: String::new(),
            page: 1,
            x: 0.0,
            y: 0.0,
            width: 150.0,
            height: 50.0,
        }
    }
}

impl Default for RadioButtonDef {
    fn default() -> Self {
        Self {
            name: String::new(),
            group: String::new(),
            page: 1,
            x: 0.0,
            y: 0.0,
            size: 12.0,
            selected: false,
            export_value: String::new(),
            required: false,
            read_only: false,
        }
    }
}

impl Default for FormElementInfo {
    fn default() -> Self {
        Self {
            element_type: 0,
            id: String::new(),
            name: String::new(),
            page: 1,
            x: 0.0,
            y: 0.0,
            width: 100.0,
            height: 20.0,
            required: false,
            readonly: false,
            disabled: false,
            default_value: String::new(),
            placeholder: String::new(),
            max_length: 0,
            checked: false,
            export_value: String::new(),
            radio_group: String::new(),
            options: String::new(),
            selected_index: -1,
            multiline: false,
            password: false,
            font_size: 12.0,
        }
    }
}

impl Default for SigningOptions {
    fn default() -> Self {
        Self {
            reason: String::new(),
            location: String::new(),
            contact_info: String::new(),
            signature_level: "B".to_string(),
            timestamp_url: String::new(),
        }
    }
}

impl Default for VisibleSignature {
    fn default() -> Self {
        Self {
            field_name: "Signature".to_string(),
            page: 1,
            x: 0.0,
            y: 0.0,
            width: 150.0,
            height: 50.0,
            show_name: true,
            show_date: true,
            show_reason: true,
            background_image: Vec::new(),
        }
    }
}

impl Default for PreparedSignature {
    fn default() -> Self {
        Self {
            pdf_data: Vec::new(),
            byte_range: Vec::new(),
            contents_offset: 0,
            contents_length: 0,
        }
    }
}

impl Default for SigningFieldDef {
    fn default() -> Self {
        Self {
            field_name: "Signature".to_string(),
            reason: String::new(),
            location: String::new(),
            contact_info: String::new(),
            page: 0, // 0 = last page
            x: 0.0,
            y: 0.0,
            width: 0.0, // 0 = invisible
            height: 0.0,
        }
    }
}

impl Default for PdfSignatureData {
    fn default() -> Self {
        Self {
            contents: Vec::new(),
            byte_range: Vec::new(),
            sub_filter: String::new(),
            reason: String::new(),
            location: String::new(),
            signing_time: String::new(),
            signer_name: String::new(),
        }
    }
}

impl Default for SignatureFieldInfo {
    fn default() -> Self {
        Self {
            name: String::new(),
            page: 1,
            x: 0.0,
            y: 0.0,
            width: 0.0,
            height: 0.0,
            is_signed: false,
        }
    }
}

impl Default for AnnotationDef {
    fn default() -> Self {
        Self {
            annotation_type: 9, // Highlight
            page: 1,
            x: 0.0,
            y: 0.0,
            width: 100.0,
            height: 20.0,
            color: 0xFFFF_00FF, // Yellow
            opacity: 1.0,
            contents: String::new(),
            author: String::new(),
            text: String::new(),
            font_size: 12.0,
        }
    }
}

impl Default for PdfAMetadataDef {
    fn default() -> Self {
        Self {
            level: 2,
            conformance: "B".to_string(),
            title: String::new(),
            author: String::new(),
            xmp_data: String::new(),
        }
    }
}

impl Default for PdfUAMetadataDef {
    fn default() -> Self {
        Self {
            part: 1,
            language: "en".to_string(),
            title: String::new(),
            xmp_data: String::new(),
        }
    }
}

// ============================================================================
// Resource fetching callback implementation
// ============================================================================

use std::io::Read;
use std::time::Duration;
use tracing::{debug, warn};

/// Default timeout for resource fetching
const DEFAULT_FETCH_TIMEOUT: Duration = Duration::from_secs(30);

/// Maximum resource size (10 MB)
const MAX_RESOURCE_SIZE: u64 = 10 * 1024 * 1024;

/// Fetch a resource from a URL - called by C++ when Blink needs a resource.
///
/// This is the callback function that C++ invokes via the cxx bridge.
/// It performs the HTTP request using ureq and returns the result.
pub fn rust_fetch_resource(url: &str) -> ffi::ResourceFetchResult {
    debug!("rust_fetch_resource called for: {}", url);

    // Build the HTTP agent
    let agent: ureq::Agent = ureq::Agent::config_builder()
        .timeout_global(Some(DEFAULT_FETCH_TIMEOUT))
        .build()
        .into();

    // Perform the request
    let response = match agent.get(url).header("User-Agent", "printwell/0.1").call() {
        Ok(resp) => resp,
        Err(e) => {
            warn!("Failed to fetch resource {}: {}", url, e);
            return ffi::ResourceFetchResult {
                success: false,
                data: Vec::new(),
                content_type: String::new(),
                error: format!("HTTP request failed: {e}"),
            };
        }
    };

    // Get content type
    let content_type = response
        .headers()
        .get("Content-Type")
        .and_then(|v: &ureq::http::HeaderValue| v.to_str().ok())
        .map_or_else(|| guess_content_type(url), ToString::to_string);

    // Read the response body with size limit
    let mut data = Vec::with_capacity(1024 * 1024); // Pre-allocate 1MB
    let (_, resp_body): (_, ureq::Body) = response.into_parts();
    let mut reader = resp_body.into_reader();
    let mut limited_reader = (&mut reader).take(MAX_RESOURCE_SIZE);

    match limited_reader.read_to_end(&mut data) {
        Ok(_) => {
            debug!("Successfully fetched {} bytes from {}", data.len(), url);
            ffi::ResourceFetchResult {
                success: true,
                data,
                content_type,
                error: String::new(),
            }
        }
        Err(e) => {
            warn!("Failed to read response body from {}: {}", url, e);
            ffi::ResourceFetchResult {
                success: false,
                data: Vec::new(),
                content_type: String::new(),
                error: format!("Failed to read response: {e}"),
            }
        }
    }
}

/// Guess content type from URL extension
#[allow(clippy::case_sensitive_file_extension_comparisons)] // url is already lowercased
fn guess_content_type(url: &str) -> String {
    let url_lower = url.to_lowercase();
    if url_lower.ends_with(".png") {
        "image/png".to_string()
    } else if url_lower.ends_with(".jpg") || url_lower.ends_with(".jpeg") {
        "image/jpeg".to_string()
    } else if url_lower.ends_with(".gif") {
        "image/gif".to_string()
    } else if url_lower.ends_with(".webp") {
        "image/webp".to_string()
    } else if url_lower.ends_with(".svg") {
        "image/svg+xml".to_string()
    } else if url_lower.ends_with(".css") {
        "text/css".to_string()
    } else if url_lower.ends_with(".js") {
        "application/javascript".to_string()
    } else if url_lower.ends_with(".woff") {
        "font/woff".to_string()
    } else if url_lower.ends_with(".woff2") {
        "font/woff2".to_string()
    } else if url_lower.ends_with(".ttf") {
        "font/ttf".to_string()
    } else if url_lower.ends_with(".otf") {
        "font/otf".to_string()
    } else if url_lower.ends_with(".html") || url_lower.ends_with(".htm") {
        "text/html".to_string()
    } else {
        "application/octet-stream".to_string()
    }
}

#[cfg(test)]
mod tests;