Skip to main content

rhwp/serializer/hwpx/
shape.rs

1//! 그리기 개체 (도형) 직렬화 — Rectangle / Line / Container.
2//!
3//! Stage 5 (#182)에서 뼈대를 만들고, #1379 3단계에서 rect 하위 요소 보존으로 확장했다.
4//!
5//! 속성·자식 순서는 한컴 원본 XML 실측(tbox-v-flow-01) 기준:
6//! `offset → orgSz → curSz → flip → rotationInfo → renderingInfo → lineShape →
7//! fillBrush → shadow → drawText → hc:pt0~pt3 → sz → pos → outMargin → shapeComment`
8//!
9//! ## 범위 한정
10//!
11//! - rect 우선 (#1379 3단계). Arc / Polygon / Curve 등 타 도형 확대는 측정 후 별도 분류.
12//! - 글상자(drawText) 문단은 본문·셀과 동일한 `render_paragraph_parts` 공유 경로로
13//!   직렬화한다 (컨트롤 슬롯 + run 분할 + lineseg IR 보존).
14
15#![allow(dead_code)]
16
17use super::section::{
18    build_secpr_run_with_storage, render_hp_p_open_with_storage,
19    render_paragraph_parts_with_storage,
20};
21use super::table::write_caption_with_storage;
22use super::utils::{
23    empty_tag_with_storage, end_tag_with_storage, start_tag_attrs_with_storage,
24    start_tag_with_storage, text_with_storage, write_xml_decl_with_storage, xml_error,
25    xml_escape_with_storage, xml_value,
26};
27use std::io::Write;
28
29use quick_xml::Writer;
30
31use crate::model::shape::{
32    CommonObjAttr, DrawingObjAttr, HorzAlign, HorzRelTo, LineShape, ObjectNumberingType,
33    OleDrawingAspect, OleShape, RectangleShape, ShapeComponentAttr, SizeCriterion, TextBox,
34    TextFlow, TextWrap, VertAlign, VertRelTo,
35};
36use crate::model::style::{Fill, FillType, ImageFillMode, ShapeBorderLine, SolidFill};
37use crate::model::ColorRef;
38
39use super::context::SerializeContext;
40use super::section::{render_hp_p_open, render_paragraph_parts};
41use super::table::write_caption;
42use super::utils::{empty_tag, end_tag, start_tag, start_tag_attrs, text};
43use super::SerializeError;
44
45// =====================================================================
46// <hp:rect>
47// =====================================================================
48
49/// `<hp:rect>` 직렬화 진입점. Rectangle IR → XML.
50pub fn write_rect<W: Write>(
51    w: &mut Writer<W>,
52    rect: &RectangleShape,
53    ctx: &mut SerializeContext,
54) -> Result<(), SerializeError> {
55    write_rect_with_storage(w, rect, ctx, &crate::storage::Unbounded)
56}
57
58pub(super) fn write_rect_with_storage<W: Write, S: crate::storage::Storage>(
59    w: &mut Writer<W>,
60    rect: &RectangleShape,
61    ctx: &mut SerializeContext,
62    storage: &S,
63) -> Result<(), SerializeError>
64where
65    S::Error: std::fmt::Display,
66{
67    let c = &rect.common;
68    let sa = &rect.drawing.shape_attr;
69    // 속성 (부모 AbstractShapeObjectType + 자신):
70    // id, zOrder, numberingType, textWrap, textFlow, lock, dropcapstyle,
71    // href, groupLevel, instid, ratio
72    let id_str = xml_value(storage, c.instance_id)?;
73    let z_order = xml_value(storage, c.z_order)?;
74    let tw = text_wrap_str(c.text_wrap);
75    let tf = text_flow_str(c.text_flow);
76    let group_level = xml_value(storage, sa.group_level)?;
77    // 파서는 instid 를 drawing.inst_id 에 보존한다 (0이면 instance_id 대체).
78    let instid = xml_value(
79        storage,
80        if rect.drawing.inst_id != 0 {
81            rect.drawing.inst_id
82        } else {
83            c.instance_id
84        },
85    )?;
86    let ratio = xml_value(storage, rect.round_rate)?;
87
88    start_tag_attrs_with_storage(
89        w,
90        "hp:rect",
91        &[
92            ("id", &id_str),
93            ("zOrder", &z_order),
94            ("numberingType", numbering_type_str(c.numbering_type)),
95            ("textWrap", tw),
96            ("textFlow", tf),
97            // [#2840] lock(개체 잠금) — 파서가 읽기 시작했으므로 IR 값을 방출한다.
98            ("lock", bool01(c.locked)),
99            ("dropcapstyle", drop_cap_style_str(c.drop_cap_style)),
100            ("href", ""),
101            ("groupLevel", &group_level),
102            ("instid", &instid),
103            ("ratio", &ratio),
104        ],
105        storage,
106    )?;
107
108    // 자식 순서 — 한컴 원본 실측 (tbox-v-flow-01) 기준.
109    write_offset_with_storage(w, sa, storage)?;
110    write_org_sz_with_storage(w, sa, storage)?;
111    write_cur_sz_with_storage(w, sa, storage)?;
112    write_flip_with_storage(w, sa, storage)?;
113    write_rotation_info_with_storage(w, sa, storage)?;
114    write_rendering_info_with_storage(w, sa, storage)?;
115    write_line_shape_with_storage(w, &rect.drawing.border_line, storage)?;
116    write_fill_brush_with_storage(w, &rect.drawing.fill, ctx, storage)?;
117    write_shadow_with_storage(w, &rect.drawing, storage)?;
118
119    // drawText: 글상자 내부 문단
120    if let Some(ref tb) = rect.drawing.text_box {
121        if !tb.paragraphs.is_empty() {
122            write_draw_text_with_storage(w, tb, ctx, storage)?;
123        }
124    }
125
126    // 꼭짓점 4점 (hc: 접두어)
127    write_rect_pts_with_storage(w, &rect.x_coords, &rect.y_coords, storage)?;
128
129    write_sz_with_storage(w, c, storage)?;
130    write_pos_with_storage(w, c, storage)?;
131    write_out_margin_with_storage(w, c, storage)?;
132    // 캡션 (#1403) — OWPML AbstractShapeObjectType 순서: outMargin 과 shapeComment 사이
133    if let Some(cap) = &rect.drawing.caption {
134        write_caption_with_storage(w, cap, ctx, storage)?;
135    }
136    write_shape_comment_with_storage(w, c, storage)?;
137
138    end_tag_with_storage(w, "hp:rect", storage)?;
139    Ok(())
140}
141
142// =====================================================================
143// <hp:line>
144// =====================================================================
145
146/// [Issue #1943] LinkLineType → HWPX `type` 속성 문자열 (parse_connect_line_type_attr 역).
147fn link_line_type_str(t: crate::model::shape::LinkLineType) -> &'static str {
148    use crate::model::shape::LinkLineType::*;
149    match t {
150        StraightNoArrow => "STRAIGHT_NOARROW",
151        StraightOneWay => "STRAIGHT_ONEWAY",
152        StraightBoth => "STRAIGHT_BOTH",
153        StrokeNoArrow => "STROKE_NOARROW",
154        StrokeOneWay => "STROKE_ONEWAY",
155        StrokeBoth => "STROKE_BOTH",
156        ArcNoArrow => "ARC_NOARROW",
157        ArcOneWay => "ARC_ONEWAY",
158        ArcBoth => "ARC_BOTH",
159    }
160}
161
162/// `<hp:line>` / `<hp:connectLine>` 직렬화 진입점. LineShape IR → XML.
163///
164/// [Issue #1943] 종전 write_line 은 골격 속성(startX/Y/endX/Y attr + sz/pos/outMargin)
165/// 만 방출해 (A) connector 보유 시에도 무조건 hp:line 으로 변질하고, (B) 컴포넌트
166/// 블록(offset/orgSz/curSz/flip/rotationInfo/renderingInfo)·lineShape(색·굵기)·
167/// fillBrush/shadow·좌표(hp:startPt/endPt 자식) 전체를 소실시켰다. 파서는 좌표를
168/// startPt/endPt **자식 요소**로만 읽으므로(startX/Y attr 무시) 종전 좌표는 dead
169/// 였다. write_rect 와 동형으로 전 구조를 방출한다.
170pub fn write_line<W: Write>(
171    w: &mut Writer<W>,
172    line: &LineShape,
173    ctx: &mut SerializeContext,
174) -> Result<(), SerializeError> {
175    write_line_with_storage(w, line, ctx, &crate::storage::Unbounded)
176}
177
178pub(super) fn write_line_with_storage<W: Write, S: crate::storage::Storage>(
179    w: &mut Writer<W>,
180    line: &LineShape,
181    ctx: &mut SerializeContext,
182    storage: &S,
183) -> Result<(), SerializeError>
184where
185    S::Error: std::fmt::Display,
186{
187    let c = &line.common;
188    let sa = &line.drawing.shape_attr;
189    let is_connector = line.connector.is_some();
190    let tag = if is_connector {
191        "hp:connectLine"
192    } else {
193        "hp:line"
194    };
195
196    let id_str = xml_value(storage, c.instance_id)?;
197    let z_order = xml_value(storage, c.z_order)?;
198    let group_level = xml_value(storage, sa.group_level)?;
199    let instid = xml_value(
200        storage,
201        if line.drawing.inst_id != 0 {
202            line.drawing.inst_id
203        } else {
204            c.instance_id
205        },
206    )?;
207    let srb = bool01(line.started_right_or_bottom);
208
209    let mut attrs: Vec<(&str, &str)> = vec![
210        ("id", &id_str),
211        ("zOrder", &z_order),
212        ("numberingType", numbering_type_str(c.numbering_type)),
213        ("textWrap", text_wrap_str(c.text_wrap)),
214        ("textFlow", text_flow_str(c.text_flow)),
215        // [#2840] lock(개체 잠금) — IR 보존 값 방출.
216        ("lock", bool01(c.locked)),
217        ("dropcapstyle", drop_cap_style_str(c.drop_cap_style)),
218        ("href", ""),
219        ("groupLevel", &group_level),
220        ("instid", &instid),
221    ];
222    if let Some(conn) = &line.connector {
223        storage
224            .push(&mut attrs, ("type", link_line_type_str(conn.link_type)))
225            .map_err(xml_error)?;
226    }
227    storage
228        .push(&mut attrs, ("isReverseHV", srb))
229        .map_err(xml_error)?;
230    start_tag_attrs_with_storage(w, tag, &attrs, storage)?;
231
232    // 컴포넌트 블록 + 지오메트리 (write_rect 동형): offset/orgSz/curSz/flip/
233    // rotationInfo/renderingInfo → lineShape → fillBrush → shadow.
234    write_shape_component_block_with_storage(w, sa, storage)?;
235    write_line_shape_with_storage(w, &line.drawing.border_line, storage)?;
236    write_fill_brush_with_storage(w, &line.drawing.fill, ctx, storage)?;
237    write_shadow_with_storage(w, &line.drawing, storage)?;
238
239    // 좌표 — startPt/endPt 자식 (파서가 읽는 유일 경로. 프리픽스 무관 로컬명
240    // 매칭). 네임스페이스는 요소별로 다르다: hp:line 의 자식은 hc: (XSD LineType
241    // — hp: 로 쓰면 한컴오피스가 문서를 거부한다), hp:connectLine 의 자식은
242    // hp: (ConnectPointType 로컬 요소, subjectIDRef/subjectIdx 포함).
243    let (sub_start_ref, sub_start_idx, sub_end_ref, sub_end_idx) = line
244        .connector
245        .as_ref()
246        .map(|conn| {
247            (
248                conn.start_subject_id,
249                conn.start_subject_index,
250                conn.end_subject_id,
251                conn.end_subject_index,
252            )
253        })
254        .unwrap_or((0, 0, 0, 0));
255    let (sx, sy) = (
256        xml_value(storage, line.start.x)?,
257        xml_value(storage, line.start.y)?,
258    );
259    let (ex, ey) = (
260        xml_value(storage, line.end.x)?,
261        xml_value(storage, line.end.y)?,
262    );
263    if is_connector {
264        let (ssr, ssi) = (
265            xml_value(storage, sub_start_ref)?,
266            xml_value(storage, sub_start_idx)?,
267        );
268        let (esr, esi) = (
269            xml_value(storage, sub_end_ref)?,
270            xml_value(storage, sub_end_idx)?,
271        );
272        empty_tag_with_storage(
273            w,
274            "hp:startPt",
275            &[
276                ("x", &sx),
277                ("y", &sy),
278                ("subjectIDRef", &ssr),
279                ("subjectIdx", &ssi),
280            ],
281            storage,
282        )?;
283        empty_tag_with_storage(
284            w,
285            "hp:endPt",
286            &[
287                ("x", &ex),
288                ("y", &ey),
289                ("subjectIDRef", &esr),
290                ("subjectIdx", &esi),
291            ],
292            storage,
293        )?;
294    } else {
295        empty_tag_with_storage(w, "hc:startPt", &[("x", &sx), ("y", &sy)], storage)?;
296        empty_tag_with_storage(w, "hc:endPt", &[("x", &ex), ("y", &ey)], storage)?;
297    }
298
299    // connectLine 제어점 (꺾인/곡선 커넥터의 경로).
300    if let Some(conn) = &line.connector {
301        if !conn.control_points.is_empty() {
302            start_tag_with_storage(w, "hp:controlPoints", storage)?;
303            for p in &conn.control_points {
304                let (px, py, pt) = (
305                    xml_value(storage, p.x)?,
306                    xml_value(storage, p.y)?,
307                    xml_value(storage, p.point_type)?,
308                );
309                empty_tag_with_storage(
310                    w,
311                    "hp:point",
312                    &[("x", &px), ("y", &py), ("type", &pt)],
313                    storage,
314                )?;
315            }
316            end_tag_with_storage(w, "hp:controlPoints", storage)?;
317        }
318    }
319
320    write_sz_with_storage(w, c, storage)?;
321    write_pos_with_storage(w, c, storage)?;
322    write_out_margin_with_storage(w, c, storage)?;
323    // 캡션 (#1403) — OWPML AbstractShapeObjectType 순서: outMargin 뒤
324    if let Some(cap) = &line.drawing.caption {
325        write_caption_with_storage(w, cap, ctx, storage)?;
326    }
327    // [#1588] 도형 설명 — caption 뒤 (write_rect/container 와 동형).
328    write_shape_comment_with_storage(w, c, storage)?;
329
330    end_tag_with_storage(w, tag, storage)?;
331    Ok(())
332}
333
334// =====================================================================
335// <hp:container> — 묶음 개체 (GroupShape). Stage 5 뼈대만.
336// =====================================================================
337
338/// `<hp:container>` 뼈대 — 내부 자식 도형 루프는 dispatcher에서 처리.
339///
340/// 한컴 실측(hwpx-h-01) 컨테이너 직계 순서:
341/// offset → orgSz → curSz → flip → rotationInfo → renderingInfo → [자식 도형들]
342/// → sz → pos → outMargin → shapeComment.
343/// 그룹 자신의 shape_attr(orgSz/curSz/offset/renderingInfo)이 누락되면 렌더러가
344/// 그룹 스케일·자식 기준 좌표를 계산하지 못해 자식이 그룹 원점에 고유 크기로 붕괴한다.
345pub fn write_container_open<W: Write>(
346    w: &mut Writer<W>,
347    common: &CommonObjAttr,
348    sa: &ShapeComponentAttr,
349) -> Result<(), SerializeError> {
350    write_container_open_with_storage(w, common, sa, &crate::storage::Unbounded)
351}
352
353pub(super) fn write_container_open_with_storage<W: Write, S: crate::storage::Storage>(
354    w: &mut Writer<W>,
355    common: &CommonObjAttr,
356    sa: &ShapeComponentAttr,
357    storage: &S,
358) -> Result<(), SerializeError>
359where
360    S::Error: std::fmt::Display,
361{
362    let id_str = xml_value(storage, common.instance_id)?;
363    let z_order = xml_value(storage, common.z_order)?;
364    let tw = text_wrap_str(common.text_wrap);
365    let tf = text_flow_str(common.text_flow);
366    // [#5716] groupLevel 은 IR(shape_attr.group_level)을 보존한다. 종전 "0" 하드코딩은
367    // 다른 그룹의 멤버인 컨테이너의 중첩 레벨이 저장 시 전부 0 으로 유실됐다
368    // (리프 도형 경로는 #2746 에서 이미 보존 — 컨테이너 자신만 누락).
369    let group_level = xml_value(storage, sa.group_level)?;
370
371    start_tag_attrs_with_storage(
372        w,
373        "hp:container",
374        &[
375            ("id", &id_str),
376            ("zOrder", &z_order),
377            ("numberingType", numbering_type_str(common.numbering_type)),
378            ("textWrap", tw),
379            ("textFlow", tf),
380            // [#2840] lock(개체 잠금) — IR 보존 값 방출.
381            ("lock", bool01(common.locked)),
382            ("dropcapstyle", drop_cap_style_str(common.drop_cap_style)),
383            ("href", ""),
384            ("groupLevel", &group_level),
385            ("instid", &id_str),
386        ],
387        storage,
388    )?;
389
390    // 그룹 자신의 좌표계 — 자식 도형 앞에 방출 (write_rect 패턴과 동일 순서).
391    write_offset_with_storage(w, sa, storage)?;
392    write_org_sz_with_storage(w, sa, storage)?;
393    write_cur_sz_with_storage(w, sa, storage)?;
394    write_flip_with_storage(w, sa, storage)?;
395    write_rotation_info_with_storage(w, sa, storage)?;
396    write_rendering_info_with_storage(w, sa, storage)?;
397
398    Ok(())
399}
400
401/// `<hp:container>` 닫기 — 자식 도형 뒤에 sz → pos → outMargin → caption(#1403) →
402/// shapeComment(#1392) 순으로 방출 (한컴 실측 hwpx-h-01/aift 순서).
403pub fn write_container_close<W: Write>(
404    w: &mut Writer<W>,
405    caption: Option<&crate::model::shape::Caption>,
406    common: &CommonObjAttr,
407    ctx: &mut SerializeContext,
408) -> Result<(), SerializeError> {
409    write_container_close_with_storage(w, caption, common, ctx, &crate::storage::Unbounded)
410}
411
412pub(super) fn write_container_close_with_storage<W: Write, S: crate::storage::Storage>(
413    w: &mut Writer<W>,
414    caption: Option<&crate::model::shape::Caption>,
415    common: &CommonObjAttr,
416    ctx: &mut SerializeContext,
417    storage: &S,
418) -> Result<(), SerializeError>
419where
420    S::Error: std::fmt::Display,
421{
422    write_sz_with_storage(w, common, storage)?;
423    write_pos_with_storage(w, common, storage)?;
424    write_out_margin_with_storage(w, common, storage)?;
425    if let Some(cap) = caption {
426        write_caption_with_storage(w, cap, ctx, storage)?;
427    }
428    // 설명 (#1392) — caption 직후
429    write_shape_comment_with_storage(w, common, storage)?;
430    end_tag_with_storage(w, "hp:container", storage)
431}
432
433// =====================================================================
434// <hp:ole> — OLE 개체 (차트 등 포함)
435//
436// 종전 직렬화는 OLE 를 legacy 공용 경로(sz/pos/outMargin 만)로 내보내 binaryItemIDRef·
437// extent·shape_attr 를 빠뜨렸다. 그 결과 라운드트립에서 OLE 데이터 참조가 소실되어
438// 렌더가 placeholder 로 강등됐다(143E: RawSvg→Placeholder). picture 패턴으로 복원한다.
439// =====================================================================
440pub(crate) fn write_ole<W: Write>(
441    w: &mut Writer<W>,
442    ole: &OleShape,
443    ctx: &mut SerializeContext,
444) -> Result<(), SerializeError> {
445    write_ole_with_storage(w, ole, ctx, &crate::storage::Unbounded)
446}
447
448pub(super) fn write_ole_with_storage<W: Write, S: crate::storage::Storage>(
449    w: &mut Writer<W>,
450    ole: &OleShape,
451    ctx: &mut SerializeContext,
452    storage: &S,
453) -> Result<(), SerializeError>
454where
455    S::Error: std::fmt::Display,
456{
457    let c = &ole.common;
458    // [#4669] 원본 `id` 는 `instid` 와 별개 값이다 — 파서가 보존한 원문을 되쓰고,
459    // HWP5 출신(None)은 종전대로 instance_id 를 겸용한다.
460    let id_str = xml_value(storage, ole.hwpx_ole_id.unwrap_or(c.instance_id))?;
461    let instid_str = xml_value(storage, c.instance_id)?;
462    let z_order = xml_value(storage, c.z_order)?;
463    let tw = text_wrap_str(c.text_wrap);
464    let tf = text_flow_str(c.text_flow);
465    // owned 으로 변환해 ctx 불변 borrow 를 즉시 해제(이후 write_caption 의 &mut 사용).
466    // [버그] ole.bin_data_id 는 HWP5 바이너리 상 4바이트(u32) 필드지만 BinData 테이블은
467    // u16 ID 로 관리된다. 종전에는 `as u16` 로 상위 비트를 자른 뒤 조회해, 65536 이상인
468    // (잘못된/조작된) 값이 하위 16비트가 같은 다른 BinData 항목을 가리키는 오참조를
469    // 일으킬 수 있었다. try_from 으로 범위를 벗어나면 미등록으로 취급해 빈 참조로
470    // 남긴다(기존 "미등록 id → 빈 문자열" 처리와 동일한 안전한 폴백).
471    let bidref = xml_value(
472        storage,
473        u16::try_from(ole.bin_data_id)
474            .ok()
475            .and_then(|id| ctx.resolve_bin_id(id))
476            .unwrap_or(""),
477    )?;
478    let draw_aspect = match ole.drawing_aspect {
479        OleDrawingAspect::Icon => "ICON",
480        OleDrawingAspect::Thumbnail => "THUMBNAIL",
481        OleDrawingAspect::DocPrint => "DOCPRINT",
482        OleDrawingAspect::Content => "CONTENT",
483    };
484    // [#2931] 개체 잠금(lock) — IR(common.locked)을 보존(종전 "0" 하드코딩 제거).
485    let lock = if c.locked { "1" } else { "0" };
486    // [#5716] groupLevel — 컨테이너와 동형. IR(drawing.shape_attr.group_level)을
487    // 보존한다(종전 "0" 하드코딩은 그룹 내 OLE 의 중첩 레벨을 저장 시 유실).
488    let group_level = xml_value(storage, ole.drawing.shape_attr.group_level)?;
489
490    start_tag_attrs_with_storage(
491        w,
492        "hp:ole",
493        &[
494            ("id", &id_str),
495            ("zOrder", &z_order),
496            ("numberingType", numbering_type_str(c.numbering_type)),
497            ("textWrap", tw),
498            ("textFlow", tf),
499            // [#2840] lock(개체 잠금) — IR 보존 값 방출.
500            ("lock", bool01(c.locked)),
501            ("dropcapstyle", drop_cap_style_str(c.drop_cap_style)),
502            ("href", ""),
503            ("groupLevel", &group_level),
504            ("instid", &instid_str),
505            ("objectType", "UNKNOWN"),
506            ("binaryItemIDRef", &bidref),
507            ("hasMoniker", "0"),
508            ("drawAspect", draw_aspect),
509            ("eqBaseLine", "0"),
510        ],
511        storage,
512    )?;
513
514    // shape_attr 블록 (offset/orgSz/curSz/flip/rotationInfo/renderingInfo)
515    write_shape_component_block_with_storage(w, &ole.drawing.shape_attr, storage)?;
516    // 개체 영역
517    let ex = xml_value(storage, ole.extent_x)?;
518    let ey = xml_value(storage, ole.extent_y)?;
519    empty_tag_with_storage(w, "hc:extent", &[("x", &ex), ("y", &ey)], storage)?;
520    write_line_shape_with_storage(w, &ole.drawing.border_line, storage)?;
521    write_sz_with_storage(w, c, storage)?;
522    write_pos_with_storage(w, c, storage)?;
523    write_out_margin_with_storage(w, c, storage)?;
524    if let Some(cap) = &ole.caption {
525        write_caption_with_storage(w, cap, ctx, storage)?;
526    }
527    write_shape_comment_with_storage(w, c, storage)?;
528
529    end_tag_with_storage(w, "hp:ole", storage)?;
530    Ok(())
531}
532
533// =====================================================================
534// <hp:chart> — HWPX OOXML 차트 원형 재방출 (#3546)
535// 파서는 hp:chart 를 OLE 모델(bin_data_id=60000+N)로 변환한다. 종전 저장은
536// 이를 일반 OLE 로 방출해 hp:chart → hp:ole 치환·Chart/chartN.xml →
537// BinData/image6000N.ooxml_chart 이동이 일어났고, 한컴오피스가 차트 XML 을
538// OLE 복합문서로 해석했다. chart_id_ref 표식이 있으면 원형 구조로 되쓴다.
539// =====================================================================
540pub(crate) fn write_ole_or_chart<W: Write>(
541    w: &mut Writer<W>,
542    ole: &OleShape,
543    ctx: &mut SerializeContext,
544) -> Result<(), SerializeError> {
545    write_ole_or_chart_with_storage(w, ole, ctx, &crate::storage::Unbounded)
546}
547
548pub(super) fn write_ole_or_chart_with_storage<W: Write, S: crate::storage::Storage>(
549    w: &mut Writer<W>,
550    ole: &OleShape,
551    ctx: &mut SerializeContext,
552    storage: &S,
553) -> Result<(), SerializeError>
554where
555    S::Error: std::fmt::Display,
556{
557    match ole.chart_id_ref.as_deref() {
558        Some(chart_id_ref) => write_chart_switch_with_storage(w, ole, chart_id_ref, ctx, storage),
559        None => write_ole_with_storage(w, ole, ctx, storage),
560    }
561}
562
563/// hp:chart 재방출 — 원본이 <hp:switch> 래핑(fallback OLE 보유)이었으면 같은
564/// 구조로, bare <hp:chart> 였으면 같은 형태로 되쓴다.
565const OOXML_CHART_REQUIRED_NS: &str = "http://www.hancom.co.kr/hwpml/2016/ooxmlchart";
566
567fn write_chart_switch<W: Write>(
568    w: &mut Writer<W>,
569    ole: &OleShape,
570    chart_id_ref: &str,
571    ctx: &mut SerializeContext,
572) -> Result<(), SerializeError> {
573    write_chart_switch_with_storage(w, ole, chart_id_ref, ctx, &crate::storage::Unbounded)
574}
575
576pub(super) fn write_chart_switch_with_storage<W: Write, S: crate::storage::Storage>(
577    w: &mut Writer<W>,
578    ole: &OleShape,
579    chart_id_ref: &str,
580    ctx: &mut SerializeContext,
581    storage: &S,
582) -> Result<(), SerializeError>
583where
584    S::Error: std::fmt::Display,
585{
586    match &ole.chart_switch_fallback {
587        Some(fallback) => {
588            start_tag_with_storage(w, "hp:switch", storage)?;
589            start_tag_attrs_with_storage(
590                w,
591                "hp:case",
592                &[("hp:required-namespace", OOXML_CHART_REQUIRED_NS)],
593                storage,
594            )?;
595            write_chart_element_with_storage(w, ole, chart_id_ref, ctx, storage)?;
596            end_tag_with_storage(w, "hp:case", storage)?;
597            start_tag_with_storage(w, "hp:default", storage)?;
598            write_ole_with_storage(w, fallback, ctx, storage)?;
599            end_tag_with_storage(w, "hp:default", storage)?;
600            end_tag_with_storage(w, "hp:switch", storage)?;
601            Ok(())
602        }
603        None => write_chart_element_with_storage(w, ole, chart_id_ref, ctx, storage),
604    }
605}
606
607fn write_chart_element<W: Write>(
608    w: &mut Writer<W>,
609    ole: &OleShape,
610    chart_id_ref: &str,
611    ctx: &mut SerializeContext,
612) -> Result<(), SerializeError> {
613    write_chart_element_with_storage(w, ole, chart_id_ref, ctx, &crate::storage::Unbounded)
614}
615
616pub(super) fn write_chart_element_with_storage<W: Write, S: crate::storage::Storage>(
617    w: &mut Writer<W>,
618    ole: &OleShape,
619    chart_id_ref: &str,
620    ctx: &mut SerializeContext,
621    storage: &S,
622) -> Result<(), SerializeError>
623where
624    S::Error: std::fmt::Display,
625{
626    let c = &ole.common;
627    let id_str = xml_value(storage, c.instance_id)?;
628    let z_order = xml_value(storage, c.z_order)?;
629    start_tag_attrs_with_storage(
630        w,
631        "hp:chart",
632        &[
633            ("id", &id_str),
634            ("zOrder", &z_order),
635            ("numberingType", numbering_type_str(c.numbering_type)),
636            ("textWrap", text_wrap_str(c.text_wrap)),
637            ("textFlow", text_flow_str(c.text_flow)),
638            ("lock", bool01(c.locked)),
639            ("dropcapstyle", drop_cap_style_str(c.drop_cap_style)),
640            ("chartIDRef", chart_id_ref),
641        ],
642        storage,
643    )?;
644    write_sz_with_storage(w, c, storage)?;
645    write_pos_with_storage(w, c, storage)?;
646    write_out_margin_with_storage(w, c, storage)?;
647    // [#4319] 캡션 — 종전엔 hp:chart 재방출 경로에만 write_caption 호출이 없어
648    // 파서를 고쳐도(ole.caption 정상 적재) 저장 시 다시 유실됐다(hp:ole 방출
649    // 경로인 write_ole 는 이미 캡션을 쓴다 — 그쪽과 동형으로 맞춘다).
650    if let Some(cap) = &ole.caption {
651        write_caption_with_storage(w, cap, ctx, storage)?;
652    }
653    end_tag_with_storage(w, "hp:chart", storage)?;
654    Ok(())
655}
656
657// =====================================================================
658// <hp:drawText> — 글상자 내부 텍스트
659// =====================================================================
660
661/// `<hp:drawText>` 직렬화 — TextBox의 paragraphs를 subList로 출력 (#1379 3단계).
662///
663/// - 문단은 본문·셀과 동일한 `render_paragraph_parts` 공유 경로 (컨트롤 슬롯 +
664///   run 분할 + lineseg IR 보존/fallback)
665/// - `textDirection` VERTICAL/VERTICALALL 구분은 `TextBox.vertical_all` 로 보존
666/// - `textMargin` 은 subList **뒤** (한컴 원본 순서, footnote-tbox-01 실측),
667///   명시적 여백은 0도 보존한다. 기존 생성기의 부재/0 기본값은 미방출한다.
668pub fn write_draw_text<W: Write>(
669    w: &mut Writer<W>,
670    tb: &TextBox,
671    ctx: &mut SerializeContext,
672) -> Result<(), SerializeError> {
673    write_draw_text_with_storage(w, tb, ctx, &crate::storage::Unbounded)
674}
675
676pub(super) fn write_draw_text_with_storage<W: Write, S: crate::storage::Storage>(
677    w: &mut Writer<W>,
678    tb: &TextBox,
679    ctx: &mut SerializeContext,
680    storage: &S,
681) -> Result<(), SerializeError>
682where
683    S::Error: std::fmt::Display,
684{
685    let depth = ctx.sub_list_depth;
686    let result = (|| -> Result<(), SerializeError> {
687        let lw = xml_value(storage, tb.max_width)?;
688        start_tag_attrs_with_storage(
689            w,
690            "hp:drawText",
691            &[("lastWidth", &lw), ("name", ""), ("editable", "0")],
692            storage,
693        )?;
694
695        // textDirection: list_attr bit 0~2 (1=세로쓰기), vertical_all 로 ALL 구분.
696        let text_direction = if tb.list_attr & 0x07 == 1 {
697            if tb.vertical_all {
698                "VERTICALALL"
699            } else {
700                "VERTICAL"
701            }
702        } else {
703            "HORIZONTAL"
704        };
705        let vert_align = match tb.vertical_align {
706            crate::model::table::VerticalAlign::Center => "CENTER",
707            crate::model::table::VerticalAlign::Bottom => "BOTTOM",
708            crate::model::table::VerticalAlign::Top => "TOP",
709        };
710
711        start_tag_attrs_with_storage(
712            w,
713            "hp:subList",
714            &[
715                ("id", ""),
716                ("textDirection", text_direction),
717                ("lineWrap", "BREAK"),
718                ("vertAlign", vert_align),
719                ("linkListIDRef", "0"),
720                ("linkListNextIDRef", "0"),
721                ("textWidth", "0"),
722                ("textHeight", "0"),
723                ("hasTextRef", "0"),
724                ("hasNumRef", "0"),
725            ],
726            storage,
727        )?;
728
729        // sub_list_depth: 글상자 경로 한정 colPr 인라인 방출 스코프 (#1379 3단계).
730        ctx.sub_list_depth += 1;
731        let mut vert_cursor: u32 = 0;
732        for para in tb.paragraphs.iter() {
733            ctx.para_shape_ids.reference(para.para_shape_id);
734            let sid = ctx.effective_style_id(para.style_id);
735            ctx.style_ids.reference(sid as u16);
736
737            let (runs, linesegs, advance) =
738                render_paragraph_parts_with_storage(para, vert_cursor, ctx, storage)?;
739            vert_cursor = advance;
740            let pid = ctx.next_para_id();
741            let mut p_xml = render_hp_p_open_with_storage(para, pid, sid, storage)?;
742            storage.push_str(&mut p_xml, &runs).map_err(xml_error)?;
743            storage.push_str(&mut p_xml, &linesegs).map_err(xml_error)?;
744            storage.push_str(&mut p_xml, "</hp:p>").map_err(xml_error)?;
745            w.get_mut()
746                .write_all(p_xml.as_bytes())
747                .map_err(|e| SerializeError::XmlError(e.to_string()))?;
748        }
749        ctx.sub_list_depth -= 1;
750
751        end_tag_with_storage(w, "hp:subList", storage)?;
752
753        if tb.text_margin_explicit
754            || tb.margin_left != 0
755            || tb.margin_right != 0
756            || tb.margin_top != 0
757            || tb.margin_bottom != 0
758        {
759            let ml = xml_value(storage, tb.margin_left)?;
760            let mr = xml_value(storage, tb.margin_right)?;
761            let mt = xml_value(storage, tb.margin_top)?;
762            let mb = xml_value(storage, tb.margin_bottom)?;
763            empty_tag_with_storage(
764                w,
765                "hp:textMargin",
766                &[("left", &ml), ("right", &mr), ("top", &mt), ("bottom", &mb)],
767                storage,
768            )?;
769        }
770
771        end_tag_with_storage(w, "hp:drawText", storage)?;
772        Ok(())
773    })();
774    ctx.sub_list_depth = depth;
775    result
776}
777
778// =====================================================================
779// ShapeComponentAttr 하위 요소 (offset / orgSz / curSz / flip / rotationInfo / renderingInfo)
780// =====================================================================
781
782/// AbstractShapeComponentType 의 좌표계 블록을 한컴 순서로 방출한다:
783/// offset → orgSz → curSz → flip → rotationInfo → renderingInfo.
784/// 누락 시 회전/뒤집힘·그룹 내 좌표가 소실되어 렌더가 어긋난다(ellipse/arc/polygon/curve 공용).
785pub(crate) fn write_shape_component_block<W: Write>(
786    w: &mut Writer<W>,
787    sa: &ShapeComponentAttr,
788) -> Result<(), SerializeError> {
789    write_shape_component_block_with_storage(w, sa, &crate::storage::Unbounded)
790}
791
792pub(super) fn write_shape_component_block_with_storage<W: Write, S: crate::storage::Storage>(
793    w: &mut Writer<W>,
794    sa: &ShapeComponentAttr,
795    storage: &S,
796) -> Result<(), SerializeError>
797where
798    S::Error: std::fmt::Display,
799{
800    write_offset_with_storage(w, sa, storage)?;
801    write_org_sz_with_storage(w, sa, storage)?;
802    write_cur_sz_with_storage(w, sa, storage)?;
803    write_flip_with_storage(w, sa, storage)?;
804    write_rotation_info_with_storage(w, sa, storage)?;
805    write_rendering_info_with_storage(w, sa, storage)?;
806    Ok(())
807}
808
809pub(super) fn write_offset<W: Write>(
810    w: &mut Writer<W>,
811    sa: &ShapeComponentAttr,
812) -> Result<(), SerializeError> {
813    write_offset_with_storage(w, sa, &crate::storage::Unbounded)
814}
815
816pub(super) fn write_offset_with_storage<W: Write, S: crate::storage::Storage>(
817    w: &mut Writer<W>,
818    sa: &ShapeComponentAttr,
819    storage: &S,
820) -> Result<(), SerializeError>
821where
822    S::Error: std::fmt::Display,
823{
824    // [#3544] hp:offset x/y 는 OWPML XSD 상 unsigned. 한컴 산출물은 음수 오프셋을
825    // u32 wraparound 십진수로 기록하고(예: -2429 → "4294964867"), 파서도
826    // `parse_u32 as i32` 로 같은 관례를 복호한다. IR 은 레이아웃 계산을 위해
827    // signed 가 정당하므로 값은 두고, XML 경계에서만 부호화를 복원한다 —
828    // signed 그대로 문자열화하면 `y="-2"` 류 스키마 위반이 된다.
829    let x = xml_value(storage, sa.offset_x as u32)?;
830    let y = xml_value(storage, sa.offset_y as u32)?;
831    empty_tag_with_storage(w, "hp:offset", &[("x", &x), ("y", &y)], storage)
832}
833
834fn write_org_sz<W: Write>(
835    w: &mut Writer<W>,
836    sa: &ShapeComponentAttr,
837) -> Result<(), SerializeError> {
838    write_org_sz_with_storage(w, sa, &crate::storage::Unbounded)
839}
840
841pub(super) fn write_org_sz_with_storage<W: Write, S: crate::storage::Storage>(
842    w: &mut Writer<W>,
843    sa: &ShapeComponentAttr,
844    storage: &S,
845) -> Result<(), SerializeError>
846where
847    S::Error: std::fmt::Display,
848{
849    // [#4669] HWP5 저장을 위해 유효 extent로 materialize했더라도 HWPX 원문의
850    // `orgSz=0` sentinel은 그대로 되돌린다.
851    let width = xml_value(
852        storage,
853        if sa.original_width_was_zero {
854            0
855        } else {
856            sa.original_width
857        },
858    )?;
859    let height = xml_value(
860        storage,
861        if sa.original_height_was_zero {
862            0
863        } else {
864            sa.original_height
865        },
866    )?;
867    empty_tag_with_storage(
868        w,
869        "hp:orgSz",
870        &[("width", &width), ("height", &height)],
871        storage,
872    )
873}
874
875fn write_cur_sz<W: Write>(
876    w: &mut Writer<W>,
877    sa: &ShapeComponentAttr,
878) -> Result<(), SerializeError> {
879    write_cur_sz_with_storage(w, sa, &crate::storage::Unbounded)
880}
881
882pub(super) fn write_cur_sz_with_storage<W: Write, S: crate::storage::Storage>(
883    w: &mut Writer<W>,
884    sa: &ShapeComponentAttr,
885    storage: &S,
886) -> Result<(), SerializeError>
887where
888    S::Error: std::fmt::Display,
889{
890    // [#2017] 파싱 시 orgSz로 materialize된 dimension 은 원본 `0` sentinel 로 복원.
891    let width = xml_value(
892        storage,
893        if sa.current_width_was_zero {
894            0
895        } else {
896            sa.current_width
897        },
898    )?;
899    let height = xml_value(
900        storage,
901        if sa.current_height_was_zero {
902            0
903        } else {
904            sa.current_height
905        },
906    )?;
907    empty_tag_with_storage(
908        w,
909        "hp:curSz",
910        &[("width", &width), ("height", &height)],
911        storage,
912    )
913}
914
915fn write_flip<W: Write>(w: &mut Writer<W>, sa: &ShapeComponentAttr) -> Result<(), SerializeError> {
916    write_flip_with_storage(w, sa, &crate::storage::Unbounded)
917}
918
919pub(super) fn write_flip_with_storage<W: Write, S: crate::storage::Storage>(
920    w: &mut Writer<W>,
921    sa: &ShapeComponentAttr,
922    storage: &S,
923) -> Result<(), SerializeError>
924where
925    S::Error: std::fmt::Display,
926{
927    empty_tag_with_storage(
928        w,
929        "hp:flip",
930        &[
931            ("horizontal", bool01(sa.horz_flip)),
932            ("vertical", bool01(sa.vert_flip)),
933        ],
934        storage,
935    )
936}
937
938fn write_rotation_info<W: Write>(
939    w: &mut Writer<W>,
940    sa: &ShapeComponentAttr,
941) -> Result<(), SerializeError> {
942    write_rotation_info_with_storage(w, sa, &crate::storage::Unbounded)
943}
944
945pub(super) fn write_rotation_info_with_storage<W: Write, S: crate::storage::Storage>(
946    w: &mut Writer<W>,
947    sa: &ShapeComponentAttr,
948    storage: &S,
949) -> Result<(), SerializeError>
950where
951    S::Error: std::fmt::Display,
952{
953    let angle = xml_value(storage, sa.rotation_angle)?;
954    let cx = xml_value(storage, sa.rotation_center.x)?;
955    let cy = xml_value(storage, sa.rotation_center.y)?;
956    empty_tag_with_storage(
957        w,
958        "hp:rotationInfo",
959        &[
960            ("angle", &angle),
961            ("centerX", &cx),
962            ("centerY", &cy),
963            ("rotateimage", bool01(sa.rotate_image)),
964        ],
965        storage,
966    )
967}
968
969/// `<hp:renderingInfo>` — `raw_rendering` (cnt u16 LE + trans 6×f64 + cnt×(sca, rot))
970/// 를 디코드해 행렬을 재구성한다 (`parse_rendering_info` 의 역). raw 비정합/빈 경우
971/// HWP와 같은 편집 변환을 생성한다. pic 자식도 공유 (그룹 내 자식 transMatrix 보존).
972pub(crate) fn write_rendering_info<W: Write>(
973    w: &mut Writer<W>,
974    sa: &ShapeComponentAttr,
975) -> Result<(), SerializeError> {
976    write_rendering_info_with_storage(w, sa, &crate::storage::Unbounded)
977}
978
979pub(super) fn write_rendering_info_with_storage<W: Write, S: crate::storage::Storage>(
980    w: &mut Writer<W>,
981    sa: &ShapeComponentAttr,
982    storage: &S,
983) -> Result<(), SerializeError>
984where
985    S::Error: std::fmt::Display,
986{
987    const IDENTITY: [f64; 6] = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0];
988    let rendering =
989        crate::serializer::control::try_shape_rendering_bytes(sa, storage).map_err(xml_error)?;
990    let (trans, pairs) = match decode_raw_rendering_with_storage(&rendering, storage)? {
991        Some(value) => value,
992        None => {
993            let mut pairs = storage.vec(1).map_err(xml_error)?;
994            storage
995                .push(&mut pairs, (IDENTITY, IDENTITY))
996                .map_err(xml_error)?;
997            (IDENTITY, pairs)
998        }
999    };
1000
1001    start_tag_with_storage(w, "hp:renderingInfo", storage)?;
1002    write_matrix_with_storage(w, "hc:transMatrix", &trans, storage)?;
1003    for (sca, rot) in &pairs {
1004        write_matrix_with_storage(w, "hc:scaMatrix", sca, storage)?;
1005        write_matrix_with_storage(w, "hc:rotMatrix", rot, storage)?;
1006    }
1007    end_tag_with_storage(w, "hp:renderingInfo", storage)
1008}
1009
1010type RenderMatrices = ([f64; 6], Vec<([f64; 6], [f64; 6])>);
1011
1012fn decode_raw_rendering(raw: &[u8]) -> Option<RenderMatrices> {
1013    decode_raw_rendering_with_storage(raw, &crate::storage::Unbounded)
1014        .expect("unbounded XML writer")
1015}
1016
1017pub(super) fn decode_raw_rendering_with_storage<S: crate::storage::Storage>(
1018    raw: &[u8],
1019    storage: &S,
1020) -> Result<Option<RenderMatrices>, SerializeError>
1021where
1022    S::Error: std::fmt::Display,
1023{
1024    if raw.len() < 2 + 48 {
1025        return Ok(None);
1026    }
1027    let cnt = u16::from_le_bytes([raw[0], raw[1]]) as usize;
1028    if raw.len() < 2 + 48 + cnt * 96 {
1029        return Ok(None);
1030    }
1031    let read6 = |off: usize| -> [f64; 6] {
1032        let mut m = [0.0f64; 6];
1033        for (i, v) in m.iter_mut().enumerate() {
1034            let p = off + i * 8;
1035            *v = f64::from_le_bytes(raw[p..p + 8].try_into().unwrap());
1036        }
1037        m
1038    };
1039    let trans = read6(2);
1040    let mut pairs = storage.vec(cnt).map_err(xml_error)?;
1041    for k in 0..cnt {
1042        let base = 2 + 48 + k * 96;
1043        storage
1044            .push(&mut pairs, (read6(base), read6(base + 48)))
1045            .map_err(xml_error)?;
1046    }
1047    Ok(Some((trans, pairs)))
1048}
1049
1050/// 행렬 값 포맷: 정수는 정수 문자열, 비정수는 f32 정밀도 (파서가 f32 로 적재 —
1051/// 원본 "1.579917" 보존).
1052fn fmt_matrix_val(v: f64) -> String {
1053    fmt_matrix_val_with_storage(v, &crate::storage::Unbounded).expect("unbounded XML writer")
1054}
1055
1056pub(super) fn fmt_matrix_val_with_storage<S: crate::storage::Storage>(
1057    v: f64,
1058    storage: &S,
1059) -> Result<String, SerializeError>
1060where
1061    S::Error: std::fmt::Display,
1062{
1063    Ok(if v.fract() == 0.0 {
1064        xml_value(storage, format_args!("{}", v as i64))?
1065    } else {
1066        xml_value(storage, format_args!("{}", v as f32))?
1067    })
1068}
1069
1070fn write_matrix<W: Write>(
1071    w: &mut Writer<W>,
1072    name: &str,
1073    m: &[f64; 6],
1074) -> Result<(), SerializeError> {
1075    write_matrix_with_storage(w, name, m, &crate::storage::Unbounded)
1076}
1077
1078pub(super) fn write_matrix_with_storage<W: Write, S: crate::storage::Storage>(
1079    w: &mut Writer<W>,
1080    name: &str,
1081    m: &[f64; 6],
1082    storage: &S,
1083) -> Result<(), SerializeError>
1084where
1085    S::Error: std::fmt::Display,
1086{
1087    let mut vals = storage.vec(6).map_err(xml_error)?;
1088    for v in m {
1089        storage
1090            .push(&mut vals, fmt_matrix_val_with_storage(*v, storage)?)
1091            .map_err(xml_error)?;
1092    }
1093    empty_tag_with_storage(
1094        w,
1095        name,
1096        &[
1097            ("e1", &vals[0]),
1098            ("e2", &vals[1]),
1099            ("e3", &vals[2]),
1100            ("e4", &vals[3]),
1101            ("e5", &vals[4]),
1102            ("e6", &vals[5]),
1103        ],
1104        storage,
1105    )
1106}
1107
1108// =====================================================================
1109// lineShape / fillBrush / shadow
1110// =====================================================================
1111
1112/// `<hp:lineShape>` — `parse_line_shape_attr` 의 역매핑.
1113/// alpha 는 파서 미적재 → "0" 고정 방출. headStyle/tailStyle 은 bit 10~21 에서 복원한다(#2956).
1114pub(crate) fn write_line_shape<W: Write>(
1115    w: &mut Writer<W>,
1116    bl: &ShapeBorderLine,
1117) -> Result<(), SerializeError> {
1118    write_line_shape_with_storage(w, bl, &crate::storage::Unbounded)
1119}
1120
1121pub(super) fn write_line_shape_with_storage<W: Write, S: crate::storage::Storage>(
1122    w: &mut Writer<W>,
1123    bl: &ShapeBorderLine,
1124    storage: &S,
1125) -> Result<(), SerializeError>
1126where
1127    S::Error: std::fmt::Display,
1128{
1129    let color = color_to_hex_with_storage(bl.color, storage)?;
1130    let width = xml_value(storage, bl.width)?;
1131    // style 은 attr 하위 6비트. 정본 코드(0=NONE/1=SOLID/2=파선…)는 표 borderFill 의
1132    // border_line_type_from_code 및 HWP5 doc_info 와 동일. 종전에는 0 이 _ => SOLID 로
1133    // 떨어져 "선 없음" 도형 외곽선이 라운드트립에서 사각형 박스로 살아났다(#1531).
1134    let style = match bl.attr & 0x3F {
1135        0 => "NONE",
1136        1 => "SOLID",
1137        2 => "DOT",
1138        3 => "DASH",
1139        4 => "DASH_DOT",
1140        5 => "DASH_DOT_DOT",
1141        6 => "LONG_DASH",
1142        7 => "CIRCLE",
1143        8 => "DOUBLE_SLIM",
1144        9 => "SLIM_THICK",
1145        10 => "THICK_SLIM",
1146        11 => "SLIM_THICK_SLIM",
1147        _ => "SOLID",
1148    };
1149    let end_cap = match (bl.attr >> 6) & 0x0F {
1150        1 => "FLAT",
1151        2 => "SQUARE",
1152        _ => "ROUND",
1153    };
1154    let head_fill_b = bl.attr & 0x8000_0000 != 0;
1155    let tail_fill_b = bl.attr & 0x4000_0000 != 0;
1156    let headfill = bool01(head_fill_b);
1157    let tailfill = bool01(tail_fill_b);
1158    let head_style = arrow_style_str((bl.attr >> 10) & 0x3F, head_fill_b);
1159    let tail_style = arrow_style_str((bl.attr >> 16) & 0x3F, tail_fill_b);
1160    let head_sz = arrow_size_str((bl.attr >> 22) & 0x0F);
1161    let tail_sz = arrow_size_str((bl.attr >> 26) & 0x0F);
1162    let outline = match bl.outline_style {
1163        1 => "OUTER",
1164        2 => "INNER",
1165        _ => "NORMAL",
1166    };
1167    empty_tag_with_storage(
1168        w,
1169        "hp:lineShape",
1170        &[
1171            ("color", &color),
1172            ("width", &width),
1173            ("style", style),
1174            ("endCap", end_cap),
1175            ("headStyle", head_style),
1176            ("tailStyle", tail_style),
1177            ("headfill", headfill),
1178            ("tailfill", tailfill),
1179            ("headSz", head_sz),
1180            ("tailSz", tail_sz),
1181            ("outlineStyle", outline),
1182            ("alpha", "0"),
1183        ],
1184        storage,
1185    )
1186}
1187
1188/// HWP5 화살표 모양 값(hwplib LineArrowShape, `arrow_type_from_hwp` 참조) →
1189/// OWPML Core `ArrowType` 역매핑. fill 은 채움 여부(bit 30/31)다.
1190fn arrow_style_str(v: u32, fill: bool) -> &'static str {
1191    match v {
1192        1 => "ARROW",
1193        2 => "SPEAR",
1194        3 => "CONCAVE_ARROW",
1195        4 if fill => "FILLED_DIAMOND",
1196        4 => "EMPTY_DIAMOND",
1197        5 if fill => "FILLED_CIRCLE",
1198        5 => "EMPTY_CIRCLE",
1199        6 if fill => "FILLED_BOX",
1200        6 => "EMPTY_BOX",
1201        _ => "NORMAL",
1202    }
1203}
1204
1205/// `parse_line_shape_attr::arrow_size` 의 역매핑 (0~8).
1206fn arrow_size_str(v: u32) -> &'static str {
1207    // OWPML Core 스키마 hc:ArrowSize 정본 리터럴은 *_LARGE (Core XML schema.xml:407).
1208    // "*_BIG" 는 스펙에 없는 비실재 토큰 — 파서는 하위호환을 위해 관용 수용하지만
1209    // (src/parser/hwpx/section.rs 의 parse_line_shape_attr), 직렬화는 정본만 방출한다.
1210    match v {
1211        1 => "SMALL_MEDIUM",
1212        2 => "SMALL_LARGE",
1213        3 => "MEDIUM_SMALL",
1214        4 => "MEDIUM_MEDIUM",
1215        5 => "MEDIUM_LARGE",
1216        6 => "LARGE_SMALL",
1217        7 => "LARGE_MEDIUM",
1218        8 => "LARGE_LARGE",
1219        _ => "SMALL_SMALL",
1220    }
1221}
1222
1223/// `<hc:fillBrush><hc:winBrush .../></hc:fillBrush>` 를 방출하는 단일 소유 함수.
1224/// FillType::Solid 경로와 보존된 빈 채우기(FillType::None + solid 존재) 경로가
1225/// 동일한 직렬화를 쓰도록 한 곳에 모은다(균일 규칙).
1226pub(crate) fn write_fill_brush<W: Write>(
1227    w: &mut Writer<W>,
1228    fill: &Fill,
1229    ctx: &SerializeContext,
1230) -> Result<(), SerializeError> {
1231    write_fill_brush_with_storage(w, fill, ctx, &crate::storage::Unbounded)
1232}
1233
1234fn write_win_brush<W: Write, S: crate::storage::Storage>(
1235    w: &mut Writer<W>,
1236    solid: &SolidFill,
1237    alpha: u8,
1238    storage: &S,
1239) -> Result<(), SerializeError>
1240where
1241    S::Error: std::fmt::Display,
1242{
1243    use super::utils::{
1244        empty_tag_with_storage as empty_tag, end_tag_with_storage as end_tag,
1245        start_tag_attrs_with_storage as start_tag_attrs, start_tag_with_storage as start_tag,
1246        xml_value,
1247    };
1248    let face = color_to_hex_with_storage(solid.background_color, storage)?;
1249    let hatch = color_to_hex_with_storage(solid.pattern_color, storage)?;
1250    let alpha = fill_alpha_str_with_storage(alpha, storage)?;
1251    start_tag(w, "hc:fillBrush", storage)?;
1252    if let Some(style) = solid.hatch() {
1253        empty_tag(
1254            w,
1255            "hc:winBrush",
1256            &[
1257                ("faceColor", &face),
1258                ("hatchColor", &hatch),
1259                ("hatchStyle", style.owpml_name()),
1260                ("alpha", &alpha),
1261            ],
1262            storage,
1263        )?;
1264    } else {
1265        empty_tag(
1266            w,
1267            "hc:winBrush",
1268            &[
1269                ("faceColor", &face),
1270                ("hatchColor", &hatch),
1271                ("alpha", &alpha),
1272            ],
1273            storage,
1274        )?;
1275    }
1276    end_tag(w, "hc:fillBrush", storage)
1277}
1278
1279/// `<hc:fillBrush>` — `parse_shape_fill_brush` 의 역매핑.
1280/// `FillType::None` 은 원본에 fillBrush 부재로 간주하되, 파서가 보존한 solid 가
1281/// 있으면(빈 winBrush) 복원한다.
1282///
1283/// 도형(rect/line)뿐 아니라 `header.rs` 의 borderFill 도 같은 fillBrush 구조를
1284/// 쓰므로 `pub(crate)` 로 공유한다.
1285pub(crate) fn write_fill_brush_with_storage<W: Write, S: crate::storage::Storage>(
1286    w: &mut Writer<W>,
1287    fill: &Fill,
1288    ctx: &SerializeContext,
1289    storage: &S,
1290) -> Result<(), SerializeError>
1291where
1292    S::Error: std::fmt::Display,
1293{
1294    use super::utils::{
1295        empty_tag_with_storage as empty_tag, end_tag_with_storage as end_tag,
1296        start_tag_attrs_with_storage as start_tag_attrs, start_tag_with_storage as start_tag,
1297        xml_value,
1298    };
1299    match fill.fill_type {
1300        // FillType::None 이지만 solid 데이터가 보존돼 있으면(원본 winBrush 가
1301        // faceColor="none"+무늬없음 으로 빈 채우기였던 경우) winBrush 를 그대로
1302        // 복원한다. solid 가 없으면 원본에 fillBrush 가 없었던 것이므로 미방출.
1303        FillType::None => match &fill.solid {
1304            Some(solid) => write_win_brush(w, solid, fill.alpha, storage),
1305            None => Ok(()),
1306        },
1307        FillType::Solid => {
1308            let solid = fill.solid.unwrap_or_default();
1309            write_win_brush(w, &solid, fill.alpha, storage)
1310        }
1311        FillType::Gradient => {
1312            let fallback = Default::default();
1313            let grad = fill.gradient.as_ref().unwrap_or(&fallback);
1314            let unknown_type;
1315            let gtype = match grad.gradient_type {
1316                1 => "LINEAR",
1317                2 => "RADIAL",
1318                3 => "CONICAL",
1319                4 => "SQUARE",
1320                other => {
1321                    unknown_type = xml_value(storage, other)?;
1322                    &unknown_type
1323                }
1324            };
1325            let angle = xml_value(storage, grad.angle)?;
1326            let cx = xml_value(storage, grad.center_x)?;
1327            let cy = xml_value(storage, grad.center_y)?;
1328            let step = xml_value(storage, grad.blur)?;
1329            let step_center = xml_value(storage, grad.step_center)?;
1330            let alpha = fill_alpha_str_with_storage(fill.alpha, storage)?;
1331            start_tag(w, "hc:fillBrush", storage)?;
1332            start_tag_attrs(
1333                w,
1334                "hc:gradation",
1335                &[
1336                    ("type", &gtype),
1337                    ("angle", &angle),
1338                    ("centerX", &cx),
1339                    ("centerY", &cy),
1340                    ("step", &step),
1341                    ("stepCenter", &step_center),
1342                    ("alpha", &alpha),
1343                ],
1344                storage,
1345            )?;
1346            for c in &grad.colors {
1347                let v = color_to_hex_with_storage(*c, storage)?;
1348                empty_tag(w, "hc:color", &[("value", &v)], storage)?;
1349            }
1350            end_tag(w, "hc:gradation", storage)?;
1351            end_tag(w, "hc:fillBrush", storage)
1352        }
1353        FillType::Image => {
1354            let fallback = Default::default();
1355            let img = fill.image.as_ref().unwrap_or(&fallback);
1356            // [#2943] parse_shape_fill_brush(section.rs)는 12종 mode 를 모두 개별
1357            // ImageFillMode 로 적재하는데, 종전엔 여기서 3종만 구분하고 나머지 7종
1358            // (TileHorzTop/Bottom, TileVertLeft/Right, CenterTop/Bottom, LeftTop)이
1359            // 전부 "TILE"로 붕괴해 저장 시 실제 배치가 유실됐다.
1360            let mode = match img.fill_mode {
1361                ImageFillMode::TileHorzTop => "TILE_HORZ_TOP",
1362                ImageFillMode::TileHorzBottom => "TILE_HORZ_BOTTOM",
1363                ImageFillMode::TileVertLeft => "TILE_VERT_LEFT",
1364                ImageFillMode::TileVertRight => "TILE_VERT_RIGHT",
1365                ImageFillMode::FitToSize => "TOTAL",
1366                // HWP5 mode 15 is emitted as ZOOM by Hancom when saving HWPX.
1367                // It is an aspect-preserving fit, not the wildcard TILE fallback.
1368                // This writer is shared by shape fills and header BorderFill.
1369                ImageFillMode::Zoom | ImageFillMode::None => "ZOOM",
1370                ImageFillMode::Total => "TOTAL",
1371                ImageFillMode::Center => "CENTER",
1372                ImageFillMode::CenterTop => "CENTER_TOP",
1373                ImageFillMode::CenterBottom => "CENTER_BOTTOM",
1374                ImageFillMode::LeftTop => "TOP_LEFT_ALIGN",
1375                _ => "TILE",
1376            };
1377            start_tag(w, "hc:fillBrush", storage)?;
1378            // bin_data_id 가 ctx 에 등록돼 있으면 <hc:img> 참조를 방출(셀/쪽 배경 이미지
1379            // 보존). 미등록(예: body shape 의 fill 파서가 bin_data_id 미캡처)이면 종전대로
1380            // 빈 imgBrush — 잘못된 image0 참조로 3-way 단언을 깨지 않는다.
1381            match ctx.resolve_bin_id(img.bin_data_id) {
1382                Some(manifest_id) => {
1383                    start_tag_attrs(w, "hc:imgBrush", &[("mode", mode)], storage)?;
1384                    // [#6895] `ImageFill` 은 이진 HWP5 저장 순서를 담으므로 HWPX 속성명으로
1385                    // 나갈 때 되돌린다. 종전엔 그대로 써서 **HWPX 를 열어 저장할 때마다 두
1386                    // 값이 뒤바뀌었다**(두 번 저장하면 원상 복귀). 한/글은 같은 문서에서
1387                    // bright/contrast 를 보존한다.
1388                    let (display_bright, display_contrast) = img.display_brightness_contrast();
1389                    let bright = xml_value(storage, display_bright)?;
1390                    let contrast = xml_value(storage, display_contrast)?;
1391                    let effect = match img.effect {
1392                        1 => "GRAY_SCALE",
1393                        2 => "BLACK_WHITE",
1394                        _ => "REAL_PIC",
1395                    };
1396                    empty_tag(
1397                        w,
1398                        "hc:img",
1399                        &[
1400                            ("binaryItemIDRef", manifest_id),
1401                            ("bright", &bright),
1402                            ("contrast", &contrast),
1403                            ("effect", effect),
1404                            ("alpha", "0"),
1405                        ],
1406                        storage,
1407                    )?;
1408                    end_tag(w, "hc:imgBrush", storage)?;
1409                }
1410                None => {
1411                    empty_tag(w, "hc:imgBrush", &[("mode", mode)], storage)?;
1412                }
1413            }
1414            end_tag(w, "hc:fillBrush", storage)
1415        }
1416    }
1417}
1418
1419/// winBrush/gradation alpha — 파서가 `f.clamp(0,1)*255` 로 적재하므로 0~1 분수로 방출.
1420fn fill_alpha_str_with_storage<S: crate::storage::Storage>(
1421    alpha: u8,
1422    storage: &S,
1423) -> Result<String, SerializeError>
1424where
1425    S::Error: std::fmt::Display,
1426{
1427    super::utils::xml_value(storage, alpha as f64 / 255.0)
1428}
1429
1430/// `<hp:shadow>` — `parse_shape_shadow_attr` 의 역매핑.
1431/// 전 필드 0 이면 원본에 shadow 부재로 간주하여 미방출.
1432/// alpha 는 정수 방출 (파서의 `>1.0` 경로와 정합 — 0/1 경계값만 비가역).
1433pub(crate) fn write_shadow<W: Write>(
1434    w: &mut Writer<W>,
1435    d: &DrawingObjAttr,
1436) -> Result<(), SerializeError> {
1437    write_shadow_with_storage(w, d, &crate::storage::Unbounded)
1438}
1439
1440pub(super) fn write_shadow_with_storage<W: Write, S: crate::storage::Storage>(
1441    w: &mut Writer<W>,
1442    d: &DrawingObjAttr,
1443    storage: &S,
1444) -> Result<(), SerializeError>
1445where
1446    S::Error: std::fmt::Display,
1447{
1448    if d.shadow_type == 0
1449        && d.shadow_color == 0
1450        && d.shadow_offset_x == 0
1451        && d.shadow_offset_y == 0
1452        && d.shadow_alpha == 0
1453    {
1454        return Ok(());
1455    }
1456    let ty = crate::model::shape::shadow::to_hwpx(d.shadow_type);
1457    let color = color_to_hex_with_storage(d.shadow_color, storage)?;
1458    let ox = xml_value(storage, d.shadow_offset_x)?;
1459    let oy = xml_value(storage, d.shadow_offset_y)?;
1460    let alpha = xml_value(storage, d.shadow_alpha)?;
1461    empty_tag_with_storage(
1462        w,
1463        "hp:shadow",
1464        &[
1465            ("type", ty),
1466            ("color", &color),
1467            ("offsetX", &ox),
1468            ("offsetY", &oy),
1469            ("alpha", &alpha),
1470        ],
1471        storage,
1472    )
1473}
1474
1475// =====================================================================
1476// 꼭짓점 / shapeComment
1477// =====================================================================
1478
1479fn write_rect_pts<W: Write>(
1480    w: &mut Writer<W>,
1481    x: &[i32; 4],
1482    y: &[i32; 4],
1483) -> Result<(), SerializeError> {
1484    write_rect_pts_with_storage(w, x, y, &crate::storage::Unbounded)
1485}
1486
1487pub(super) fn write_rect_pts_with_storage<W: Write, S: crate::storage::Storage>(
1488    w: &mut Writer<W>,
1489    x: &[i32; 4],
1490    y: &[i32; 4],
1491    storage: &S,
1492) -> Result<(), SerializeError>
1493where
1494    S::Error: std::fmt::Display,
1495{
1496    for (i, name) in ["hc:pt0", "hc:pt1", "hc:pt2", "hc:pt3"].iter().enumerate() {
1497        let px = xml_value(storage, x[i])?;
1498        let py = xml_value(storage, y[i])?;
1499        empty_tag_with_storage(w, name, &[("x", &px), ("y", &py)], storage)?;
1500    }
1501    Ok(())
1502}
1503
1504/// `<hp:shapeComment>` 직렬화 — 도형(rect)·그림(#1392)·수식(#1392)·묶음(#1392) 공유.
1505///
1506/// 빈 description 은 미방출 (한컴 원본도 설명 부재 시 요소 없음).
1507pub(super) fn write_shape_comment<W: Write>(
1508    w: &mut Writer<W>,
1509    c: &CommonObjAttr,
1510) -> Result<(), SerializeError> {
1511    write_shape_comment_with_storage(w, c, &crate::storage::Unbounded)
1512}
1513
1514pub(super) fn write_shape_comment_with_storage<W: Write, S: crate::storage::Storage>(
1515    w: &mut Writer<W>,
1516    c: &CommonObjAttr,
1517    storage: &S,
1518) -> Result<(), SerializeError>
1519where
1520    S::Error: std::fmt::Display,
1521{
1522    if c.description.is_empty() {
1523        return Ok(());
1524    }
1525    start_tag_with_storage(w, "hp:shapeComment", storage)?;
1526    text_with_storage(w, &c.description, storage)?;
1527    end_tag_with_storage(w, "hp:shapeComment", storage)
1528}
1529
1530// =====================================================================
1531// 공통 자식 요소 (sz / pos / outMargin)
1532// =====================================================================
1533
1534fn write_sz<W: Write>(w: &mut Writer<W>, c: &CommonObjAttr) -> Result<(), SerializeError> {
1535    write_sz_with_storage(w, c, &crate::storage::Unbounded)
1536}
1537
1538pub(super) fn write_sz_with_storage<W: Write, S: crate::storage::Storage>(
1539    w: &mut Writer<W>,
1540    c: &CommonObjAttr,
1541    storage: &S,
1542) -> Result<(), SerializeError>
1543where
1544    S::Error: std::fmt::Display,
1545{
1546    let width = xml_value(storage, c.width)?;
1547    let height = xml_value(storage, c.height)?;
1548    // [#2712] widthRelTo/heightRelTo/protect 는 IR 을 보존한다. 종전 "ABSOLUTE"/"0"
1549    // 하드코딩은 파서가 이미 읽어 둔 값(section.rs:2901/2904/2907, OLE 는 5967)을 저장 때
1550    // 버려, 단/쪽/문단에 맞춘 도형이 절대값으로 굳고 "크기 고정"이 풀렸다. 실제 한글 산출
1551    // 파일 samples/hwpx/143E433F503322BD33.hwpx 의 hp:rect·hp:ole 이 protect="1" 인데
1552    // 종전 방출은 이를 "0" 으로 되썼다. 이웃 write_pos 는 이미 모든 필드를 통과시키고,
1553    // 같은 hp:sz 를 다루는 form.rs:183-188 도 3속성 모두 보존한다. 표는 #2697/#2701 에서
1554    // 같은 결함을 같은 방식으로 정리했다.
1555    empty_tag_with_storage(
1556        w,
1557        "hp:sz",
1558        &[
1559            ("width", &width),
1560            ("widthRelTo", size_criterion_str(c.width_criterion)),
1561            ("height", &height),
1562            ("heightRelTo", height_criterion_str(c.height_criterion)),
1563            ("protect", bool01(c.size_protect)),
1564        ],
1565        storage,
1566    )
1567}
1568
1569/// 너비 기준 → HWPX `widthRelTo`. 파서 `parse_size_criterion(_, true)` 의 정확한 역이다
1570/// (`parser/hwpx/section.rs:1844`, 호출부 `:2901`). 너비는 HWP5 attr bit 15-17 로 3비트라
1571/// 5값 전부를 담는다(`model/shape.rs:83`).
1572pub(super) fn size_criterion_str(c: SizeCriterion) -> &'static str {
1573    match c {
1574        SizeCriterion::Paper => "PAPER",
1575        SizeCriterion::Page => "PAGE",
1576        SizeCriterion::Column => "COLUMN",
1577        SizeCriterion::Para => "PARA",
1578        SizeCriterion::Absolute => "ABSOLUTE",
1579    }
1580}
1581
1582/// 높이 기준 → HWPX `heightRelTo`. 파서는 높이를
1583/// `parse_size_criterion(_, allow_column_para = false)` 로 읽으므로(`section.rs:2904`)
1584/// 치역이 `{PAPER, PAGE, ABSOLUTE}` 3값뿐이다. 방출도 같은 3값으로 접어야 왕복이 정확한
1585/// 역이 된다. HWP5 측 `height_criterion_to_bits`(`common_obj_attr_writer.rs:160`)와 모델
1586/// 주석(`model/shape.rs:85`, bit 18-19)도 동일하게 접는다.
1587pub(super) fn height_criterion_str(c: SizeCriterion) -> &'static str {
1588    match c {
1589        SizeCriterion::Paper => "PAPER",
1590        SizeCriterion::Page => "PAGE",
1591        SizeCriterion::Column | SizeCriterion::Para | SizeCriterion::Absolute => "ABSOLUTE",
1592    }
1593}
1594
1595fn write_pos<W: Write>(w: &mut Writer<W>, c: &CommonObjAttr) -> Result<(), SerializeError> {
1596    write_pos_with_storage(w, c, &crate::storage::Unbounded)
1597}
1598
1599pub(super) fn write_pos_with_storage<W: Write, S: crate::storage::Storage>(
1600    w: &mut Writer<W>,
1601    c: &CommonObjAttr,
1602    storage: &S,
1603) -> Result<(), SerializeError>
1604where
1605    S::Error: std::fmt::Display,
1606{
1607    let treat = bool01(c.treat_as_char);
1608    let vert_offset = xml_value(storage, c.vertical_offset)?;
1609    let horz_offset = xml_value(storage, c.horizontal_offset)?;
1610    let hold = bool01(c.prevent_page_break != 0); // [#1594] IR 보존
1611    empty_tag_with_storage(
1612        w,
1613        "hp:pos",
1614        &[
1615            ("treatAsChar", treat),
1616            // [#2784] affectLSpacing 은 IR(affect_line_spacing)을 보존한다. 종전 "0"
1617            // 하드코딩은 "줄 간격에 영향" 켜진 도형이 저장 시 1→0 으로 드롭됐다.
1618            ("affectLSpacing", bool01(c.affect_line_spacing)),
1619            ("flowWithText", bool01(c.flow_with_text)),
1620            ("allowOverlap", bool01(c.allow_overlap)),
1621            ("holdAnchorAndSO", hold),
1622            ("vertRelTo", vert_rel_to_str(c.vert_rel_to)),
1623            ("horzRelTo", horz_rel_to_str(c.horz_rel_to)),
1624            ("vertAlign", vert_align_str(c.vert_align)),
1625            ("horzAlign", horz_align_str(c.horz_align)),
1626            ("vertOffset", &vert_offset),
1627            ("horzOffset", &horz_offset),
1628        ],
1629        storage,
1630    )
1631}
1632
1633fn write_out_margin<W: Write>(w: &mut Writer<W>, c: &CommonObjAttr) -> Result<(), SerializeError> {
1634    write_out_margin_with_storage(w, c, &crate::storage::Unbounded)
1635}
1636
1637pub(super) fn write_out_margin_with_storage<W: Write, S: crate::storage::Storage>(
1638    w: &mut Writer<W>,
1639    c: &CommonObjAttr,
1640    storage: &S,
1641) -> Result<(), SerializeError>
1642where
1643    S::Error: std::fmt::Display,
1644{
1645    let l = xml_value(storage, c.margin.left)?;
1646    let r = xml_value(storage, c.margin.right)?;
1647    let t = xml_value(storage, c.margin.top)?;
1648    let b = xml_value(storage, c.margin.bottom)?;
1649    empty_tag_with_storage(
1650        w,
1651        "hp:outMargin",
1652        &[("left", &l), ("right", &r), ("top", &t), ("bottom", &b)],
1653        storage,
1654    )
1655}
1656
1657/// ColorRef (0xAABBGGRR) → "#RRGGBB" / "#AARRGGBB". 0xFFFFFFFF → "#FFFFFFFF" (한글 2018 호환).
1658/// `parse_color_str` 의 역매핑 (header.rs `color_hex` 와 동일 규칙).
1659pub(crate) fn color_to_hex(c: ColorRef) -> String {
1660    color_to_hex_with_storage(c, &crate::storage::Unbounded).expect("unbounded color")
1661}
1662pub(super) fn color_to_hex_with_storage<S: crate::storage::Storage>(
1663    c: ColorRef,
1664    storage: &S,
1665) -> Result<String, SerializeError>
1666where
1667    S::Error: std::fmt::Display,
1668{
1669    let a = ((c >> 24) & 0xFF) as u8;
1670    let r = (c & 0xFF) as u8;
1671    let g = ((c >> 8) & 0xFF) as u8;
1672    let b = ((c >> 16) & 0xFF) as u8;
1673    if a == 0 {
1674        super::utils::xml_value(storage, format_args!("#{:02X}{:02X}{:02X}", r, g, b))
1675    } else {
1676        super::utils::xml_value(
1677            storage,
1678            format_args!("#{:02X}{:02X}{:02X}{:02X}", a, r, g, b),
1679        )
1680    }
1681}
1682
1683pub(crate) fn numbering_type_str(n: ObjectNumberingType) -> &'static str {
1684    match n {
1685        ObjectNumberingType::Picture => "PICTURE",
1686        ObjectNumberingType::Table => "TABLE",
1687        ObjectNumberingType::Equation => "EQUATION",
1688        ObjectNumberingType::None => "NONE",
1689    }
1690}
1691
1692/// `dropcapstyle` 방출 문자열. OWPML Core 스키마 `DropCapStyleType`
1693/// (None/DoubleLine/TripleLine/Margin) 그대로 왕복한다.
1694pub(crate) fn drop_cap_style_str(s: crate::model::shape::DropCapStyle) -> &'static str {
1695    use crate::model::shape::DropCapStyle;
1696    match s {
1697        DropCapStyle::None => "None",
1698        DropCapStyle::DoubleLine => "DoubleLine",
1699        DropCapStyle::TripleLine => "TripleLine",
1700        DropCapStyle::Margin => "Margin",
1701    }
1702}
1703
1704fn bool01(b: bool) -> &'static str {
1705    if b {
1706        "1"
1707    } else {
1708        "0"
1709    }
1710}
1711
1712fn text_wrap_str(w: TextWrap) -> &'static str {
1713    use TextWrap::*;
1714    match w {
1715        Square => "SQUARE",
1716        Tight => "TIGHT",
1717        Through => "THROUGH",
1718        TopAndBottom => "TOP_AND_BOTTOM",
1719        BehindText => "BEHIND_TEXT",
1720        InFrontOfText => "IN_FRONT_OF_TEXT",
1721    }
1722}
1723
1724fn text_flow_str(f: TextFlow) -> &'static str {
1725    match f {
1726        TextFlow::BothSides => "BOTH_SIDES",
1727        TextFlow::LeftOnly => "LEFT_ONLY",
1728        TextFlow::RightOnly => "RIGHT_ONLY",
1729        TextFlow::LargestOnly => "LARGEST_ONLY",
1730    }
1731}
1732
1733fn vert_rel_to_str(v: VertRelTo) -> &'static str {
1734    use VertRelTo::*;
1735    match v {
1736        Paper => "PAPER",
1737        Page => "PAGE",
1738        Para => "PARA",
1739    }
1740}
1741
1742fn horz_rel_to_str(h: HorzRelTo) -> &'static str {
1743    use HorzRelTo::*;
1744    match h {
1745        Paper => "PAPER",
1746        Page => "PAGE",
1747        Column => "COLUMN",
1748        Para => "PARA",
1749    }
1750}
1751
1752fn vert_align_str(v: VertAlign) -> &'static str {
1753    use VertAlign::*;
1754    match v {
1755        Top => "TOP",
1756        Center => "CENTER",
1757        Bottom => "BOTTOM",
1758        Inside => "INSIDE",
1759        Outside => "OUTSIDE",
1760    }
1761}
1762
1763fn horz_align_str(h: HorzAlign) -> &'static str {
1764    use HorzAlign::*;
1765    match h {
1766        Left => "LEFT",
1767        Center => "CENTER",
1768        Right => "RIGHT",
1769        Inside => "INSIDE",
1770        Outside => "OUTSIDE",
1771    }
1772}
1773
1774#[cfg(test)]
1775mod tests {
1776    use super::*;
1777    use crate::model::paragraph::Paragraph;
1778    use crate::model::shape::{LineShape, RectangleShape};
1779    use crate::model::Point;
1780
1781    fn serialize_rect(rect: &RectangleShape) -> String {
1782        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
1783        let mut ctx = SerializeContext::collect_from_document(&Default::default());
1784        write_rect(&mut w, rect, &mut ctx).expect("write_rect");
1785        String::from_utf8(w.into_inner()).unwrap()
1786    }
1787
1788    fn serialize_line(line: &LineShape) -> String {
1789        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
1790        let mut ctx = SerializeContext::collect_from_document(&Default::default());
1791        write_line(&mut w, line, &mut ctx).expect("write_line");
1792        String::from_utf8(w.into_inner()).unwrap()
1793    }
1794
1795    fn line_shape_style(attr: u32) -> String {
1796        use crate::model::style::ShapeBorderLine;
1797        let bl = ShapeBorderLine {
1798            attr,
1799            ..Default::default()
1800        };
1801        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
1802        write_line_shape(&mut w, &bl).expect("write_line_shape");
1803        let xml = String::from_utf8(w.into_inner()).unwrap();
1804        let i = xml.find("style=\"").expect("style attr") + 7;
1805        xml[i..].split('"').next().unwrap().to_string()
1806    }
1807
1808    /// #2943: imgBrush mode 는 12종 중 3종만 구분하면 나머지 7종
1809    /// (TileHorzTop 등)이 저장 시 전부 TILE 로 붕괴한다. 각 모드가 자기 고유의
1810    /// mode 문자열로 방출돼야 한다.
1811    #[test]
1812    fn task2943_img_brush_mode_roundtrip_not_collapsed_to_tile() {
1813        use crate::model::style::{Fill, FillType, ImageFill, ImageFillMode};
1814        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
1815        let ctx = SerializeContext::collect_from_document(&Default::default());
1816        let fill = Fill {
1817            fill_type: FillType::Image,
1818            image: Some(ImageFill {
1819                fill_mode: ImageFillMode::TileHorzTop,
1820                ..Default::default()
1821            }),
1822            ..Default::default()
1823        };
1824        write_fill_brush(&mut w, &fill, &ctx).expect("write_fill_brush");
1825        let xml = String::from_utf8(w.into_inner()).unwrap();
1826        assert!(
1827            xml.contains("mode=\"TILE_HORZ_TOP\""),
1828            "TileHorzTop 이 TILE 로 붕괴함: {xml}"
1829        );
1830    }
1831
1832    /// #1531: 선 없음(style code 0) 도형 외곽선이 라운드트립에서 SOLID(사각형 박스)로
1833    /// 살아나면 안 된다. endCap(bit 6~9)이 함께 설정돼도 NONE 이 보존돼야 한다.
1834    #[test]
1835    fn task1531_line_shape_none_preserved() {
1836        assert_eq!(line_shape_style(0), "NONE"); // 정본 코드 0 = NONE
1837        assert_eq!(line_shape_style(1), "SOLID"); // 1 = SOLID
1838        assert_eq!(line_shape_style(2), "DOT"); // HWP5 파선은 HWPX DOT로 저장한다.
1839        let none_with_flat_end_cap = 1 << 6;
1840        assert_eq!(line_shape_style(none_with_flat_end_cap), "NONE");
1841    }
1842
1843    /// #2956: attr 에 파싱된 화살표 끝 모양(bit 16~21, 채움 bit 30)이 저장 시
1844    /// "NORMAL" 로 하드코딩되지 않고 보존돼야 한다.
1845    #[test]
1846    fn task2956_line_shape_arrow_style_preserved() {
1847        use crate::model::style::ShapeBorderLine;
1848        // tail = FILLED_DIAMOND(4) + tail_fill(bit30)
1849        let attr = (4u32 << 16) | (1 << 30);
1850        let bl = ShapeBorderLine {
1851            attr,
1852            ..Default::default()
1853        };
1854        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
1855        write_line_shape(&mut w, &bl).expect("write_line_shape");
1856        let xml = String::from_utf8(w.into_inner()).unwrap();
1857        assert!(
1858            xml.contains("tailStyle=\"FILLED_DIAMOND\""),
1859            "화살표 끝 모양이 소실됨: {xml}"
1860        );
1861    }
1862
1863    /// #3022: hc:ArrowSize 의 스펙 리터럴은 `*_LARGE` 이다(Core XML schema.xml:407).
1864    /// headSz/tailSz 방출이 스펙에 없는 `*_BIG` 표기로 나가면 안 된다.
1865    #[test]
1866    fn task3022_arrow_size_uses_spec_large_literal() {
1867        assert_eq!(arrow_size_str(2), "SMALL_LARGE");
1868        assert_eq!(arrow_size_str(5), "MEDIUM_LARGE");
1869        assert_eq!(arrow_size_str(6), "LARGE_SMALL");
1870        assert_eq!(arrow_size_str(7), "LARGE_MEDIUM");
1871        assert_eq!(arrow_size_str(8), "LARGE_LARGE");
1872    }
1873
1874    /// #1588: 선 도형 설명(shapeComment)이 저장 시 방출돼야 한다.
1875    /// write_rect/container 는 호출하나 write_line 만 누락 → 드롭(RED).
1876    #[test]
1877    fn task1588_line_shape_comment_emitted() {
1878        let mut line = LineShape::default();
1879        line.common.description = "선입니다.".to_string();
1880        let xml = serialize_line(&line);
1881        assert!(
1882            xml.contains("<hp:shapeComment>선입니다.</hp:shapeComment>"),
1883            "선 도형 shapeComment 방출돼야 한다 (현재 드롭): {xml}"
1884        );
1885    }
1886
1887    /// #1588: 설명 없는 선 도형은 shapeComment 미방출 (빈 태그 금지).
1888    #[test]
1889    fn task1588_line_shape_no_comment_when_empty() {
1890        let line = LineShape::default();
1891        let xml = serialize_line(&line);
1892        assert!(!xml.contains("<hp:shapeComment"), "빈 설명 미방출: {xml}");
1893    }
1894
1895    fn cs(start_pos: u32, char_shape_id: u32) -> crate::model::paragraph::CharShapeRef {
1896        crate::model::paragraph::CharShapeRef {
1897            start_pos,
1898            char_shape_id,
1899        }
1900    }
1901
1902    fn rect_with_text_paragraph(p: Paragraph) -> RectangleShape {
1903        let mut tb = TextBox::default();
1904        tb.paragraphs.push(p);
1905        let mut rect = RectangleShape::default();
1906        rect.drawing.text_box = Some(tb);
1907        rect
1908    }
1909
1910    #[test]
1911    fn task1378_drawtext_multi_run_split() {
1912        // 글상자 문단 다중 char_shapes → 경계 기준 다중 run 분할 (#1378 3단계).
1913        let mut p = Paragraph::default();
1914        p.text = "abcd".to_string();
1915        p.char_offsets = vec![0, 1, 2, 3];
1916        p.char_count = 5;
1917        p.char_shapes = vec![cs(0, 3), cs(2, 4)];
1918        let xml = serialize_rect(&rect_with_text_paragraph(p));
1919        assert!(
1920            xml.contains(
1921                r#"<hp:run charPrIDRef="3"><hp:t>ab</hp:t></hp:run><hp:run charPrIDRef="4"><hp:t>cd</hp:t></hp:run>"#
1922            ),
1923            "글상자 문단이 경계에서 2 run 으로 분할되어야 함: {}",
1924            xml
1925        );
1926    }
1927
1928    #[test]
1929    fn task1378_drawtext_tab_and_linebreak_rendered() {
1930        // 탭/lineBreak 가 raw 제어문자 대신 인라인 요소로 방출된다.
1931        let mut p = Paragraph::default();
1932        p.text = "a\tb\nc".to_string();
1933        p.tab_extended = vec![[2000, 0, 0x0100, 0, 0, 0, 0]];
1934        let xml = serialize_rect(&rect_with_text_paragraph(p));
1935        assert!(
1936            xml.contains(
1937                r#"<hp:t>a<hp:tab width="2000" leader="0" type="1"/>b<hp:lineBreak/>c</hp:t>"#
1938            ),
1939            "글상자 텍스트는 hp:tab/hp:lineBreak 인라인 요소로 방출되어야 함: {}",
1940            xml
1941        );
1942    }
1943
1944    #[test]
1945    fn rect_emits_root_tag() {
1946        let mut rect = RectangleShape::default();
1947        rect.common.width = 1000;
1948        rect.common.height = 500;
1949        let xml = serialize_rect(&rect);
1950        assert!(xml.contains("<hp:rect "));
1951        assert!(xml.contains("</hp:rect>"));
1952    }
1953
1954    #[test]
1955    fn rect_has_canonical_attrs() {
1956        let rect = RectangleShape::default();
1957        let xml = serialize_rect(&rect);
1958        assert!(xml.contains(r#"id=""#));
1959        assert!(xml.contains(r#"zOrder=""#));
1960        assert!(xml.contains(r#"textWrap=""#));
1961        assert!(xml.contains(r#"textFlow="BOTH_SIDES""#));
1962    }
1963
1964    #[test]
1965    fn line_emits_start_end_attrs() {
1966        // [Issue #1943] 좌표는 startPt/endPt 자식으로 방출한다 (파서가 읽는
1967        // 유일 경로). 종전 startX/Y attr 은 파서가 무시하는 dead 출력이었다.
1968        // hp:line 의 자식 네임스페이스는 hc: 다 (XSD LineType — hp: 로 쓰면
1969        // 한컴오피스가 문서를 거부한다).
1970        let mut line = LineShape::default();
1971        line.start = Point { x: 100, y: 200 };
1972        line.end = Point { x: 300, y: 400 };
1973        let xml = serialize_line(&line);
1974        assert!(
1975            xml.contains(r#"<hc:startPt x="100" y="200""#),
1976            "startPt 자식 방출: {xml}"
1977        );
1978        assert!(
1979            xml.contains(r#"<hc:endPt x="300" y="400""#),
1980            "endPt 자식 방출: {xml}"
1981        );
1982        // 컴포넌트 블록·lineShape 보존 (#1943 (B)).
1983        assert!(xml.contains("<hp:offset "), "컴포넌트 블록: {xml}");
1984        assert!(xml.contains("<hp:lineShape "), "lineShape: {xml}");
1985    }
1986
1987    /// [Issue #1943 (A)] connector 보유 LineShape 는 hp:connectLine 으로 방출하고
1988    /// type/제어점을 보존한다 (종전 hp:line 변질로 커넥터 소실).
1989    #[test]
1990    fn connector_line_emits_connect_line_tag_and_type() {
1991        use crate::model::shape::{ConnectorControlPoint, ConnectorData, LinkLineType};
1992        let mut line = LineShape::default();
1993        line.start = Point { x: 0, y: 0 };
1994        line.end = Point { x: 1257, y: 0 };
1995        line.connector = Some(ConnectorData {
1996            link_type: LinkLineType::StrokeOneWay,
1997            control_points: vec![
1998                ConnectorControlPoint {
1999                    x: 0,
2000                    y: 0,
2001                    point_type: 3,
2002                },
2003                ConnectorControlPoint {
2004                    x: 100,
2005                    y: 0,
2006                    point_type: 26,
2007                },
2008            ],
2009            ..Default::default()
2010        });
2011        let xml = serialize_line(&line);
2012        assert!(xml.contains("<hp:connectLine "), "connectLine 태그: {xml}");
2013        assert!(
2014            xml.contains(r#"type="STROKE_ONEWAY""#),
2015            "connector type: {xml}"
2016        );
2017        assert!(xml.contains("<hp:controlPoints>"), "제어점 방출: {xml}");
2018        assert!(xml.contains(r#"<hp:point x="100" y="0" type="26"/>"#));
2019        assert!(
2020            !xml.contains("<hp:line "),
2021            "connectLine 이 hp:line 으로 변질 금지"
2022        );
2023    }
2024
2025    #[test]
2026    fn rect_has_sz_pos_out_margin() {
2027        let rect = RectangleShape::default();
2028        let xml = serialize_rect(&rect);
2029        assert!(xml.contains("<hp:sz "));
2030        assert!(xml.contains("<hp:pos "));
2031        assert!(xml.contains("<hp:outMargin "));
2032    }
2033
2034    // ================= #1379 3단계 =================
2035
2036    #[test]
2037    fn task1379_drawtext_paragraph_emits_picture_control() {
2038        // 글상자 문단의 Picture 컨트롤이 hp:pic 으로 방출되어야 함 (#1379 3단계).
2039        let mut p = Paragraph::default();
2040        p.char_count = 9; // 슬롯 1개(8 유닛) + 종단 1
2041        {
2042            let mut pic = crate::model::image::Picture::default();
2043            pic.image_attr.bin_data_id = 1;
2044            p.controls
2045                .push(crate::model::control::Control::Picture(Box::new(pic)));
2046        }
2047        let rect = rect_with_text_paragraph(p);
2048
2049        let mut doc = crate::model::document::Document::default();
2050        doc.bin_data_content
2051            .push(crate::model::bin_data::BinDataContent {
2052                id: 1,
2053                data: vec![0u8; 4].into(),
2054                extension: "png".to_string(),
2055            });
2056        let mut ctx = SerializeContext::collect_from_document(&doc);
2057        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
2058        write_rect(&mut w, &rect, &mut ctx).expect("write_rect");
2059        let xml = String::from_utf8(w.into_inner()).unwrap();
2060        assert!(
2061            xml.contains("<hp:pic "),
2062            "글상자 문단의 Picture 가 hp:pic 으로 방출되어야 함: {}",
2063            xml
2064        );
2065    }
2066
2067    #[test]
2068    fn task1379_drawtext_vertical_direction_preserved() {
2069        // textDirection VERTICAL / VERTICALALL / HORIZONTAL 구분 보존.
2070        let mut p = Paragraph::default();
2071        p.text = "a".to_string();
2072        let mut rect = rect_with_text_paragraph(p);
2073        {
2074            let tb = rect.drawing.text_box.as_mut().unwrap();
2075            tb.list_attr = 1; // 세로쓰기
2076            tb.vertical_all = true;
2077            tb.vertical_align = crate::model::table::VerticalAlign::Center;
2078        }
2079        let xml = serialize_rect(&rect);
2080        assert!(
2081            xml.contains(r#"textDirection="VERTICALALL""#),
2082            "VERTICALALL 보존: {}",
2083            xml
2084        );
2085        assert!(xml.contains(r#"vertAlign="CENTER""#), "vertAlign: {}", xml);
2086
2087        rect.drawing.text_box.as_mut().unwrap().vertical_all = false;
2088        let xml = serialize_rect(&rect);
2089        assert!(
2090            xml.contains(r#"textDirection="VERTICAL""#) && !xml.contains("VERTICALALL"),
2091            "VERTICAL (ALL 아님) 보존: {}",
2092            xml
2093        );
2094    }
2095
2096    /// [Issue #3544] hp:offset x/y 는 OWPML XSD 상 unsigned — 음수 IR 오프셋은
2097    /// 한컴 관례대로 u32 wraparound 십진수로 방출해야 한다 (파서 `parse_u32 as
2098    /// i32` 복호의 역함수). signed 그대로 문자열화하면 `y="-2"` 류 스키마 위반.
2099    #[test]
2100    fn issue3544_negative_offset_emitted_as_u32_wraparound() {
2101        let mut rect = RectangleShape::default();
2102        rect.drawing.shape_attr.offset_x = -8974;
2103        rect.drawing.shape_attr.offset_y = -2;
2104        let xml = serialize_rect(&rect);
2105        assert!(
2106            xml.contains(r#"<hp:offset x="4294958322" y="4294967294"/>"#),
2107            "음수 오프셋은 u32 wraparound 십진수로 방출되어야 한다: {xml}"
2108        );
2109    }
2110
2111    #[test]
2112    fn task1379_rect_emits_pts_and_element_order() {
2113        // hc:pt0~pt3 방출 + 자식 순서 (offset→…→drawText→pt→sz→pos→outMargin→comment).
2114        let mut p = Paragraph::default();
2115        p.text = "x".to_string();
2116        let mut rect = rect_with_text_paragraph(p);
2117        rect.x_coords = [0, 13514, 13514, 0];
2118        rect.y_coords = [0, 0, 14898, 14898];
2119        rect.common.description = "사각형입니다.".to_string();
2120        rect.drawing.shape_attr.original_width = 13514;
2121        rect.drawing.shape_attr.current_width = 21351;
2122        let xml = serialize_rect(&rect);
2123
2124        assert!(
2125            xml.contains(r#"<hc:pt1 x="13514" y="0"/>"#),
2126            "pt1 좌표: {}",
2127            xml
2128        );
2129        let order = [
2130            "<hp:offset ",
2131            "<hp:orgSz ",
2132            "<hp:curSz ",
2133            "<hp:flip ",
2134            "<hp:rotationInfo ",
2135            "<hp:renderingInfo>",
2136            "<hp:lineShape ",
2137            "<hp:drawText ",
2138            "<hc:pt0 ",
2139            "<hp:sz ",
2140            "<hp:pos ",
2141            "<hp:outMargin ",
2142            "<hp:shapeComment>",
2143        ];
2144        let mut last = 0usize;
2145        for tag in order {
2146            let pos = xml
2147                .find(tag)
2148                .unwrap_or_else(|| panic!("{} 누락: {}", tag, xml));
2149            assert!(
2150                pos > last,
2151                "{} 순서 오류 (pos={}, last={}): {}",
2152                tag,
2153                pos,
2154                last,
2155                xml
2156            );
2157            last = pos;
2158        }
2159        assert!(
2160            xml.contains("<hp:shapeComment>사각형입니다.</hp:shapeComment>"),
2161            "shapeComment 보존: {}",
2162            xml
2163        );
2164    }
2165
2166    #[test]
2167    fn task1379_rect_line_fill_shadow_attrs() {
2168        // lineShape/fillBrush/shadow 속성 역매핑.
2169        let mut rect = RectangleShape::default();
2170        rect.drawing.border_line.color = 0; // #000000
2171        rect.drawing.border_line.width = 33;
2172        // SOLID(1) + endCap FLAT(1<<6) + headfill/tailfill + headSz/tailSz MEDIUM_MEDIUM(4)
2173        rect.drawing.border_line.attr =
2174            1 | (1 << 6) | 0x8000_0000 | 0x4000_0000 | (4 << 22) | (4 << 26);
2175        rect.drawing.fill.fill_type = FillType::Solid;
2176        rect.drawing.fill.solid = Some(crate::model::style::SolidFill {
2177            background_color: 0x00FFFFFF, // #FFFFFF
2178            pattern_color: 0,
2179            pattern_type: -1,
2180        });
2181        rect.drawing.shadow_type = 0;
2182        rect.drawing.shadow_color = crate::parser::hwpx::utils::parse_color_str("#B2B2B2");
2183        let xml = serialize_rect(&rect);
2184
2185        assert!(
2186            xml.contains(
2187                r##"<hp:lineShape color="#000000" width="33" style="SOLID" endCap="FLAT" headStyle="NORMAL" tailStyle="NORMAL" headfill="1" tailfill="1" headSz="MEDIUM_MEDIUM" tailSz="MEDIUM_MEDIUM" outlineStyle="NORMAL" alpha="0"/>"##
2188            ),
2189            "lineShape 역매핑: {}",
2190            xml
2191        );
2192        assert!(
2193            xml.contains(
2194                r##"<hc:fillBrush><hc:winBrush faceColor="#FFFFFF" hatchColor="#000000" alpha="0"/></hc:fillBrush>"##
2195            ),
2196            "fillBrush winBrush: {}",
2197            xml
2198        );
2199        assert!(
2200            xml.contains(
2201                r##"<hp:shadow type="NONE" color="#B2B2B2" offsetX="0" offsetY="0" alpha="0"/>"##
2202            ),
2203            "shadow NONE + 색상 보존: {}",
2204            xml
2205        );
2206    }
2207
2208    #[test]
2209    fn task1379_tbox_v_flow_01_roundtrip_preserves_textbox() {
2210        // 이슈 대표 샘플 — roundtrip 후 글상자 rect 의 구조 보존.
2211        fn find_rect(doc: &crate::model::document::Document) -> Option<&RectangleShape> {
2212            doc.sections
2213                .iter()
2214                .flat_map(|s| &s.paragraphs)
2215                .flat_map(|p| &p.controls)
2216                .find_map(|c| match c {
2217                    crate::model::control::Control::Shape(s) => match s.as_ref() {
2218                        crate::model::shape::ShapeObject::Rectangle(r) => Some(r),
2219                        _ => None,
2220                    },
2221                    _ => None,
2222                })
2223        }
2224        let bytes = std::fs::read("samples/hwpx/tbox-v-flow-01.hwpx").expect("샘플 읽기");
2225        let doc1 = crate::parser::hwpx::parse_hwpx(&bytes).expect("파싱");
2226        let r1 = find_rect(&doc1).expect("원본 rect");
2227        let tb1 = r1.drawing.text_box.as_ref().expect("원본 글상자");
2228        assert!(tb1.vertical_all, "원본 textDirection=VERTICALALL");
2229        let n_para = tb1.paragraphs.len();
2230        assert!(n_para > 1, "글상자 다문단 샘플");
2231
2232        let out = crate::serializer::hwpx::serialize_hwpx(&doc1).expect("직렬화");
2233        let doc2 = crate::parser::hwpx::parse_hwpx(&out).expect("재파싱");
2234        let r2 = find_rect(&doc2).expect("roundtrip rect");
2235        let tb2 = r2.drawing.text_box.as_ref().expect("roundtrip 글상자");
2236
2237        assert_eq!(tb2.paragraphs.len(), n_para, "글상자 문단 수 보존");
2238        assert!(tb2.vertical_all, "VERTICALALL 보존");
2239        assert_eq!(
2240            tb2.paragraphs[0].text, tb1.paragraphs[0].text,
2241            "첫 문단 텍스트 보존"
2242        );
2243        assert_eq!(
2244            r2.common.numbering_type,
2245            crate::model::shape::ObjectNumberingType::Picture,
2246            "numberingType=PICTURE 보존"
2247        );
2248        assert_eq!(r2.x_coords, r1.x_coords, "pt 꼭짓점 x 보존");
2249        assert_eq!(
2250            (r2.common.flow_with_text, r2.common.allow_overlap),
2251            (r1.common.flow_with_text, r1.common.allow_overlap),
2252            "pos flowWithText/allowOverlap 보존"
2253        );
2254        // 비정수 scaMatrix 값 f32 정밀도 보존 (원본 "1.579917")
2255        let cursor = std::io::Cursor::new(&out);
2256        let mut archive = zip::ZipArchive::new(cursor).expect("zip");
2257        let mut sec0 = archive
2258            .by_name("Contents/section0.xml")
2259            .expect("section0.xml");
2260        let mut xml = String::new();
2261        std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read section0");
2262        assert!(xml.contains("1.579917"), "scaMatrix 비정수 값 보존");
2263    }
2264
2265    // ---------- #1403: 도형 캡션 직렬화 ----------
2266
2267    fn caption_with_text(text: &str) -> crate::model::shape::Caption {
2268        let mut para = Paragraph::default();
2269        para.text = text.to_string();
2270        let mut caption = crate::model::shape::Caption::default();
2271        caption.width = 8504;
2272        caption.spacing = 850;
2273        caption.max_width = 47624;
2274        caption.paragraphs.push(para);
2275        caption
2276    }
2277
2278    #[test]
2279    fn task1403_rect_caption_is_serialized() {
2280        // OWPML AbstractShapeObjectType 순서: outMargin → caption → shapeComment.
2281        let mut rect = RectangleShape::default();
2282        rect.common.description = "설명".to_string();
2283        rect.drawing.caption = Some(caption_with_text("사각형 캡션"));
2284        let xml = serialize_rect(&rect);
2285        assert!(
2286            xml.contains("<hp:t>사각형 캡션</hp:t>"),
2287            "캡션 subList 문단 텍스트가 방출되어야 함: {}",
2288            xml
2289        );
2290        let om = xml.find("<hp:outMargin").unwrap();
2291        let cp = xml.find("<hp:caption").unwrap();
2292        let sc = xml.find("<hp:shapeComment").unwrap();
2293        assert!(
2294            om < cp && cp < sc,
2295            "caption 은 outMargin 과 shapeComment 사이"
2296        );
2297    }
2298
2299    #[test]
2300    fn task1403_line_caption_is_serialized() {
2301        let mut line = LineShape::default();
2302        line.drawing.caption = Some(caption_with_text("선 캡션"));
2303        let xml = serialize_line(&line);
2304        assert!(
2305            xml.contains("<hp:t>선 캡션</hp:t>"),
2306            "캡션 subList 문단 텍스트가 방출되어야 함: {}",
2307            xml
2308        );
2309        let om = xml.find("<hp:outMargin").unwrap();
2310        let cp = xml.find("<hp:caption").unwrap();
2311        assert!(om < cp, "caption 은 outMargin 뒤");
2312    }
2313
2314    #[test]
2315    fn task1403_shape_without_caption_emits_none() {
2316        let xml = serialize_rect(&RectangleShape::default());
2317        assert!(!xml.contains("<hp:caption"), "캡션 부재 시 미방출: {}", xml);
2318        let xml = serialize_line(&LineShape::default());
2319        assert!(!xml.contains("<hp:caption"), "캡션 부재 시 미방출: {}", xml);
2320    }
2321
2322    // ---------- #2712: 도형 hp:sz 크기 기준·크기 보호 라운드트립 ----------
2323
2324    /// 도형을 한 문단짜리 `<hs:sec>` 으로 감싸 다시 파싱한다(IR 수준 역검증용).
2325    fn reparse_shape_common(fragment: &str) -> crate::model::shape::CommonObjAttr {
2326        let xml = format!(
2327            concat!(
2328                r#"<?xml version="1.0" encoding="UTF-8"?>"#,
2329                r#"<hs:sec xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph""#,
2330                r#" xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section">"#,
2331                r#"<hp:p id="0" paraPrIDRef="0" styleIDRef="0">"#,
2332                r#"<hp:run charPrIDRef="0">{}<hp:t/></hp:run></hp:p></hs:sec>"#
2333            ),
2334            fragment
2335        );
2336        let section = crate::parser::hwpx::section::parse_hwpx_section(&xml)
2337            .expect("파싱 가능한 도형 조각이어야 함");
2338        match &section.paragraphs[0].controls[0] {
2339            crate::model::control::Control::Shape(s) => s.common().clone(),
2340            other => panic!("도형 컨트롤이어야 함: {other:?}"),
2341        }
2342    }
2343
2344    #[test]
2345    fn task2712_shape_sz_criteria_and_protect_emitted_from_ir() {
2346        // [#2712] hp:sz 의 widthRelTo/heightRelTo/protect 는 IR 을 보존해야 한다.
2347        // 종전 "ABSOLUTE"/"ABSOLUTE"/"0" 하드코딩은 파서가 이미 읽어 둔 값
2348        // (section.rs:2901/2904/2907)을 저장 때 버렸다. RED.
2349        let mut rect = RectangleShape::default();
2350        rect.common.width_criterion = SizeCriterion::Column;
2351        rect.common.height_criterion = SizeCriterion::Paper;
2352        rect.common.size_protect = true;
2353        let xml = serialize_rect(&rect);
2354        assert!(
2355            xml.contains(r#"widthRelTo="COLUMN""#),
2356            "widthRelTo 가 IR(Column)로 방출돼야 함(종전 ABSOLUTE 하드코딩): {xml}"
2357        );
2358        assert!(
2359            xml.contains(r#"heightRelTo="PAPER""#),
2360            "heightRelTo 가 IR(Paper)로 방출돼야 함(종전 ABSOLUTE 하드코딩): {xml}"
2361        );
2362        assert!(
2363            xml.contains(r#"protect="1""#),
2364            "protect 가 IR(size_protect=true)로 방출돼야 함(종전 0 하드코딩): {xml}"
2365        );
2366
2367        // IR 수준 역검증 — 되읽었을 때 값이 그대로 복원돼야 한다.
2368        let back = reparse_shape_common(&xml);
2369        assert_eq!(back.width_criterion, SizeCriterion::Column);
2370        assert_eq!(back.height_criterion, SizeCriterion::Paper);
2371        assert!(back.size_protect);
2372    }
2373
2374    #[test]
2375    fn task2712_line_sz_criteria_and_protect_emitted_from_ir() {
2376        // write_sz 는 rect/line/container/ole 이 공유하므로 선 도형에서도 확인한다.
2377        let mut line = LineShape::default();
2378        line.common.width_criterion = SizeCriterion::Page;
2379        line.common.size_protect = true;
2380        let xml = serialize_line(&line);
2381        assert!(xml.contains(r#"widthRelTo="PAGE""#), "{xml}");
2382        assert!(xml.contains(r#"protect="1""#), "{xml}");
2383    }
2384
2385    #[test]
2386    fn task2712_height_criterion_is_exact_inverse_of_parser() {
2387        // 파서는 높이를 parse_size_criterion(_, allow_column_para=false) 로 읽어
2388        // 치역이 {PAPER, PAGE, ABSOLUTE} 3값뿐이다(section.rs:2904). 방출도 같은 3값으로
2389        // 접어야 왕복이 정확한 역이 된다. Column/Para 를 그대로 내보내면 되읽을 때
2390        // Absolute 로 떨어져 왕복이 깨진다.
2391        assert_eq!(height_criterion_str(SizeCriterion::Paper), "PAPER");
2392        assert_eq!(height_criterion_str(SizeCriterion::Page), "PAGE");
2393        assert_eq!(height_criterion_str(SizeCriterion::Absolute), "ABSOLUTE");
2394        assert_eq!(height_criterion_str(SizeCriterion::Column), "ABSOLUTE");
2395        assert_eq!(height_criterion_str(SizeCriterion::Para), "ABSOLUTE");
2396
2397        // 너비는 5값 전부를 담는다(bit 15-17).
2398        assert_eq!(size_criterion_str(SizeCriterion::Paper), "PAPER");
2399        assert_eq!(size_criterion_str(SizeCriterion::Page), "PAGE");
2400        assert_eq!(size_criterion_str(SizeCriterion::Column), "COLUMN");
2401        assert_eq!(size_criterion_str(SizeCriterion::Para), "PARA");
2402        assert_eq!(size_criterion_str(SizeCriterion::Absolute), "ABSOLUTE");
2403
2404        // 높이에 Column 을 넣어도 방출은 ABSOLUTE 로 접히고, 되읽어도 Absolute 다.
2405        let mut rect = RectangleShape::default();
2406        rect.common.height_criterion = SizeCriterion::Column;
2407        let xml = serialize_rect(&rect);
2408        assert!(xml.contains(r#"heightRelTo="ABSOLUTE""#), "{xml}");
2409        assert_eq!(
2410            reparse_shape_common(&xml).height_criterion,
2411            SizeCriterion::Absolute
2412        );
2413    }
2414
2415    #[test]
2416    fn task2712_shape_sz_defaults_unchanged() {
2417        // 기본 IR(Absolute/Absolute/false)은 종전 출력과 동일해야 한다(무변화 보장).
2418        // 실측상 samples/hwpx 의 hp:rect 309개·hp:pic 188개가 모두 이 조합이다.
2419        let xml = serialize_rect(&RectangleShape::default());
2420        assert!(xml.contains(r#"widthRelTo="ABSOLUTE""#), "{xml}");
2421        assert!(xml.contains(r#"heightRelTo="ABSOLUTE""#), "{xml}");
2422        assert!(xml.contains(r#"protect="0""#), "{xml}");
2423    }
2424
2425    #[test]
2426    fn hatch_style_follows_hancom_hwp_to_hwpx_save() {
2427        // 한컴 2024가 무늬 0~5인 HWP를 HWPX로 저장한 값과 같아야 한다 (#8978).
2428        // 무늬 없음(-1)·범위 밖(6, 99)은 hatchStyle 을 쓰지 않는다.
2429        let expected = [
2430            (0, Some("HORIZONTAL")),
2431            (1, Some("VERTICAL")),
2432            (2, Some("SLASH")),
2433            (3, Some("BACK_SLASH")),
2434            (4, Some("CROSS")),
2435            (5, Some("CROSS_DIAGONAL")),
2436            (6, None),
2437            (99, None),
2438            (-1, None),
2439        ];
2440        for (pattern_type, name) in expected {
2441            let solid = crate::model::style::SolidFill {
2442                background_color: 0x00FF_FFFF,
2443                pattern_color: 0,
2444                pattern_type,
2445            };
2446            assert_eq!(
2447                solid.hatch().map(|h| h.owpml_name()),
2448                name,
2449                "{pattern_type}"
2450            );
2451        }
2452    }
2453
2454    /// [#4669] 재방출 `id` 는 파서가 보존한 원문(hwpx_ole_id)을 되쓰고 `instid`
2455    /// 는 instance_id 를 쓴다 — 원산 파일은 두 값이 다르다(실측 2141242094 /
2456    /// 1067500271). 종전엔 둘 다 instance_id 로 방출돼 id 원문이 유실됐다.
2457    /// curSz=0 센티널(#2017)의 OLE 경로 복원도 함께 고정한다.
2458    #[test]
2459    fn issue4669_write_ole_preserves_original_id_and_cur_sz_zero() {
2460        use crate::model::document::Document;
2461
2462        let doc = Document::default();
2463        let mut ctx = SerializeContext::collect_from_document(&doc);
2464
2465        let mut ole = OleShape::default();
2466        ole.hwpx_ole_id = Some(2141242094);
2467        ole.common.instance_id = 1067500271;
2468        ole.drawing.shape_attr.original_width = 42001;
2469        ole.drawing.shape_attr.original_height = 13501;
2470        ole.drawing.shape_attr.current_width = 42001;
2471        ole.drawing.shape_attr.current_height = 13501;
2472        ole.drawing.shape_attr.current_width_was_zero = true;
2473        ole.drawing.shape_attr.current_height_was_zero = true;
2474
2475        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
2476        write_ole(&mut w, &ole, &mut ctx).expect("write_ole");
2477        let xml = String::from_utf8(w.into_inner()).unwrap();
2478
2479        assert!(xml.contains(r#"id="2141242094""#), "id 원문 보존: {xml}");
2480        assert!(
2481            xml.contains(r#"instid="1067500271""#),
2482            "instid 는 instance_id: {xml}"
2483        );
2484        assert!(
2485            xml.contains(r#"<hp:curSz width="0" height="0"/>"#),
2486            "curSz=0 원문 복원(#2017 센티널): {xml}"
2487        );
2488        assert!(
2489            xml.contains(r#"<hp:orgSz width="42001" height="13501"/>"#),
2490            "orgSz 보존: {xml}"
2491        );
2492    }
2493
2494    /// [#4669] HWP5 출신(hwpx_ole_id=None)은 종전대로 id=instid=instance_id.
2495    #[test]
2496    fn issue4669_write_ole_without_original_id_falls_back_to_instance_id() {
2497        use crate::model::document::Document;
2498
2499        let doc = Document::default();
2500        let mut ctx = SerializeContext::collect_from_document(&doc);
2501
2502        let mut ole = OleShape::default();
2503        ole.common.instance_id = 77;
2504
2505        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
2506        write_ole(&mut w, &ole, &mut ctx).expect("write_ole");
2507        let xml = String::from_utf8(w.into_inner()).unwrap();
2508        assert!(xml.contains(r#"id="77""#), "{xml}");
2509        assert!(xml.contains(r#"instid="77""#), "{xml}");
2510    }
2511
2512    /// [버그] OLE 의 `bin_data_id` 는 HWP5 바이너리상 u32 필드다. 종전 코드는
2513    /// `as u16` 로 상위 비트를 잘라 조회했기 때문에, 65536 이상인 id가 하위 16비트가
2514    /// 같은 *다른* BinData 항목(예: id=5)을 잘못 가리킬 수 있었다. 이 값이 등록된
2515    /// BinData 범위(u16)를 벗어나면 그 어떤 항목도 가리키지 않고 빈 참조로 남아야
2516    /// 한다(오참조 방지).
2517    #[test]
2518    fn ole_bin_data_id_beyond_u16_does_not_alias_truncated_entry() {
2519        use crate::model::bin_data::{BinData, BinDataContent, BinDataType};
2520        use crate::model::document::Document;
2521
2522        let mut doc = Document::default();
2523        // 하위 16비트가 0x10005 와 같은(=5) 정상 BinData 항목을 등록해 둔다.
2524        doc.bin_data_content.push(BinDataContent {
2525            id: 5,
2526            data: vec![0, 1, 2].into(),
2527            extension: "png".to_string(),
2528        });
2529        doc.doc_info.bin_data_list.push(BinData {
2530            data_type: BinDataType::Embedding,
2531            storage_id: 5,
2532            extension: Some("png".to_string()),
2533            ..Default::default()
2534        });
2535        let mut ctx = SerializeContext::collect_from_document(&doc);
2536        // 등록 확인: id=5 는 정상적으로 조회돼야 한다.
2537        assert_eq!(ctx.resolve_bin_id(5), Some("image5"));
2538
2539        let ole = OleShape {
2540            bin_data_id: 0x1_0005, // truncate 시 5 가 되는 값(범위 밖)
2541            drawing_aspect: OleDrawingAspect::Content,
2542            ..Default::default()
2543        };
2544
2545        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
2546        write_ole(&mut w, &ole, &mut ctx).expect("write_ole");
2547        let xml = String::from_utf8(w.into_inner()).unwrap();
2548
2549        assert!(
2550            !xml.contains(r#"binaryItemIDRef="image5""#),
2551            "u32 bin_data_id 가 u16 로 잘려 무관한 image5 를 오참조함: {xml}"
2552        );
2553    }
2554}