1#![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
45pub 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 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 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 ("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 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 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 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 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
142fn 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
162pub 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 ("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_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 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 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 if let Some(cap) = &line.drawing.caption {
325 write_caption_with_storage(w, cap, ctx, storage)?;
326 }
327 write_shape_comment_with_storage(w, c, storage)?;
329
330 end_tag_with_storage(w, tag, storage)?;
331 Ok(())
332}
333
334pub 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 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 ("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_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
401pub 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 write_shape_comment_with_storage(w, common, storage)?;
430 end_tag_with_storage(w, "hp:container", storage)
431}
432
433pub(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 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 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 let lock = if c.locked { "1" } else { "0" };
486 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 ("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 write_shape_component_block_with_storage(w, &ole.drawing.shape_attr, storage)?;
516 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
533pub(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
563const 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 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
657pub 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 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 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
778pub(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 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 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 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
969pub(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
1050fn 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
1108pub(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 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
1188fn 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
1205fn arrow_size_str(v: u32) -> &'static str {
1207 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
1223pub(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
1279pub(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 => 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", >ype),
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 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 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 match ctx.resolve_bin_id(img.bin_data_id) {
1382 Some(manifest_id) => {
1383 start_tag_attrs(w, "hc:imgBrush", &[("mode", mode)], storage)?;
1384 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
1419fn 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
1430pub(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
1475fn 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
1504pub(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
1530fn 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 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
1569pub(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
1582pub(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); empty_tag_with_storage(
1612 w,
1613 "hp:pos",
1614 &[
1615 ("treatAsChar", treat),
1616 ("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
1657pub(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
1692pub(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 #[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 #[test]
1835 fn task1531_line_shape_none_preserved() {
1836 assert_eq!(line_shape_style(0), "NONE"); assert_eq!(line_shape_style(1), "SOLID"); assert_eq!(line_shape_style(2), "DOT"); let none_with_flat_end_cap = 1 << 6;
1840 assert_eq!(line_shape_style(none_with_flat_end_cap), "NONE");
1841 }
1842
1843 #[test]
1846 fn task2956_line_shape_arrow_style_preserved() {
1847 use crate::model::style::ShapeBorderLine;
1848 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 #[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 #[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 #[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 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 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 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 assert!(xml.contains("<hp:offset "), "컴포넌트 블록: {xml}");
1984 assert!(xml.contains("<hp:lineShape "), "lineShape: {xml}");
1985 }
1986
1987 #[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 #[test]
2037 fn task1379_drawtext_paragraph_emits_picture_control() {
2038 let mut p = Paragraph::default();
2040 p.char_count = 9; {
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 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; 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 #[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 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 let mut rect = RectangleShape::default();
2170 rect.drawing.border_line.color = 0; rect.drawing.border_line.width = 33;
2172 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, 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 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 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 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 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 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 §ion.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 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 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 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 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 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 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 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 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 #[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 #[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 #[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 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 assert_eq!(ctx.resolve_bin_id(5), Some("image5"));
2538
2539 let ole = OleShape {
2540 bin_data_id: 0x1_0005, 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}