harumi 1.12.0

Pure-Rust PDF — CJK font embedding (Chinese/Japanese/Korean), OCR text overlay, text extraction, HTML→PDF, page merge/split. WASM-ready, zero C deps.
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
use lopdf::{Dictionary, Object, ObjectId, Stream};
use ttf_parser::Face;

use crate::error::{Error, Result};

use super::types::{Color, FieldType, FormField};

pub(super) fn lopdf_string_to_rust(obj: &lopdf::Object) -> Option<String> {
    match obj {
        lopdf::Object::String(bytes, _) => {
            if bytes.starts_with(&[0xFE, 0xFF]) {
                let units: Vec<u16> = bytes[2..]
                    .chunks(2)
                    .map(|c| u16::from_be_bytes([c[0], c.get(1).copied().unwrap_or(0)]))
                    .collect();
                String::from_utf16(&units).ok()
            } else {
                String::from_utf8(bytes.clone())
                    .ok()
                    .or_else(|| Some(bytes.iter().map(|&b| b as char).collect()))
            }
        }
        _ => None,
    }
}

/// Encodes a Rust `&str` as a PDF text string.
///
/// ASCII-only strings use a literal byte encoding. Strings containing non-ASCII
/// characters (e.g. CJK) are encoded as UTF-16BE with a 0xFE 0xFF BOM prefix,
/// which is the standard for PDF `/Title` and other text string fields.
pub(super) fn pdf_text_string(s: &str) -> Object {
    use lopdf::StringFormat;
    if s.is_ascii() {
        return Object::String(s.as_bytes().to_vec(), StringFormat::Literal);
    }
    let mut bytes: Vec<u8> = vec![0xFE, 0xFF]; // UTF-16BE BOM
    for unit in s.encode_utf16() {
        bytes.push((unit >> 8) as u8);
        bytes.push((unit & 0xFF) as u8);
    }
    Object::String(bytes, StringFormat::Literal)
}

/// Returns the ObjectId of the /AcroForm dictionary if one exists.
pub(super) fn acroform_id(doc: &lopdf::Document) -> Option<ObjectId> {
    let root_ref = doc.trailer.get(b"Root").ok()?.as_reference().ok()?;
    let catalog = doc.get_object(root_ref).ok()?.as_dict().ok()?;
    catalog.get(b"AcroForm").ok()?.as_reference().ok()
}

/// Ensures an /AcroForm entry exists in the document catalog.
/// Returns the ObjectId of the /AcroForm dictionary (either existing or newly created).
pub(super) fn ensure_acroform(doc: &mut lopdf::Document) -> Result<ObjectId> {
    // Check if AcroForm already exists
    if let Some(id) = acroform_id(doc) {
        return Ok(id);
    }

    // Create a new /AcroForm dictionary with an empty /Fields array
    let mut acroform_dict = Dictionary::new();
    acroform_dict.set("Fields", Object::Array(Vec::new()));
    let acroform_id = doc.add_object(Object::Dictionary(acroform_dict));

    // Get the catalog and add the /AcroForm reference
    let root_ref = doc
        .trailer
        .get(b"Root")
        .ok()
        .and_then(|o| o.as_reference().ok())
        .ok_or(Error::InvalidInput("catalog not found".into()))?;

    let catalog = doc.get_object_mut(root_ref)?.as_dict_mut()?;
    catalog.set("AcroForm", Object::Reference(acroform_id));

    Ok(acroform_id)
}

/// Recursively collects `FormField` entries from a PDF field array.
pub(super) fn collect_fields_recursive(
    doc: &lopdf::Document,
    field_refs: &[Object],
    parent_name: &str,
    out: &mut Vec<FormField>,
) {
    for obj in field_refs {
        let id = match obj {
            Object::Reference(id) => *id,
            _ => continue,
        };
        let Ok(field_obj) = doc.get_object(id) else {
            continue;
        };
        let Ok(fd) = field_obj.as_dict() else {
            continue;
        };

        let partial = fd
            .get(b"T")
            .ok()
            .and_then(|o| match o {
                Object::String(b, _) => String::from_utf8(b.clone()).ok().or_else(|| {
                    if b.starts_with(&[0xFE, 0xFF]) {
                        let units: Vec<u16> = b[2..]
                            .chunks(2)
                            .map(|c| u16::from_be_bytes([c[0], c.get(1).copied().unwrap_or(0)]))
                            .collect();
                        String::from_utf16(&units).ok()
                    } else {
                        None
                    }
                }),
                _ => None,
            })
            .unwrap_or_default();

        let full_name = if parent_name.is_empty() {
            partial.clone()
        } else if partial.is_empty() {
            parent_name.to_owned()
        } else {
            format!("{parent_name}.{partial}")
        };

        // If /Kids present: intermediate node, recurse.
        if let Ok(kids_obj) = fd.get(b"Kids") {
            let kids: Vec<Object> = match kids_obj {
                Object::Array(arr) => arr.clone(),
                Object::Reference(kid_id) => doc
                    .get_object(*kid_id)
                    .ok()
                    .and_then(|o| {
                        if let Object::Array(a) = o {
                            Some(a.clone())
                        } else {
                            None
                        }
                    })
                    .unwrap_or_default(),
                _ => vec![],
            };
            collect_fields_recursive(doc, &kids, &full_name, out);
            continue;
        }

        // Leaf field.
        let ft = fd.get(b"FT").ok().and_then(|o| {
            if let Object::Name(n) = o {
                Some(n.as_slice())
            } else {
                None
            }
        });

        let field_type = match ft {
            Some(b"Tx") => FieldType::Text,
            Some(b"Btn") => {
                let flags = fd
                    .get(b"Ff")
                    .ok()
                    .and_then(|o| o.as_i64().ok())
                    .unwrap_or(0);
                if flags & (1 << 15) != 0 {
                    FieldType::Radio
                } else {
                    FieldType::Checkbox
                }
            }
            Some(b"Ch") => FieldType::Choice,
            Some(b"Sig") => FieldType::Signature,
            _ => FieldType::Unknown,
        };

        let value = fd
            .get(b"V")
            .ok()
            .map(|v| match v {
                Object::String(b, _) => {
                    if b.starts_with(&[0xFE, 0xFF]) {
                        let units: Vec<u16> = b[2..]
                            .chunks(2)
                            .map(|c| u16::from_be_bytes([c[0], c.get(1).copied().unwrap_or(0)]))
                            .collect();
                        String::from_utf16(&units).unwrap_or_default()
                    } else {
                        String::from_utf8(b.clone()).unwrap_or_default()
                    }
                }
                Object::Name(n) => String::from_utf8_lossy(n).into_owned(),
                _ => String::new(),
            })
            .unwrap_or_default();

        if !full_name.is_empty() {
            out.push(FormField {
                name: full_name,
                field_type,
                value,
            });
        }
    }
}

/// Collects (ObjectId, FieldType, full_name) for all leaf fields under /AcroForm.
pub(super) fn collect_field_ids(
    doc: &lopdf::Document,
    acroform_id: ObjectId,
) -> Vec<(ObjectId, FieldType, String)> {
    let Ok(acroform) = doc.get_object(acroform_id).and_then(|o| o.as_dict()) else {
        return vec![];
    };
    let field_refs: Vec<Object> = match acroform.get(b"Fields") {
        Ok(Object::Array(arr)) => arr.clone(),
        Ok(Object::Reference(id)) => doc
            .get_object(*id)
            .ok()
            .and_then(|o| {
                if let Object::Array(a) = o {
                    Some(a.clone())
                } else {
                    None
                }
            })
            .unwrap_or_default(),
        _ => return vec![],
    };

    let mut out = Vec::new();
    collect_field_ids_recursive(doc, &field_refs, "", &mut out);
    out
}

pub(super) fn collect_field_ids_recursive(
    doc: &lopdf::Document,
    field_refs: &[Object],
    parent_name: &str,
    out: &mut Vec<(ObjectId, FieldType, String)>,
) {
    for obj in field_refs {
        let id = match obj {
            Object::Reference(id) => *id,
            _ => continue,
        };
        let Ok(field_obj) = doc.get_object(id) else {
            continue;
        };
        let Ok(fd) = field_obj.as_dict() else {
            continue;
        };

        let partial = fd
            .get(b"T")
            .ok()
            .and_then(lopdf_string_to_rust)
            .unwrap_or_default();

        let full_name = if parent_name.is_empty() {
            partial.clone()
        } else if partial.is_empty() {
            parent_name.to_owned()
        } else {
            format!("{parent_name}.{partial}")
        };

        if let Ok(kids_obj) = fd.get(b"Kids") {
            let kids: Vec<Object> = match kids_obj {
                Object::Array(arr) => arr.clone(),
                Object::Reference(kid_id) => doc
                    .get_object(*kid_id)
                    .ok()
                    .and_then(|o| {
                        if let Object::Array(a) = o {
                            Some(a.clone())
                        } else {
                            None
                        }
                    })
                    .unwrap_or_default(),
                _ => vec![],
            };
            collect_field_ids_recursive(doc, &kids, &full_name, out);
            continue;
        }

        let ft = fd.get(b"FT").ok().and_then(|o| {
            if let Object::Name(n) = o {
                Some(n.as_slice())
            } else {
                None
            }
        });
        let field_type = match ft {
            Some(b"Tx") => FieldType::Text,
            Some(b"Btn") => {
                let flags = fd
                    .get(b"Ff")
                    .ok()
                    .and_then(|o| o.as_i64().ok())
                    .unwrap_or(0);
                if flags & (1 << 15) != 0 {
                    FieldType::Radio
                } else {
                    FieldType::Checkbox
                }
            }
            Some(b"Ch") => FieldType::Choice,
            Some(b"Sig") => FieldType::Signature,
            _ => FieldType::Unknown,
        };

        if !full_name.is_empty() {
            out.push((id, field_type, full_name));
        }
    }
}

/// Builds a markup annotation dictionary (Highlight, Underline, StrikeOut).
pub(super) fn build_markup_annot(subtype: &[u8], rect: [f32; 4], color: Color) -> Dictionary {
    let x2 = rect[0] + rect[2];
    let y2 = rect[1] + rect[3];
    let mut d = Dictionary::new();
    d.set("Type", Object::Name(b"Annot".to_vec()));
    d.set("Subtype", Object::Name(subtype.to_vec()));
    d.set(
        "Rect",
        Object::Array(vec![
            Object::Real(rect[0]),
            Object::Real(rect[1]),
            Object::Real(x2),
            Object::Real(y2),
        ]),
    );
    // QuadPoints: upper-left, upper-right, lower-left, lower-right (Acrobat convention)
    d.set(
        "QuadPoints",
        Object::Array(vec![
            Object::Real(rect[0]),
            Object::Real(y2),
            Object::Real(x2),
            Object::Real(y2),
            Object::Real(rect[0]),
            Object::Real(rect[1]),
            Object::Real(x2),
            Object::Real(rect[1]),
        ]),
    );
    let color_array = match color {
        Color::Rgb(c) => vec![Object::Real(c[0]), Object::Real(c[1]), Object::Real(c[2])],
        Color::Cmyk(c) => vec![
            Object::Real(c[0]),
            Object::Real(c[1]),
            Object::Real(c[2]),
            Object::Real(c[3]),
        ],
    };
    d.set("C", Object::Array(color_array));
    d.set(
        "Border",
        Object::Array(vec![
            Object::Integer(0),
            Object::Integer(0),
            Object::Integer(0),
        ]),
    );
    d
}

/// Builds the common fields of a /Link annotation dictionary (without the /A or /Dest key).
pub(super) fn build_link_annot_base(rect: [f32; 4]) -> Dictionary {
    let mut d = Dictionary::new();
    d.set("Type", Object::Name(b"Annot".to_vec()));
    d.set("Subtype", Object::Name(b"Link".to_vec()));
    d.set(
        "Rect",
        Object::Array(vec![
            Object::Real(rect[0]),
            Object::Real(rect[1]),
            Object::Real(rect[0] + rect[2]),
            Object::Real(rect[1] + rect[3]),
        ]),
    );
    // No visible border ([0 0 0] = no border)
    d.set(
        "Border",
        Object::Array(vec![
            Object::Integer(0),
            Object::Integer(0),
            Object::Integer(0),
        ]),
    );
    d
}

/// Appends an annotation object reference to the /Annots array of a page dictionary.
///
/// Handles both the case where /Annots is a direct array and where it is an
/// indirect reference to an array object.
pub(super) fn append_annotation_to_page(
    doc: &mut lopdf::Document,
    page_id: ObjectId,
    annot_id: ObjectId,
) -> Result<()> {
    let new_ref = Object::Reference(annot_id);

    // Read the current /Annots value without borrowing `doc` mutably.
    let annots_val = doc
        .get_object(page_id)?
        .as_dict()?
        .get(b"Annots")
        .ok()
        .cloned();

    match annots_val {
        Some(Object::Array(mut arr)) => {
            arr.push(new_ref);
            doc.get_object_mut(page_id)?
                .as_dict_mut()?
                .set("Annots", Object::Array(arr));
        }
        Some(Object::Reference(arr_id)) => {
            // /Annots points to an indirect array object.
            let is_array = doc
                .get_object(arr_id)
                .ok()
                .map(|o| matches!(o, Object::Array(_)))
                .unwrap_or(false);
            if is_array {
                doc.get_object_mut(arr_id)?.as_array_mut()?.push(new_ref);
            } else {
                // Indirect reference doesn't point to an array — replace with direct array.
                doc.get_object_mut(page_id)?
                    .as_dict_mut()?
                    .set("Annots", Object::Array(vec![new_ref]));
            }
        }
        _ => {
            // No /Annots entry (or malformed) — create a fresh direct array.
            doc.get_object_mut(page_id)?
                .as_dict_mut()?
                .set("Annots", Object::Array(vec![new_ref]));
        }
    }
    Ok(())
}

/// Reads a named page box (e.g. CropBox) from the page dict.
/// Returns `None` when the key is absent. Parses `[x1 y1 x2 y2]` → `[x, y, w, h]`.
pub(super) fn read_page_box(doc: &lopdf::Document, page_id: ObjectId, key: &[u8]) -> Result<Option<[f32; 4]>> {
    let dict = doc.get_object(page_id)?.as_dict()?;
    match dict.get(key).ok().cloned() {
        Some(Object::Reference(ref_id)) => parse_box_array(doc.get_object(ref_id)?).map(Some),
        Some(obj) => parse_box_array(&obj).map(Some),
        None => Ok(None),
    }
}

pub(super) fn parse_box_array(obj: &Object) -> Result<[f32; 4]> {
    let arr = obj.as_array()?;
    if arr.len() < 4 {
        return Err(Error::Pdf(lopdf::Error::DictKey(
            "box array too short".to_string(),
        )));
    }
    let get = |i: usize| -> f32 {
        match &arr[i] {
            Object::Integer(v) => *v as f32,
            Object::Real(v) => *v,
            _ => 0.0,
        }
    };
    let (x1, y1, x2, y2) = (get(0), get(1), get(2), get(3));
    Ok([x1, y1, x2 - x1, y2 - y1])
}

/// Writes a named page box (e.g. CropBox) to the page dict.
/// Accepts `[x, y, w, h]` and stores as `[x1 y1 x2 y2]`.
pub(super) fn set_page_box(
    doc: &mut lopdf::Document,
    page_id: ObjectId,
    key: &[u8],
    rect: [f32; 4],
) -> Result<()> {
    let box_arr = Object::Array(vec![
        Object::Real(rect[0]),
        Object::Real(rect[1]),
        Object::Real(rect[0] + rect[2]),
        Object::Real(rect[1] + rect[3]),
    ]);
    doc.get_object_mut(page_id)?
        .as_dict_mut()?
        .set(key, box_arr);
    Ok(())
}

/// Returns a 16-byte pseudo-random document ID using system time + PID.
/// Used as the /ID trailer entry required by PDF encryption (RC4/AES).
pub(super) fn generate_file_id() -> [u8; 16] {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    let pid = std::process::id() as u128;
    // LCG mix so that docs saved at the same nanosecond differ.
    // Mix time + PID using Knuth's MMIX LCG constants (a=6364136223846793005,
    // c=1442695040888963407) so that docs saved in the same process at similar
    // times produce distinct IDs. Not cryptographically secure, but sufficient
    // for PDF's /ID uniqueness requirement (PDF spec §14.4).
    let mixed = nanos
        .wrapping_mul(6364136223846793005u128)
        .wrapping_add(pid.wrapping_mul(1442695040888963407u128));
    let mut id = [0u8; 16];
    id.copy_from_slice(&mixed.to_le_bytes());
    id
}

pub(super) fn map_lopdf_password_err(e: lopdf::Error) -> Error {
    match e {
        lopdf::Error::InvalidPassword => Error::WrongPassword,
        lopdf::Error::IO(io_err) => Error::Io(io_err),
        other => Error::Pdf(other),
    }
}

pub(super) fn check_finite(values: &[f32], label: &str) -> Result<()> {
    if values.iter().any(|v| !v.is_finite()) {
        return Err(Error::InvalidInput(format!(
            "{label} contains NaN or Infinity"
        )));
    }
    Ok(())
}

pub(super) fn check_positive_size(width: f32, height: f32, label: &str) -> Result<()> {
    if width <= 0.0 || height <= 0.0 {
        return Err(Error::InvalidInput(format!(
            "{label}: rect width and height must be positive, got ({width}, {height})"
        )));
    }
    Ok(())
}

/// Returns true for characters that can line-break at any position (CJK scripts).
pub(crate) fn is_cjk(ch: char) -> bool {
    matches!(
        ch as u32,
        0x1100..=0x11FF    // Hangul Jamo
        | 0x3000..=0x9FFF  // CJK unified ideographs, hiragana, katakana, etc.
        | 0xA960..=0xA97F  // Hangul Jamo Extended-A
        | 0xAC00..=0xD7FF  // Hangul syllables + Jamo Extended-B
        | 0xF900..=0xFAFF  // CJK compatibility ideographs
        | 0xFE30..=0xFE4F  // CJK compatibility forms
        | 0xFF00..=0xFFEF  // fullwidth / halfwidth forms
        | 0x20000..=0x2A6DF | 0x2A700..=0x2CEAF  // CJK extension B / C / D
    )
}

/// Width of one character in PDF points given the font face and font size.
/// Returns None if the character is not present in the font (no glyph mapping).
pub fn glyph_advance_pt(face: &Face, ch: char, font_size: f32) -> Option<f32> {
    let upem = face.units_per_em() as f32;
    face.glyph_index(ch)
        .and_then(|g| face.glyph_hor_advance(g))
        .map(|adv| adv as f32 * font_size / upem)
}

/// Return `true` when `font_bytes` contains a glyph for `ch`.
///
/// Uses [ttf-parser](https://docs.rs/ttf-parser) to check the font's `cmap` table.
/// Returns `false` when `font_bytes` cannot be parsed.
///
/// # Example
/// ```no_run
/// # let font_bytes = std::fs::read("NotoSansJP-Regular.ttf").unwrap();
/// assert!(harumi::font_covers_char(&font_bytes, '日'));
/// assert!(!harumi::font_covers_char(&font_bytes, '؟')); // Arabic question mark
/// ```
pub fn font_covers_char(font_bytes: &[u8], ch: char) -> bool {
    ttf_parser::Face::parse(font_bytes, 0)
        .map(|face| face.glyph_index(ch).is_some())
        .unwrap_or(false)
}

/// Calculate the total width of a text string in PDF points from raw TTF bytes.
///
/// This helper is useful for checking text overflow without needing access to Font objects.
/// Returns None if the font bytes are invalid or if any character is missing from the font.
pub fn calculate_text_width(text: &str, font_bytes: &[u8], font_size: f32) -> Option<f32> {
    let face = ttf_parser::Face::parse(font_bytes, 0).ok()?;
    Some(text_width_with_face(text, &face, font_size))
}

/// Like [`calculate_text_width`] but reuses a pre-parsed [`ttf_parser::Face`].
///
/// Use this inside loops (e.g. shrink-to-fit) to avoid re-parsing the font on
/// every iteration.  Characters missing from the font contribute 0 width.
pub(super) fn text_width_with_face(text: &str, face: &ttf_parser::Face<'_>, font_size: f32) -> f32 {
    text.chars()
        .filter_map(|ch| glyph_advance_pt(face, ch, font_size))
        .sum()
}

/// Greedy line-breaking for a single paragraph (no embedded newlines).
pub fn wrap_paragraph(paragraph: &str, face: &Face, font_size: f32, box_width: f32) -> Vec<String> {
    // Validate inputs.
    // If font_size or box_width is invalid, return the paragraph as a single line.
    if !font_size.is_finite() || font_size <= 0.0 || !box_width.is_finite() || box_width <= 0.0 {
        return if paragraph.is_empty() {
            Vec::new()
        } else {
            vec![paragraph.to_owned()]
        };
    }

    let mut lines: Vec<String> = Vec::new();
    let mut current = String::new();
    let mut current_w: f32 = 0.0;
    // byte index of last ASCII space in `current`; width after that space (= start of next word)
    let mut last_space_byte: Option<usize> = None;
    let mut width_at_word_start: f32 = 0.0;

    for ch in paragraph.chars() {
        let ch_w = glyph_advance_pt(face, ch, font_size).unwrap_or(font_size * 0.5);

        if current_w + ch_w > box_width && !current.is_empty() {
            if is_cjk(ch) || last_space_byte.is_none() {
                // CJK or no word boundary found → break at the current character
                lines.push(std::mem::take(&mut current));
                current_w = 0.0;
                last_space_byte = None;
            } else {
                // Break at the last space: emit everything before it, keep the word after
                let sp = last_space_byte.unwrap();
                let word = current[sp + 1..].to_owned(); // sp+1 safe: space is ASCII (1 byte)
                current.truncate(sp);
                lines.push(std::mem::take(&mut current));
                current = word;
                current_w = (current_w - width_at_word_start).max(0.0);
                last_space_byte = None;
            }
        }

        if ch == ' ' {
            last_space_byte = Some(current.len()); // byte index of space before it is pushed
            width_at_word_start = current_w + ch_w; // total width including the space
        }
        current.push(ch);
        current_w += ch_w;
    }

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

/// Compute how `text` lays out inside a rectangle with the given font face, without
/// mutating any document state.  Used by [`crate::Document::fit_text_to_box`].
///
/// `line_height = fs * 1.2` — matches the constant in `replace_text_fragments_opts`.
pub(super) fn plan_text_fit(
    text: &str,
    face: &ttf_parser::Face<'_>,
    rect: [f32; 4],
    initial_font_size: f32,
    opts: &super::types::BoxFitOptions,
) -> super::types::FitResult {
    use super::types::{FitResult, OverflowPolicy};

    let [rx, ry, rw, rh] = rect;
    let fs0 = initial_font_size.max(opts.min_font_size.max(0.1));

    let line_height = |fs: f32| fs * 1.2_f32;

    let (lines, fs) = match opts.overflow {
        OverflowPolicy::Shrink => {
            // No wrap — shrink until single line fits in width.
            let mut fs = fs0;
            let min_fs = opts.min_font_size.max(0.1);
            loop {
                let w = text_width_with_face(text, face, fs);
                if w <= rw || fs <= min_fs {
                    break;
                }
                fs = (fs * rw / w).max(min_fs);
            }
            (vec![text.to_owned()], fs)
        }
        OverflowPolicy::WrapThenShrink => {
            let min_fs = opts.min_font_size.max(0.1);
            let mut fs = fs0;
            let mut lines = if opts.wrap {
                wrap_paragraph(text, face, fs, rw)
            } else {
                vec![text.to_owned()]
            };
            // Shrink until total height fits or we hit min_font_size.
            loop {
                let total_h = lines.len() as f32 * line_height(fs);
                if total_h <= rh || fs <= min_fs {
                    break;
                }
                let factor = rh / total_h;
                fs = (fs * factor).max(min_fs);
                lines = if opts.wrap {
                    wrap_paragraph(text, face, fs, rw)
                } else {
                    vec![text.to_owned()]
                };
            }
            (lines, fs)
        }
        OverflowPolicy::Truncate => {
            let lines = if opts.wrap {
                wrap_paragraph(text, face, fs0, rw)
            } else {
                vec![text.to_owned()]
            };
            let lh = line_height(fs0);
            let max_by_height = if lh > 0.0 && rh > 0.0 {
                (rh / lh).floor() as usize
            } else {
                lines.len()
            };
            let cap = opts.max_lines.unwrap_or(usize::MAX).min(max_by_height);
            let truncated: Vec<String> = lines.into_iter().take(cap.max(1)).collect();
            (truncated, fs0)
        }
        OverflowPolicy::Report => {
            let lines = if opts.wrap {
                wrap_paragraph(text, face, fs0, rw)
            } else {
                vec![text.to_owned()]
            };
            let lines = if let Some(max) = opts.max_lines {
                lines.into_iter().take(max.max(1)).collect()
            } else {
                lines
            };
            (lines, fs0)
        }
    };

    let lh = line_height(fs);
    let used_h = lines.len() as f32 * lh;
    let used_w = lines
        .iter()
        .map(|l| text_width_with_face(l, face, fs))
        .fold(0.0_f32, f32::max)
        .min(rw);

    // Top-aligned within the requested rect (matching add_text_box placement).
    let used_rect = [rx, ry + rh - used_h, used_w, used_h];

    let overflow_horizontal =
        lines.iter().any(|l| text_width_with_face(l, face, fs) > rw);
    let overflow_vertical = used_h > rh;

    FitResult { lines, font_size: fs, used_rect, overflow_horizontal, overflow_vertical }
}

pub(super) fn root_pages_id(doc: &lopdf::Document) -> Result<ObjectId> {
    let root_ref = doc.trailer.get(b"Root")?.as_reference()?;
    let catalog = doc.get_object(root_ref)?.as_dict()?;
    Ok(catalog.get(b"Pages")?.as_reference()?)
}

/// Materialize inherited PDF page attributes onto `page_id` before the page's
/// `/Parent` is changed (i.e., before the tree is flattened).
///
/// The PDF spec allows `/MediaBox`, `/CropBox`, `/Rotate`, `/Resources`, and
/// `/UserUnit` to be placed on intermediate `/Pages` nodes and inherited by
/// descendant pages. When those intermediate nodes are bypassed (by re-parenting
/// pages directly to the root), any values they hold are no longer reachable via
/// the inheritance chain. This function copies the missing values directly onto
/// the page dict so they survive the re-parenting.
///
/// Closest ancestor wins: the first ancestor to provide a value for a given key
/// is used; outer ancestors' values for the same key are ignored.
pub(super) fn realize_page_inherited_attrs(doc: &mut lopdf::Document, page_id: ObjectId) -> Result<()> {
    const INHERITABLE: &[&[u8]] = &[
        b"MediaBox",
        b"CropBox",
        b"Rotate",
        b"Resources",
        b"UserUnit",
    ];

    // Walk up the parent chain and collect attrs missing from the page itself.
    let mut to_apply: Vec<(Vec<u8>, Object)> = Vec::new();
    let mut cursor = page_id;
    let mut depth = 0u32;

    loop {
        if depth > 64 {
            break; // cycle / pathological-depth guard
        }
        depth += 1;

        // Get cursor's /Parent reference.
        let parent_id = match doc
            .get_object(cursor)
            .ok()
            .and_then(|o| o.as_dict().ok())
            .and_then(|d| d.get(b"Parent").ok())
            .and_then(|o| {
                if let Object::Reference(id) = o {
                    Some(*id)
                } else {
                    None
                }
            }) {
            Some(id) => id,
            None => break,
        };

        // Only inherit from /Pages nodes.
        let parent_is_pages = doc
            .get_object(parent_id)
            .ok()
            .and_then(|o| o.as_dict().ok())
            .and_then(|d| d.get(b"Type").ok())
            .and_then(|o| {
                if let Object::Name(n) = o {
                    Some(n.as_slice() == b"Pages")
                } else {
                    None
                }
            })
            .unwrap_or(false);

        if !parent_is_pages {
            break;
        }

        // Clone the parent dict so we can check its keys without holding a borrow.
        let parent_dict = match doc
            .get_object(parent_id)
            .ok()
            .and_then(|o| o.as_dict().ok())
        {
            Some(d) => d.clone(),
            None => break,
        };
        // Clone the page dict to check which keys are already present.
        let page_dict = match doc.get_object(page_id).ok().and_then(|o| o.as_dict().ok()) {
            Some(d) => d.clone(),
            None => break,
        };

        for &key in INHERITABLE {
            // Already on the page itself — skip.
            if page_dict.get(key).is_ok() {
                continue;
            }
            // Already queued from a closer ancestor — skip.
            if to_apply.iter().any(|(k, _)| k.as_slice() == key) {
                continue;
            }
            // Inherit from this ancestor.
            if let Ok(val) = parent_dict.get(key) {
                to_apply.push((key.to_vec(), val.clone()));
            }
        }

        cursor = parent_id;
    }

    // Write collected attributes onto the page dict.
    if !to_apply.is_empty() {
        let page_dict = doc.get_object_mut(page_id)?.as_dict_mut()?;
        for (key, val) in to_apply {
            page_dict.set(key, val);
        }
    }

    Ok(())
}

/// Inserts `new_stream_id` before all existing content streams in a page's `/Contents`.
pub(super) fn prepend_to_contents(
    doc: &mut lopdf::Document,
    page_id: ObjectId,
    new_stream_id: ObjectId,
) -> Result<()> {
    let contents_ref = doc
        .get_object(page_id)?
        .as_dict()?
        .get(b"Contents")
        .ok()
        .cloned();

    let new_ref = Object::Reference(new_stream_id);

    match contents_ref {
        Some(Object::Reference(r)) => {
            let is_array = doc
                .get_object(r)
                .ok()
                .map(|o| matches!(o, Object::Array(_)))
                .unwrap_or(false);
            if is_array {
                doc.get_object_mut(r)?.as_array_mut()?.insert(0, new_ref);
            } else {
                let arr = Object::Array(vec![new_ref, Object::Reference(r)]);
                doc.get_object_mut(page_id)?
                    .as_dict_mut()?
                    .set("Contents", arr);
            }
        }
        Some(Object::Array(mut arr)) => {
            arr.insert(0, new_ref);
            doc.get_object_mut(page_id)?
                .as_dict_mut()?
                .set("Contents", Object::Array(arr));
        }
        None => {
            doc.get_object_mut(page_id)?
                .as_dict_mut()?
                .set("Contents", new_ref);
        }
        _ => {}
    }
    Ok(())
}

pub(super) fn append_to_contents(
    doc: &mut lopdf::Document,
    page_id: ObjectId,
    new_stream_id: ObjectId,
) -> Result<()> {
    let contents_ref = doc
        .get_object(page_id)?
        .as_dict()?
        .get(b"Contents")
        .ok()
        .cloned();

    let new_ref = Object::Reference(new_stream_id);

    match contents_ref {
        Some(Object::Reference(r)) => {
            // Check whether the reference points to an Array (indirect Contents array,
            // common in InDesign-generated PDFs) or a single content stream.
            let is_array = doc
                .get_object(r)
                .ok()
                .map(|o| matches!(o, Object::Array(_)))
                .unwrap_or(false);
            if is_array {
                let arr_obj = doc.get_object_mut(r)?.as_array_mut()?;
                arr_obj.push(new_ref);
            } else {
                let arr = Object::Array(vec![Object::Reference(r), new_ref]);
                doc.get_object_mut(page_id)?
                    .as_dict_mut()?
                    .set("Contents", arr);
            }
        }
        Some(Object::Array(mut arr)) => {
            arr.push(new_ref);
            doc.get_object_mut(page_id)?
                .as_dict_mut()?
                .set("Contents", Object::Array(arr));
        }
        None => {
            doc.get_object_mut(page_id)?
                .as_dict_mut()?
                .set("Contents", new_ref);
        }
        _ => {}
    }
    Ok(())
}

/// Wraps all existing content streams of a page in a `q`/`Q` pair to isolate any
/// unbalanced `cm` operators from affecting subsequently appended streams.
pub(super) fn wrap_page_contents_in_q_q(doc: &mut lopdf::Document, page_id: ObjectId) -> Result<()> {
    let has_contents = doc
        .get_object(page_id)
        .ok()
        .and_then(|o| o.as_dict().ok())
        .and_then(|d| d.get(b"Contents").ok().cloned())
        .is_some();
    if !has_contents {
        return Ok(());
    }
    let q_id = doc.add_object(Object::Stream(Stream::new(Dictionary::new(), b"q\n".to_vec())));
    let big_q_id =
        doc.add_object(Object::Stream(Stream::new(Dictionary::new(), b"Q\n".to_vec())));
    prepend_to_contents(doc, page_id, q_id)?;
    append_to_contents(doc, page_id, big_q_id)?;
    Ok(())
}

pub(super) fn add_font_to_resources(
    doc: &mut lopdf::Document,
    page_id: ObjectId,
    pdf_name: &[u8],
    type0_id: ObjectId,
) -> Result<()> {
    let resources_id: Option<ObjectId> = {
        let page_dict = doc.get_object(page_id)?.as_dict()?;
        match page_dict.get(b"Resources").ok() {
            Some(Object::Reference(r)) => Some(*r),
            _ => None,
        }
    };

    let font_ref = Object::Reference(type0_id);

    if let Some(res_id) = resources_id {
        let res_dict = doc.get_object_mut(res_id)?.as_dict_mut()?;
        ensure_font_entry(res_dict, pdf_name, font_ref);
    } else {
        let page_dict = doc.get_object_mut(page_id)?.as_dict_mut()?;
        match page_dict.get_mut(b"Resources") {
            Ok(res_obj) => {
                let res_dict = res_obj.as_dict_mut()?;
                ensure_font_entry(res_dict, pdf_name, font_ref);
            }
            Err(_) => {
                let mut font_dict = Dictionary::new();
                font_dict.set(pdf_name, font_ref);
                let mut res_dict = Dictionary::new();
                res_dict.set("Font", Object::Dictionary(font_dict));
                page_dict.set("Resources", Object::Dictionary(res_dict));
            }
        }
    }

    Ok(())
}

/// Add a font to a Form XObject's own `/Resources/Font` dict.
///
/// The XObject's /Resources may be inline (Object::Dictionary in the stream dict) or
/// indirect (Object::Reference pointing to a separate dict object); both are handled.
pub(super) fn add_font_to_xobject_resources(
    doc: &mut lopdf::Document,
    xobj_id: lopdf::ObjectId,
    pdf_name: &[u8],
    type0_id: lopdf::ObjectId,
) -> Result<()> {
    let font_ref = Object::Reference(type0_id);

    // Determine whether /Resources is an indirect reference or inline.
    let resources_ref_id: Option<lopdf::ObjectId> = {
        let xobj_obj = doc.get_object(xobj_id)?;
        let xobj_stream = xobj_obj.as_stream()?;
        match xobj_stream.dict.get(b"Resources").ok() {
            Some(Object::Reference(r)) => Some(*r),
            _ => None,
        }
    };

    if let Some(res_id) = resources_ref_id {
        let res_dict = doc.get_object_mut(res_id)?.as_dict_mut()?;
        ensure_font_entry(res_dict, pdf_name, font_ref);
    } else {
        let xobj_obj = doc.get_object_mut(xobj_id)?;
        let xobj_stream = xobj_obj.as_stream_mut()?;
        match xobj_stream.dict.get_mut(b"Resources") {
            Ok(res_obj) => {
                if let Ok(res_dict) = res_obj.as_dict_mut() {
                    ensure_font_entry(res_dict, pdf_name, font_ref);
                }
            }
            Err(_) => {
                let mut font_dict = Dictionary::new();
                font_dict.set(pdf_name, font_ref);
                let mut res_dict = Dictionary::new();
                res_dict.set("Font", Object::Dictionary(font_dict));
                xobj_stream.dict.set("Resources", Object::Dictionary(res_dict));
            }
        }
    }

    Ok(())
}

pub(super) fn ensure_font_entry(res_dict: &mut Dictionary, pdf_name: &[u8], font_ref: Object) {
    match res_dict.get_mut(b"Font") {
        Ok(font_obj) => {
            if let Ok(fd) = font_obj.as_dict_mut() {
                fd.set(pdf_name, font_ref);
            }
        }
        Err(_) => {
            let mut font_dict = Dictionary::new();
            font_dict.set(pdf_name, font_ref);
            res_dict.set("Font", Object::Dictionary(font_dict));
        }
    }
}

/// Resolves the Resources dict for a page (direct or indirect) and applies `f`.
pub(super) fn with_resources_dict_mut<F>(doc: &mut lopdf::Document, page_id: ObjectId, f: F) -> Result<()>
where
    F: FnOnce(&mut Dictionary),
{
    let resources_id: Option<ObjectId> = {
        let page_dict = doc.get_object(page_id)?.as_dict()?;
        match page_dict.get(b"Resources").ok() {
            Some(Object::Reference(r)) => Some(*r),
            _ => None,
        }
    };

    if let Some(res_id) = resources_id {
        f(doc.get_object_mut(res_id)?.as_dict_mut()?);
    } else {
        let page_dict = doc.get_object_mut(page_id)?.as_dict_mut()?;
        match page_dict.get_mut(b"Resources") {
            Ok(res_obj) => f(res_obj.as_dict_mut()?),
            Err(_) => {
                let mut res_dict = Dictionary::new();
                f(&mut res_dict);
                page_dict.set("Resources", Object::Dictionary(res_dict));
            }
        }
    }
    Ok(())
}

#[cfg(feature = "draw")]
pub(super) fn add_ext_gstate_to_resources(
    doc: &mut lopdf::Document,
    page_id: ObjectId,
    registry: crate::draw::ExtGStateRegistry,
) -> Result<()> {
    let ext_g_dict = registry.to_lopdf_dict();
    with_resources_dict_mut(doc, page_id, |res| match res.get_mut(b"ExtGState") {
        Ok(obj) => {
            if let Ok(existing) = obj.as_dict_mut() {
                for (k, v) in ext_g_dict.iter() {
                    existing.set(k.as_slice(), v.clone());
                }
            }
        }
        Err(_) => {
            res.set("ExtGState", Object::Dictionary(ext_g_dict.clone()));
        }
    })
}

pub(super) fn add_xobject_to_resources(
    doc: &mut lopdf::Document,
    page_id: ObjectId,
    name: &[u8],
    xobj_id: ObjectId,
) -> Result<()> {
    let xobj_ref = Object::Reference(xobj_id);
    with_resources_dict_mut(doc, page_id, |res| match res.get_mut(b"XObject") {
        Ok(obj) => {
            if let Ok(d) = obj.as_dict_mut() {
                d.set(name, xobj_ref.clone());
            }
        }
        Err(_) => {
            let mut xobj_dict = Dictionary::new();
            xobj_dict.set(name, xobj_ref.clone());
            res.set("XObject", Object::Dictionary(xobj_dict));
        }
    })
}

/// Returns the MediaBox for a page as raw `[x1, y1, x2, y2]`, traversing the parent chain.
/// Falls back to A4 dimensions if no MediaBox is found.
pub(super) fn inherited_media_box_raw(doc: &lopdf::Document, page_id: ObjectId) -> [f32; 4] {
    let mut current_id = page_id;
    for _ in 0..32 {
        let Ok(dict) = doc.get_object(current_id).and_then(|o| o.as_dict()) else {
            break;
        };
        if let Ok(mb) = dict.get(b"MediaBox")
            && let Ok(arr) = mb.as_array()
            && arr.len() >= 4
        {
            let get = |i: usize| -> f32 {
                match &arr[i] {
                    Object::Integer(v) => *v as f32,
                    Object::Real(v) => *v,
                    _ => 0.0,
                }
            };
            return [get(0), get(1), get(2), get(3)]; // x1, y1, x2, y2
        }
        match dict.get(b"Parent").ok() {
            Some(Object::Reference(id)) => current_id = *id,
            _ => break,
        }
    }
    [0.0, 0.0, 595.0, 842.0] // A4 fallback
}

/// Returns the `/Resources` dictionary for a page, traversing the parent chain for inheritance.
pub(super) fn inherited_resources(doc: &lopdf::Document, page_id: ObjectId) -> Option<Dictionary> {
    let mut current_id = page_id;
    for _ in 0..32 {
        let dict = doc.get_object(current_id).ok()?.as_dict().ok()?;
        if let Ok(res) = dict.get(b"Resources") {
            return match res {
                Object::Dictionary(d) => Some(d.clone()),
                Object::Reference(id) => doc.get_object(*id).ok()?.as_dict().ok().cloned(),
                _ => None,
            };
        }
        match dict.get(b"Parent").ok() {
            Some(Object::Reference(id)) => current_id = *id,
            _ => break,
        }
    }
    None
}

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

    #[test]
    fn document_is_send() {
        fn assert_send<T: Send>() {}
        assert_send::<Document>();
    }

    #[test]
    fn is_cjk_cjk_unified_ideographs() {
        assert!(is_cjk('')); // U+65E5
        assert!(is_cjk('')); // U+672C
        assert!(is_cjk('')); // U+8A9E
    }

    #[test]
    fn is_cjk_hiragana_katakana() {
        assert!(is_cjk('')); // Hiragana U+3042
        assert!(is_cjk('')); // Katakana U+30A2
        assert!(is_cjk('')); // Hiragana U+3093
    }

    #[test]
    fn is_cjk_korean_hangul() {
        assert!(is_cjk('')); // U+AC00
        assert!(is_cjk('')); // U+B098
        assert!(is_cjk('')); // U+D7A3 (last Hangul syllable)
    }

    #[test]
    fn is_cjk_hangul_jamo() {
        assert!(is_cjk('')); // Hangul Jamo U+1100
        assert!(is_cjk('')); // Hangul Jamo U+1161
    }

    #[test]
    fn is_cjk_cjk_extension_planes() {
        assert!(is_cjk('\u{20000}')); // CJK Extension B U+20000
        assert!(is_cjk('\u{2A6D0}')); // CJK Extension C U+2A6D0
    }

    #[test]
    fn is_cjk_non_cjk_returns_false() {
        assert!(!is_cjk('a'));
        assert!(!is_cjk('A'));
        assert!(!is_cjk('1'));
        assert!(!is_cjk(' '));
        assert!(!is_cjk('é')); // Latin Extended
    }
}