rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
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
//! Provenance of a retained cell-border drawing, independent of its visible paint.
//! Native files keep the drawing. A bounded rhwp sidecar keeps its editing owner.
use super::{
    bin_data::BinDataContent,
    control::Control,
    document::Document,
    image::Picture,
    paragraph::Paragraph,
    shape::{CommonObjAttr, HorzRelTo, RectangleShape, ShapeObject, TextWrap, VertRelTo},
    style::FillType,
};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};

pub const HWP_STREAM: &str = "/RhwpCellBorderPaint";
pub const HWPX_ENTRY: &str = "META-INF/rhwp-cell-border-paint.bin";
pub const MAX_BYTES: usize = 4 * 1024 * 1024;
const MAGIC: &[u8; 8] = b"RBPO\0\0\0\x01";
const MAGIC_OUTSIDE: &[u8; 8] = b"RBPO\0\0\0\x02";
const MAGIC_RASTER: &[u8; 8] = b"RBPO\0\0\0\x03";
const MAGIC_COMPOUND: &[u8; 8] = b"RBPO\0\0\0\x04";
const MAGIC_CELL_PEN: &[u8; 8] = b"RBPO\0\0\0\x05";
const MAGIC_CELL_FRAME: &[u8; 8] = b"RBPO\0\0\0\x06";
const HEADER_BYTES: usize = 12;
const RECORD_BYTES: usize = 65;
const MAX_RECORDS: usize = (MAX_BYTES - HEADER_BYTES) / RECORD_BYTES;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CellSide {
    Left,
    Right,
    Top,
    Bottom,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CellBorderPaint {
    pub side: CellSide,
    /// Opaque origin identity shared by physical pieces of the same source paint.
    /// It is not the current drawing's ID and is never used to locate a control.
    pub source_id: u32,
    /// Zero is the legacy single side. Nonzero is a certified union of sides.
    #[serde(default, skip_serializing_if = "zero")]
    pub sides: u8,
    /// The cell's own exact pen, when a wider neighbour wins the visible edge.
    /// Absent for source paint and whenever own and physical widths agree.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cell_pen: Option<u32>,
}
fn zero(v: &u8) -> bool {
    *v == 0
}
impl CellSide {
    pub(crate) fn index(self) -> usize {
        match self {
            Self::Left => 0,
            Self::Right => 1,
            Self::Top => 2,
            Self::Bottom => 3,
        }
    }
    pub(crate) fn from_index(i: usize) -> Self {
        [Self::Left, Self::Right, Self::Top, Self::Bottom][i]
    }
}
impl CellBorderPaint {
    pub(crate) fn from_mask(mask: u8, source_id: u32) -> Option<Self> {
        if mask == 0 || mask & !15 != 0 {
            return None;
        }
        Some(Self {
            side: CellSide::from_index(mask.trailing_zeros() as usize),
            source_id,
            sides: if mask.count_ones() > 1 { mask } else { 0 },
            cell_pen: None,
        })
    }
    pub(crate) fn mask(self) -> Option<u8> {
        if self
            .cell_pen
            .is_some_and(|p| p < 2 || p > i32::MAX as u32 || self.sides != 0)
        {
            return None;
        }
        if self.sides == 0 {
            Some(1 << self.side.index())
        } else if self.sides & !15 == 0
            && self.sides.count_ones() > 1
            && self.sides.trailing_zeros() as usize == self.side.index()
        {
            Some(self.sides)
        } else {
            None
        }
    }
}
/// Called only after validating the current binding. Remaining sides keep the
/// same physical crop/resource; the journal captures the old role for undo.
pub(crate) fn keep_sides(c: &mut Control, mask: u8, outside: bool) -> Option<()> {
    let a = match c {
        Control::Picture(p) => &mut p.common,
        Control::Shape(s) => s.common_mut(),
        _ => return None,
    };
    if outside {
        let tag = a.outside_cell_border_paint.as_mut()?;
        let pen = tag.paint.cell_pen;
        tag.paint = CellBorderPaint::from_mask(mask, tag.paint.source_id)?;
        tag.paint.cell_pen = pen;
    } else {
        let tag = a.cell_border_paint?;
        let mut kept = CellBorderPaint::from_mask(mask, tag.source_id)?;
        kept.cell_pen = tag.cell_pen;
        a.cell_border_paint = Some(kept);
    }
    Some(())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Owner {
    table: u32,
    row: u16,
    col: u16,
    row_span: u16,
    col_span: u16,
    width: u32,
    height: u32,
    left: i16,
    top: i16,
}

/// A page drawing keeps its physical owner; this is only its editing link.
/// The producer certifies closure of the original stroke, never a bbox guess.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct OutsideCellBorderPaint {
    owner: Owner,
    paint: CellBorderPaint,
    table_fingerprint: [u8; 32],
    fingerprint: [u8; 32],
}

// Feed the same canonical JSON bytes into the digest without an intermediate Vec.
fn hash_json(value: &mut Sha256, source: &impl Serialize) {
    struct DigestWriter<'a>(&'a mut Sha256);
    impl std::io::Write for DigestWriter<'_> {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.0.update(bytes);
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }
    serde_json::to_writer(DigestWriter(value), source).expect("serializable paint fingerprint");
}
fn table_fingerprint(t: &super::table::Table) -> [u8; 32] {
    let a = &t.common;
    let mut h = Sha256::new();
    for v in [
        a.instance_id,
        a.horizontal_offset,
        a.vertical_offset,
        a.width,
        a.height,
    ] {
        h.update(v.to_le_bytes());
    }
    hash_json(
        &mut h,
        &(
            a.horz_rel_to,
            a.vert_rel_to,
            a.horz_align,
            a.vert_align,
            a.treat_as_char,
            a.flow_with_text,
            a.text_wrap,
        ),
    );
    for c in &t.cells {
        hash_json(&mut h, &Owner::new(a.instance_id, c));
    }
    h.finalize().into()
}

/// One source paint contract consumed by serialization and native editing.
#[derive(Clone, Copy)]
pub(crate) enum PaintRef<'a> {
    Rectangle(&'a RectangleShape),
    Picture(&'a Picture),
}
impl<'a> PaintRef<'a> {
    pub(crate) fn from_control(c: &'a Control) -> Option<Self> {
        match c {
            Control::Shape(s) => match s.as_ref() {
                ShapeObject::Rectangle(r) => Some(Self::Rectangle(r)),
                _ => None,
            },
            Control::Picture(p) => Some(Self::Picture(p)),
            _ => None,
        }
    }
    pub(crate) fn common(self) -> &'a CommonObjAttr {
        match self {
            Self::Rectangle(r) => &r.common,
            Self::Picture(p) => &p.common,
        }
    }
    fn raster(self) -> bool {
        matches!(self, Self::Picture(_))
    }
    fn digest(self, resources: &mut Resources<'_>) -> Option<[u8; 32]> {
        match self {
            Self::Rectangle(r) => geometry_digest(r),
            Self::Picture(p) => picture_digest(p, resources),
        }
    }
    fn sealed(self, hash: [u8; 32]) -> bool {
        match self {
            Self::Rectangle(_) => true,
            Self::Picture(p) => p.border_paint_fingerprint == Some(hash),
        }
    }
}
enum PaintMut<'a> {
    Rectangle(&'a mut RectangleShape),
    Picture(&'a mut Picture),
}
impl PaintMut<'_> {
    fn as_ref(&self) -> PaintRef<'_> {
        match self {
            Self::Rectangle(r) => PaintRef::Rectangle(r),
            Self::Picture(p) => PaintRef::Picture(p),
        }
    }
    fn common(&mut self) -> &mut CommonObjAttr {
        match self {
            Self::Rectangle(r) => &mut r.common,
            Self::Picture(p) => &mut p.common,
        }
    }
    fn seal(&mut self, hash: [u8; 32]) {
        if let Self::Picture(p) = self {
            p.border_paint_fingerprint = Some(hash);
        }
    }
}
/// Hash each referenced PNG once per operation, using the renderer's index mapping.
/// Only producer-generated PNG stroke bitmaps can acquire this role.
pub(crate) struct Resources<'a> {
    contents: &'a [BinDataContent],
    hashes: BTreeMap<u16, Option<([u8; 32], (u32, u32))>>,
    reserve: Option<&'a dyn Fn(usize) -> Option<()>>,
}
impl<'a> Resources<'a> {
    pub(crate) fn new(contents: &'a [BinDataContent]) -> Self {
        Self {
            contents,
            hashes: BTreeMap::new(),
            reserve: None,
        }
    }

    pub(crate) fn with_reservation(
        contents: &'a [BinDataContent],
        reserve: &'a dyn Fn(usize) -> Option<()>,
    ) -> Self {
        Self {
            reserve: Some(reserve),
            ..Self::new(contents)
        }
    }

    fn image(&mut self, id: u16) -> Option<([u8; 32], (u32, u32))> {
        if !self.hashes.contains_key(&id) {
            if let Some(reserve) = self.reserve {
                reserve(
                    std::mem::size_of::<(u16, Option<([u8; 32], (u32, u32))>)>()
                        + 4 * std::mem::size_of::<usize>(),
                )?;
            }
        }
        *self.hashes.entry(id).or_insert_with(|| {
            let i = super::bin_data::content_index(self.contents, id)?;
            let bytes = match &self.contents[i].data {
                super::bin_data::BinDataBytes::Loaded(bytes) => {
                    std::borrow::Cow::Borrowed(bytes.as_slice())
                }
                other => {
                    if let Some(reserve) = self.reserve {
                        reserve(super::bin_data::MAX_BIN_DATA_BYTES)?;
                    }
                    std::borrow::Cow::Owned(
                        other.load_limited(super::bin_data::MAX_BIN_DATA_BYTES)?,
                    )
                }
            };
            if bytes.len() > super::bin_data::MAX_BIN_DATA_BYTES {
                return None;
            }
            if bytes.get(..16)? != b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR" {
                return None;
            }
            let w = u32::from_be_bytes(bytes.get(16..20)?.try_into().ok()?).checked_mul(75)?;
            let h = u32::from_be_bytes(bytes.get(20..24)?.try_into().ok()?).checked_mul(75)?;
            if w == 0 || h == 0 {
                return None;
            }
            Some((Sha256::digest(&bytes).into(), (w, h)))
        })
    }
}
pub(crate) fn picture_digest(p: &Picture, resources: &mut Resources<'_>) -> Option<[u8; 32]> {
    let a = &p.common;
    let s = &p.shape_attr;
    let (image, dim) = resources.image(p.image_attr.bin_data_id)?;
    // HWP has no imgDim field; its canonical PNG coordinate system is 75HU/px.
    if (p.img_dim != (0, 0) && p.img_dim != dim)
        || a.instance_id == 0
        || a.width == 0
        || a.height == 0
        || s.rotation_angle != 0
        || s.horz_flip
        || s.vert_flip
        || s.offset_x != 0
        || s.offset_y != 0
        || s.render_sx != 1.0
        || s.render_sy != 1.0
        || s.render_tx != 0.0
        || s.render_ty != 0.0
        || s.render_b != 0.0
        || s.render_c != 0.0
        || s.current_width != a.width
        || s.current_height != a.height
        || p.border_width != 0
        || p.reverse
        || p.caption.is_some()
        || p.effects.shadow.is_some()
        || p.href.is_some()
        || p.image_attr.brightness != 0
        || p.image_attr.contrast != 0
        || p.image_attr.transparency != 0
        || p.image_attr.external_path.is_some()
        || !matches!(p.image_attr.effect, super::image::ImageEffect::RealPic)
        || p.border_x != [0, 0, a.width as i32, 0]
        || p.border_y != [a.width as i32, a.height as i32, 0, a.height as i32]
        || p.crop.left < 0
        || p.crop.top < 0
        || p.crop.right <= p.crop.left
        || p.crop.bottom <= p.crop.top
        || p.crop.right as u32 > dim.0
        || p.crop.bottom as u32 > dim.1
        || p.padding.left != 0
        || p.padding.right != 0
        || p.padding.top != 0
        || p.padding.bottom != 0
    {
        return None;
    }
    let mut h = Sha256::new();
    for v in [a.horizontal_offset, a.vertical_offset, a.width, a.height] {
        h.update(v.to_le_bytes());
    }
    h.update(a.z_order.to_le_bytes());
    for v in [p.crop.left, p.crop.top, p.crop.right, p.crop.bottom] {
        h.update(v.to_le_bytes());
    }
    h.update(image);
    Some(h.finalize().into())
}
fn outside_fingerprint(p: PaintRef<'_>, resources: &mut Resources<'_>) -> Option<[u8; 32]> {
    let a = p.common();
    if a.treat_as_char
        || a.flow_with_text
        || a.horz_rel_to != HorzRelTo::Paper
        || a.vert_rel_to != VertRelTo::Paper
        || a.text_wrap != TextWrap::InFrontOfText
    {
        return None;
    }
    p.digest(resources)
}
pub(crate) fn seal_picture(c: &mut Control, resources: &mut Resources<'_>) -> Option<()> {
    if let Control::Picture(p) = c {
        p.border_paint_fingerprint = Some(picture_digest(p, resources)?);
    }
    Some(())
}
pub(crate) fn bind_outside(
    c: &mut Control,
    t: &super::table::Table,
    cell: usize,
    paint: CellBorderPaint,
    resources: &mut Resources<'_>,
) -> Option<()> {
    paint.mask()?;
    let owner = Owner::new(t.common.instance_id, t.cells.get(cell)?);
    let fingerprint = outside_fingerprint(PaintRef::from_control(c)?, resources)?;
    if owner.table == 0 || paint.source_id == 0 {
        return None;
    }
    let tag = OutsideCellBorderPaint {
        owner,
        paint,
        table_fingerprint: table_fingerprint(t),
        fingerprint,
    };
    match c {
        Control::Shape(s) => s.common_mut().outside_cell_border_paint = Some(tag),
        Control::Picture(p) => {
            p.border_paint_fingerprint = Some(fingerprint);
            p.common.outside_cell_border_paint = Some(tag);
        }
        _ => return None,
    }
    Some(())
}
pub(crate) fn outside_owner(
    p: PaintRef<'_>,
    t: &super::table::Table,
    resources: &mut Resources<'_>,
) -> Option<(usize, CellBorderPaint)> {
    let tag = p.common().outside_cell_border_paint?;
    tag.paint.mask()?;
    if tag.owner.table != t.common.instance_id
        || tag.table_fingerprint != table_fingerprint(t)
        || outside_fingerprint(p, resources) != Some(tag.fingerprint)
        || !p.sealed(tag.fingerprint)
    {
        return None;
    }
    Some((
        t.cells
            .iter()
            .position(|c| Owner::new(t.common.instance_id, c) == tag.owner)?,
        tag.paint,
    ))
}
pub(crate) fn outside_binding(p: PaintRef<'_>) -> Option<(u32, u16, u16, CellBorderPaint)> {
    p.common()
        .outside_cell_border_paint
        .map(|v| (v.owner.table, v.owner.row, v.owner.col, v.paint))
}
impl Owner {
    fn new(id: u32, c: &super::table::Cell) -> Self {
        Self {
            table: id,
            row: c.row,
            col: c.col,
            row_span: c.row_span,
            col_span: c.col_span,
            width: c.width,
            height: c.height,
            left: c.padding.left,
            top: c.padding.top,
        }
    }
}

/// Recheck the producer's binding against the current physical cell.
/// A stale tag never authorizes deletion of a drawing.
pub(crate) fn valid_paint(
    table: u32,
    cell: &super::table::Cell,
    p: PaintRef<'_>,
    resources: &mut Resources<'_>,
) -> Option<CellBorderPaint> {
    let paint = p.common().cell_border_paint?;
    let hash = fingerprint(p, Owner::new(table, cell), paint, resources)?;
    p.sealed(hash).then_some(paint)
}

/// Paint partitioned by the producer into a cell frame belongs before its text
/// flow. Hancom attaches a floating control after multiline text to the last
/// line, even with a zero offset. The caller supplies the actual source paint;
/// a coincident drawing or an editing-side tag alone does not prove this role.
/// Ordinary content controls retain their logical positions and relative order.
pub(crate) fn prepend_cell_paint(p: &mut Paragraph, mut paint: Vec<Control>) {
    if paint.is_empty() {
        return;
    }
    let count = paint.len();
    for c in &mut paint {
        match c {
            Control::Picture(p) => p.common.cell_frame_paint = true,
            Control::Shape(s) => s.common_mut().cell_frame_paint = true,
            _ => unreachable!("cell-frame producer emits drawings"),
        }
    }
    let mut positions = vec![0; count];
    positions.extend(p.logical_control_positions());
    let old_line_starts: Vec<_> = p.line_segs.iter().map(|s| s.text_start).collect();
    p.align_ctrl_data_records();
    p.controls.splice(0..0, paint);
    p.ctrl_data_records
        .splice(0..0, std::iter::repeat_n(None, count));
    for range in &mut p.field_ranges {
        range.control_idx += count;
    }
    p.control_mask |= 0x800;
    p.rebuild_char_offsets(&positions);
    for (start, _) in &mut p.layout_space_metrics {
        if let Some(i) = old_line_starts.iter().position(|old| old == start) {
            *start = p.line_segs[i].text_start;
        }
    }
    for (start, _) in &mut p.hwp3_saved_space_corrections {
        if let Some(i) = old_line_starts.iter().position(|old| old == start) {
            *start = p.line_segs[i].text_start;
        }
    }
}

fn frame_attributes(a: &CommonObjAttr) -> bool {
    !a.treat_as_char
        && a.flow_with_text
        && a.horz_rel_to == HorzRelTo::Column
        && a.vert_rel_to == VertRelTo::Para
        && a.text_wrap == TextWrap::BehindText
        && matches!(a.horz_align, super::shape::HorzAlign::Left)
        && matches!(a.vert_align, super::shape::VertAlign::Top)
}
pub(crate) fn is_cell_frame_paint(c: &Control) -> bool {
    PaintRef::from_control(c).is_some_and(|p| is_cell_frame_attributes(p.common()))
}
pub(crate) fn is_cell_frame_attributes(a: &CommonObjAttr) -> bool {
    a.cell_frame_paint && frame_attributes(a)
}
fn frame_fingerprint(p: PaintRef<'_>, o: Owner, resources: &mut Resources<'_>) -> Option<[u8; 32]> {
    let a = p.common();
    if !frame_attributes(a) {
        return None;
    }
    let x = i64::from(a.horizontal_offset as i32) + i64::from(o.left);
    let y = i64::from(a.vertical_offset as i32) + i64::from(o.top);
    if a.width == 0
        || a.height == 0
        || x < -1
        || y < -1
        || x + i64::from(a.width) > i64::from(o.width) + 1
        || y + i64::from(a.height) > i64::from(o.height) + 1
    {
        return None;
    }
    p.digest(resources)
}

fn geometry_digest(r: &RectangleShape) -> Option<[u8; 32]> {
    let a = &r.common;
    let s = &r.drawing.shape_attr;
    let color = r.drawing.fill.solid.as_ref()?.background_color;
    if a.instance_id == 0
        || a.width == 0
        || a.height == 0
        || r.drawing.text_box.is_some()
        || r.drawing.fill.fill_type != FillType::Solid
        || r.drawing.fill.alpha != 0
        || r.drawing.border_line.width != 0
        || r.round_rate != 0
        || r.drawing.shadow_type != 0
        || s.rotation_angle != 0
        || s.horz_flip
        || s.vert_flip
        || s.offset_x != 0
        || s.offset_y != 0
        || s.render_sx != 1.0
        || s.render_sy != 1.0
        || s.render_tx != 0.0
        || s.render_ty != 0.0
        || s.render_b != 0.0
        || s.render_c != 0.0
        || r.x_coords != [0, a.width as i32, a.width as i32, 0]
        || r.y_coords != [0, 0, a.height as i32, a.height as i32]
    {
        return None;
    }
    let mut h = Sha256::new();
    for v in [
        a.horizontal_offset,
        a.vertical_offset,
        a.width,
        a.height,
        color,
    ] {
        h.update(v.to_le_bytes());
    }
    h.update(a.z_order.to_le_bytes());
    Some(h.finalize().into())
}

fn fingerprint(
    p: PaintRef<'_>,
    o: Owner,
    paint: CellBorderPaint,
    resources: &mut Resources<'_>,
) -> Option<[u8; 32]> {
    let a = p.common();
    if o.table == 0
        || paint.source_id == 0
        || o.row_span == 0
        || o.col_span == 0
        || a.treat_as_char
        || !a.flow_with_text
        || a.horz_rel_to != HorzRelTo::Column
        || a.vert_rel_to != VertRelTo::Para
        || a.text_wrap != TextWrap::BehindText
    {
        return None;
    }
    let x = i64::from(a.horizontal_offset as i32) + i64::from(o.left);
    let y = i64::from(a.vertical_offset as i32) + i64::from(o.top);
    let right = x + i64::from(a.width);
    let bottom = y + i64::from(a.height);
    let mask = paint.mask()?;
    let edges = [
        x,
        right - i64::from(o.width),
        y,
        bottom - i64::from(o.height),
    ];
    // One source HWPUNIT of quantization; never relocate the drawing to fit.
    if edges
        .iter()
        .enumerate()
        .any(|(i, edge)| mask & (1 << i) != 0 && edge.abs() > 1)
        || x < -1
        || y < -1
        || right > i64::from(o.width) + 1
        || bottom > i64::from(o.height) + 1
    {
        return None;
    }
    p.digest(resources)
}

// SectionDef controls mirror the canonical master list; do not visit both copies.
fn walk<E>(
    ps: &[Paragraph],
    owner: Option<Owner>,
    f: &mut impl FnMut(&CommonObjAttr, Option<Owner>, Option<PaintRef<'_>>) -> Result<(), E>,
    depth: usize,
) -> Result<(), E> {
    if depth > 64 {
        return Ok(());
    }
    fn shape<E>(
        s: &ShapeObject,
        owner: Option<Owner>,
        f: &mut impl FnMut(&CommonObjAttr, Option<Owner>, Option<PaintRef<'_>>) -> Result<(), E>,
        depth: usize,
    ) -> Result<(), E> {
        if depth > 64 {
            return Ok(());
        }
        f(
            s.common(),
            owner,
            if let ShapeObject::Rectangle(r) = s {
                Some(PaintRef::Rectangle(r))
            } else {
                None
            },
        )?;
        if let Some(tb) = s.drawing().and_then(|d| d.text_box.as_ref()) {
            walk(&tb.paragraphs, None, f, depth + 1)?;
        }
        if let ShapeObject::Group(g) = s {
            for c in &g.children {
                shape(c, None, f, depth + 1)?;
            }
        }
        Ok(())
    }
    for p in ps {
        for c in &p.controls {
            match c {
                Control::Table(t) => {
                    f(&t.common, None, None)?;
                    for cell in &t.cells {
                        walk(
                            &cell.paragraphs,
                            Some(Owner::new(t.common.instance_id, cell)),
                            f,
                            depth + 1,
                        )?;
                    }
                }
                Control::Shape(s) => shape(s, owner, f, depth + 1)?,
                Control::Picture(p) => f(&p.common, owner, Some(PaintRef::Picture(p)))?,
                Control::Header(h) => walk(&h.paragraphs, None, f, depth + 1)?,
                Control::Footer(h) => walk(&h.paragraphs, None, f, depth + 1)?,
                Control::Footnote(n) => walk(&n.paragraphs, None, f, depth + 1)?,
                Control::Endnote(n) => walk(&n.paragraphs, None, f, depth + 1)?,
                _ => {}
            }
        }
    }
    Ok(())
}
fn walk_mut(
    ps: &mut [Paragraph],
    owner: Option<Owner>,
    f: &mut impl FnMut(PaintMut<'_>, Option<Owner>),
    depth: usize,
) {
    if depth > 64 {
        return;
    }
    fn shape(
        s: &mut ShapeObject,
        owner: Option<Owner>,
        f: &mut impl FnMut(PaintMut<'_>, Option<Owner>),
        depth: usize,
    ) {
        if depth > 64 {
            return;
        }
        if let ShapeObject::Rectangle(r) = s {
            f(PaintMut::Rectangle(r), owner);
        }
        if let Some(tb) = s.drawing_mut().and_then(|d| d.text_box.as_mut()) {
            walk_mut(&mut tb.paragraphs, None, f, depth + 1);
        }
        if let ShapeObject::Group(g) = s {
            for c in &mut g.children {
                shape(c, None, f, depth + 1);
            }
        }
    }
    for p in ps {
        for c in &mut p.controls {
            match c {
                Control::Table(t) => {
                    for cell in &mut t.cells {
                        let o = Owner::new(t.common.instance_id, cell);
                        walk_mut(&mut cell.paragraphs, Some(o), f, depth + 1);
                    }
                }
                Control::Shape(s) => shape(s, owner, f, depth + 1),
                Control::Picture(p) => f(PaintMut::Picture(p), owner),
                Control::Header(h) => walk_mut(&mut h.paragraphs, None, f, depth + 1),
                Control::Footer(h) => walk_mut(&mut h.paragraphs, None, f, depth + 1),
                Control::Footnote(n) => walk_mut(&mut n.paragraphs, None, f, depth + 1),
                Control::Endnote(n) => walk_mut(&mut n.paragraphs, None, f, depth + 1),
                _ => {}
            }
        }
    }
}
fn each(doc: &Document, f: &mut impl FnMut(&CommonObjAttr, Option<Owner>, Option<PaintRef<'_>>)) {
    let result: Result<(), std::convert::Infallible> = try_each(doc, &mut |a, owner, rect| {
        f(a, owner, rect);
        Ok(())
    });
    match result {
        Ok(()) => (),
        Err(never) => match never {},
    }
}
fn try_each<E>(
    doc: &Document,
    f: &mut impl FnMut(&CommonObjAttr, Option<Owner>, Option<PaintRef<'_>>) -> Result<(), E>,
) -> Result<(), E> {
    for s in &doc.sections {
        walk(&s.paragraphs, None, f, 0)?;
        for m in &s.section_def.master_pages {
            walk(&m.paragraphs, None, f, 0)?;
        }
    }
    Ok(())
}

struct Record {
    id: u32,
    owner: Owner,
    paint: CellBorderPaint,
    fingerprint: [u8; 32],
    outside: Option<[u8; 32]>,
    raster: bool,
    frame: bool,
    frame_only: bool,
}
impl Record {
    fn write(&self, out: &mut Vec<u8>, compound: bool, cell_pens: bool) {
        let o = self.owner;
        out.extend(self.id.to_le_bytes());
        out.extend(o.table.to_le_bytes());
        for v in [o.row, o.col, o.row_span, o.col_span] {
            out.extend(v.to_le_bytes());
        }
        for v in [o.width, o.height] {
            out.extend(v.to_le_bytes());
        }
        for v in [o.left, o.top] {
            out.extend(v.to_le_bytes());
        }
        out.push(
            (if self.frame_only {
                0
            } else if compound {
                self.paint.mask().expect("validated paint mask")
            } else {
                match self.paint.side {
                    CellSide::Left => 0,
                    CellSide::Right => 1,
                    CellSide::Top => 2,
                    CellSide::Bottom => 3,
                }
            }) | if self.frame { 0x10 } else { 0 }
                | if self.frame_only { 0x20 } else { 0 }
                | if self.outside.is_some() { 0x80 } else { 0 }
                | if self.raster { 0x40 } else { 0 },
        );
        out.extend(self.paint.source_id.to_le_bytes());
        out.extend(self.fingerprint);
        if let Some(frame) = self.outside {
            out.extend(frame);
        }
        if cell_pens {
            out.extend(self.paint.cell_pen.unwrap_or(0).to_le_bytes());
        }
    }
    fn read(bytes: &[u8], compound: bool, cell_pens: bool, frames: bool) -> Option<Self> {
        fn take<const N: usize>(b: &[u8], i: &mut usize) -> Option<[u8; N]> {
            let v = b.get(*i..*i + N)?.try_into().ok()?;
            *i += N;
            Some(v)
        }
        let mut i = 0;
        let id = u32::from_le_bytes(take(bytes, &mut i)?);
        let owner = Owner {
            table: u32::from_le_bytes(take(bytes, &mut i)?),
            row: u16::from_le_bytes(take(bytes, &mut i)?),
            col: u16::from_le_bytes(take(bytes, &mut i)?),
            row_span: u16::from_le_bytes(take(bytes, &mut i)?),
            col_span: u16::from_le_bytes(take(bytes, &mut i)?),
            width: u32::from_le_bytes(take(bytes, &mut i)?),
            height: u32::from_le_bytes(take(bytes, &mut i)?),
            left: i16::from_le_bytes(take(bytes, &mut i)?),
            top: i16::from_le_bytes(take(bytes, &mut i)?),
        };
        let flag = take::<1>(bytes, &mut i)?[0];
        if !frames && flag & 0x30 != 0 {
            return None;
        }
        let frame = flag & 0x10 != 0;
        let frame_only = flag & 0x20 != 0;
        let paint_flag = flag & if frames { 0x0f } else { 0x3f };
        if frame_only && (!frame || paint_flag != 0 || flag & 0x80 != 0) {
            return None;
        }
        let side = if frame_only {
            CellSide::Left
        } else if compound {
            CellBorderPaint::from_mask(paint_flag, 1)?.side
        } else {
            match paint_flag {
                0 => CellSide::Left,
                1 => CellSide::Right,
                2 => CellSide::Top,
                3 => CellSide::Bottom,
                _ => return None,
            }
        };
        let source_id = u32::from_le_bytes(take(bytes, &mut i)?);
        let mut record = Self {
            id,
            owner,
            paint: if compound && !frame_only {
                CellBorderPaint::from_mask(paint_flag, source_id)?
            } else {
                CellBorderPaint {
                    side,
                    source_id,
                    sides: 0,
                    cell_pen: None,
                }
            },
            fingerprint: take(bytes, &mut i)?,
            raster: flag & 0x40 != 0,
            frame,
            frame_only,
            outside: if flag & 0x80 != 0 {
                Some(take(bytes, &mut i)?)
            } else {
                None
            },
        };
        if cell_pens {
            let pen = u32::from_le_bytes(take(bytes, &mut i)?);
            if record.frame_only && pen != 0 {
                return None;
            }
            record.paint.cell_pen = (pen != 0).then_some(pen);
            record.paint.mask()?;
        }
        Some(record)
    }
}

pub fn encode(doc: &Document) -> Result<Option<Vec<u8>>, String> {
    encode_with_storage(doc, &crate::storage::Unbounded)
}
pub(crate) fn encode_with_storage<S: crate::storage::Storage>(
    doc: &Document,
    storage: &S,
) -> Result<Option<Vec<u8>>, String>
where
    S::Error: std::fmt::Display,
{
    let mut counts = BTreeMap::<u32, usize>::new();
    let mut records = Vec::new();
    let mut over_budget = false;
    let failure = std::cell::RefCell::new(None);
    let reserve = |count| match storage.bytes(count) {
        Ok(()) => Some(()),
        Err(error) => {
            *failure.borrow_mut() = Some(error.to_string());
            None
        }
    };
    let mut resources = Resources::with_reservation(&doc.bin_data_content, &reserve);
    try_each(doc, &mut |a, owner, rect| {
        storage.bytes(0).map_err(|e| e.to_string())?;
        if !counts.contains_key(&a.instance_id) {
            storage
                .tree_entry::<u32, usize>()
                .map_err(|e| e.to_string())?;
        }
        *counts.entry(a.instance_id).or_default() += 1;
        if let (Some(owner), Some(rect)) = (owner, rect) {
            let border = a.cell_border_paint.and_then(|paint| {
                fingerprint(rect, owner, paint, &mut resources)
                    .filter(|h| rect.sealed(*h))
                    .map(|h| (paint, h))
            });
            let frame = a
                .cell_frame_paint
                .then(|| frame_fingerprint(rect, owner, &mut resources))
                .flatten();
            if border.is_some() || frame.is_some() {
                if records.len() == MAX_RECORDS {
                    over_budget = true;
                    return Ok(());
                }
                let (paint, hash, frame_only) = if let Some((paint, hash)) = border {
                    (paint, hash, false)
                } else {
                    (
                        CellBorderPaint {
                            side: CellSide::Left,
                            source_id: 0,
                            sides: 0,
                            cell_pen: None,
                        },
                        frame.unwrap(),
                        true,
                    )
                };
                storage
                    .push(
                        &mut records,
                        Record {
                            id: a.instance_id,
                            owner,
                            paint,
                            fingerprint: hash,
                            outside: None,
                            raster: rect.raster(),
                            frame: frame == Some(hash),
                            frame_only,
                        },
                    )
                    .map_err(|e| e.to_string())?;
            }
        }
        if let (Some(tag), None, Some(rect)) = (a.outside_cell_border_paint, owner, rect) {
            let table = doc
                .sections
                .iter()
                .flat_map(|s| &s.paragraphs)
                .flat_map(|p| &p.controls)
                .find_map(|c| match c {
                    Control::Table(t) if t.common.instance_id == tag.owner.table => {
                        Some(t.as_ref())
                    }
                    _ => None,
                });
            if table.is_some_and(|t| outside_owner(rect, t, &mut resources).is_some()) {
                if records.len() == MAX_RECORDS {
                    over_budget = true;
                    return Ok(());
                }
                storage
                    .push(
                        &mut records,
                        Record {
                            id: a.instance_id,
                            owner: tag.owner,
                            paint: tag.paint,
                            fingerprint: tag.fingerprint,
                            outside: Some(tag.table_fingerprint),
                            raster: rect.raster(),
                            frame: false,
                            frame_only: false,
                        },
                    )
                    .map_err(|e| e.to_string())?;
            }
        }
        if let Some(error) = failure.borrow_mut().take() {
            return Err(error);
        }
        Ok(())
    })?;
    if records.is_empty() {
        return Ok(None);
    }
    let frames = records.iter().any(|r| r.frame);
    let cell_pens = frames || records.iter().any(|r| r.paint.cell_pen.is_some());
    let size = HEADER_BYTES
        + records
            .iter()
            .map(|r| {
                RECORD_BYTES
                    + if r.outside.is_some() { 32 } else { 0 }
                    + if cell_pens { 4 } else { 0 }
            })
            .sum::<usize>();
    if over_budget || size > MAX_BYTES {
        return Err("cell border paint metadata budget exceeded".into());
    }
    if records
        .iter()
        .any(|r| counts.get(&r.id) != Some(&1) || counts.get(&r.owner.table) != Some(&1))
    {
        return Err("ambiguous cell border paint ownership".into());
    }
    let mut bytes = storage.vec(size).map_err(|e| e.to_string())?;
    let compound = cell_pens || records.iter().any(|r| r.paint.sides != 0);
    bytes.extend(if frames {
        MAGIC_CELL_FRAME
    } else if cell_pens {
        MAGIC_CELL_PEN
    } else if compound {
        MAGIC_COMPOUND
    } else if records.iter().any(|r| r.raster) {
        MAGIC_RASTER
    } else if records.iter().any(|r| r.outside.is_some()) {
        MAGIC_OUTSIDE
    } else {
        MAGIC
    });
    bytes.extend((records.len() as u32).to_le_bytes());
    for r in records {
        r.write(&mut bytes, compound, cell_pens);
    }
    Ok(Some(bytes))
}
pub fn decode(doc: &mut Document, bytes: &[u8]) {
    if bytes.len() > MAX_BYTES {
        return;
    }
    if bytes.len() < HEADER_BYTES
        || (&bytes[..8] != MAGIC
            && &bytes[..8] != MAGIC_OUTSIDE
            && &bytes[..8] != MAGIC_RASTER
            && &bytes[..8] != MAGIC_COMPOUND
            && &bytes[..8] != MAGIC_CELL_PEN
            && &bytes[..8] != MAGIC_CELL_FRAME)
    {
        return;
    }
    let count = u32::from_le_bytes(bytes[8..12].try_into().unwrap()) as usize;
    let frames = &bytes[..8] == MAGIC_CELL_FRAME;
    let cell_pens = frames || &bytes[..8] == MAGIC_CELL_PEN;
    let compound = cell_pens || &bytes[..8] == MAGIC_COMPOUND;
    let outside_version = &bytes[..8] == MAGIC_OUTSIDE || &bytes[..8] == MAGIC_RASTER || compound;
    let raster_version = &bytes[..8] == MAGIC_RASTER || compound;
    if count > MAX_RECORDS || bytes.len() < HEADER_BYTES + count * RECORD_BYTES {
        return;
    }
    let mut ids = BTreeSet::new();
    let mut records = BTreeMap::new();
    let mut offset = HEADER_BYTES;
    for _ in 0..count {
        let Some(r) = Record::read(&bytes[offset..], compound, cell_pens, frames) else {
            return;
        };
        if (r.outside.is_some() && !outside_version)
            || (r.raster && !raster_version)
            || r.owner.table == 0
            || (r.paint.source_id == 0 && !r.frame_only)
            || (r.frame_only && r.paint.source_id != 0)
            || (r.frame && r.outside.is_some())
        {
            return;
        }
        offset +=
            RECORD_BYTES + if r.outside.is_some() { 32 } else { 0 } + if cell_pens { 4 } else { 0 };
        if r.id == 0 || !ids.insert(r.id) {
            return;
        }
        records.insert(r.id, r);
    }
    if offset != bytes.len() {
        return;
    }
    let mut counts = BTreeMap::<u32, usize>::new();
    each(doc, &mut |a, _, _| {
        *counts.entry(a.instance_id).or_default() += 1
    });
    let tables = doc
        .sections
        .iter()
        .flat_map(|s| &s.paragraphs)
        .flat_map(|p| &p.controls)
        .filter_map(|c| match c {
            Control::Table(t) => Some((
                t.common.instance_id,
                (
                    table_fingerprint(t),
                    t.cells
                        .iter()
                        .map(|c| Owner::new(t.common.instance_id, c))
                        .collect::<Vec<_>>(),
                ),
            )),
            _ => None,
        })
        .collect::<BTreeMap<_, _>>();
    let mut resources = Resources::new(&doc.bin_data_content);
    let mut restore = |mut r: PaintMut<'_>, owner: Option<Owner>| {
        let Some(record) = records.get(&r.as_ref().common().instance_id) else {
            return;
        };
        if counts.get(&record.id) != Some(&1)
            || counts.get(&record.owner.table) != Some(&1)
            || r.as_ref().raster() != record.raster
        {
            return;
        }
        if let Some(frame) = record.outside {
            if owner.is_none()
                && tables
                    .get(&record.owner.table)
                    .is_some_and(|(hash, cells)| *hash == frame && cells.contains(&record.owner))
                && outside_fingerprint(r.as_ref(), &mut resources) == Some(record.fingerprint)
            {
                r.seal(record.fingerprint);
                r.common().outside_cell_border_paint = Some(OutsideCellBorderPaint {
                    owner: record.owner,
                    paint: record.paint,
                    table_fingerprint: frame,
                    fingerprint: record.fingerprint,
                });
            }
        } else if counts.get(&record.id) == Some(&1)
            && counts.get(&record.owner.table) == Some(&1)
            && owner == Some(record.owner)
            && (if record.frame_only {
                frame_fingerprint(r.as_ref(), record.owner, &mut resources)
            } else {
                fingerprint(r.as_ref(), record.owner, record.paint, &mut resources)
            }) == Some(record.fingerprint)
            && (!record.frame
                || frame_fingerprint(r.as_ref(), record.owner, &mut resources)
                    == Some(record.fingerprint))
        {
            r.seal(record.fingerprint);
            r.common().cell_frame_paint = record.frame;
            if !record.frame_only {
                r.common().cell_border_paint = Some(record.paint);
            }
        }
    };
    for s in &mut doc.sections {
        walk_mut(&mut s.paragraphs, None, &mut restore, 0);
        for m in &mut s.section_def.master_pages {
            walk_mut(&mut m.paragraphs, None, &mut restore, 0);
        }
    }
}
pub fn native_editing_loss() -> crate::serializer::content_loss::ContentLoss {
    match native_editing_loss_with_storage(&crate::storage::Unbounded) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}
pub(crate) fn native_editing_loss_with_storage<S: crate::storage::Storage>(
    storage: &S,
) -> Result<crate::serializer::content_loss::ContentLoss, S::Error> {
    use crate::serializer::content_loss::*;
    Ok(ContentLoss {
        code: ContentLossCode::MetadataReduced,
        subject: ContentLossSubject::Control,
        path: storage.string("셀 테두리 그림 소유: rhwp 왕복 보존, 한컴 편집 소유 미지원")?,
        reason: ContentLossReason::UnsupportedByOutputFormat,
        resource_id: None,
    })
}