use super::section::{
build_secpr_run_with_storage, render_hp_p_open_with_storage,
render_paragraph_parts_with_storage,
};
use super::shape::color_to_hex_with_storage;
use super::table::write_caption_with_storage;
use super::utils::{
empty_tag_with_storage, end_tag_with_storage, start_tag_attrs_with_storage,
start_tag_with_storage, text_with_storage, write_xml_decl_with_storage, xml_error,
xml_escape_with_storage, xml_value,
};
use std::io::Write;
use quick_xml::Writer;
use crate::model::image::{
EffectColor, EffectPoint, EffectRgb, ImageEffect, Picture, PictureShadow,
};
use crate::model::shape::{
CommonObjAttr, HorzAlign, HorzRelTo, ShapeComponentAttr, SizeCriterion, TextFlow, TextWrap,
VertAlign, VertRelTo,
};
use super::context::SerializeContext;
use super::shape::{height_criterion_str, numbering_type_str, size_criterion_str};
use super::table::write_caption;
use super::utils::{empty_tag, end_tag, start_tag, start_tag_attrs};
use super::SerializeError;
pub fn write_picture<W: Write>(
w: &mut Writer<W>,
pic: &Picture,
ctx: &mut SerializeContext,
) -> Result<(), SerializeError> {
write_picture_with_storage(w, pic, ctx, &crate::storage::Unbounded)
}
pub(super) fn write_picture_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
pic: &Picture,
ctx: &mut SerializeContext,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let id_str = xml_value(storage, pic.common.instance_id)?;
let z_order = xml_value(storage, pic.common.z_order)?;
let tw = text_wrap_str(pic.common.text_wrap);
let tf = text_flow_str(pic.common.text_flow);
let instid = xml_value(storage, pic.instance_id)?;
let href = pic.href.as_deref().unwrap_or("");
let reverse = bool01(pic.reverse);
let lock = bool01(pic.lock);
let numbering_type = numbering_type_str(pic.common.numbering_type);
let group_level = xml_value(storage, pic.shape_attr.group_level)?;
start_tag_attrs_with_storage(
w,
"hp:pic",
&[
("id", &id_str),
("zOrder", &z_order),
("numberingType", &numbering_type),
("textWrap", tw),
("textFlow", tf),
("lock", lock),
(
"dropcapstyle",
super::shape::drop_cap_style_str(pic.common.drop_cap_style),
),
("href", href),
("groupLevel", &group_level),
("instid", &instid),
("reverse", reverse),
],
storage,
)?;
super::shape::write_offset_with_storage(w, &pic.shape_attr, storage)?;
write_org_sz_with_storage(w, &pic.shape_attr, storage)?;
write_cur_sz_with_storage(w, pic, storage)?;
write_flip_with_storage(w, &pic.shape_attr, storage)?;
write_rotation_info_with_storage(w, &pic.shape_attr, storage)?;
super::shape::write_rendering_info_with_storage(w, &pic.shape_attr, storage)?;
if pic.border_attr.attr != 0
|| pic.border_color != 0
|| pic.border_width != 0
|| pic.border_attr.outline_style != 0
{
let border = crate::model::style::ShapeBorderLine {
color: pic.border_color,
width: pic.border_width,
..pic.border_attr
};
super::shape::write_line_shape_with_storage(w, &border, storage)?;
}
write_img_rect_with_storage(w, pic, storage)?;
write_img_clip_with_storage(w, pic, storage)?;
write_in_margin_with_storage(w, pic, storage)?;
write_img_dim_with_storage(w, pic, storage)?;
write_img_with_storage(w, pic, ctx, storage)?; write_effects_with_storage(w, pic, storage)?;
write_sz_with_storage(w, &pic.common, storage)?;
write_pos_with_storage(w, &pic.common, storage)?;
write_out_margin_with_storage(w, &pic.common, storage)?;
if let Some(cap) = &pic.caption {
write_caption_with_storage(w, cap, ctx, storage)?;
}
super::shape::write_shape_comment_with_storage(w, &pic.common, storage)?;
end_tag_with_storage(w, "hp:pic", storage)?;
Ok(())
}
fn write_org_sz<W: Write>(
w: &mut Writer<W>,
sa: &ShapeComponentAttr,
) -> Result<(), SerializeError> {
write_org_sz_with_storage(w, sa, &crate::storage::Unbounded)
}
pub(super) fn write_org_sz_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
sa: &ShapeComponentAttr,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let ow = xml_value(storage, sa.original_width)?;
let oh = xml_value(storage, sa.original_height)?;
empty_tag_with_storage(w, "hp:orgSz", &[("width", &ow), ("height", &oh)], storage)
}
fn write_cur_sz<W: Write>(w: &mut Writer<W>, p: &Picture) -> Result<(), SerializeError> {
write_cur_sz_with_storage(w, p, &crate::storage::Unbounded)
}
pub(super) fn write_cur_sz_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
p: &Picture,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let cw = if p.shape_attr.current_width_was_zero {
0
} else if p.shape_attr.current_width > 0 {
p.shape_attr.current_width
} else {
p.common.width
};
let ch = if p.shape_attr.current_height_was_zero {
0
} else if p.shape_attr.current_height > 0 {
p.shape_attr.current_height
} else {
p.common.height
};
empty_tag_with_storage(
w,
"hp:curSz",
&[
("width", &xml_value(storage, cw)?),
("height", &xml_value(storage, ch)?),
],
storage,
)
}
fn write_flip<W: Write>(w: &mut Writer<W>, sa: &ShapeComponentAttr) -> Result<(), SerializeError> {
write_flip_with_storage(w, sa, &crate::storage::Unbounded)
}
pub(super) fn write_flip_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
sa: &ShapeComponentAttr,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let h = bool01(sa.horz_flip);
let v = bool01(sa.vert_flip);
empty_tag_with_storage(w, "hp:flip", &[("horizontal", h), ("vertical", v)], storage)
}
fn write_rotation_info<W: Write>(
w: &mut Writer<W>,
sa: &ShapeComponentAttr,
) -> Result<(), SerializeError> {
write_rotation_info_with_storage(w, sa, &crate::storage::Unbounded)
}
pub(super) fn write_rotation_info_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
sa: &ShapeComponentAttr,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let angle = xml_value(storage, sa.rotation_angle)?;
let cx = xml_value(storage, sa.rotation_center.x)?;
let cy = xml_value(storage, sa.rotation_center.y)?;
let ri = bool01(sa.rotate_image);
empty_tag_with_storage(
w,
"hp:rotationInfo",
&[
("angle", &angle),
("centerX", &cx),
("centerY", &cy),
("rotateimage", ri),
],
storage,
)
}
fn write_img_rect<W: Write>(w: &mut Writer<W>, p: &Picture) -> Result<(), SerializeError> {
write_img_rect_with_storage(w, p, &crate::storage::Unbounded)
}
pub(super) fn write_img_rect_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
p: &Picture,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let bx = &p.border_x;
let by = &p.border_y;
if bx.iter().all(|&v| v == 0) && by.iter().all(|&v| v == 0) {
let w_str = xml_value(storage, p.common.width)?;
let h_str = xml_value(storage, p.common.height)?;
start_tag_with_storage(w, "hp:imgRect", storage)?;
empty_tag_with_storage(w, "hc:pt0", &[("x", "0"), ("y", "0")], storage)?;
empty_tag_with_storage(w, "hc:pt1", &[("x", &w_str), ("y", "0")], storage)?;
empty_tag_with_storage(w, "hc:pt2", &[("x", &w_str), ("y", &h_str)], storage)?;
empty_tag_with_storage(w, "hc:pt3", &[("x", "0"), ("y", &h_str)], storage)?;
end_tag_with_storage(w, "hp:imgRect", storage)?;
return Ok(());
}
let pts = [
(bx[0], bx[1]), (bx[2], bx[3]), (by[0], by[1]), (by[2], by[3]), ];
start_tag_with_storage(w, "hp:imgRect", storage)?;
for (i, (x, y)) in pts.iter().enumerate() {
empty_tag_with_storage(
w,
&xml_value(storage, format_args!("hc:pt{i}"))?,
&[
("x", &xml_value(storage, x)?),
("y", &xml_value(storage, y)?),
],
storage,
)?;
}
end_tag_with_storage(w, "hp:imgRect", storage)?;
Ok(())
}
fn write_img_clip<W: Write>(w: &mut Writer<W>, p: &Picture) -> Result<(), SerializeError> {
write_img_clip_with_storage(w, p, &crate::storage::Unbounded)
}
pub(super) fn write_img_clip_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
p: &Picture,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let l = xml_value(storage, p.crop.left)?;
let r = xml_value(storage, p.crop.right)?;
let t = xml_value(storage, p.crop.top)?;
let b = xml_value(storage, p.crop.bottom)?;
empty_tag_with_storage(
w,
"hp:imgClip",
&[("left", &l), ("right", &r), ("top", &t), ("bottom", &b)],
storage,
)
}
fn write_in_margin<W: Write>(w: &mut Writer<W>, p: &Picture) -> Result<(), SerializeError> {
write_in_margin_with_storage(w, p, &crate::storage::Unbounded)
}
pub(super) fn write_in_margin_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
p: &Picture,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let l = xml_value(storage, p.padding.left)?;
let r = xml_value(storage, p.padding.right)?;
let t = xml_value(storage, p.padding.top)?;
let b = xml_value(storage, p.padding.bottom)?;
empty_tag_with_storage(
w,
"hp:inMargin",
&[("left", &l), ("right", &r), ("top", &t), ("bottom", &b)],
storage,
)
}
fn write_img_dim<W: Write>(w: &mut Writer<W>, p: &Picture) -> Result<(), SerializeError> {
write_img_dim_with_storage(w, p, &crate::storage::Unbounded)
}
pub(super) fn write_img_dim_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
p: &Picture,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
empty_tag_with_storage(
w,
"hp:imgDim",
&[
("dimwidth", &xml_value(storage, p.img_dim.0)?),
("dimheight", &xml_value(storage, p.img_dim.1)?),
],
storage,
)
}
fn write_img<W: Write>(
w: &mut Writer<W>,
p: &Picture,
ctx: &SerializeContext,
) -> Result<(), SerializeError> {
write_img_with_storage(w, p, ctx, &crate::storage::Unbounded)
}
pub(super) fn write_img_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
p: &Picture,
ctx: &SerializeContext,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let bin_id = p.image_attr.bin_data_id;
let manifest_id = match ctx.resolve_bin_id(bin_id) {
Some(id) => id,
None if bin_id == 0 => "",
None => {
return Err(SerializeError::XmlError(xml_value(
storage,
format_args!(
"<hp:pic> binaryItemIDRef 미등록 bin_data_id={} (BinDataContent 누락)",
bin_id
),
)?))
}
};
let bright = xml_value(storage, p.image_attr.brightness)?;
let contrast = xml_value(storage, p.image_attr.contrast)?;
let effect = image_effect_str(p.image_attr.effect);
let alpha = picture_alpha_str_with_storage(p.image_attr.clamped_transparency(), storage)?;
empty_tag_with_storage(
w,
"hc:img",
&[
("binaryItemIDRef", manifest_id),
("bright", &bright),
("contrast", &contrast),
("effect", effect),
("alpha", &alpha),
],
storage,
)
}
fn picture_alpha_str(transparency: u8) -> String {
picture_alpha_str_with_storage(transparency, &crate::storage::Unbounded)
.expect("unbounded XML writer")
}
pub(super) fn picture_alpha_str_with_storage<S: crate::storage::Storage>(
transparency: u8,
storage: &S,
) -> Result<String, SerializeError>
where
S::Error: std::fmt::Display,
{
xml_value(
storage,
crate::model::image::transparency_percent_to_alpha_byte(transparency),
)
}
fn write_effects<W: Write>(w: &mut Writer<W>, pic: &Picture) -> Result<(), SerializeError> {
write_effects_with_storage(w, pic, &crate::storage::Unbounded)
}
pub(super) fn write_effects_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
pic: &Picture,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
start_tag_with_storage(w, "hp:effects", storage)?;
if let Some(shadow) = &pic.effects.shadow {
write_shadow_with_storage(w, shadow, storage)?;
}
end_tag_with_storage(w, "hp:effects", storage)?;
Ok(())
}
fn write_shadow<W: Write>(w: &mut Writer<W>, shadow: &PictureShadow) -> Result<(), SerializeError> {
write_shadow_with_storage(w, shadow, &crate::storage::Unbounded)
}
pub(super) fn write_shadow_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
shadow: &PictureShadow,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let mut attrs = Vec::new();
push_opt_attr_with_storage(&mut attrs, "style", shadow.style.as_deref(), storage)?;
push_opt_attr_with_storage(&mut attrs, "alpha", shadow.alpha.as_deref(), storage)?;
push_opt_attr_with_storage(&mut attrs, "radius", shadow.radius.as_deref(), storage)?;
push_opt_attr_with_storage(
&mut attrs,
"direction",
shadow.direction.as_deref(),
storage,
)?;
push_opt_attr_with_storage(&mut attrs, "distance", shadow.distance.as_deref(), storage)?;
push_opt_attr_with_storage(
&mut attrs,
"alignStyle",
shadow.align_style.as_deref(),
storage,
)?;
push_opt_attr_with_storage(
&mut attrs,
"rotationStyle",
shadow.rotation_style.as_deref(),
storage,
)?;
start_tag_attrs_with_storage(w, "hp:shadow", &attrs, storage)?;
if let Some(skew) = &shadow.skew {
write_effect_point_with_storage(w, "hp:skew", skew, storage)?;
}
if let Some(scale) = &shadow.scale {
write_effect_point_with_storage(w, "hp:scale", scale, storage)?;
}
if let Some(color) = &shadow.color {
write_effect_color_with_storage(w, color, storage)?;
}
end_tag_with_storage(w, "hp:shadow", storage)?;
Ok(())
}
fn write_effect_point<W: Write>(
w: &mut Writer<W>,
name: &str,
point: &EffectPoint,
) -> Result<(), SerializeError> {
write_effect_point_with_storage(w, name, point, &crate::storage::Unbounded)
}
pub(super) fn write_effect_point_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
name: &str,
point: &EffectPoint,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let mut attrs = Vec::new();
push_opt_attr_with_storage(&mut attrs, "x", point.x.as_deref(), storage)?;
push_opt_attr_with_storage(&mut attrs, "y", point.y.as_deref(), storage)?;
empty_tag_with_storage(w, name, &attrs, storage)
}
fn write_effect_color<W: Write>(
w: &mut Writer<W>,
color: &EffectColor,
) -> Result<(), SerializeError> {
write_effect_color_with_storage(w, color, &crate::storage::Unbounded)
}
pub(super) fn write_effect_color_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
color: &EffectColor,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let mut attrs = Vec::new();
push_opt_attr_with_storage(&mut attrs, "type", color.color_type.as_deref(), storage)?;
push_opt_attr_with_storage(
&mut attrs,
"schemeIdx",
color.scheme_idx.as_deref(),
storage,
)?;
push_opt_attr_with_storage(
&mut attrs,
"systemIdx",
color.system_idx.as_deref(),
storage,
)?;
push_opt_attr_with_storage(
&mut attrs,
"presetIdx",
color.preset_idx.as_deref(),
storage,
)?;
if let Some(rgb) = &color.rgb {
start_tag_attrs_with_storage(w, "hp:effectsColor", &attrs, storage)?;
write_effect_rgb_with_storage(w, rgb, storage)?;
end_tag_with_storage(w, "hp:effectsColor", storage)?;
} else {
empty_tag_with_storage(w, "hp:effectsColor", &attrs, storage)?;
}
Ok(())
}
fn write_effect_rgb<W: Write>(w: &mut Writer<W>, rgb: &EffectRgb) -> Result<(), SerializeError> {
write_effect_rgb_with_storage(w, rgb, &crate::storage::Unbounded)
}
pub(super) fn write_effect_rgb_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
rgb: &EffectRgb,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let mut attrs = Vec::new();
push_opt_attr_with_storage(&mut attrs, "r", rgb.r.as_deref(), storage)?;
push_opt_attr_with_storage(&mut attrs, "g", rgb.g.as_deref(), storage)?;
push_opt_attr_with_storage(&mut attrs, "b", rgb.b.as_deref(), storage)?;
empty_tag_with_storage(w, "hp:rgb", &attrs, storage)
}
fn push_opt_attr<'a>(
attrs: &mut Vec<(&'static str, &'a str)>,
key: &'static str,
value: Option<&'a str>,
) {
push_opt_attr_with_storage(attrs, key, value, &crate::storage::Unbounded)
.expect("unbounded XML writer")
}
pub(super) fn push_opt_attr_with_storage<'a, S: crate::storage::Storage>(
attrs: &mut Vec<(&'static str, &'a str)>,
key: &'static str,
value: Option<&'a str>,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
if let Some(value) = value {
storage.push(attrs, (key, value)).map_err(xml_error)?;
}
Ok(())
}
fn write_sz<W: Write>(w: &mut Writer<W>, c: &CommonObjAttr) -> Result<(), SerializeError> {
write_sz_with_storage(w, c, &crate::storage::Unbounded)
}
pub(super) fn write_sz_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
c: &CommonObjAttr,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let width = xml_value(storage, c.width)?;
let height = xml_value(storage, c.height)?;
empty_tag_with_storage(
w,
"hp:sz",
&[
("width", &width),
("widthRelTo", size_criterion_str(c.width_criterion)),
("height", &height),
("heightRelTo", height_criterion_str(c.height_criterion)),
("protect", bool01(c.size_protect)),
],
storage,
)
}
fn write_pos<W: Write>(w: &mut Writer<W>, c: &CommonObjAttr) -> Result<(), SerializeError> {
write_pos_with_storage(w, c, &crate::storage::Unbounded)
}
pub(super) fn write_pos_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
c: &CommonObjAttr,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let treat = bool01(c.treat_as_char);
let flow_with_text = bool01(c.flow_with_text);
let allow_overlap = bool01(c.allow_overlap);
let vert_offset = xml_value(storage, c.vertical_offset)?;
let horz_offset = xml_value(storage, c.horizontal_offset)?;
let hold = bool01(c.prevent_page_break != 0); empty_tag_with_storage(
w,
"hp:pos",
&[
("treatAsChar", treat),
("affectLSpacing", bool01(c.affect_line_spacing)),
("flowWithText", flow_with_text),
("allowOverlap", allow_overlap),
("holdAnchorAndSO", hold),
("vertRelTo", vert_rel_to_str(c.vert_rel_to)),
("horzRelTo", horz_rel_to_str(c.horz_rel_to)),
("vertAlign", vert_align_str(c.vert_align)),
("horzAlign", horz_align_str(c.horz_align)),
("vertOffset", &vert_offset),
("horzOffset", &horz_offset),
],
storage,
)
}
fn write_out_margin<W: Write>(w: &mut Writer<W>, c: &CommonObjAttr) -> Result<(), SerializeError> {
write_out_margin_with_storage(w, c, &crate::storage::Unbounded)
}
pub(super) fn write_out_margin_with_storage<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
c: &CommonObjAttr,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let l = xml_value(storage, c.margin.left)?;
let r = xml_value(storage, c.margin.right)?;
let t = xml_value(storage, c.margin.top)?;
let b = xml_value(storage, c.margin.bottom)?;
empty_tag_with_storage(
w,
"hp:outMargin",
&[("left", &l), ("right", &r), ("top", &t), ("bottom", &b)],
storage,
)
}
fn bool01(b: bool) -> &'static str {
if b {
"1"
} else {
"0"
}
}
fn text_wrap_str(w: TextWrap) -> &'static str {
use TextWrap::*;
match w {
Square => "SQUARE",
Tight => "TIGHT",
Through => "THROUGH",
TopAndBottom => "TOP_AND_BOTTOM",
BehindText => "BEHIND_TEXT",
InFrontOfText => "IN_FRONT_OF_TEXT",
}
}
fn text_flow_str(f: TextFlow) -> &'static str {
match f {
TextFlow::BothSides => "BOTH_SIDES",
TextFlow::LeftOnly => "LEFT_ONLY",
TextFlow::RightOnly => "RIGHT_ONLY",
TextFlow::LargestOnly => "LARGEST_ONLY",
}
}
fn vert_rel_to_str(v: VertRelTo) -> &'static str {
use VertRelTo::*;
match v {
Paper => "PAPER",
Page => "PAGE",
Para => "PARA",
}
}
fn horz_rel_to_str(h: HorzRelTo) -> &'static str {
use HorzRelTo::*;
match h {
Paper => "PAPER",
Page => "PAGE",
Column => "COLUMN",
Para => "PARA",
}
}
fn vert_align_str(v: VertAlign) -> &'static str {
use VertAlign::*;
match v {
Top => "TOP",
Center => "CENTER",
Bottom => "BOTTOM",
Inside => "INSIDE",
Outside => "OUTSIDE",
}
}
fn horz_align_str(h: HorzAlign) -> &'static str {
use HorzAlign::*;
match h {
Left => "LEFT",
Center => "CENTER",
Right => "RIGHT",
Inside => "INSIDE",
Outside => "OUTSIDE",
}
}
fn image_effect_str(e: ImageEffect) -> &'static str {
use ImageEffect::*;
match e {
RealPic => "REAL_PIC",
GrayScale => "GRAY_SCALE",
BlackWhite => "BLACK_WHITE",
Pattern8x8 => "PATTERN_8_8",
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::bin_data::BinDataContent;
use crate::model::document::Document;
use crate::model::image::{
EffectColor, EffectPoint, EffectRgb, ImageAttr, Picture, PictureEffects, PictureShadow,
};
use crate::serializer::hwpx::context::SerializeContext;
fn make_picture(bin_data_id: u16) -> Picture {
let mut pic = Picture::default();
pic.image_attr = ImageAttr {
bin_data_id,
brightness: 0,
contrast: 0,
effect: ImageEffect::RealPic,
transparency: 0,
external_path: None,
};
pic.common.width = 1000;
pic.common.height = 500;
pic
}
fn make_doc_with_bin(bin_data_id: u16, ext: &str) -> Document {
let mut doc = Document::default();
doc.bin_data_content.push(BinDataContent {
id: bin_data_id,
data: vec![0u8; 4].into(),
extension: ext.to_string(),
});
doc
}
fn serialize(pic: &Picture, ctx: &mut SerializeContext) -> String {
let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
write_picture(&mut w, pic, ctx).expect("write_picture");
String::from_utf8(w.into_inner()).unwrap()
}
#[test]
fn issue2875_pic_lock_is_preserved_on_serialize() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1);
pic.lock = true;
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains(r#"lock="1""#),
"hp:pic lock=1 이 저장 시 보존돼야 한다: {xml}"
);
}
#[test]
fn task1389_cur_sz_uses_shape_attr() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1); pic.shape_attr.current_width = 1366;
pic.shape_attr.current_height = 1268;
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains(r#"<hp:curSz width="1366" height="1268"/>"#),
"curSz 는 shape_attr.current 사용(sz 아님): {xml}"
);
}
#[test]
fn dropcapstyle_round_trips_instead_of_always_none() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1);
pic.common.drop_cap_style = crate::model::shape::DropCapStyle::TripleLine;
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains(r#"dropcapstyle="TripleLine""#),
"dropcapstyle 는 원본 값을 보존해야 한다(하드코딩 \"None\" 아님): {xml}"
);
}
#[test]
fn task1389_cur_sz_falls_back_to_common_when_zero() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let pic = make_picture(1); let xml = serialize(&pic, &mut ctx);
assert!(xml.contains(r#"<hp:curSz width="1000" height="500"/>"#));
}
#[test]
fn task1389_img_rect_uses_border_scalar_layout() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1);
pic.border_x = [0, 0, 49380, 0];
pic.border_y = [49380, 45840, 0, 45840];
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains(
r#"<hp:imgRect><hc:pt0 x="0" y="0"/><hc:pt1 x="49380" y="0"/><hc:pt2 x="49380" y="45840"/><hc:pt3 x="0" y="45840"/></hp:imgRect>"#
),
"imgRect 는 border 스칼라 레이아웃 역매핑: {xml}"
);
}
#[test]
fn issue1452_img_alpha_uses_hwp_alpha_byte() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1);
pic.image_attr.transparency = 50;
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains(r#"alpha="127""#),
"그림 투명도 50%는 한컴 HWPX alpha byte 127로 저장되어야 한다: {xml}"
);
pic.image_attr.transparency = 100;
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains(r#"alpha="255""#),
"그림 투명도 100%는 한컴 HWPX alpha byte 255로 저장되어야 한다: {xml}"
);
}
#[test]
fn issue2861_pic_reverse_is_preserved_on_serialize() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1);
pic.reverse = true;
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains(r#"reverse="1""#),
"hp:pic reverse=1 이 저장 시 보존돼야 한다: {xml}"
);
}
#[test]
fn task1389_img_rect_synthesizes_when_border_zero() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let pic = make_picture(1); let xml = serialize(&pic, &mut ctx);
assert!(xml.contains(r#"<hc:pt2 x="1000" y="500"/>"#), "{xml}");
}
#[test]
fn task1389_img_dim_verbatim() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1);
pic.img_dim = (49380, 45840);
pic.crop.right = 99999;
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains(r#"<hp:imgDim dimwidth="49380" dimheight="45840"/>"#),
"imgDim 은 IR verbatim (clip 파생 금지): {xml}"
);
}
#[test]
fn task1392_pic_shape_comment_emitted_after_caption() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1);
pic.common.description = "그림입니다.".to_string();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "캡션".to_string();
let mut cap = crate::model::shape::Caption::default();
cap.paragraphs.push(para);
pic.caption = Some(cap);
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains("<hp:shapeComment>그림입니다.</hp:shapeComment>"),
"shapeComment 방출: {xml}"
);
let cp = xml.find("<hp:caption").unwrap();
let sc = xml.find("<hp:shapeComment").unwrap();
assert!(cp < sc, "caption 이 shapeComment 보다 먼저");
}
#[test]
fn task1392_pic_no_description_omits_comment() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let pic = make_picture(1); let xml = serialize(&pic, &mut ctx);
assert!(!xml.contains("<hp:shapeComment"), "빈 설명은 미방출: {xml}");
}
#[test]
fn pic_root_attrs_in_canonical_order() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let pic = make_picture(1);
let xml = serialize(&pic, &mut ctx);
assert!(xml.contains("<hp:pic "));
let ip = xml.find("id=").unwrap();
let zp = xml.find("zOrder=").unwrap();
let nt = xml.find("numberingType=").unwrap();
let tw = xml.find("textWrap=").unwrap();
let href = xml.find("href=").unwrap();
let rev = xml.find("reverse=").unwrap();
assert!(ip < zp && zp < nt && nt < tw && tw < href && href < rev);
}
#[test]
fn img_uses_manifest_id() {
let doc = make_doc_with_bin(5, "jpg");
let mut ctx = SerializeContext::collect_from_document(&doc);
let pic = make_picture(5);
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains(r#"binaryItemIDRef="image5""#),
"binaryItemIDRef must resolve to manifest id image5 (숫자 불변식): {}",
xml
);
}
#[test]
fn task1567_empty_binary_ref_pic_preserved() {
let doc = Document::default(); let mut ctx = SerializeContext::collect_from_document(&doc);
let pic = make_picture(0);
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains(r#"binaryItemIDRef="""#),
"빈 ref pic 은 binaryItemIDRef=\"\" 로 보존(드롭 금지): {xml}"
);
assert!(xml.contains("<hp:pic "), "pic 컨트롤 자체 보존: {xml}");
}
#[test]
fn shape_component_attrs_are_serialized() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1);
pic.shape_attr.original_width = 23456;
pic.shape_attr.original_height = 12345;
pic.shape_attr.horz_flip = true;
pic.shape_attr.vert_flip = true;
pic.shape_attr.rotation_angle = 34;
pic.shape_attr.rotation_center.x = 11700;
pic.shape_attr.rotation_center.y = 14794;
pic.shape_attr.rotate_image = true;
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains(r#"<hp:orgSz width="23456" height="12345"/>"#),
"orgSz must use ShapeComponentAttr values: {}",
xml
);
assert!(
xml.contains(r#"<hp:flip horizontal="1" vertical="1"/>"#),
"flip must use ShapeComponentAttr values: {}",
xml
);
assert!(
xml.contains(
r#"<hp:rotationInfo angle="34" centerX="11700" centerY="14794" rotateimage="1"/>"#
),
"rotationInfo must use ShapeComponentAttr values: {}",
xml
);
}
#[test]
fn unresolved_bin_data_id_errors() {
let doc = Document::default(); let mut ctx = SerializeContext::collect_from_document(&doc);
let pic = make_picture(99); let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
let err = write_picture(&mut w, &pic, &mut ctx).unwrap_err();
let msg = format!("{}", err);
assert!(msg.contains("binaryItemIDRef"), "error msg: {}", msg);
assert!(
msg.contains("99"),
"error should include bin_data_id: {}",
msg
);
}
#[test]
fn rendering_info_has_three_matrices() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let pic = make_picture(1);
let xml = serialize(&pic, &mut ctx);
assert!(xml.contains("<hc:transMatrix "));
assert!(xml.contains("<hc:scaMatrix "));
assert!(xml.contains("<hc:rotMatrix "));
}
#[test]
fn img_rect_has_four_points() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let pic = make_picture(1);
let xml = serialize(&pic, &mut ctx);
assert!(xml.contains("<hc:pt0 "));
assert!(xml.contains("<hc:pt1 "));
assert!(xml.contains("<hc:pt2 "));
assert!(xml.contains("<hc:pt3 "));
}
#[test]
fn image_effect_maps_to_string() {
assert_eq!(image_effect_str(ImageEffect::RealPic), "REAL_PIC");
assert_eq!(image_effect_str(ImageEffect::GrayScale), "GRAY_SCALE");
assert_eq!(image_effect_str(ImageEffect::BlackWhite), "BLACK_WHITE");
}
#[test]
fn picture_effects_shadow_are_serialized() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1);
pic.effects = PictureEffects {
shadow: Some(PictureShadow {
style: Some("OUTSIDE".to_string()),
alpha: Some("0.8".to_string()),
radius: Some("400".to_string()),
direction: Some("45".to_string()),
distance: Some("1000".to_string()),
align_style: Some("TOP_LEFT".to_string()),
rotation_style: Some("0".to_string()),
skew: None,
scale: Some(EffectPoint {
x: Some("1".to_string()),
y: Some("1".to_string()),
}),
color: Some(EffectColor {
color_type: Some("RGB".to_string()),
scheme_idx: Some("-1".to_string()),
system_idx: Some("-1".to_string()),
preset_idx: Some("-1".to_string()),
rgb: Some(EffectRgb {
r: Some("0".to_string()),
g: Some("0".to_string()),
b: Some("0".to_string()),
}),
}),
}),
};
let xml = serialize(&pic, &mut ctx);
assert!(xml.contains(r#"<hp:shadow style="OUTSIDE" alpha="0.8" radius="400" direction="45" distance="1000" alignStyle="TOP_LEFT" rotationStyle="0">"#));
assert!(xml.contains(r#"<hp:scale x="1" y="1"/>"#));
assert!(xml.contains(
r#"<hp:effectsColor type="RGB" schemeIdx="-1" systemIdx="-1" presetIdx="-1">"#
));
assert!(xml.contains(r#"<hp:rgb r="0" g="0" b="0"/>"#));
}
#[test]
fn task1403_pic_caption_is_serialized() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1);
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "그림 캡션".to_string();
let mut cap = crate::model::shape::Caption::default();
cap.width = 8504;
cap.spacing = 850;
cap.max_width = 48081;
cap.paragraphs.push(para);
pic.caption = Some(cap);
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains(
r#"<hp:caption side="BOTTOM" fullSz="0" width="8504" gap="850" lastWidth="48081">"#
),
"caption 속성이 IR 값으로 방출되어야 함: {}",
xml
);
assert!(
xml.contains("<hp:t>그림 캡션</hp:t>"),
"캡션 subList 문단 텍스트가 방출되어야 함: {}",
xml
);
let om = xml.find("<hp:outMargin").unwrap();
let cp = xml.find("<hp:caption").unwrap();
assert!(om < cp, "caption 은 outMargin 뒤 (한컴 실물 순서)");
}
#[test]
fn task1403_pic_without_caption_emits_none() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let pic = make_picture(1);
let xml = serialize(&pic, &mut ctx);
assert!(!xml.contains("<hp:caption"), "캡션 부재 시 미방출: {}", xml);
}
fn reparse_pic_common(fragment: &str) -> CommonObjAttr {
let xml = format!(
concat!(
r#"<?xml version="1.0" encoding="UTF-8"?>"#,
r#"<hs:sec xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph""#,
r#" xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section">"#,
r#"<hp:p id="0" paraPrIDRef="0" styleIDRef="0">"#,
r#"<hp:run charPrIDRef="0">{}<hp:t/></hp:run></hp:p></hs:sec>"#
),
fragment
);
let section = crate::parser::hwpx::section::parse_hwpx_section(&xml)
.expect("파싱 가능한 그림 조각이어야 함");
match §ion.paragraphs[0].controls[0] {
crate::model::control::Control::Picture(p) => p.common.clone(),
other => panic!("그림 컨트롤이어야 함: {other:?}"),
}
}
#[test]
fn task2712_pic_sz_criteria_and_protect_emitted_from_ir() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1);
pic.common.width_criterion = SizeCriterion::Column;
pic.common.height_criterion = SizeCriterion::Page;
pic.common.size_protect = true;
let xml = serialize(&pic, &mut ctx);
assert!(
xml.contains(r#"widthRelTo="COLUMN""#),
"widthRelTo 가 IR(Column)로 방출돼야 함(종전 ABSOLUTE 하드코딩): {xml}"
);
assert!(
xml.contains(r#"heightRelTo="PAGE""#),
"heightRelTo 가 IR(Page)로 방출돼야 함(종전 ABSOLUTE 하드코딩): {xml}"
);
assert!(
xml.contains(r#"protect="1""#),
"protect 가 IR(size_protect=true)로 방출돼야 함(종전 0 하드코딩): {xml}"
);
}
#[test]
fn task2712_pic_sz_round_trips_through_parser() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1);
pic.common.width_criterion = SizeCriterion::Para;
pic.common.height_criterion = SizeCriterion::Paper;
pic.common.size_protect = true;
let xml = serialize(&pic, &mut ctx);
let back = reparse_pic_common(&xml);
assert_eq!(
back.width_criterion,
SizeCriterion::Para,
"그림 widthRelTo 가 IR 로 되읽혀야 함"
);
assert_eq!(
back.height_criterion,
SizeCriterion::Paper,
"그림 heightRelTo 가 IR 로 되읽혀야 함"
);
assert!(back.size_protect, "그림 protect 가 IR 로 되읽혀야 함");
}
#[test]
fn task2712_pic_height_criterion_is_exact_inverse() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let mut pic = make_picture(1);
pic.common.height_criterion = SizeCriterion::Para;
let xml = serialize(&pic, &mut ctx);
assert!(xml.contains(r#"heightRelTo="ABSOLUTE""#), "{xml}");
assert_eq!(
reparse_pic_common(&xml).height_criterion,
SizeCriterion::Absolute
);
}
#[test]
fn task2712_pic_sz_defaults_unchanged() {
let doc = make_doc_with_bin(1, "png");
let mut ctx = SerializeContext::collect_from_document(&doc);
let xml = serialize(&make_picture(1), &mut ctx);
assert!(xml.contains(r#"widthRelTo="ABSOLUTE""#), "{xml}");
assert!(xml.contains(r#"heightRelTo="ABSOLUTE""#), "{xml}");
assert!(xml.contains(r#"protect="0""#), "{xml}");
}
}