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
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
//! `<hp:pic>` 그림 직렬화 + `<hc:img binaryItemIDRef>` 참조.
//!
//! Stage 4 (#182): Picture IR → `<hp:pic>` + `<hc:img>`. BinData 참조는
//! `SerializeContext::bin_data_map` 을 통해 manifest id 로 변환된다.
//!
//! 속성·자식 순서는 한컴 OWPML 공식 (hancom-io/hwpx-owpml-model, Apache 2.0)
//! `Class/Para/PictureType.cpp` 의 `WriteElement()`, `InitMap()` 기준.
//!
//! ## 자식 순서 (PictureType.cpp:79-102)
//!
//! 부모(AbstractShapeObjectType): sz, pos, outMargin, caption, shapeComment,
//! parameterset, metaTag
//! 부모(AbstractShapeComponentType): offset, orgSz, curSz, flip, rotationInfo,
//! renderingInfo, lineShape, imgRect
//! 자신: imgClip, effects, inMargin, imgDim, img
//!
//! 한컴 관찰 샘플에서 실제 출력은: offset → orgSz → curSz → flip → rotationInfo →
//! renderingInfo → imgRect → imgClip → inMargin → imgDim → img → effects → sz → pos → outMargin
//! (부모 요소들이 자신보다 뒤에 출력됨 — XMLSerializer 구현 특성)
//!
//! ## 3-way 단언
//!
//! `<hc:img binaryItemIDRef>` 에 쓸 manifest id 는 반드시 `ctx.bin_data_map` 에 등록돼
//! 있어야 한다. 등록되지 않은 bin_data_id 참조 시 `SerializeError::XmlError` 반환.

use super::section::{
    build_secpr_run_with_storage, render_hp_p_open_with_storage,
    render_paragraph_parts_with_storage,
};
use super::shape::color_to_hex_with_storage;
use super::table::write_caption_with_storage;
use super::utils::{
    empty_tag_with_storage, end_tag_with_storage, start_tag_attrs_with_storage,
    start_tag_with_storage, text_with_storage, write_xml_decl_with_storage, xml_error,
    xml_escape_with_storage, xml_value,
};
use std::io::Write;

use quick_xml::Writer;

use crate::model::image::{
    EffectColor, EffectPoint, EffectRgb, ImageEffect, Picture, PictureShadow,
};
use crate::model::shape::{
    CommonObjAttr, HorzAlign, HorzRelTo, ShapeComponentAttr, SizeCriterion, TextFlow, TextWrap,
    VertAlign, VertRelTo,
};

use super::context::SerializeContext;
// [#2712] hp:sz 크기 기준 헬퍼는 도형 직렬화기와 공유한다(관례 이중화 방지).
use super::shape::{height_criterion_str, numbering_type_str, size_criterion_str};
use super::table::write_caption;
use super::utils::{empty_tag, end_tag, start_tag, start_tag_attrs};
use super::SerializeError;

/// `<hp:pic>` 직렬화 진입점.
///
/// ctx 가 `&mut` 인 이유: 캡션 subList 문단 직렬화(#1403)가 para id 발급과
/// para_shape/style 참조 수집을 수행한다 (표 캡션 #1387 과 동일 경로).
pub fn write_picture<W: Write>(
    w: &mut Writer<W>,
    pic: &Picture,
    ctx: &mut SerializeContext,
) -> Result<(), SerializeError> {
    write_picture_with_storage(w, pic, ctx, &crate::storage::Unbounded)
}

pub(super) fn write_picture_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    pic: &Picture,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    // --- <hp:pic> 속성 ---
    // 속성 순서 (PictureType + 부모 AbstractShapeObjectType):
    // id, zOrder, numberingType, textWrap, textFlow, lock, dropcapstyle,
    // href, groupLevel, instid, reverse
    let id_str = xml_value(storage, pic.common.instance_id)?;
    let z_order = xml_value(storage, pic.common.z_order)?;
    let tw = text_wrap_str(pic.common.text_wrap);
    let tf = text_flow_str(pic.common.text_flow);
    let instid = xml_value(storage, pic.instance_id)?;
    let href = pic.href.as_deref().unwrap_or("");
    // [#2861] 좌우 반전 — 종전 하드코딩 "0" 은 reverse="1" 로 저장된 그림의 반전 정보를
    // 왕복 시 소실시켰다.
    let reverse = bool01(pic.reverse);
    // [#2875] 개체 잠금 — 종전 하드코딩 "0" 은 lock="1" 로 저장된 그림의 잠금 정보를
    // 왕복 시 소실시켰다 (#2861 reverse, #2855 hp:tbl lock 과 동일 패턴).
    let lock = bool01(pic.lock);
    // [#2697 동형] numberingType 은 IR(common.numbering_type)을 보존한다. 종전 "PICTURE"
    // 하드코딩은 그림에 번호 범주를 변경한(예: NONE) 문서에서 저장 시 원본 속성이 유실됐다.
    // 도형·표 계열은 이미 #1379/#2697 에서 IR 보존으로 정리됐다.
    let numbering_type = numbering_type_str(pic.common.numbering_type);
    // [#TODO-IR] groupLevel 은 IR(shape_attr.group_level)을 보존한다. 종전 "0" 하드코딩은
    // 그룹 내 그림 개체의 중첩 레벨이 저장 시 유실됐다(shape.rs rect/line 경로는 이미 보존).
    let group_level = xml_value(storage, pic.shape_attr.group_level)?;

    start_tag_attrs_with_storage(
        w,
        "hp:pic",
        &[
            ("id", &id_str),
            ("zOrder", &z_order),
            ("numberingType", &numbering_type),
            ("textWrap", tw),
            ("textFlow", tf),
            ("lock", lock),
            (
                "dropcapstyle",
                super::shape::drop_cap_style_str(pic.common.drop_cap_style),
            ),
            ("href", href),
            ("groupLevel", &group_level),
            ("instid", &instid),
            ("reverse", reverse),
        ],
        storage,
    )?;

    // --- 자식 순서 (한컴 관찰 샘플 기준) ---
    // offset, orgSz, curSz, flip, rotationInfo, renderingInfo, imgRect, imgClip,
    // inMargin, imgDim, img, effects, sz, pos, outMargin
    // [#4668] hp:offset 은 shape_attr 원문 — pic 전용 writer 가 pos 유래로
    // 재작성하면 쪽 밖(wraparound) 그림이 무편집 저장 후 쪽 안에 노출된다.
    super::shape::write_offset_with_storage(w, &pic.shape_attr, storage)?;
    write_org_sz_with_storage(w, &pic.shape_attr, storage)?;
    write_cur_sz_with_storage(w, pic, storage)?;
    write_flip_with_storage(w, &pic.shape_attr, storage)?;
    write_rotation_info_with_storage(w, &pic.shape_attr, storage)?;
    // [#1501] 그룹 자식 pic 의 transMatrix(render_tx/sx) 보존 — 종전 identity 고정 출력은
    // 그룹 내 자식을 원점·고유크기로 붕괴시켰다. shape.rs 의 raw_rendering 디코더 공유.
    super::shape::write_rendering_info_with_storage(w, &pic.shape_attr, storage)?;
    // The outline belongs to the outer object frame, before its crop
    // rectangle. Keep a stored style even when its width is zero.
    // A missing/default NONE outline remains absent.
    if pic.border_attr.attr != 0
        || pic.border_color != 0
        || pic.border_width != 0
        || pic.border_attr.outline_style != 0
    {
        let border = crate::model::style::ShapeBorderLine {
            color: pic.border_color,
            width: pic.border_width,
            ..pic.border_attr
        };
        super::shape::write_line_shape_with_storage(w, &border, storage)?;
    }
    write_img_rect_with_storage(w, pic, storage)?;
    write_img_clip_with_storage(w, pic, storage)?;
    write_in_margin_with_storage(w, pic, storage)?;
    write_img_dim_with_storage(w, pic, storage)?;
    write_img_with_storage(w, pic, ctx, storage)?; // 3-way 단언 지점
    write_effects_with_storage(w, pic, storage)?;
    write_sz_with_storage(w, &pic.common, storage)?;
    write_pos_with_storage(w, &pic.common, storage)?;
    write_out_margin_with_storage(w, &pic.common, storage)?;
    // 캡션 (#1403) — 한컴 실물(aift.hwpx) 자식 순서: outMargin 뒤
    if let Some(cap) = &pic.caption {
        write_caption_with_storage(w, cap, ctx, storage)?;
    }
    // 설명 (#1392) — caption 직후 (aift 실물 공존 9건 전수 caption→shapeComment 순서)
    super::shape::write_shape_comment_with_storage(w, &pic.common, storage)?;

    end_tag_with_storage(w, "hp:pic", storage)?;
    Ok(())
}

// ---------- 자식 요소 ----------

fn write_org_sz<W: Write>(
    w: &mut Writer<W>,
    sa: &ShapeComponentAttr,
) -> Result<(), SerializeError> {
    write_org_sz_with_storage(w, sa, &crate::storage::Unbounded)
}

pub(super) fn write_org_sz_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    sa: &ShapeComponentAttr,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let ow = xml_value(storage, sa.original_width)?;
    let oh = xml_value(storage, sa.original_height)?;
    empty_tag_with_storage(w, "hp:orgSz", &[("width", &ow), ("height", &oh)], storage)
}

fn write_cur_sz<W: Write>(w: &mut Writer<W>, p: &Picture) -> Result<(), SerializeError> {
    write_cur_sz_with_storage(w, p, &crate::storage::Unbounded)
}

pub(super) fn write_cur_sz_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    p: &Picture,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    // [#1389] 현재 크기는 shape_attr.current_width/height (IR 보존). 0 이면 common(sz)
    // 폴백 — 원본도 그 경우 sz=curSz. 종전 common 직출이라 current≠sz 인 pic 변형.
    // [#2017] 파싱 시 orgSz로 materialize된 dimension 은 원본 `0` sentinel 로 복원.
    let cw = if p.shape_attr.current_width_was_zero {
        0
    } else if p.shape_attr.current_width > 0 {
        p.shape_attr.current_width
    } else {
        p.common.width
    };
    let ch = if p.shape_attr.current_height_was_zero {
        0
    } else if p.shape_attr.current_height > 0 {
        p.shape_attr.current_height
    } else {
        p.common.height
    };
    empty_tag_with_storage(
        w,
        "hp:curSz",
        &[
            ("width", &xml_value(storage, cw)?),
            ("height", &xml_value(storage, ch)?),
        ],
        storage,
    )
}

fn write_flip<W: Write>(w: &mut Writer<W>, sa: &ShapeComponentAttr) -> Result<(), SerializeError> {
    write_flip_with_storage(w, sa, &crate::storage::Unbounded)
}

pub(super) fn write_flip_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    sa: &ShapeComponentAttr,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let h = bool01(sa.horz_flip);
    let v = bool01(sa.vert_flip);
    empty_tag_with_storage(w, "hp:flip", &[("horizontal", h), ("vertical", v)], storage)
}

fn write_rotation_info<W: Write>(
    w: &mut Writer<W>,
    sa: &ShapeComponentAttr,
) -> Result<(), SerializeError> {
    write_rotation_info_with_storage(w, sa, &crate::storage::Unbounded)
}

pub(super) fn write_rotation_info_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    sa: &ShapeComponentAttr,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let angle = xml_value(storage, sa.rotation_angle)?;
    let cx = xml_value(storage, sa.rotation_center.x)?;
    let cy = xml_value(storage, sa.rotation_center.y)?;
    let ri = bool01(sa.rotate_image);
    empty_tag_with_storage(
        w,
        "hp:rotationInfo",
        &[
            ("angle", &angle),
            ("centerX", &cx),
            ("centerY", &cy),
            ("rotateimage", ri),
        ],
        storage,
    )
}

fn write_img_rect<W: Write>(w: &mut Writer<W>, p: &Picture) -> Result<(), SerializeError> {
    write_img_rect_with_storage(w, p, &crate::storage::Unbounded)
}

pub(super) fn write_img_rect_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    p: &Picture,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    // [#1389] 꼭짓점은 border_x/border_y (IR 보존). 파서(parse_picture_img_rect)는
    // HWP5 SHAPE_PICTURE 스칼라 레이아웃으로 저장한다:
    //   border_x = [pt0.x, pt0.y, pt1.x, pt1.y], border_y = [pt2.x, pt2.y, pt3.x, pt3.y]
    // 따라서 역매핑하여 pt0~pt3 을 복원한다. 모두 0(미적재)이면 common 합성 폴백.
    let bx = &p.border_x;
    let by = &p.border_y;
    if bx.iter().all(|&v| v == 0) && by.iter().all(|&v| v == 0) {
        let w_str = xml_value(storage, p.common.width)?;
        let h_str = xml_value(storage, p.common.height)?;
        start_tag_with_storage(w, "hp:imgRect", storage)?;
        empty_tag_with_storage(w, "hc:pt0", &[("x", "0"), ("y", "0")], storage)?;
        empty_tag_with_storage(w, "hc:pt1", &[("x", &w_str), ("y", "0")], storage)?;
        empty_tag_with_storage(w, "hc:pt2", &[("x", &w_str), ("y", &h_str)], storage)?;
        empty_tag_with_storage(w, "hc:pt3", &[("x", "0"), ("y", &h_str)], storage)?;
        end_tag_with_storage(w, "hp:imgRect", storage)?;
        return Ok(());
    }
    let pts = [
        (bx[0], bx[1]), // pt0
        (bx[2], bx[3]), // pt1
        (by[0], by[1]), // pt2
        (by[2], by[3]), // pt3
    ];
    start_tag_with_storage(w, "hp:imgRect", storage)?;
    for (i, (x, y)) in pts.iter().enumerate() {
        empty_tag_with_storage(
            w,
            &xml_value(storage, format_args!("hc:pt{i}"))?,
            &[
                ("x", &xml_value(storage, x)?),
                ("y", &xml_value(storage, y)?),
            ],
            storage,
        )?;
    }
    end_tag_with_storage(w, "hp:imgRect", storage)?;
    Ok(())
}

fn write_img_clip<W: Write>(w: &mut Writer<W>, p: &Picture) -> Result<(), SerializeError> {
    write_img_clip_with_storage(w, p, &crate::storage::Unbounded)
}

pub(super) fn write_img_clip_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    p: &Picture,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let l = xml_value(storage, p.crop.left)?;
    let r = xml_value(storage, p.crop.right)?;
    let t = xml_value(storage, p.crop.top)?;
    let b = xml_value(storage, p.crop.bottom)?;
    empty_tag_with_storage(
        w,
        "hp:imgClip",
        &[("left", &l), ("right", &r), ("top", &t), ("bottom", &b)],
        storage,
    )
}

fn write_in_margin<W: Write>(w: &mut Writer<W>, p: &Picture) -> Result<(), SerializeError> {
    write_in_margin_with_storage(w, p, &crate::storage::Unbounded)
}

pub(super) fn write_in_margin_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    p: &Picture,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let l = xml_value(storage, p.padding.left)?;
    let r = xml_value(storage, p.padding.right)?;
    let t = xml_value(storage, p.padding.top)?;
    let b = xml_value(storage, p.padding.bottom)?;
    empty_tag_with_storage(
        w,
        "hp:inMargin",
        &[("left", &l), ("right", &r), ("top", &t), ("bottom", &b)],
        storage,
    )
}

fn write_img_dim<W: Write>(w: &mut Writer<W>, p: &Picture) -> Result<(), SerializeError> {
    write_img_dim_with_storage(w, p, &crate::storage::Unbounded)
}

pub(super) fn write_img_dim_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    p: &Picture,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    // [#1389] 원본 crop 좌표계의 기준 크기 그대로 보존(IR img_dim). 종전 간이 계산
    // (common - crop)은 imgClip extent 의미 오해로 음수→0 변형이었다.
    empty_tag_with_storage(
        w,
        "hp:imgDim",
        &[
            ("dimwidth", &xml_value(storage, p.img_dim.0)?),
            ("dimheight", &xml_value(storage, p.img_dim.1)?),
        ],
        storage,
    )
}

/// `<hc:img binaryItemIDRef>` 출력. 3-way 단언의 1차 지점.
fn write_img<W: Write>(
    w: &mut Writer<W>,
    p: &Picture,
    ctx: &SerializeContext,
) -> Result<(), SerializeError> {
    write_img_with_storage(w, p, ctx, &crate::storage::Unbounded)
}

pub(super) fn write_img_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    p: &Picture,
    ctx: &SerializeContext,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let bin_id = p.image_attr.bin_data_id;
    // #1567: bin_id==0 은 원본 `binaryItemIDRef=""`(이미지 참조 없는 placeholder pic, 표 셀
    // 등)에 대응한다(파서 `unwrap_or(0)`). resolve 실패해도 빈 ref 를 verbatim 방출해
    // pic 컨트롤을 보존한다(종전: Err → 호출자 section.rs:701 이 조용히 드롭 → IR_DIFF).
    // 비-0 미해결은 진짜 BinDataContent 누락이므로 진단(Err)을 유지해 손실 은폐를 막는다.
    let manifest_id = match ctx.resolve_bin_id(bin_id) {
        Some(id) => id,
        None if bin_id == 0 => "",
        None => {
            return Err(SerializeError::XmlError(xml_value(
                storage,
                format_args!(
                    "<hp:pic> binaryItemIDRef 미등록 bin_data_id={} (BinDataContent 누락)",
                    bin_id
                ),
            )?))
        }
    };

    let bright = xml_value(storage, p.image_attr.brightness)?;
    let contrast = xml_value(storage, p.image_attr.contrast)?;
    let effect = image_effect_str(p.image_attr.effect);
    let alpha = picture_alpha_str_with_storage(p.image_attr.clamped_transparency(), storage)?;
    empty_tag_with_storage(
        w,
        "hc:img",
        &[
            ("binaryItemIDRef", manifest_id),
            ("bright", &bright),
            ("contrast", &contrast),
            ("effect", effect),
            ("alpha", &alpha),
        ],
        storage,
    )
}

fn picture_alpha_str(transparency: u8) -> String {
    picture_alpha_str_with_storage(transparency, &crate::storage::Unbounded)
        .expect("unbounded XML writer")
}

pub(super) fn picture_alpha_str_with_storage<S: crate::storage::Storage>(
    transparency: u8,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    xml_value(
        storage,
        crate::model::image::transparency_percent_to_alpha_byte(transparency),
    )
}

fn write_effects<W: Write>(w: &mut Writer<W>, pic: &Picture) -> Result<(), SerializeError> {
    write_effects_with_storage(w, pic, &crate::storage::Unbounded)
}

pub(super) fn write_effects_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    pic: &Picture,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    start_tag_with_storage(w, "hp:effects", storage)?;
    if let Some(shadow) = &pic.effects.shadow {
        write_shadow_with_storage(w, shadow, storage)?;
    }
    if let Some(radius) = pic
        .effects
        .soft_edge_radius
        .filter(|radius| radius.is_finite() && *radius >= 0.0)
    {
        let radius = xml_value(storage, radius)?;
        empty_tag_with_storage(w, "hp:softEdge", &[("radius", radius.as_str())], storage)?;
    }
    end_tag_with_storage(w, "hp:effects", storage)?;
    Ok(())
}

fn write_shadow<W: Write>(w: &mut Writer<W>, shadow: &PictureShadow) -> Result<(), SerializeError> {
    write_shadow_with_storage(w, shadow, &crate::storage::Unbounded)
}

pub(super) fn write_shadow_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    shadow: &PictureShadow,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let mut attrs = Vec::new();
    push_opt_attr_with_storage(&mut attrs, "style", shadow.style.as_deref(), storage)?;
    push_opt_attr_with_storage(&mut attrs, "alpha", shadow.alpha.as_deref(), storage)?;
    push_opt_attr_with_storage(&mut attrs, "radius", shadow.radius.as_deref(), storage)?;
    push_opt_attr_with_storage(
        &mut attrs,
        "direction",
        shadow.direction.as_deref(),
        storage,
    )?;
    push_opt_attr_with_storage(&mut attrs, "distance", shadow.distance.as_deref(), storage)?;
    push_opt_attr_with_storage(
        &mut attrs,
        "alignStyle",
        shadow.align_style.as_deref(),
        storage,
    )?;
    push_opt_attr_with_storage(
        &mut attrs,
        "rotationStyle",
        shadow.rotation_style.as_deref(),
        storage,
    )?;

    start_tag_attrs_with_storage(w, "hp:shadow", &attrs, storage)?;
    if let Some(skew) = &shadow.skew {
        write_effect_point_with_storage(w, "hp:skew", skew, storage)?;
    }
    if let Some(scale) = &shadow.scale {
        write_effect_point_with_storage(w, "hp:scale", scale, storage)?;
    }
    if let Some(color) = &shadow.color {
        write_effect_color_with_storage(w, color, storage)?;
    }
    end_tag_with_storage(w, "hp:shadow", storage)?;
    Ok(())
}

fn write_effect_point<W: Write>(
    w: &mut Writer<W>,
    name: &str,
    point: &EffectPoint,
) -> Result<(), SerializeError> {
    write_effect_point_with_storage(w, name, point, &crate::storage::Unbounded)
}

pub(super) fn write_effect_point_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    name: &str,
    point: &EffectPoint,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let mut attrs = Vec::new();
    push_opt_attr_with_storage(&mut attrs, "x", point.x.as_deref(), storage)?;
    push_opt_attr_with_storage(&mut attrs, "y", point.y.as_deref(), storage)?;
    empty_tag_with_storage(w, name, &attrs, storage)
}

fn write_effect_color<W: Write>(
    w: &mut Writer<W>,
    color: &EffectColor,
) -> Result<(), SerializeError> {
    write_effect_color_with_storage(w, color, &crate::storage::Unbounded)
}

pub(super) fn write_effect_color_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    color: &EffectColor,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let mut attrs = Vec::new();
    push_opt_attr_with_storage(&mut attrs, "type", color.color_type.as_deref(), storage)?;
    push_opt_attr_with_storage(
        &mut attrs,
        "schemeIdx",
        color.scheme_idx.as_deref(),
        storage,
    )?;
    push_opt_attr_with_storage(
        &mut attrs,
        "systemIdx",
        color.system_idx.as_deref(),
        storage,
    )?;
    push_opt_attr_with_storage(
        &mut attrs,
        "presetIdx",
        color.preset_idx.as_deref(),
        storage,
    )?;

    if let Some(rgb) = &color.rgb {
        start_tag_attrs_with_storage(w, "hp:effectsColor", &attrs, storage)?;
        write_effect_rgb_with_storage(w, rgb, storage)?;
        end_tag_with_storage(w, "hp:effectsColor", storage)?;
    } else {
        empty_tag_with_storage(w, "hp:effectsColor", &attrs, storage)?;
    }
    Ok(())
}

fn write_effect_rgb<W: Write>(w: &mut Writer<W>, rgb: &EffectRgb) -> Result<(), SerializeError> {
    write_effect_rgb_with_storage(w, rgb, &crate::storage::Unbounded)
}

pub(super) fn write_effect_rgb_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    rgb: &EffectRgb,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let mut attrs = Vec::new();
    push_opt_attr_with_storage(&mut attrs, "r", rgb.r.as_deref(), storage)?;
    push_opt_attr_with_storage(&mut attrs, "g", rgb.g.as_deref(), storage)?;
    push_opt_attr_with_storage(&mut attrs, "b", rgb.b.as_deref(), storage)?;
    empty_tag_with_storage(w, "hp:rgb", &attrs, storage)
}

fn push_opt_attr<'a>(
    attrs: &mut Vec<(&'static str, &'a str)>,
    key: &'static str,
    value: Option<&'a str>,
) {
    push_opt_attr_with_storage(attrs, key, value, &crate::storage::Unbounded)
        .expect("unbounded XML writer")
}

pub(super) fn push_opt_attr_with_storage<'a, S: crate::storage::Storage>(
    attrs: &mut Vec<(&'static str, &'a str)>,
    key: &'static str,
    value: Option<&'a str>,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    if let Some(value) = value {
        storage.push(attrs, (key, value)).map_err(xml_error)?;
    }

    Ok(())
}

fn write_sz<W: Write>(w: &mut Writer<W>, c: &CommonObjAttr) -> Result<(), SerializeError> {
    write_sz_with_storage(w, c, &crate::storage::Unbounded)
}

pub(super) fn write_sz_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    c: &CommonObjAttr,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let width = xml_value(storage, c.width)?;
    let height = xml_value(storage, c.height)?;
    // [#2712] widthRelTo/heightRelTo/protect 는 IR 을 보존한다. 종전 "ABSOLUTE"/"0"
    // 하드코딩은 HWP5 입력(parser/control/shape.rs:348/380/388 이 attr bit 20/15-17/18-19
    // 에서 채움)과 문서 코어 편집(set_cell_picture_properties 의 sizeProtect,
    // tests/issue_1436_size_protect_properties.rs:48)으로 들어온 값을 저장 때 버렸다.
    // 헬퍼는 도형 직렬화기와 공유해 관례를 하나로 유지한다(shape.rs:1000/1013).
    empty_tag_with_storage(
        w,
        "hp:sz",
        &[
            ("width", &width),
            ("widthRelTo", size_criterion_str(c.width_criterion)),
            ("height", &height),
            ("heightRelTo", height_criterion_str(c.height_criterion)),
            ("protect", bool01(c.size_protect)),
        ],
        storage,
    )
}

fn write_pos<W: Write>(w: &mut Writer<W>, c: &CommonObjAttr) -> Result<(), SerializeError> {
    write_pos_with_storage(w, c, &crate::storage::Unbounded)
}

pub(super) fn write_pos_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    c: &CommonObjAttr,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let treat = bool01(c.treat_as_char);
    let flow_with_text = bool01(c.flow_with_text);
    let allow_overlap = bool01(c.allow_overlap);
    let vert_offset = xml_value(storage, c.vertical_offset)?;
    let horz_offset = xml_value(storage, c.horizontal_offset)?;
    let hold = bool01(c.prevent_page_break != 0); // [#1594] IR 보존
    empty_tag_with_storage(
        w,
        "hp:pos",
        &[
            ("treatAsChar", treat),
            // [#2784] affectLSpacing 은 IR(affect_line_spacing)을 보존한다. 종전 "0"
            // 하드코딩은 "줄 간격에 영향" 켜진 그림이 저장 시 1→0 으로 드롭됐다.
            ("affectLSpacing", bool01(c.affect_line_spacing)),
            ("flowWithText", flow_with_text),
            ("allowOverlap", allow_overlap),
            ("holdAnchorAndSO", hold),
            ("vertRelTo", vert_rel_to_str(c.vert_rel_to)),
            ("horzRelTo", horz_rel_to_str(c.horz_rel_to)),
            ("vertAlign", vert_align_str(c.vert_align)),
            ("horzAlign", horz_align_str(c.horz_align)),
            ("vertOffset", &vert_offset),
            ("horzOffset", &horz_offset),
        ],
        storage,
    )
}

fn write_out_margin<W: Write>(w: &mut Writer<W>, c: &CommonObjAttr) -> Result<(), SerializeError> {
    write_out_margin_with_storage(w, c, &crate::storage::Unbounded)
}

pub(super) fn write_out_margin_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    c: &CommonObjAttr,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let l = xml_value(storage, c.margin.left)?;
    let r = xml_value(storage, c.margin.right)?;
    let t = xml_value(storage, c.margin.top)?;
    let b = xml_value(storage, c.margin.bottom)?;
    empty_tag_with_storage(
        w,
        "hp:outMargin",
        &[("left", &l), ("right", &r), ("top", &t), ("bottom", &b)],
        storage,
    )
}

// ---------- 변환 헬퍼 ----------

fn bool01(b: bool) -> &'static str {
    if b {
        "1"
    } else {
        "0"
    }
}

fn text_wrap_str(w: TextWrap) -> &'static str {
    use TextWrap::*;
    match w {
        Square => "SQUARE",
        Tight => "TIGHT",
        Through => "THROUGH",
        TopAndBottom => "TOP_AND_BOTTOM",
        BehindText => "BEHIND_TEXT",
        InFrontOfText => "IN_FRONT_OF_TEXT",
    }
}

fn text_flow_str(f: TextFlow) -> &'static str {
    match f {
        TextFlow::BothSides => "BOTH_SIDES",
        TextFlow::LeftOnly => "LEFT_ONLY",
        TextFlow::RightOnly => "RIGHT_ONLY",
        TextFlow::LargestOnly => "LARGEST_ONLY",
    }
}

fn vert_rel_to_str(v: VertRelTo) -> &'static str {
    use VertRelTo::*;
    match v {
        Paper => "PAPER",
        Page => "PAGE",
        Para => "PARA",
    }
}

fn horz_rel_to_str(h: HorzRelTo) -> &'static str {
    use HorzRelTo::*;
    match h {
        Paper => "PAPER",
        Page => "PAGE",
        Column => "COLUMN",
        Para => "PARA",
    }
}

fn vert_align_str(v: VertAlign) -> &'static str {
    use VertAlign::*;
    match v {
        Top => "TOP",
        Center => "CENTER",
        Bottom => "BOTTOM",
        Inside => "INSIDE",
        Outside => "OUTSIDE",
    }
}

fn horz_align_str(h: HorzAlign) -> &'static str {
    use HorzAlign::*;
    match h {
        Left => "LEFT",
        Center => "CENTER",
        Right => "RIGHT",
        Inside => "INSIDE",
        Outside => "OUTSIDE",
    }
}

fn image_effect_str(e: ImageEffect) -> &'static str {
    use ImageEffect::*;
    match e {
        RealPic => "REAL_PIC",
        GrayScale => "GRAY_SCALE",
        BlackWhite => "BLACK_WHITE",
        Pattern8x8 => "PATTERN_8_8",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::bin_data::BinDataContent;
    use crate::model::document::Document;
    use crate::model::image::{
        EffectColor, EffectPoint, EffectRgb, ImageAttr, Picture, PictureEffects, PictureShadow,
    };
    use crate::serializer::hwpx::context::SerializeContext;

    fn make_picture(bin_data_id: u16) -> Picture {
        let mut pic = Picture::default();
        pic.image_attr = ImageAttr {
            bin_data_id,
            brightness: 0,
            contrast: 0,
            effect: ImageEffect::RealPic,
            transparency: 0,
            external_path: None,
        };
        pic.common.width = 1000;
        pic.common.height = 500;
        pic
    }

    fn make_doc_with_bin(bin_data_id: u16, ext: &str) -> Document {
        let mut doc = Document::default();
        doc.bin_data_content.push(BinDataContent {
            id: bin_data_id,
            data: vec![0u8; 4].into(),
            extension: ext.to_string(),
        });
        doc
    }

    fn serialize(pic: &Picture, ctx: &mut SerializeContext) -> String {
        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
        write_picture(&mut w, pic, ctx).expect("write_picture");
        String::from_utf8(w.into_inner()).unwrap()
    }

    // [#2875] hp:pic lock="1" 이 IR 에 있어도 종전에는 하드코딩 "0" 으로 방출됐다.
    #[test]
    fn issue2875_pic_lock_is_preserved_on_serialize() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1);
        pic.lock = true;
        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains(r#"lock="1""#),
            "hp:pic lock=1 이 저장 시 보존돼야 한다: {xml}"
        );
    }

    #[test]
    fn task1389_cur_sz_uses_shape_attr() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1); // common 1000x500
        pic.shape_attr.current_width = 1366;
        pic.shape_attr.current_height = 1268;
        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains(r#"<hp:curSz width="1366" height="1268"/>"#),
            "curSz 는 shape_attr.current 사용(sz 아님): {xml}"
        );
    }

    #[test]
    fn dropcapstyle_round_trips_instead_of_always_none() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1);
        pic.common.drop_cap_style = crate::model::shape::DropCapStyle::TripleLine;
        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains(r#"dropcapstyle="TripleLine""#),
            "dropcapstyle 는 원본 값을 보존해야 한다(하드코딩 \"None\" 아님): {xml}"
        );
    }

    #[test]
    fn task1389_cur_sz_falls_back_to_common_when_zero() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let pic = make_picture(1); // current_width=0 → common 폴백
        let xml = serialize(&pic, &mut ctx);
        assert!(xml.contains(r#"<hp:curSz width="1000" height="500"/>"#));
    }

    #[test]
    fn task1389_img_rect_uses_border_scalar_layout() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1);
        // ta-pic pic0 실측: pt0(0,0) pt1(49380,0) pt2(49380,45840) pt3(0,45840)
        // 스칼라 레이아웃: border_x=[pt0.x,pt0.y,pt1.x,pt1.y], border_y=[pt2.x,pt2.y,pt3.x,pt3.y]
        pic.border_x = [0, 0, 49380, 0];
        pic.border_y = [49380, 45840, 0, 45840];
        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains(
                r#"<hp:imgRect><hc:pt0 x="0" y="0"/><hc:pt1 x="49380" y="0"/><hc:pt2 x="49380" y="45840"/><hc:pt3 x="0" y="45840"/></hp:imgRect>"#
            ),
            "imgRect 는 border 스칼라 레이아웃 역매핑: {xml}"
        );
    }

    #[test]
    fn issue1452_img_alpha_uses_hwp_alpha_byte() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1);

        pic.image_attr.transparency = 50;
        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains(r#"alpha="127""#),
            "그림 투명도 50%는 한컴 HWPX alpha byte 127로 저장되어야 한다: {xml}"
        );

        pic.image_attr.transparency = 100;
        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains(r#"alpha="255""#),
            "그림 투명도 100%는 한컴 HWPX alpha byte 255로 저장되어야 한다: {xml}"
        );
    }

    // [#2861] reverse="1" 이 IR 에 있어도 종전에는 하드코딩 "0" 으로 방출됐다.
    #[test]
    fn issue2861_pic_reverse_is_preserved_on_serialize() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1);

        pic.reverse = true;
        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains(r#"reverse="1""#),
            "hp:pic reverse=1 이 저장 시 보존돼야 한다: {xml}"
        );
    }

    #[test]
    fn task1389_img_rect_synthesizes_when_border_zero() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let pic = make_picture(1); // border 전부 0 → common 합성
        let xml = serialize(&pic, &mut ctx);
        assert!(xml.contains(r#"<hc:pt2 x="1000" y="500"/>"#), "{xml}");
    }

    #[test]
    fn task1389_img_dim_verbatim() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1);
        pic.img_dim = (49380, 45840);
        // crop 이 달라도 img_dim verbatim (clip 파생 아님)
        pic.crop.right = 99999;
        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains(r#"<hp:imgDim dimwidth="49380" dimheight="45840"/>"#),
            "imgDim 은 IR verbatim (clip 파생 금지): {xml}"
        );
    }

    #[test]
    fn task1392_pic_shape_comment_emitted_after_caption() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1);
        pic.common.description = "그림입니다.".to_string();
        let mut para = crate::model::paragraph::Paragraph::default();
        para.text = "캡션".to_string();
        let mut cap = crate::model::shape::Caption::default();
        cap.paragraphs.push(para);
        pic.caption = Some(cap);
        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains("<hp:shapeComment>그림입니다.</hp:shapeComment>"),
            "shapeComment 방출: {xml}"
        );
        // 순서: caption → shapeComment (aift 실물)
        let cp = xml.find("<hp:caption").unwrap();
        let sc = xml.find("<hp:shapeComment").unwrap();
        assert!(cp < sc, "caption 이 shapeComment 보다 먼저");
    }

    #[test]
    fn task1392_pic_no_description_omits_comment() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let pic = make_picture(1); // description 빈 문자열
        let xml = serialize(&pic, &mut ctx);
        assert!(!xml.contains("<hp:shapeComment"), "빈 설명은 미방출: {xml}");
    }

    #[test]
    fn pic_root_attrs_in_canonical_order() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let pic = make_picture(1);
        let xml = serialize(&pic, &mut ctx);
        assert!(xml.contains("<hp:pic "));
        let ip = xml.find("id=").unwrap();
        let zp = xml.find("zOrder=").unwrap();
        let nt = xml.find("numberingType=").unwrap();
        let tw = xml.find("textWrap=").unwrap();
        let href = xml.find("href=").unwrap();
        let rev = xml.find("reverse=").unwrap();
        assert!(ip < zp && zp < nt && nt < tw && tw < href && href < rev);
    }

    #[test]
    fn img_uses_manifest_id() {
        // [#1891] manifest id 는 `image{bin_data_id}` 숫자 불변식을 따라야 한다.
        // 파서(section.rs)가 binaryItemIDRef 의 숫자를 그대로 bin_data_id 로 읽으므로,
        // 종전 순번 명명(id=5 → "image1")은 재파스에서 참조가 1 로 어긋났다.
        let doc = make_doc_with_bin(5, "jpg");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let pic = make_picture(5);
        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains(r#"binaryItemIDRef="image5""#),
            "binaryItemIDRef must resolve to manifest id image5 (숫자 불변식): {}",
            xml
        );
    }

    #[test]
    fn task1567_empty_binary_ref_pic_preserved() {
        // #1567: bin_data_id==0(원본 binaryItemIDRef="" placeholder)은 BinDataContent 가
        // 없어 resolve 실패해도 binaryItemIDRef="" 로 보존되어야 한다(드롭 금지).
        let doc = Document::default(); // bin 미등록
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let pic = make_picture(0);
        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains(r#"binaryItemIDRef="""#),
            "빈 ref pic 은 binaryItemIDRef=\"\" 로 보존(드롭 금지): {xml}"
        );
        assert!(xml.contains("<hp:pic "), "pic 컨트롤 자체 보존: {xml}");
    }

    #[test]
    fn shape_component_attrs_are_serialized() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1);
        pic.shape_attr.original_width = 23456;
        pic.shape_attr.original_height = 12345;
        pic.shape_attr.horz_flip = true;
        pic.shape_attr.vert_flip = true;
        pic.shape_attr.rotation_angle = 34;
        pic.shape_attr.rotation_center.x = 11700;
        pic.shape_attr.rotation_center.y = 14794;
        pic.shape_attr.rotate_image = true;

        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains(r#"<hp:orgSz width="23456" height="12345"/>"#),
            "orgSz must use ShapeComponentAttr values: {}",
            xml
        );
        assert!(
            xml.contains(r#"<hp:flip horizontal="1" vertical="1"/>"#),
            "flip must use ShapeComponentAttr values: {}",
            xml
        );
        assert!(
            xml.contains(
                r#"<hp:rotationInfo angle="34" centerX="11700" centerY="14794" rotateimage="1"/>"#
            ),
            "rotationInfo must use ShapeComponentAttr values: {}",
            xml
        );
    }

    #[test]
    fn unresolved_bin_data_id_errors() {
        let doc = Document::default(); // bin_data 없음
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let pic = make_picture(99); // 미등록 id
        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
        let err = write_picture(&mut w, &pic, &mut ctx).unwrap_err();
        let msg = format!("{}", err);
        assert!(msg.contains("binaryItemIDRef"), "error msg: {}", msg);
        assert!(
            msg.contains("99"),
            "error should include bin_data_id: {}",
            msg
        );
    }

    #[test]
    fn rendering_info_has_three_matrices() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let pic = make_picture(1);
        let xml = serialize(&pic, &mut ctx);
        assert!(xml.contains("<hc:transMatrix "));
        assert!(xml.contains("<hc:scaMatrix "));
        assert!(xml.contains("<hc:rotMatrix "));
    }

    #[test]
    fn img_rect_has_four_points() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let pic = make_picture(1);
        let xml = serialize(&pic, &mut ctx);
        assert!(xml.contains("<hc:pt0 "));
        assert!(xml.contains("<hc:pt1 "));
        assert!(xml.contains("<hc:pt2 "));
        assert!(xml.contains("<hc:pt3 "));
    }

    #[test]
    fn image_effect_maps_to_string() {
        assert_eq!(image_effect_str(ImageEffect::RealPic), "REAL_PIC");
        assert_eq!(image_effect_str(ImageEffect::GrayScale), "GRAY_SCALE");
        assert_eq!(image_effect_str(ImageEffect::BlackWhite), "BLACK_WHITE");
    }

    #[test]
    fn picture_effects_shadow_are_serialized() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1);
        pic.effects = PictureEffects {
            soft_edge_radius: None,
            shadow: Some(PictureShadow {
                style: Some("OUTSIDE".to_string()),
                alpha: Some("0.8".to_string()),
                radius: Some("400".to_string()),
                direction: Some("45".to_string()),
                distance: Some("1000".to_string()),
                align_style: Some("TOP_LEFT".to_string()),
                rotation_style: Some("0".to_string()),
                skew: None,
                scale: Some(EffectPoint {
                    x: Some("1".to_string()),
                    y: Some("1".to_string()),
                }),
                color: Some(EffectColor {
                    color_type: Some("RGB".to_string()),
                    scheme_idx: Some("-1".to_string()),
                    system_idx: Some("-1".to_string()),
                    preset_idx: Some("-1".to_string()),
                    rgb: Some(EffectRgb {
                        r: Some("0".to_string()),
                        g: Some("0".to_string()),
                        b: Some("0".to_string()),
                    }),
                }),
            }),
        };

        let xml = serialize(&pic, &mut ctx);
        assert!(xml.contains(r#"<hp:shadow style="OUTSIDE" alpha="0.8" radius="400" direction="45" distance="1000" alignStyle="TOP_LEFT" rotationStyle="0">"#));
        assert!(xml.contains(r#"<hp:scale x="1" y="1"/>"#));
        assert!(xml.contains(
            r#"<hp:effectsColor type="RGB" schemeIdx="-1" systemIdx="-1" presetIdx="-1">"#
        ));
        assert!(xml.contains(r#"<hp:rgb r="0" g="0" b="0"/>"#));
    }

    // ---------- #1403: 그림 캡션 직렬화 ----------

    #[test]
    fn task1403_pic_caption_is_serialized() {
        // 캡션 유실(#1403) 회귀 고정 — 한컴 실물(aift.hwpx) 순서: outMargin 뒤 마지막 자식.
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1);
        let mut para = crate::model::paragraph::Paragraph::default();
        para.text = "그림 캡션".to_string();
        let mut cap = crate::model::shape::Caption::default();
        cap.width = 8504;
        cap.spacing = 850;
        cap.max_width = 48081;
        cap.paragraphs.push(para);
        pic.caption = Some(cap);

        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains(
                r#"<hp:caption side="BOTTOM" fullSz="0" width="8504" gap="850" lastWidth="48081">"#
            ),
            "caption 속성이 IR 값으로 방출되어야 함: {}",
            xml
        );
        assert!(
            xml.contains("<hp:t>그림 캡션</hp:t>"),
            "캡션 subList 문단 텍스트가 방출되어야 함: {}",
            xml
        );
        let om = xml.find("<hp:outMargin").unwrap();
        let cp = xml.find("<hp:caption").unwrap();
        assert!(om < cp, "caption 은 outMargin 뒤 (한컴 실물 순서)");
    }

    #[test]
    fn task1403_pic_without_caption_emits_none() {
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let pic = make_picture(1);
        let xml = serialize(&pic, &mut ctx);
        assert!(!xml.contains("<hp:caption"), "캡션 부재 시 미방출: {}", xml);
    }

    // ---------- #2712: 그림 hp:sz 크기 기준·크기 보호 라운드트립 ----------

    /// 그림 조각을 한 문단짜리 `<hs:sec>` 으로 감싸 다시 파싱한다(IR 수준 역검증용).
    fn reparse_pic_common(fragment: &str) -> CommonObjAttr {
        let xml = format!(
            concat!(
                r#"<?xml version="1.0" encoding="UTF-8"?>"#,
                r#"<hs:sec xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph""#,
                r#" xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section">"#,
                r#"<hp:p id="0" paraPrIDRef="0" styleIDRef="0">"#,
                r#"<hp:run charPrIDRef="0">{}<hp:t/></hp:run></hp:p></hs:sec>"#
            ),
            fragment
        );
        let section = crate::parser::hwpx::section::parse_hwpx_section(&xml)
            .expect("파싱 가능한 그림 조각이어야 함");
        match &section.paragraphs[0].controls[0] {
            crate::model::control::Control::Picture(p) => p.common.clone(),
            other => panic!("그림 컨트롤이어야 함: {other:?}"),
        }
    }

    #[test]
    fn task2712_pic_sz_criteria_and_protect_emitted_from_ir() {
        // [#2712] 그림 hp:sz 도 IR 을 보존해야 한다. 종전 "ABSOLUTE"/"ABSOLUTE"/"0"
        // 하드코딩은 HWP5 입력(parser/control/shape.rs:348/380/388)과 문서 코어
        // 편집(sizeProtect, tests/issue_1436_size_protect_properties.rs)으로 들어온
        // 값을 저장 때 버렸다. RED.
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1);
        pic.common.width_criterion = SizeCriterion::Column;
        pic.common.height_criterion = SizeCriterion::Page;
        pic.common.size_protect = true;
        let xml = serialize(&pic, &mut ctx);
        assert!(
            xml.contains(r#"widthRelTo="COLUMN""#),
            "widthRelTo 가 IR(Column)로 방출돼야 함(종전 ABSOLUTE 하드코딩): {xml}"
        );
        assert!(
            xml.contains(r#"heightRelTo="PAGE""#),
            "heightRelTo 가 IR(Page)로 방출돼야 함(종전 ABSOLUTE 하드코딩): {xml}"
        );
        assert!(
            xml.contains(r#"protect="1""#),
            "protect 가 IR(size_protect=true)로 방출돼야 함(종전 0 하드코딩): {xml}"
        );
    }

    #[test]
    fn task2712_pic_sz_round_trips_through_parser() {
        // [#2712] 그림 파서는 hp:sz 의 크기 기준·크기 보호 arm 이 아예 없어 왕복이 막혀
        // 있었다(section.rs:2308 인라인 arm 에 width/height 만 존재). 파서 arm 추가로
        // 방출→파싱이 정확한 역이 돼야 한다. RED.
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1);
        pic.common.width_criterion = SizeCriterion::Para;
        pic.common.height_criterion = SizeCriterion::Paper;
        pic.common.size_protect = true;
        let xml = serialize(&pic, &mut ctx);

        let back = reparse_pic_common(&xml);
        assert_eq!(
            back.width_criterion,
            SizeCriterion::Para,
            "그림 widthRelTo 가 IR 로 되읽혀야 함"
        );
        assert_eq!(
            back.height_criterion,
            SizeCriterion::Paper,
            "그림 heightRelTo 가 IR 로 되읽혀야 함"
        );
        assert!(back.size_protect, "그림 protect 가 IR 로 되읽혀야 함");
    }

    #[test]
    fn task2712_pic_height_criterion_is_exact_inverse() {
        // 높이는 파서가 allow_column_para=false 로 읽으므로 방출도 3값으로 접어야 한다.
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut pic = make_picture(1);
        pic.common.height_criterion = SizeCriterion::Para;
        let xml = serialize(&pic, &mut ctx);
        assert!(xml.contains(r#"heightRelTo="ABSOLUTE""#), "{xml}");
        assert_eq!(
            reparse_pic_common(&xml).height_criterion,
            SizeCriterion::Absolute
        );
    }

    #[test]
    fn task2712_pic_sz_defaults_unchanged() {
        // 기본 IR(Absolute/Absolute/false)은 종전 출력과 동일해야 한다(무변화 보장).
        // 실측상 samples/hwpx 의 hp:pic 188개가 전부 이 조합이라 회귀 위험이 없다.
        let doc = make_doc_with_bin(1, "png");
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = serialize(&make_picture(1), &mut ctx);
        assert!(xml.contains(r#"widthRelTo="ABSOLUTE""#), "{xml}");
        assert!(xml.contains(r#"heightRelTo="ABSOLUTE""#), "{xml}");
        assert!(xml.contains(r#"protect="0""#), "{xml}");
    }
}