rhwp 0.9.1

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
//! 컨트롤 파싱 (표, 도형, 그림, 머리말/꼬리말, 각주/미주)
//!
//! CTRL_HEADER의 ctrl_id로 컨트롤 종류를 식별하여 파싱한다.
//! 셀, 머리말/꼬리말 등의 내부 문단은 body_text::parse_paragraph_list로 재귀 처리.

use super::body_text::parse_paragraph_list;
use super::byte_reader::ByteReader;
use super::record::Record;
use super::tags;

use crate::model::control::{
    AutoNumber, AutoNumberType, Bookmark, CharOverlap, Control, Equation, Field, FieldType,
    FormObject, FormType, HiddenComment, IndexMark, NewNumber, PageHide, PageNumCtrl,
    PageNumberPos, PageStartsOn, UnknownControl,
};
use crate::model::footnote::{Endnote, Footnote};
use crate::model::header_footer::{Footer, Header, HeaderFooterApply};
use crate::model::shape::{Caption, CaptionDirection, CaptionVertAlign};
use crate::model::table::{Cell, Table, TablePageBreak, VerticalAlign};
use crate::model::Padding;

/// ctrl_id 기반으로 컨트롤 파싱
///
/// body_text::parse_ctrl_header에서 secd/cold 이외의 컨트롤을 위임받는다.
pub fn parse_control(ctrl_id: u32, ctrl_data: &[u8], child_records: &[Record]) -> Control {
    match ctrl_id {
        tags::CTRL_TABLE => parse_table_control(ctrl_data, child_records),
        tags::CTRL_GEN_SHAPE => parse_gso_control(ctrl_data, child_records),
        tags::CTRL_HEADER => parse_header_control(ctrl_data, child_records),
        tags::CTRL_FOOTER => parse_footer_control(ctrl_data, child_records),
        tags::CTRL_FOOTNOTE => parse_footnote_control(ctrl_data, child_records),
        tags::CTRL_ENDNOTE => parse_endnote_control(ctrl_data, child_records),
        tags::CTRL_HIDDEN_COMMENT => parse_hidden_comment_control(child_records),
        tags::CTRL_AUTO_NUMBER => parse_auto_number(ctrl_data),
        tags::CTRL_NEW_NUMBER => parse_new_number(ctrl_data),
        tags::CTRL_PAGE_NUM_POS => parse_page_num_pos(ctrl_data),
        tags::CTRL_PAGE_HIDE => parse_page_hide(ctrl_data),
        tags::CTRL_BOOKMARK => parse_bookmark(ctrl_data),
        tags::CTRL_INDEX_MARK => parse_index_mark(ctrl_data),
        tags::CTRL_PAGE_NUM_CTRL => parse_page_num_ctrl(ctrl_data),
        // [#4397] 'tdut'(덧말) — 상수 이름과 달리 CTRL_CHAR_OVERLAP 이 'tdut' 다.
        tags::CTRL_CHAR_OVERLAP => parse_ruby(ctrl_data),
        tags::CTRL_TCPS => parse_char_overlap(ctrl_data),
        tags::CTRL_EQUATION => parse_equation_control(ctrl_data, child_records),
        tags::CTRL_FORM => parse_form_control(ctrl_data, child_records),
        id if tags::is_field_ctrl_id(id) => parse_field_control(id, ctrl_data),
        _ => Control::Unknown(UnknownControl { ctrl_id }),
    }
}

// ============================================================
// 필드 컨트롤 (%clk, %hlk 등)
// ============================================================

/// ctrl_id를 FieldType으로 매핑
fn ctrl_id_to_field_type(ctrl_id: u32) -> FieldType {
    match ctrl_id {
        tags::FIELD_CLICKHERE => FieldType::ClickHere,
        tags::FIELD_HYPERLINK => FieldType::Hyperlink,
        tags::FIELD_BOOKMARK => FieldType::Bookmark,
        tags::FIELD_DATE => FieldType::Date,
        tags::FIELD_DOCDATE => FieldType::DocDate,
        tags::FIELD_PATH => FieldType::Path,
        tags::FIELD_MAILMERGE => FieldType::MailMerge,
        tags::FIELD_CROSSREF => FieldType::CrossRef,
        tags::FIELD_FORMULA => FieldType::Formula,
        tags::FIELD_SUMMARY => FieldType::Summary,
        tags::FIELD_USERINFO => FieldType::UserInfo,
        tags::FIELD_MEMO => FieldType::Memo,
        tags::FIELD_PRIVATE_INFO => FieldType::PrivateInfoSecurity,
        tags::FIELD_TOC => FieldType::TableOfContents,
        _ => FieldType::Unknown,
    }
}

/// 필드 컨트롤 파싱 (표 154: ctrl_id + 속성 + 기타속성 + command + id)
///
/// ctrl_data는 CTRL_HEADER에서 ctrl_id(4바이트)를 제외한 나머지 데이터이다.
/// 그러나 HWP 파일에서 필드의 CTRL_HEADER 포맷은 일반 컨트롤과 다르다:
/// - 일반 컨트롤: CTRL_HEADER = [ctrl_id(4)] + [ctrl_data]
/// - 필드 컨트롤: CTRL_HEADER = [ctrl_id(4)] + [속성(4)] + [기타속성(1)] + [command_len(2)] + [command] + [id(4)]
fn parse_field_control(ctrl_id: u32, ctrl_data: &[u8]) -> Control {
    let mut field_type = ctrl_id_to_field_type(ctrl_id);

    // ctrl_data: 속성(4) + 기타속성(1) + command_len(2) + command(가변) + id(4)
    if ctrl_data.len() < 7 {
        // 데이터가 부족하면 최소한의 Field 반환
        return Control::Field(Field {
            field_type,
            ctrl_id,
            ..Default::default()
        });
    }

    let mut reader = ByteReader::new(ctrl_data);
    let properties = reader.read_u32().unwrap_or(0);
    let extra_properties = reader.read_u8().unwrap_or(0);
    let command_len = reader.read_u16().unwrap_or(0) as usize;

    let command = if command_len > 0 && reader.remaining() >= command_len * 2 {
        let mut chars = Vec::with_capacity(command_len);
        for _ in 0..command_len {
            chars.push(reader.read_u16().unwrap_or(0));
        }
        String::from_utf16_lossy(&chars)
    } else {
        String::new()
    };

    let field_id = if reader.remaining() >= 4 {
        reader.read_u32().unwrap_or(0)
    } else {
        0
    };

    let mut memo_index = if reader.remaining() >= 4 {
        reader.read_u32().unwrap_or(0)
    } else {
        0
    };
    // Hancom writes a memo's control id as `%unk` and only the command says
    // MEMO. The real number may live in the command when the trailing slot is 0.
    if command.starts_with("MEMO/") {
        if field_type == FieldType::Unknown {
            field_type = FieldType::Memo;
        }
        if memo_index == 0 {
            memo_index = command
                .split('/')
                .nth(2)
                .and_then(|token| token.parse().ok())
                .unwrap_or(0);
        }
    }

    Control::Field(Field {
        field_type,
        command,
        properties,
        extra_properties,
        field_id,
        ctrl_id,
        instance_id: None,
        // [#4896] HWP5 는 ctrl_id 자체가 종류라 원문 문자열이 없다 — 직렬화기가
        // `tags::OWPML_EXTRA_FIELD_TYPES` 로 ctrl_id 에서 이름을 되찾는다.
        raw_type: None,
        ctrl_data_name: None,
        memo_index,
        memo_paragraphs: Vec::new(),
        memo_text_direction: None,
        raw_parameters_xml: None,
        parameters: Default::default(),
        guide_residue: None,
        hyperlink_format: None,
    })
}

// ============================================================
// 표 ('tbl ')
// ============================================================

/// 표 컨트롤 파싱
fn parse_table_control(ctrl_data: &[u8], child_records: &[Record]) -> Control {
    let mut table = Table::default();

    // ctrl_data = CommonObjAttr (Shape/GSO와 동일 구조, hwplib: ForCtrlHeaderGso)
    // 표의 CTRL_HEADER는 Shape와 동일한 CommonObjAttr로 시작
    if !ctrl_data.is_empty() {
        table.common = super::control::shape::parse_common_obj_attr(ctrl_data);
        // CommonObjAttr.attr → table.attr 동기화 (기존 코드 호환)
        table.attr = table.common.attr;
        // 라운드트립 보존용 원본 데이터
        table.raw_ctrl_data = ctrl_data.to_vec();
        // 바깥 여백 파싱 (CommonObjAttr 내 offset 24..32)
        if ctrl_data.len() >= 32 {
            table.outer_margin_left = i16::from_le_bytes([ctrl_data[24], ctrl_data[25]]);
            table.outer_margin_right = i16::from_le_bytes([ctrl_data[26], ctrl_data[27]]);
            table.outer_margin_top = i16::from_le_bytes([ctrl_data[28], ctrl_data[29]]);
            table.outer_margin_bottom = i16::from_le_bytes([ctrl_data[30], ctrl_data[31]]);
        }
    }

    // HWPTAG_TABLE 레코드 위치 찾기
    //
    // [#3528] **직계 자식 레벨**의 것만 본다. 종전에는 첫 HWPTAG_TABLE 을 그냥 집었는데,
    // 캡션 문단 안에 표가 들어 있으면 그 표가 자기 HWPTAG_TABLE 을 더 앞에 방출한다
    // (저장 순서: CTRL_TABLE → 캡션 → HWPTAG_TABLE → 셀). 그러면 캡션 범위가 거기서
    // 끊겨 캡션 문단이 잘리고, 그 안의 표도 얕게 읽힌다.
    //
    // 직계 자식은 모두 CTRL_HEADER 바로 아래 레벨이므로(캡션 LIST_HEADER·HWPTAG_TABLE·
    // 셀 LIST_HEADER 가 같은 레벨), 자식 레코드의 최소 레벨이 곧 직계 레벨이다.
    let direct_level = child_records.iter().map(|r| r.level).min();
    let table_record_idx = child_records
        .iter()
        .position(|r| r.tag_id == tags::HWPTAG_TABLE && Some(r.level) == direct_level);

    // HWPTAG_TABLE 이전에 LIST_HEADER가 있으면 캡션
    if let Some(table_idx) = table_record_idx {
        // 캡션 LIST_HEADER 찾기 (TABLE 이전)
        let caption_start = child_records[..table_idx]
            .iter()
            .position(|r| r.tag_id == tags::HWPTAG_LIST_HEADER);

        if let Some(start) = caption_start {
            // 캡션 레코드 범위 수집 (TABLE 레코드 이전까지)
            let caption_records: Vec<Record> =
                child_records[start..table_idx].iter().cloned().collect();
            if !caption_records.is_empty() {
                table.caption = Some(parse_caption(&caption_records));
            }
        }
    }

    // 자식 레코드 순회: TABLE, LIST_HEADER(셀)
    let mut idx = 0;
    let mut table_record_seen = false;

    while idx < child_records.len() {
        match child_records[idx].tag_id {
            tags::HWPTAG_TABLE => {
                parse_table_record(&child_records[idx].data, &mut table);
                table_record_seen = true;
                idx += 1;
            }
            tags::HWPTAG_LIST_HEADER => {
                // TABLE 레코드 이전의 LIST_HEADER는 캡션 (이미 처리됨)
                if !table_record_seen {
                    // 캡션 레코드 건너뛰기
                    let base_level = child_records[idx].level;
                    idx += 1;
                    while idx < child_records.len() {
                        if child_records[idx].level <= base_level {
                            if child_records[idx].tag_id == tags::HWPTAG_TABLE
                                || child_records[idx].tag_id == tags::HWPTAG_LIST_HEADER
                            {
                                break;
                            }
                        }
                        idx += 1;
                    }
                    continue;
                }

                // TABLE 레코드 이후의 LIST_HEADER는 셀
                let base_level = child_records[idx].level;
                let start = idx;
                idx += 1;
                // 다음 셀(LIST_HEADER) 또는 다른 레코드까지 수집
                while idx < child_records.len() {
                    if child_records[idx].level < base_level {
                        break;
                    }
                    // 같은 레벨의 LIST_HEADER/TABLE은 다음 셀이므로 중단
                    if child_records[idx].level == base_level {
                        match child_records[idx].tag_id {
                            tags::HWPTAG_LIST_HEADER | tags::HWPTAG_TABLE => break,
                            _ => {}
                        }
                    }
                    idx += 1;
                }
                let cell = parse_cell(&child_records[start..idx]);
                table.cells.push(cell);
            }
            _ => {
                idx += 1;
            }
        }
    }

    table.rebuild_grid();
    Control::Table(Box::new(table))
}

/// HWPTAG_TABLE 레코드 데이터 파싱
fn parse_table_record(data: &[u8], table: &mut Table) {
    let mut r = ByteReader::new(data);

    let attr = r.read_u32().unwrap_or(0);
    table.page_break = match attr & 0x03 {
        1 | 3 => TablePageBreak::CellBreak,
        2 => TablePageBreak::RowBreak,
        _ => TablePageBreak::None,
    };
    table.repeat_header = attr & 0x04 != 0;
    // 원본 attr 전체 보존 (라운드트립용)
    table.raw_table_record_attr = attr;

    table.row_count = r.read_u16().unwrap_or(0);
    table.col_count = r.read_u16().unwrap_or(0);
    table.cell_spacing = r.read_i16().unwrap_or(0);

    // 안쪽 여백
    table.padding = Padding {
        left: r.read_i16().unwrap_or(0),
        right: r.read_i16().unwrap_or(0),
        top: r.read_i16().unwrap_or(0),
        bottom: r.read_i16().unwrap_or(0),
    };

    // 행별 셀 수 (HWP 스펙: UINT16[NRows])
    for _ in 0..table.row_count {
        if let Ok(h) = r.read_i16() {
            table.row_sizes.push(h);
        }
    }

    table.border_fill_id = r.read_u16().unwrap_or(0);

    // 영역 속성 (zones): UINT16 nZones + TableZone[nZones]
    if r.remaining() >= 2 {
        let n_zones = r.read_u16().unwrap_or(0) as usize;
        for _ in 0..n_zones {
            if r.remaining() >= 10 {
                let start_row = r.read_u16().unwrap_or(0);
                let start_col = r.read_u16().unwrap_or(0);
                let end_row = r.read_u16().unwrap_or(0);
                let end_col = r.read_u16().unwrap_or(0);
                let bf_id = r.read_u16().unwrap_or(0);
                table.zones.push(crate::model::table::TableZone {
                    start_col,
                    start_row,
                    end_col,
                    end_row,
                    border_fill_id: bf_id,
                });
            }
        }
    }

    // 나머지 추가 데이터 보존 (라운드트립용)
    if r.remaining() > 0 {
        table.raw_table_record_extra = r.read_bytes(r.remaining()).unwrap_or_default();
    }
}

/// 표 셀 파싱 (LIST_HEADER + 내부 문단)
///
/// records[0] = LIST_HEADER, records[1..] = 셀 내부 레코드
fn parse_cell(records: &[Record]) -> Cell {
    let mut cell = Cell::default();

    if records.is_empty() {
        return cell;
    }

    let data = &records[0].data;
    let mut r = ByteReader::new(data);

    // LIST_HEADER 공통 필드
    let _n_paragraphs = r.read_u16().unwrap_or(0);
    let list_attr = r.read_u32().unwrap_or(0);
    cell.list_header_width_ref = r.read_u16().unwrap_or(0);

    // list_attr 비트필드에서 텍스트 방향, 세로 정렬 추출 (표 67)
    // 스펙 문서는 bit 0~6으로 기술하지만, 실제로는 상위 16비트(bit 16~22)에 위치
    // bit 16~18: 텍스트 방향 (0=가로, 1=세로)
    // bit 19~20: 줄바꿈 방식
    // bit 21~22: 세로 정렬 (0=top, 1=center, 2=bottom)
    cell.text_direction = ((list_attr >> 16) & 0x07) as u8;
    // [#4898] 줄바꿈 방식(bit 19~20)도 싣는다 — 종전엔 읽지 않아 저장에서 0(BREAK)으로
    // 굳었고, SQUEEZE 셀의 줄 수·높이가 달라져 한글 쪽수까지 흔들렸다.
    cell.line_wrap = ((list_attr >> 19) & 0x03) as u8;
    let v_align = ((list_attr >> 21) & 0x03) as u8;
    cell.vertical_align = match v_align {
        1 => VerticalAlign::Center,
        2 => VerticalAlign::Bottom,
        _ => VerticalAlign::Top,
    };

    // list_header_width_ref (bytes 6-7)에는 셀 확장 속성이 포함됨
    // hwplib ListHeaderPropertyForCell 기준:
    //   bit 0 (=property bit 16): 안 여백 지정
    //   bit 1 (=property bit 17): 셀 보호
    //   bit 2 (=property bit 18): 제목 셀
    //   bit 3 (=property bit 19): 양식모드 편집 가능
    // 현재 IR은 미해석 확장 bit를 분해하지 않고 list_header_width_ref 원값으로 보존한다.
    cell.is_header = cell.list_header_width_ref & crate::model::table::CELL_FLAG_HEADER != 0;

    // 셀 속성 (표 82: 26바이트)
    cell.col = r.read_u16().unwrap_or(0);
    cell.row = r.read_u16().unwrap_or(0);
    // 손상된 문서는 colSpan/rowSpan에 0을 기록할 수 있다. HWPX/HWP3 파서는
    // 이미 .max(1)로 최소 1을 보장하므로 HWP5도 동일하게 정규화한다
    // (0이면 이후 병합/렌더링 로직의 `row + row_span - 1` 계산이 언더플로한다).
    cell.col_span = r.read_u16().unwrap_or(1).max(1);
    cell.row_span = r.read_u16().unwrap_or(1).max(1);
    cell.width = r.read_u32().unwrap_or(0);
    cell.height = r.read_u32().unwrap_or(0);

    cell.padding = Padding {
        left: r.read_i16().unwrap_or(0),
        right: r.read_i16().unwrap_or(0),
        top: r.read_i16().unwrap_or(0),
        bottom: r.read_i16().unwrap_or(0),
    };

    cell.border_fill_id = r.read_u16().unwrap_or(0);

    // "안 여백 지정" (LIST_HEADER bytes 6-7 bit 0, hwplib: isApplyInnerMargin) 미설정이면
    // 셀 패딩을 무시하고 테이블 기본 패딩을 사용해야 함
    // HWP는 이 비트가 0이어도 패딩 필드에 값을 저장하지만 렌더링에서 무시
    // "안 여백 지정" (width_ref bit 0): 셀 고유 여백 vs 표 기본 여백 선택
    // bit 0=1: 셀 고유 여백 사용 (파싱한 패딩값 그대로)
    // bit 0=0: 표 기본 여백 사용 — 단, 레이아웃 시 표 기본 패딩으로 대체
    // → 파싱 단계에서는 원본값을 보존하고, 레이아웃에서 처리
    cell.apply_inner_margin =
        cell.list_header_width_ref & crate::model::table::CELL_FLAG_HAS_MARGIN != 0;

    // 34바이트 이후 추가 데이터 보존 (라운드트립용)
    if r.remaining() > 0 {
        cell.raw_list_extra = r.read_bytes(r.remaining()).unwrap_or_default();
        // 셀 필드명 추출: raw_list_extra offset 15..17(name_len) + 17..(UTF-16LE)
        cell.field_name = parse_cell_field_name(&cell.raw_list_extra);
    }

    // 셀 내부 문단 파싱
    cell.paragraphs = parse_paragraph_list(&records[1..]);

    cell
}

/// 셀의 raw_list_extra에서 필드 이름을 추출한다.
/// 구조: raw_list_extra[15..17] = name_len (u16 LE), [17..17+name_len*2] = UTF-16LE 문자열
/// (직렬화 대칭: serializer::control::build_cell_list_extra — #1808)
/// Borrow the existing validated UTF-16 field-name surface without owned scratch.
pub(crate) fn cell_field_name_units(
    extra: &[u8],
) -> Option<impl Iterator<Item = u16> + Clone + '_> {
    if extra.len() < 18 {
        return None;
    }
    let name_len = u16::from_le_bytes([extra[15], extra[16]]) as usize;
    if name_len == 0 || extra.len() < 17 + name_len * 2 {
        return None;
    }
    Some(
        extra[17..17 + name_len * 2]
            .chunks_exact(2)
            .map(|bytes| u16::from_le_bytes([bytes[0], bytes[1]])),
    )
}
pub(crate) fn parse_cell_field_name(extra: &[u8]) -> Option<String> {
    let name: String = char::decode_utf16(cell_field_name_units(extra)?)
        .map(|scalar| scalar.unwrap_or(char::REPLACEMENT_CHARACTER))
        .collect();
    if name.is_empty() {
        None
    } else {
        Some(name)
    }
}

/// 캡션 파싱 (LIST_HEADER + 캡션 데이터 + 내부 문단)
///
/// records[0] = LIST_HEADER (캡션 데이터 포함), records[1..] = 캡션 내부 문단
/// HWP 스펙: 표 73 (캡션 리스트), 표 74 (캡션), 표 75 (캡션 속성)
pub(crate) fn parse_caption(records: &[Record]) -> Caption {
    let mut caption = Caption::default();

    if records.is_empty() {
        return caption;
    }

    let data = &records[0].data;
    let mut r = ByteReader::new(data);

    // LIST_HEADER 공통 필드 (8바이트: n_para + list_attr + width_ref)
    let _n_paragraphs = r.read_u16().unwrap_or(0);
    let _list_attr = r.read_u32().unwrap_or(0);
    let _width_ref = r.read_u16().unwrap_or(0);

    // 캡션 데이터 (14바이트)
    // 속성 (4바이트): bit 0~1 = 방향, bit 2 = include_margin
    let caption_attr = r.read_u32().unwrap_or(0);
    caption.direction = match caption_attr & 0x03 {
        0 => CaptionDirection::Left,
        1 => CaptionDirection::Right,
        2 => CaptionDirection::Top,
        _ => CaptionDirection::Bottom,
    };
    caption.include_margin = (caption_attr >> 2) & 0x01 != 0;
    // list_attr bit 21~22: Left/Right 캡션의 세로 정렬 (0=Top, 1=Center, 2=Bottom)
    caption.vert_align = match (_list_attr >> 21) & 0x03 {
        1 => CaptionVertAlign::Center,
        2 => CaptionVertAlign::Bottom,
        _ => CaptionVertAlign::Top,
    };

    // 캡션 폭 (세로 방향일 때 사용)
    caption.width = r.read_u32().unwrap_or(0);

    // 캡션-틀 간격
    caption.spacing = r.read_i16().unwrap_or(0);

    // 텍스트 최대 길이
    caption.max_width = r.read_u32().unwrap_or(0);

    // 캡션 내부 문단 파싱
    caption.paragraphs = parse_paragraph_list(&records[1..]);

    caption
}

mod shape;
pub(crate) use shape::{parse_common_obj_attr, parse_gso_control};

// ============================================================
// 머리말/꼬리말 ('head'/'foot')
// ============================================================

/// 머리말 컨트롤 파싱
fn parse_header_control(ctrl_data: &[u8], child_records: &[Record]) -> Control {
    let mut header = Header::default();

    if !ctrl_data.is_empty() {
        let mut r = ByteReader::new(ctrl_data);
        let attr = r.read_u32().unwrap_or(0);
        header.raw_attr = attr;
        header.apply_to = match attr & 0x03 {
            1 => HeaderFooterApply::Even,
            2 => HeaderFooterApply::Odd,
            _ => HeaderFooterApply::Both,
        };
        // 4바이트 이후 추가 데이터 보존 (라운드트립용)
        if ctrl_data.len() > 4 {
            header.raw_ctrl_extra = ctrl_data[4..].to_vec();
        }
    }

    let (layout, paragraphs) = find_list_header_layout_and_paragraphs(child_records);
    header.list_attr = layout.list_attr;
    header.text_width = layout.text_width;
    header.text_height = layout.text_height;
    header.text_ref = layout.text_ref;
    header.num_ref = layout.num_ref;
    header.paragraphs = paragraphs;

    Control::Header(Box::new(header))
}

/// 꼬리말 컨트롤 파싱
fn parse_footer_control(ctrl_data: &[u8], child_records: &[Record]) -> Control {
    let mut footer = Footer::default();

    if !ctrl_data.is_empty() {
        let mut r = ByteReader::new(ctrl_data);
        let attr = r.read_u32().unwrap_or(0);
        footer.raw_attr = attr;
        footer.apply_to = match attr & 0x03 {
            1 => HeaderFooterApply::Even,
            2 => HeaderFooterApply::Odd,
            _ => HeaderFooterApply::Both,
        };
        // 4바이트 이후 추가 데이터 보존 (라운드트립용)
        if ctrl_data.len() > 4 {
            footer.raw_ctrl_extra = ctrl_data[4..].to_vec();
        }
    }

    let (layout, paragraphs) = find_list_header_layout_and_paragraphs(child_records);
    footer.list_attr = layout.list_attr;
    footer.text_width = layout.text_width;
    footer.text_height = layout.text_height;
    footer.text_ref = layout.text_ref;
    footer.num_ref = layout.num_ref;
    footer.paragraphs = paragraphs;

    Control::Footer(Box::new(footer))
}

// ============================================================
// 각주/미주 ('fn  '/'en  ')
// ============================================================

/// 각주 컨트롤 파싱
fn parse_footnote_control(ctrl_data: &[u8], child_records: &[Record]) -> Control {
    let mut footnote = Footnote::default();
    // [Task #1050] hwplib CtrlHeaderFootnote 정합:
    //   number(UInt4) + before(WChar) + after(WChar) + numberShape(UInt4) + instanceId(UInt4, optional)
    if ctrl_data.len() >= 4 {
        let mut r = ByteReader::new(ctrl_data);
        footnote.number = r.read_u32().unwrap_or(0) as u16;
        if ctrl_data.len() >= 8 {
            footnote.before_decoration_letter = r.read_u16().unwrap_or(0);
            footnote.after_decoration_letter = r.read_u16().unwrap_or(0);
        }
        if ctrl_data.len() >= 12 {
            footnote.number_shape = r.read_u32().unwrap_or(0);
        }
        if ctrl_data.len() >= 16 {
            footnote.instance_id = r.read_u32().unwrap_or(0);
        }
    }

    footnote.paragraphs = find_list_header_paragraphs(child_records);
    footnote.list_header_property = find_list_header_property_for_footnote_endnote(child_records);

    Control::Footnote(Box::new(footnote))
}

/// 미주 컨트롤 파싱
fn parse_endnote_control(ctrl_data: &[u8], child_records: &[Record]) -> Control {
    let mut endnote = Endnote::default();
    // [Task #1050] CTRL_FOOTNOTE 와 동일 구조
    if ctrl_data.len() >= 4 {
        let mut r = ByteReader::new(ctrl_data);
        endnote.number = r.read_u32().unwrap_or(0) as u16;
        if ctrl_data.len() >= 8 {
            endnote.before_decoration_letter = r.read_u16().unwrap_or(0);
            endnote.after_decoration_letter = r.read_u16().unwrap_or(0);
        }
        if ctrl_data.len() >= 12 {
            endnote.number_shape = r.read_u32().unwrap_or(0);
        }
        if ctrl_data.len() >= 16 {
            endnote.instance_id = r.read_u32().unwrap_or(0);
        }
    }

    endnote.paragraphs = find_list_header_paragraphs(child_records);
    endnote.list_header_property = find_list_header_property_for_footnote_endnote(child_records);

    Control::Endnote(Box::new(endnote))
}

/// [Task #1050] CTRL_FOOTNOTE / CTRL_ENDNOTE 의 직속 LIST_HEADER property 읽기.
/// 형식: paraCount(SInt4) + property(UInt4) + 8 byte zero padding.
fn find_list_header_property_for_footnote_endnote(child_records: &[Record]) -> u32 {
    for record in child_records {
        if record.tag_id == crate::parser::tags::HWPTAG_LIST_HEADER && record.data.len() >= 8 {
            let mut r = ByteReader::new(&record.data);
            let _para_count = r.read_i32().unwrap_or(0);
            return r.read_u32().unwrap_or(0);
        }
    }
    0
}

// ============================================================
// 숨은 설명 ('tcmt')
// ============================================================

/// 숨은 설명 컨트롤 파싱
fn parse_hidden_comment_control(child_records: &[Record]) -> Control {
    let mut comment = HiddenComment::default();
    comment.paragraphs = find_list_header_paragraphs(child_records);
    Control::HiddenComment(Box::new(comment))
}

// ============================================================
// 단순 컨트롤 (AutoNumber, Bookmark, etc.)
// ============================================================

/// 자동 번호 파싱 (HWP 스펙 표 144, 표 145)
fn parse_auto_number(ctrl_data: &[u8]) -> Control {
    let mut an = AutoNumber::default();
    if ctrl_data.len() >= 4 {
        let mut r = ByteReader::new(ctrl_data);
        let attr = r.read_u32().unwrap_or(0);
        an.number_type = match attr & 0x0F {
            0 => AutoNumberType::Page,
            1 => AutoNumberType::Footnote,
            2 => AutoNumberType::Endnote,
            3 => AutoNumberType::Picture,
            4 => AutoNumberType::Table,
            5 => AutoNumberType::Equation,
            // 6 = 총 쪽수 ('전체 쪽 번호' 필드). exam_eng.hwp 실측: 꼬리말 쪽번호 상자의
            // 두 번째 atno가 attr&0x0F=6 으로 인코딩됨. 과거엔 fallback으로 Page 취급되어
            // 현재 쪽번호가 두 번 표시되는 버그가 있었다.
            6 => AutoNumberType::TotalPage,
            _ => AutoNumberType::Page,
        };
        an.format = ((attr >> 4) & 0xFF) as u8; // bit 4~11: 번호 모양 (표 134)
        an.superscript = attr & 0x1000 != 0; // bit 12: 위 첨자
                                             // 표 144: UINT16 번호 + WCHAR 사용자기호 + WCHAR 앞장식 + WCHAR 뒤장식
        an.number = r.read_u16().unwrap_or(0);
        an.user_symbol = char::from_u32(r.read_u16().unwrap_or(0) as u32).unwrap_or('\0');
        an.prefix_char = char::from_u32(r.read_u16().unwrap_or(0) as u32).unwrap_or('\0');
        an.suffix_char = char::from_u32(r.read_u16().unwrap_or(0) as u32).unwrap_or('\0');
    }
    Control::AutoNumber(an)
}

/// 새 번호 지정 파싱
fn parse_new_number(ctrl_data: &[u8]) -> Control {
    let mut nn = NewNumber::default();
    if ctrl_data.len() >= 6 {
        let mut r = ByteReader::new(ctrl_data);
        let attr = r.read_u32().unwrap_or(0);
        nn.number_type = match attr & 0x0F {
            0 => AutoNumberType::Page,
            1 => AutoNumberType::Footnote,
            2 => AutoNumberType::Endnote,
            3 => AutoNumberType::Picture,
            4 => AutoNumberType::Table,
            5 => AutoNumberType::Equation,
            6 => AutoNumberType::TotalPage,
            _ => AutoNumberType::Page,
        };
        nn.number = r.read_u16().unwrap_or(0);
    }
    Control::NewNumber(nn)
}

/// 쪽 번호 위치 파싱 (HWP 스펙 표 149, 표 150)
fn parse_page_num_pos(ctrl_data: &[u8]) -> Control {
    let mut pnp = PageNumberPos::default();
    if ctrl_data.len() >= 4 {
        let mut r = ByteReader::new(ctrl_data);
        let attr = r.read_u32().unwrap_or(0);
        pnp.format = (attr & 0xFF) as u8; // bit 0~7: 번호 모양 (표 134)
        pnp.position = ((attr >> 8) & 0x0F) as u8; // bit 8~11: 표시 위치 (표 150)
                                                   // 표 149: WCHAR 사용자기호 + 앞장식 + 뒤장식 + 대시
        pnp.user_symbol = char::from_u32(r.read_u16().unwrap_or(0) as u32).unwrap_or('\0');
        pnp.prefix_char = char::from_u32(r.read_u16().unwrap_or(0) as u32).unwrap_or('\0');
        pnp.suffix_char = char::from_u32(r.read_u16().unwrap_or(0) as u32).unwrap_or('\0');
        pnp.dash_char = char::from_u32(r.read_u16().unwrap_or(0) as u32).unwrap_or('\0');
    }
    Control::PageNumberPos(pnp)
}

/// 감추기 파싱
fn parse_page_hide(ctrl_data: &[u8]) -> Control {
    let mut ph = PageHide::default();
    if ctrl_data.len() >= 4 {
        let mut r = ByteReader::new(ctrl_data);
        let attr = r.read_u32().unwrap_or(0);
        ph.hide_header = attr & 0x01 != 0;
        ph.hide_footer = attr & 0x02 != 0;
        ph.hide_master_page = attr & 0x04 != 0;
        ph.hide_border = attr & 0x08 != 0;
        ph.hide_fill = attr & 0x10 != 0;
        ph.hide_page_num = attr & 0x20 != 0;
    }
    Control::PageHide(ph)
}

/// 책갈피 파싱
fn parse_bookmark(ctrl_data: &[u8]) -> Control {
    let mut bm = Bookmark::default();
    if ctrl_data.len() >= 2 {
        let mut r = ByteReader::new(ctrl_data);
        if let Ok(name) = r.read_hwp_string() {
            bm.name = name;
        }
    }
    Control::Bookmark(bm)
}

/// 쪽 번호 시작 쪽 파싱 ('pgct')
///
/// ctrl_data 는 `u32` 하나다(실측 11문서·102건 전부 8바이트 CTRL_HEADER).
fn parse_page_num_ctrl(ctrl_data: &[u8]) -> Control {
    let raw = if ctrl_data.len() >= 4 {
        u32::from_le_bytes([ctrl_data[0], ctrl_data[1], ctrl_data[2], ctrl_data[3]])
    } else {
        0
    };
    Control::PageNumCtrl(PageNumCtrl {
        page_starts_on: PageStartsOn::from_hwp5(raw),
    })
}

/// 찾아보기 표식 파싱 ('idxm')
///
/// ctrl_data 레이아웃 (ctrl_id 4바이트는 이미 제거된 상태) — 실측 06926:
///   WORD(2) + WCHAR[n]  첫째 키
///   WORD(2) + WCHAR[m]  둘째 키
///   4바이트 예약(전부 0)
///
/// arm 이 없으면 `Control::Unknown` 이 되는데, 그러면 HWPX 저장기가 슬롯으로는
/// 세어 놓고 XML 은 내지 않아 문단 축이 8유닛 짧아진다 — 한글은 범위를 넘는
/// `textpos` 를 만나면 파일을 아예 열지 못한다.
fn parse_index_mark(ctrl_data: &[u8]) -> Control {
    let mut im = IndexMark::default();
    let mut r = ByteReader::new(ctrl_data);
    if let Ok(first) = r.read_hwp_string() {
        im.first_key = first;
    }
    if let Ok(second) = r.read_hwp_string() {
        im.second_key = second;
    }
    Control::IndexMark(im)
}

/// 글자 겹침 파싱 (HWP 스펙 표 152)
///
/// ctrl_data 레이아웃 (ctrl_id 4바이트는 이미 제거된 상태):
///   WORD(2): 겹칠 글자 길이(len)
///   WCHAR[len](2×len): 겹칠 글자
///   UINT8(1): 테두리 타입
///   INT8(1): 내부 글자 크기
///   UINT8(1): 펼침
///   UINT8(1): charshape 아이디 수(cnt)
///   UINT[cnt](4×cnt): charshape_id 배열
/// [#4397] 덧말('tdut') CTRL_HEADER payload 파싱 — HWP5 스펙 표 151.
///
/// `mainText`(HWP string) + `subText`(HWP string) + 덧말 위치/Fsizeratio/Option/
/// Style number/정렬 (UINT32 ×5). 종전에는 arm 이 없어 `Control::Unknown` 으로
/// 떨어졌고, HWPX→HWP5 저장도 최소 CTRL_HEADER(짝 맞춤, #4677)만 내 내용이
/// 통째로 소실됐다 — 저장측(serialize_control)과 함께 양방향을 잇는다.
fn parse_ruby(ctrl_data: &[u8]) -> Control {
    let mut ruby = crate::model::control::Ruby::default();
    let mut r = ByteReader::new(ctrl_data);
    ruby.main_text = r.read_hwp_string().unwrap_or_default();
    ruby.ruby_text = r.read_hwp_string().unwrap_or_default();
    ruby.pos_type = r.read_u32().unwrap_or(0) as u8;
    ruby.sz_ratio = r.read_u32().unwrap_or(0) as u8;
    ruby.option = r.read_u32().unwrap_or(0);
    ruby.style_id_ref = r.read_u32().unwrap_or(0) as u16;
    ruby.align = r.read_u32().unwrap_or(0) as u8;
    Control::Ruby(ruby)
}

fn parse_char_overlap(ctrl_data: &[u8]) -> Control {
    let mut co = CharOverlap::default();
    co.hwp_wire_chars = true;
    if ctrl_data.len() < 2 {
        return Control::CharOverlap(co);
    }

    let mut r = ByteReader::new(ctrl_data);

    let char_len = r.read_u16().unwrap_or(0) as usize;
    // WCHAR 배열 읽기 (UTF-16 서로게이트 쌍 처리)
    let mut wchars: Vec<u16> = Vec::with_capacity(char_len);
    for _ in 0..char_len {
        if let Ok(ch) = r.read_u16() {
            wchars.push(ch);
        }
    }
    // UTF-16 디코딩 (서로게이트 쌍 → Unicode 코드포인트)
    let mut i = 0;
    while i < wchars.len() {
        let w = wchars[i];
        if (0xD800..=0xDBFF).contains(&w) && i + 1 < wchars.len() {
            // 서로게이트 쌍
            let hi = w as u32;
            let lo = wchars[i + 1] as u32;
            if (0xDC00..=0xDFFF).contains(&(lo as u16)) {
                let code_point = 0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00);
                if let Some(c) = char::from_u32(code_point) {
                    co.chars.push(c);
                }
                i += 2;
                continue;
            }
        }
        // 일반 BMP 문자
        if let Some(c) = char::from_u32(w as u32) {
            co.chars.push(c);
        }
        i += 1;
    }

    co.border_type = r.read_u8().unwrap_or(0);
    co.inner_char_size = r.read_i8().unwrap_or(0);
    co.expansion = r.read_u8().unwrap_or(0);

    let cs_count = r.read_u8().unwrap_or(0) as usize;
    for _ in 0..cs_count {
        if let Ok(id) = r.read_u32() {
            co.char_shape_ids.push(id);
        }
    }

    Control::CharOverlap(co)
}

// ============================================================
// 헬퍼 함수
// ============================================================

/// LIST_HEADER 이후의 문단 목록을 추출
///
/// 자식 레코드에서 LIST_HEADER를 찾고, 그 이후 레코드에서 문단 목록을 파싱.
/// LIST_HEADER와 PARA_HEADER가 동일 level인 경우가 있으므로 (표 셀 내 각주 등),
/// level 필터링 대신 LIST_HEADER 이후의 모든 레코드를 parse_paragraph_list에 위임.
fn find_list_header_paragraphs(
    child_records: &[Record],
) -> Vec<crate::model::paragraph::Paragraph> {
    let mut idx = 0;
    while idx < child_records.len() {
        if child_records[idx].tag_id == tags::HWPTAG_LIST_HEADER {
            return parse_paragraph_list(&child_records[idx + 1..]);
        }
        idx += 1;
    }
    Vec::new()
}

/// 머리말/꼬리말 LIST_HEADER 레코드 페이로드.
///
/// [#2648] `find_list_header_paragraphs` 는 레코드 뒤의 문단만 파싱하고 레코드
/// 자체의 페이로드(list_attr/text_width/text_height/text_ref/num_ref)는 읽지
/// 않았다. 직렬화(`build_header_footer_list_header`, serializer/control.rs)는
/// 이 값들을 무조건 사용하므로 저장 왕복마다 0 으로 뭉개졌다. 바이트 레이아웃은
/// 그 직렬화 함수의 역이다:
/// u16 para_count | u32 list_attr | u16(예약) | u32 text_width | u32 text_height
/// | u8 text_ref | u8 num_ref | u16 ext_flags | [u8;14] 예약
struct HeaderFooterListLayoutFields {
    list_attr: u32,
    text_width: u32,
    text_height: u32,
    text_ref: u8,
    num_ref: u8,
}

fn find_list_header_layout_and_paragraphs(
    child_records: &[Record],
) -> (
    HeaderFooterListLayoutFields,
    Vec<crate::model::paragraph::Paragraph>,
) {
    let mut layout = HeaderFooterListLayoutFields {
        list_attr: 0,
        text_width: 0,
        text_height: 0,
        text_ref: 0,
        num_ref: 0,
    };
    let mut idx = 0;
    while idx < child_records.len() {
        if child_records[idx].tag_id == tags::HWPTAG_LIST_HEADER {
            let mut r = ByteReader::new(&child_records[idx].data);
            let _para_count = r.read_u16().unwrap_or(0);
            layout.list_attr = r.read_u32().unwrap_or(0);
            let _reserved = r.read_u16().unwrap_or(0);
            layout.text_width = r.read_u32().unwrap_or(0);
            layout.text_height = r.read_u32().unwrap_or(0);
            layout.text_ref = r.read_u8().unwrap_or(0);
            layout.num_ref = r.read_u8().unwrap_or(0);
            let paragraphs = parse_paragraph_list(&child_records[idx + 1..]);
            return (layout, paragraphs);
        }
        idx += 1;
    }
    (layout, Vec::new())
}

// ============================================================
// 수식 ('eqed')
// ============================================================

/// 수식 컨트롤 파싱
///
/// CTRL_HEADER(eqed)의 ctrl_data에서 CommonObjAttr를 읽고,
/// 자식 레코드 HWPTAG_EQEDIT에서 수식 스크립트 등을 추출한다.
fn parse_equation_control(ctrl_data: &[u8], child_records: &[Record]) -> Control {
    let common = parse_common_obj_attr(ctrl_data);

    let mut equation = Equation {
        common,
        raw_ctrl_data: ctrl_data.to_vec(),
        ..Default::default()
    };

    // HWPTAG_EQEDIT 자식 레코드 탐색
    if let Some(eq_rec) = child_records
        .iter()
        .find(|r| r.tag_id == tags::HWPTAG_EQEDIT)
    {
        let data = &eq_rec.data;
        let mut r = ByteReader::new(data);

        // attr: u32 (4바이트) — bit0: lineMode (0=글자단위/CHAR, 1=줄단위/LINE)
        // `attr`/`eqedit` 두 필드가 동일한 값을 보관하므로 함께 채운다.
        let raw_attr = r.read_u32().unwrap_or(0);
        equation.attr = raw_attr;
        equation.eqedit = raw_attr;

        // script: WCHAR 문자열 (길이 접두 UTF-16LE)
        if let Ok(script) = r.read_hwp_string() {
            equation.script = script;
        }

        // font_size: u32 (4바이트, HWPUNIT)
        equation.font_size = r.read_u32().unwrap_or(1000);

        // color: u32 (4바이트, COLORREF)
        equation.color = r.read_u32().unwrap_or(0);

        // baseline: i16 (2바이트)
        equation.baseline = r.read_i16().unwrap_or(0);

        // [Task #1061] unknown: u16 (2바이트) — HWP5 spec 표 105 누락 영역.
        // hwplib ForEQEdit.readUInt2() 정합. 한컴 실제 저장본에 baseline 과
        // version_info 사이 UINT16 zero 가 위치.
        equation.unknown = r.read_u16().unwrap_or(0);

        // 실제 필드 부재를 명시한 빈 문자열과 구분한다. 잘린 문자열을
        // 옛 표시 계약으로 받아들이지 않고 필수 필드를 모두 읽은 경우만 보존한다.
        equation.implicit_legacy_font = data.get(4..6).is_some_and(|length| {
            let script_units = usize::from(u16::from_le_bytes([length[0], length[1]]));
            data.len() == 18 + script_units * 2 && r.remaining() == 0
        });

        // version_info: WCHAR 문자열
        if let Ok(ver) = r.read_hwp_string() {
            equation.version_info = ver;
        }

        // font_name: WCHAR 문자열
        if let Ok(font) = r.read_hwp_string() {
            equation.font_name = font;
        }
    }

    equation.retain_legacy_source_frame();
    Control::Equation(Box::new(equation))
}

// ============================================================
// 양식 개체 (form)
// ============================================================

/// 양식 개체 파싱
///
/// ctrl_data에서 width/height를 추출하고,
/// HWPTAG_FORM_OBJECT 자식 레코드에서 타입 ID와 속성 문자열을 파싱한다.
fn parse_form_control(ctrl_data: &[u8], child_records: &[Record]) -> Control {
    let mut form = FormObject {
        enabled: true,
        ..Default::default()
    };

    // [#6266] ctrl_data 는 다른 개체와 같은 `CommonObjAttr` 다 — 종전에는 앞
    // 12바이트(attr·세로/가로 오프셋)를 버리고 width/height 만 읽어 배치를
    // 잃었고, 그래서 렌더러가 양식 개체를 인라인 말고는 놓을 수 없었다.
    if !ctrl_data.is_empty() {
        form.common = parse_common_obj_attr(ctrl_data);
    }
    // width/height 는 종전 오프셋(12..20)을 그대로 유지한다 — 이 두 필드는
    // 직렬화·왕복이 이미 참조하고 있어 값의 출처를 바꾸지 않는다.
    if ctrl_data.len() >= 20 {
        let mut r = ByteReader::new(ctrl_data);
        let _attr = r.read_u32().unwrap_or(0);
        let _y_offset = r.read_i32().unwrap_or(0);
        let _x_offset = r.read_i32().unwrap_or(0);
        form.width = r.read_u32().unwrap_or(0);
        form.height = r.read_u32().unwrap_or(0);
    }

    // HWPTAG_FORM_OBJECT 자식 레코드에서 타입/속성 파싱
    if let Some(rec) = child_records
        .iter()
        .find(|r| r.tag_id == tags::HWPTAG_FORM_OBJECT)
    {
        let data = &rec.data;
        if data.len() >= 14 {
            // bytes 0-3: 타입 ID 문자열 (예: "tbp+", "tbc+", "boc+", "tbr+", "tde+")
            let type_id = &data[0..4];
            form.form_type = match type_id {
                b"tbp+" => FormType::PushButton,
                b"tbc+" => FormType::CheckBox,
                b"boc+" => FormType::ComboBox,
                b"tbr+" => FormType::RadioButton,
                b"tde+" => FormType::Edit,
                _ => FormType::PushButton,
            };

            // bytes 8-11: u32 전체 길이, bytes 12-13: u16 문자열 길이 (WCHAR 단위)
            let str_char_count = u16::from_le_bytes([data[12], data[13]]) as usize;
            let str_byte_start = 14;
            let str_byte_len = str_char_count * 2;

            if data.len() >= str_byte_start + str_byte_len {
                let str_bytes = &data[str_byte_start..str_byte_start + str_byte_len];
                let prop_str = decode_utf16le(str_bytes);
                parse_form_properties(&prop_str, &mut form);
            }
        }
    }

    Control::Form(Box::new(form))
}

/// UTF-16LE 바이트를 String으로 디코딩
fn decode_utf16le(data: &[u8]) -> String {
    let u16s: Vec<u16> = data
        .chunks_exact(2)
        .map(|c| u16::from_le_bytes([c[0], c[1]]))
        .collect();
    String::from_utf16_lossy(&u16s)
}

/// 양식 개체 속성 문자열 파싱
///
/// 포맷: 속성간 공백 구분, 속성 내부 콜론 구분
/// - `Key:set:N:` → 컨테이너 (N=바이트 길이, 내용은 이어지는 속성들)
/// - `Key:wstring:N:VALUE` → N문자 길이 WCHAR 문자열
/// - `Key:int:VALUE` / `Key:bool:VALUE` → 정수/불린 (공백까지)
fn parse_form_properties(prop_str: &str, form: &mut FormObject) {
    let chars: Vec<char> = prop_str.chars().collect();
    let len = chars.len();
    let mut pos = 0;

    while pos < len {
        // 공백 건너뛰기
        while pos < len && chars[pos] == ' ' {
            pos += 1;
        }
        if pos >= len {
            break;
        }

        // Key 읽기 (':'까지)
        let key_start = pos;
        while pos < len && chars[pos] != ':' {
            pos += 1;
        }
        let key: String = chars[key_start..pos].iter().collect();
        if pos < len {
            pos += 1;
        } // ':' 건너뛰기

        // Type 읽기 (':'까지)
        let type_start = pos;
        while pos < len && chars[pos] != ':' {
            pos += 1;
        }
        let type_str: String = chars[type_start..pos].iter().collect();
        if pos < len {
            pos += 1;
        } // ':' 건너뛰기

        match type_str.as_str() {
            "set" => {
                // N(바이트 길이) 읽고 ':' 건너뛰기 — 내용은 이어지는 속성으로 처리됨
                while pos < len && chars[pos] != ':' {
                    pos += 1;
                }
                if pos < len {
                    pos += 1;
                }
            }
            "wstring" => {
                // N(문자 수) 읽기
                let n_start = pos;
                while pos < len && chars[pos] != ':' {
                    pos += 1;
                }
                let n: usize = chars[n_start..pos]
                    .iter()
                    .collect::<String>()
                    .parse()
                    .unwrap_or(0);
                if pos < len {
                    pos += 1;
                } // ':' 건너뛰기
                  // 정확히 N문자 읽기
                let end = (pos + n).min(len);
                let value: String = chars[pos..end].iter().collect();
                pos = end;
                apply_form_property(&key, &value, form);
            }
            "int" | "bool" => {
                // 공백까지 값 읽기
                let v_start = pos;
                while pos < len && chars[pos] != ' ' {
                    pos += 1;
                }
                let value: String = chars[v_start..pos].iter().collect();
                apply_form_property(&key, &value, form);
            }
            _ => {
                // 알 수 없는 타입 — 공백까지 건너뛰기
                while pos < len && chars[pos] != ' ' {
                    pos += 1;
                }
            }
        }
    }
}

/// 파싱된 속성을 FormObject에 적용
fn apply_form_property(key: &str, value: &str, form: &mut FormObject) {
    match key {
        "Name" => form.name = value.to_string(),
        "Caption" => form.caption = value.to_string(),
        "Text" => form.text = value.to_string(),
        "ForeColor" => {
            form.fore_color = value.parse::<u32>().unwrap_or(0);
        }
        "BackColor" => {
            form.back_color = value.parse::<u32>().unwrap_or(0);
        }
        "Value" => {
            form.value = value.parse::<i32>().unwrap_or(0);
        }
        "Enabled" => {
            form.enabled = value != "0" && value.to_lowercase() != "false";
        }
        _ => {
            form.properties.insert(key.to_string(), value.to_string());
        }
    }
}

#[cfg(test)]
mod tests;