use std::io::Write;
use quick_xml::Writer;
use crate::model::document::{DocInfo, DocProperties, Document};
use crate::model::style::{
border_width_mm_str, para_line_wrap_str, Alignment, BorderFill, BorderLine, BorderLineType,
CenterLine, CharShape, DiagonalLine, FillType, Font, HeadType, LineSpacingType, Numbering,
ParaShape, Style, SubstFont, TabDef,
};
use crate::model::ColorRef;
use crate::parser::tags;
use super::canonical_defaults::FONTFACE_LANG_NAMES;
use super::context::SerializeContext;
use super::utils::{
empty_tag_with_storage as empty_tag, end_tag_with_storage as end_tag,
start_tag_attrs_with_storage as start_tag_attrs, start_tag_with_storage as start_tag,
text_with_storage as text, write_xml_decl_with_storage as write_xml_decl, xml_error, xml_value,
};
use super::SerializeError;
pub fn write_header(doc: &Document, ctx: &SerializeContext) -> Result<Vec<u8>, SerializeError> {
write_header_with_storage(doc, ctx, &crate::storage::Unbounded)
}
pub(crate) fn write_header_with_storage<S: crate::storage::Storage>(
doc: &Document,
ctx: &SerializeContext,
storage: &S,
) -> Result<Vec<u8>, SerializeError>
where
S::Error: std::fmt::Display,
{
let mut w = Writer::new(crate::serializer::budget_cursor::BudgetCursor::new(
storage,
usize::MAX,
));
write_xml_decl(&mut w, storage)?;
let sec_cnt = xml_value(storage, doc.sections.len().max(1))?;
let hwpml_version = doc.doc_info.hwpml_version.as_deref().unwrap_or("1.2");
start_tag_attrs(
&mut w,
"hh:head",
&[
("xmlns:ha", "http://www.hancom.co.kr/hwpml/2011/app"),
("xmlns:hp", "http://www.hancom.co.kr/hwpml/2011/paragraph"),
("xmlns:hp10", "http://www.hancom.co.kr/hwpml/2016/paragraph"),
("xmlns:hs", "http://www.hancom.co.kr/hwpml/2011/section"),
("xmlns:hc", "http://www.hancom.co.kr/hwpml/2011/core"),
("xmlns:hh", "http://www.hancom.co.kr/hwpml/2011/head"),
("xmlns:hhs", "http://www.hancom.co.kr/hwpml/2011/history"),
("xmlns:hm", "http://www.hancom.co.kr/hwpml/2011/master-page"),
("xmlns:dc", "http://purl.org/dc/elements/1.1/"),
("xmlns:opf", "http://www.idpf.org/2007/opf/"),
("xmlns:epub", "http://www.idpf.org/2007/ops"),
(
"xmlns:ooxmlchart",
"http://www.hancom.co.kr/hwpml/2016/ooxmlchart",
),
(
"xmlns:hwpunitchar",
"http://www.hancom.co.kr/hwpml/2016/HwpUnitChar",
),
("xmlns:hpf", "http://www.hancom.co.kr/schema/2011/hpf"),
(
"xmlns:config",
"urn:oasis:names:tc:opendocument:xmlns:config:1.0",
),
("version", hwpml_version),
("secCnt", &sec_cnt),
],
storage,
)?;
write_begin_num(&mut w, &doc.doc_properties, storage)?;
start_tag(&mut w, "hh:refList", storage)?;
write_fontfaces(&mut w, &doc.doc_info, ctx, storage)?;
write_border_fills(&mut w, &doc.doc_info, ctx, storage)?;
write_char_properties(&mut w, &doc.doc_info, ctx, storage)?;
write_tab_properties(&mut w, &doc.doc_info, storage)?;
write_numberings(&mut w, &doc.doc_info, storage)?;
write_bullets(&mut w, &doc.doc_info, ctx, storage)?;
write_para_properties(
&mut w,
&doc.doc_info,
ctx,
doc.hwpx_aux_entry("version.xml")
.and_then(|bytes| std::str::from_utf8(bytes).ok())
.is_none_or(crate::parser::hwpx::physical_para_margin_units_from_version),
storage,
)?;
write_styles(&mut w, &doc.doc_info, ctx, storage)?;
let memo_shapes = crate::model::memo_shape::memo_shapes(&doc.doc_info);
let memo_properties = match &doc.doc_info.memo_properties_xml {
Some(original) => Some(std::borrow::Cow::Borrowed(original.as_str())),
None if !memo_shapes.is_empty() => Some(std::borrow::Cow::Owned(
crate::model::memo_shape::memo_properties_xml(&memo_shapes),
)),
None => None,
};
if let Some(memo_properties) = memo_properties {
w.get_mut()
.write_all(memo_properties.as_bytes())
.map_err(|e| SerializeError::XmlError(format!("memoProperties splice: {e}")))?;
}
end_tag(&mut w, "hh:refList", storage)?;
match &doc.doc_info.hwpx_head_tail {
Some(tail) => {
w.get_mut()
.write_all(tail.as_bytes())
.map_err(|e| SerializeError::XmlError(format!("head tail splice: {e}")))?;
}
None => {
write_compatible_document(&mut w, storage)?;
write_doc_option(&mut w, storage)?;
write_track_change_config(&mut w, doc.doc_info.track_change_flags(), storage)?;
}
}
end_tag(&mut w, "hh:head", storage)?;
Ok(w.into_inner().into_inner())
}
fn write_begin_num<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
props: &DocProperties,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
empty_tag(
w,
"hh:beginNum",
&[
("page", &xml_value(storage, props.page_start_num.max(1))?),
(
"footnote",
&xml_value(storage, props.footnote_start_num.max(1))?,
),
(
"endnote",
&xml_value(storage, props.endnote_start_num.max(1))?,
),
("pic", &xml_value(storage, props.picture_start_num.max(1))?),
("tbl", &xml_value(storage, props.table_start_num.max(1))?),
(
"equation",
&xml_value(storage, props.equation_start_num.max(1))?,
),
],
storage,
)
}
fn write_fontfaces<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
doc_info: &DocInfo,
ctx: &SerializeContext,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let groups: [&Vec<Font>; 7] =
std::array::from_fn(|i| doc_info.font_faces.get(i).unwrap_or(&EMPTY_FONT_VEC));
let item_cnt = groups.iter().filter(|g| !g.is_empty()).count();
if item_cnt == 0 {
return Ok(());
}
start_tag_attrs(
w,
"hh:fontfaces",
&[(
"itemCnt",
&xml_value(storage, groups.iter().filter(|g| !g.is_empty()).count())?,
)],
storage,
)?;
for (lang_idx, fonts) in groups.iter().enumerate() {
if fonts.is_empty() {
continue;
}
let lang = FONTFACE_LANG_NAMES[lang_idx];
start_tag_attrs(
w,
"hh:fontface",
&[
("lang", lang),
("fontCnt", &xml_value(storage, fonts.len())?),
],
storage,
)?;
for (id, font) in fonts.iter().enumerate() {
let id_str = xml_value(storage, id)?;
let binary_item_id_ref = resolve_font_binary_item_id_ref(
ctx,
font.resolved_bin_data_id,
&font.bin_item_id_ref,
&font.name,
storage,
)?;
let font_attrs = [
("id", id_str.as_str()),
("face", font.name.as_str()),
("type", font_type_str(font.alt_type)),
("isEmbedded", if font.is_embedded { "1" } else { "0" }),
("binaryItemIDRef", binary_item_id_ref.as_str()),
];
let font_attrs = &font_attrs[..if binary_item_id_ref.is_empty() { 4 } else { 5 }];
if font.subst_font.is_some() || font.type_info.is_some() {
start_tag_attrs(w, "hh:font", font_attrs, storage)?;
if let Some(sf) = &font.subst_font {
write_subst_font(w, sf, ctx, storage)?;
}
if let Some(ti) = &font.type_info {
write_font_type_info(w, ti, storage)?;
}
end_tag(w, "hh:font", storage)?;
} else {
empty_tag(w, "hh:font", font_attrs, storage)?;
}
}
end_tag(w, "hh:fontface", storage)?;
}
end_tag(w, "hh:fontfaces", storage)?;
Ok(())
}
static EMPTY_FONT_VEC: Vec<Font> = Vec::new();
fn resolve_font_binary_item_id_ref<S: crate::storage::Storage>(
ctx: &SerializeContext,
resolved_bin_data_id: Option<u16>,
original_ref: &str,
font_name: &str,
storage: &S,
) -> Result<String, SerializeError>
where
S::Error: std::fmt::Display,
{
let value = match resolved_bin_data_id {
Some(id) => ctx.resolve_bin_id(id).ok_or_else(|| {
SerializeError::XmlError(format!(
"embedded font `{font_name}` references missing BinData id {id}"
))
})?,
None => original_ref,
};
xml_value(storage, value)
}
fn font_type_str(alt_type: u8) -> &'static str {
match alt_type {
1 => "TTF",
2 => "HFT",
_ => "TTF", }
}
fn write_font_type_info<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
ti: &[u8; 10],
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let weight = xml_value(storage, ti[2])?;
let proportion = xml_value(storage, ti[3])?;
let contrast = xml_value(storage, ti[4])?;
let stroke_variation = xml_value(storage, ti[5])?;
let arm_style = xml_value(storage, ti[6])?;
let letterform = xml_value(storage, ti[7])?;
let midline = xml_value(storage, ti[8])?;
let x_height = xml_value(storage, ti[9])?;
empty_tag(
w,
"hh:typeInfo",
&[
("familyType", font_family_type_str(ti[0])),
("weight", &weight),
("proportion", &proportion),
("contrast", &contrast),
("strokeVariation", &stroke_variation),
("armStyle", &arm_style),
("letterform", &letterform),
("midline", &midline),
("xHeight", &x_height),
],
storage,
)
}
fn write_subst_font<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
sf: &SubstFont,
ctx: &SerializeContext,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let binary_item_id_ref = resolve_font_binary_item_id_ref(
ctx,
sf.resolved_bin_data_id,
&sf.bin_item_id_ref,
&sf.face,
storage,
)?;
empty_tag(
w,
"hh:substFont",
&[
("face", &sf.face),
("type", font_type_str(sf.font_type)),
("isEmbedded", if sf.is_embedded { "1" } else { "0" }),
("binaryItemIDRef", binary_item_id_ref.as_str()),
],
storage,
)
}
fn font_family_type_str(v: u8) -> &'static str {
match v {
1 => "FCAT_MYUNGJO",
2 => "FCAT_GOTHIC",
3 => "FCAT_SSERIF",
4 => "FCAT_BRUSHSCRIPT",
5 => "FCAT_DECORATIVE",
6 => "FCAT_NONRECTMJ",
7 => "FCAT_NONRECTGT",
_ => "FCAT_UNKNOWN",
}
}
fn write_border_fills<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
doc_info: &DocInfo,
ctx: &SerializeContext,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
if doc_info.border_fills.is_empty() {
return Ok(());
}
start_tag_attrs(
w,
"hh:borderFills",
&[("itemCnt", &xml_value(storage, doc_info.border_fills.len())?)],
storage,
)?;
for (idx, bf) in doc_info.border_fills.iter().enumerate() {
write_border_fill(w, idx as u16, bf, ctx, storage)?;
}
end_tag(w, "hh:borderFills", storage)?;
Ok(())
}
fn write_border_fill<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
id: u16,
bf: &BorderFill,
ctx: &SerializeContext,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let attr = effective_border_fill_attr(bf);
let three_d = bool01(attr & 1 != 0);
let shadow = bool01(attr & (1 << 1) != 0);
start_tag_attrs(
w,
"hh:borderFill",
&[
("id", &xml_value(storage, id + 1)?), ("threeD", three_d),
("shadow", shadow),
("centerLine", center_line_type(bf)),
("breakCellSeparateLine", bool01(bf.break_cell_separate_line)),
],
storage,
)?;
write_diag_line(
w,
"hh:slash",
diagonal_shape_type(((attr >> 2) & 0x07) as u8),
(attr >> 8) & 0x03,
attr & (1 << 11) != 0,
storage,
)?;
write_diag_line(
w,
"hh:backSlash",
diagonal_shape_type(((attr >> 5) & 0x07) as u8),
(attr >> 10) & 0x01,
attr & (1 << 12) != 0,
storage,
)?;
write_border_line(w, "hh:leftBorder", &bf.borders[0], storage)?;
write_border_line(w, "hh:rightBorder", &bf.borders[1], storage)?;
write_border_line(w, "hh:topBorder", &bf.borders[2], storage)?;
write_border_line(w, "hh:bottomBorder", &bf.borders[3], storage)?;
write_diagonal(w, &bf.diagonal, storage)?;
super::shape::write_fill_brush_with_storage(w, &bf.fill, ctx, storage)?;
end_tag(w, "hh:borderFill", storage)?;
Ok(())
}
fn write_diag_line<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
name: &str,
type_str: &str,
crooked: u16,
is_counter: bool,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let crooked = xml_value(storage, crooked)?;
let is_counter = if is_counter { "1" } else { "0" };
empty_tag(
w,
name,
&[
("type", type_str),
("Crooked", crooked.as_str()),
("isCounter", is_counter),
],
storage,
)
}
fn numbering_head_align_str(attr: u32) -> &'static str {
match attr & 0x03 {
1 => "CENTER",
2 => "RIGHT",
_ => "LEFT",
}
}
fn para_head_text_offset_type_str(attr: u32) -> &'static str {
if (attr >> 4) & 0x01 != 0 {
"HWPUNIT"
} else {
"PERCENT"
}
}
pub(crate) fn numbering_format_str(code: u8) -> &'static str {
match code {
1 => "CIRCLED_DIGIT",
2 => "ROMAN_CAPITAL",
3 => "ROMAN_SMALL",
4 => "LATIN_CAPITAL",
5 => "LATIN_SMALL",
6 => "CIRCLED_LATIN_CAPITAL",
7 => "CIRCLED_LATIN_SMALL",
8 => "HANGUL_SYLLABLE",
9 => "CIRCLED_HANGUL_SYLLABLE",
10 => "HANGUL_JAMO",
11 => "CIRCLED_HANGUL_JAMO",
12 => "HANGUL_PHONETIC",
13 => "IDEOGRAPH",
14 => "CIRCLED_IDEOGRAPH",
15 => "DECAGON_CIRCLE",
16 => "DECAGON_CIRCLE_HANJA",
0x80 => "SYMBOL",
0x81 => "USER_CHAR",
_ => "DIGIT",
}
}
fn diagonal_shape_type(code: u8) -> &'static str {
match code & 0x07 {
0 => "NONE",
0b010 => "CENTER",
0b011 => "CENTER_BELOW",
0b110 => "CENTER_ABOVE",
_ => "ALL",
}
}
fn center_line_type(bf: &BorderFill) -> &'static str {
effective_center_line(bf).as_hwpx()
}
fn effective_center_line(bf: &BorderFill) -> CenterLine {
if bf.center_line != CenterLine::None {
bf.center_line
} else {
CenterLine::from_hwp_attr(bf.attr)
}
}
fn effective_border_fill_attr(bf: &BorderFill) -> u16 {
let center_line = effective_center_line(bf);
if center_line == CenterLine::None {
return bf.attr;
}
let mut attr = bf.attr;
attr &=
!((0x07 << 2) | (0x07 << 5) | (0x03 << 8) | (1 << 10) | (1 << 11) | (1 << 12) | (1 << 13));
attr | center_line.hwp_attr_bits()
}
fn write_border_line<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
name: &str,
line: &BorderLine,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let type_str = border_line_type_str(line.line_type);
let width_mm = xml_value(storage, format_args!("{} mm", border_width_mm(line.width)))?;
let color = color_hex(line.color, storage)?;
empty_tag(
w,
name,
&[("type", type_str), ("width", &width_mm), ("color", &color)],
storage,
)
}
fn write_diagonal<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
d: &DiagonalLine,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
if d.diagonal_type == 0 {
return Ok(());
}
let type_str = border_line_type_str(border_line_type_from_code(d.diagonal_type));
let width_mm = xml_value(storage, format_args!("{} mm", border_width_mm(d.width)))?;
let color = color_hex(d.color, storage)?;
empty_tag(
w,
"hh:diagonal",
&[("type", type_str), ("width", &width_mm), ("color", &color)],
storage,
)
}
pub(super) fn border_line_type_from_code(code: u8) -> BorderLineType {
use BorderLineType::*;
match code {
0 => None,
1 => Solid,
2 => Dash,
3 => Dot,
4 => DashDot,
5 => DashDotDot,
6 => LongDash,
7 => Circle,
8 => Double,
9 => ThinThickDouble,
10 => ThickThinDouble,
11 => ThinThickThinTriple,
12 => Wave,
13 => DoubleWave,
14 => Thick3D,
15 => Thick3DReverse,
16 => Thin3D,
17 => Thin3DReverse,
_ => Solid,
}
}
pub(super) fn border_line_type_str(t: BorderLineType) -> &'static str {
use BorderLineType::*;
match t {
None => "NONE",
Solid => "SOLID",
Dash => "DOT",
Dot => "DASH",
DashDot => "DASH_DOT",
DashDotDot => "DASH_DOT_DOT",
LongDash => "LONG_DASH",
Circle => "CIRCLE",
Double => "DOUBLE_SLIM",
ThinThickDouble => "SLIM_THICK",
ThickThinDouble => "THICK_SLIM",
ThinThickThinTriple => "SLIM_THICK_SLIM",
Wave => "WAVE",
DoubleWave => "DOUBLE_WAVE",
Thick3D => "THICK3D",
Thick3DReverse => "THICKREV3D",
Thin3D => "3D",
Thin3DReverse => "REV3D",
}
}
fn border_width_mm(w: u8) -> &'static str {
border_width_mm_str(w)
}
fn color_hex<S: crate::storage::Storage>(c: ColorRef, storage: &S) -> Result<String, SerializeError>
where
S::Error: std::fmt::Display,
{
super::shape::color_to_hex_with_storage(c, storage)
}
fn write_char_properties<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
doc_info: &DocInfo,
ctx: &SerializeContext,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let _ = ctx;
if doc_info.char_shapes.is_empty() {
return Ok(());
}
start_tag_attrs(
w,
"hh:charProperties",
&[("itemCnt", &xml_value(storage, doc_info.char_shapes.len())?)],
storage,
)?;
for (idx, cs) in doc_info.char_shapes.iter().enumerate() {
super::char_shapes::write_char_pr_with_storage(w, idx as u32, cs, storage)?;
}
end_tag(w, "hh:charProperties", storage)?;
Ok(())
}
fn write_char_pr<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
id: u32,
cs: &CharShape,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
super::char_shapes::write_char_pr_with_storage(w, id, cs, storage)
}
fn bool01(b: bool) -> &'static str {
if b {
"1"
} else {
"0"
}
}
fn shadow_type_str(t: u8) -> &'static str {
super::char_shape_tables::shadow_type_str(t)
}
fn write_tab_properties<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
doc_info: &DocInfo,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
if doc_info.tab_defs.is_empty() {
return Ok(());
}
start_tag_attrs(
w,
"hh:tabProperties",
&[("itemCnt", &xml_value(storage, doc_info.tab_defs.len())?)],
storage,
)?;
for (idx, td) in doc_info.tab_defs.iter().enumerate() {
write_tab_pr(w, idx as u16, td, storage)?;
}
end_tag(w, "hh:tabProperties", storage)?;
Ok(())
}
fn write_tab_pr<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
id: u16,
td: &TabDef,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let attrs = [
("id", xml_value(storage, id)?),
("autoTabLeft", xml_value(storage, bool01(td.auto_tab_left))?),
(
"autoTabRight",
xml_value(storage, bool01(td.auto_tab_right))?,
),
];
let attrs_ref = attrs.each_ref().map(|(k, v)| (*k, v.as_str()));
if td.tabs.is_empty() {
empty_tag(w, "hh:tabPr", &attrs_ref, storage)?;
} else {
start_tag_attrs(w, "hh:tabPr", &attrs_ref, storage)?;
for tab in &td.tabs {
write_tab_item_switch(w, tab, storage)?;
}
end_tag(w, "hh:tabPr", storage)?;
}
Ok(())
}
fn write_tab_item_switch<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
tab: &crate::model::style::TabItem,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
start_tag(w, "hp:switch", storage)?;
start_tag_attrs(
w,
"hp:case",
&[(
"hp:required-namespace",
"http://www.hancom.co.kr/hwpml/2016/HwpUnitChar",
)],
storage,
)?;
write_tab_item(w, tab, true, storage)?;
end_tag(w, "hp:case", storage)?;
start_tag(w, "hp:default", storage)?;
write_tab_item(w, tab, false, storage)?;
end_tag(w, "hp:default", storage)?;
end_tag(w, "hp:switch", storage)?;
Ok(())
}
fn write_tab_item<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
tab: &crate::model::style::TabItem,
half: bool,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let pos = if half { tab.position / 2 } else { tab.position };
let pos = xml_value(storage, pos)?;
let attrs = [
("pos", pos.as_str()),
("type", tab_type_str(tab.tab_type)),
("leader", tab_leader_str(tab.fill_type)),
("unit", "HWPUNIT"),
];
let attrs = &attrs[..if half { 4 } else { 3 }];
empty_tag(w, "hh:tabItem", attrs, storage)?;
Ok(())
}
fn tab_type_str(t: u8) -> &'static str {
match t {
0 => "LEFT",
1 => "RIGHT",
2 => "CENTER",
3 => "DECIMAL",
_ => "LEFT",
}
}
fn tab_leader_str(f: u8) -> &'static str {
match f {
0 => "NONE",
1 => "SOLID",
2 => "DOT",
3 => "DASH",
4 => "DASH_DOT",
5 => "DASH_DOT_DOT",
6 => "LONG_DASH",
7 => "CIRCLE",
8 => "DOUBLE_SLIM",
9 => "SLIM_THICK",
10 => "THICK_SLIM",
11 => "SLIM_THICK_SLIM",
_ => "NONE",
}
}
fn write_numberings<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
doc_info: &DocInfo,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
if doc_info.numberings.is_empty() {
return Ok(());
}
start_tag_attrs(
w,
"hh:numberings",
&[("itemCnt", &xml_value(storage, doc_info.numberings.len())?)],
storage,
)?;
for (idx, n) in doc_info.numberings.iter().enumerate() {
write_numbering(w, idx as u16, n, storage)?;
}
end_tag(w, "hh:numberings", storage)?;
Ok(())
}
fn write_numbering<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
id: u16,
n: &Numbering,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
start_tag_attrs(
w,
"hh:numbering",
&[
("id", &xml_value(storage, id + 1)?), ("start", &xml_value(storage, n.start_number)?),
],
storage,
)?;
if let Some(raw) = &n.raw_para_heads {
w.get_mut()
.write_all(raw.as_bytes())
.map_err(|e| SerializeError::XmlError(format!("numbering paraHead splice: {e}")))?;
end_tag(w, "hh:numbering", storage)?;
return Ok(());
}
for (idx, h) in n.heads.iter().enumerate() {
let start = n.level_start_numbers[idx];
let level_s = xml_value(storage, idx + 1)?;
let start_s = xml_value(storage, start)?;
let wa = xml_value(storage, h.width_adjust)?;
let num_format = numbering_format_str(h.number_format);
let text_offset_s = xml_value(storage, h.text_distance)?;
let char_pr_id_ref_s = xml_value(storage, h.char_shape_id)?;
let align = numbering_head_align_str(h.attr);
let use_inst_width = if (h.attr >> 2) & 0x01 != 0 { "1" } else { "0" };
let auto_indent = if (h.attr >> 3) & 0x01 != 0 { "1" } else { "0" };
let attrs = [
("start", start_s.as_str()),
("level", level_s.as_str()),
("align", align),
("useInstWidth", use_inst_width),
("autoIndent", auto_indent),
("widthAdjust", wa.as_str()),
("textOffsetType", para_head_text_offset_type_str(h.attr)),
("textOffset", text_offset_s.as_str()),
("numFormat", num_format),
("charPrIDRef", char_pr_id_ref_s.as_str()),
("checkable", "0"),
];
let format_str = n.level_formats[idx].as_str();
if format_str.is_empty() {
empty_tag(w, "hh:paraHead", &attrs, storage)?;
} else {
start_tag_attrs(w, "hh:paraHead", &attrs, storage)?;
text(w, format_str, storage)?;
end_tag(w, "hh:paraHead", storage)?;
}
}
end_tag(w, "hh:numbering", storage)?;
Ok(())
}
fn write_bullets<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
doc_info: &DocInfo,
ctx: &SerializeContext,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
if doc_info.bullets.is_empty() {
return Ok(());
}
start_tag_attrs(
w,
"hh:bullets",
&[("itemCnt", &xml_value(storage, doc_info.bullets.len())?)],
storage,
)?;
for (idx, b) in doc_info.bullets.iter().enumerate() {
write_bullet(w, idx as u16, b, ctx, storage)?;
}
end_tag(w, "hh:bullets", storage)?;
Ok(())
}
fn write_bullet<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
id: u16,
b: &crate::model::style::Bullet,
ctx: &SerializeContext,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let id_s = xml_value(storage, id + 1)?; let char_s = xml_value(storage, b.bullet_char)?;
let use_image = if b.image_bullet > 0 || b.hwpx_image_without_ref {
"1"
} else {
"0"
};
let has_checked_char = b.check_bullet_char != '\0';
let checked_char_s = xml_value(storage, b.check_bullet_char)?;
let attrs = [
("id", id_s.as_str()),
("char", char_s.as_str()),
if has_checked_char {
("checkedChar", checked_char_s.as_str())
} else {
("useImage", use_image)
},
("useImage", use_image),
];
let attrs = &attrs[..if has_checked_char { 4 } else { 3 }];
start_tag_attrs(w, "hh:bullet", attrs, storage)?;
if let Some(raw) = &b.raw_para_head {
w.get_mut()
.write_all(raw.as_bytes())
.map_err(|e| SerializeError::XmlError(format!("bullet paraHead splice: {e}")))?;
} else {
if let Some(id) = b.image_reference() {
let manifest_id = ctx.resolve_bin_id(id).ok_or_else(|| {
SerializeError::XmlError(format!(
"그림 글머리표 BinData 참조 {id}를 찾을 수 없습니다"
))
})?;
let contrast = xml_value(storage, b.image_data[0] as i8)?;
let bright = xml_value(storage, b.image_data[1] as i8)?;
let effect = match b.image_data[2] {
1 => "GRAY_SCALE",
2 => "BLACK_WHITE",
3 => {
return Err(SerializeError::XmlError(
"그림 글머리표의 8×8 패턴 효과는 HWPX 이미지 사양에서 지원하지 않습니다"
.into(),
));
}
_ => "REAL_PIC",
};
empty_tag(
w,
"hc:img",
&[
("binaryItemIDRef", manifest_id),
("bright", &bright),
("contrast", &contrast),
("effect", effect),
("alpha", "0"),
],
storage,
)?;
}
empty_tag(
w,
"hh:paraHead",
&[
("level", "0"),
("align", numbering_head_align_str(b.attr)),
(
"useInstWidth",
if (b.attr >> 2) & 0x01 != 0 { "1" } else { "0" },
),
(
"autoIndent",
if (b.attr >> 3) & 0x01 != 0 { "1" } else { "0" },
),
("widthAdjust", &xml_value(storage, b.width_adjust)?),
("textOffsetType", para_head_text_offset_type_str(b.attr)),
("textOffset", &xml_value(storage, b.text_distance)?),
("numFormat", "DIGIT"),
("charPrIDRef", &xml_value(storage, b.char_shape_id)?),
("checkable", if has_checked_char { "1" } else { "0" }),
],
storage,
)?;
}
end_tag(w, "hh:bullet", storage)?;
Ok(())
}
fn write_para_properties<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
doc_info: &DocInfo,
ctx: &SerializeContext,
physical_margin_units: bool,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let _ = ctx;
if doc_info.para_shapes.is_empty() {
return Ok(());
}
start_tag_attrs(
w,
"hh:paraProperties",
&[("itemCnt", &xml_value(storage, doc_info.para_shapes.len())?)],
storage,
)?;
for (idx, ps) in doc_info.para_shapes.iter().enumerate() {
if !physical_margin_units && !ps.hwpx_plain_para_margin {
let mut stored = storage.clone_record(ps).map_err(xml_error)?;
stored.margin_left = stored.margin_left.saturating_mul(2);
stored.margin_right = stored.margin_right.saturating_mul(2);
stored.indent = stored.indent.saturating_mul(2);
stored.spacing_before = stored.spacing_before.saturating_mul(2);
stored.spacing_after = stored.spacing_after.saturating_mul(2);
if stored.line_spacing_type != LineSpacingType::Percent {
stored.line_spacing = stored.line_spacing.saturating_mul(2);
}
write_para_pr(w, idx as u16, &stored, storage)?;
} else {
write_para_pr(w, idx as u16, ps, storage)?;
}
}
end_tag(w, "hh:paraProperties", storage)?;
Ok(())
}
fn write_para_pr<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
id: u16,
ps: &ParaShape,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let condense = xml_value(storage, (ps.attr1 >> 9) & 0x7f)?;
let font_line_height = xml_value(storage, (ps.attr1 >> 22) & 1)?;
let snap_to_grid = xml_value(storage, (ps.attr1 >> 8) & 1)?;
start_tag_attrs(
w,
"hh:paraPr",
&[
("id", &xml_value(storage, id)?),
("tabPrIDRef", &xml_value(storage, ps.tab_def_id)?),
("condense", &condense),
("fontLineHeight", &font_line_height),
("snapToGrid", &snap_to_grid),
("suppressLineNumbers", "0"),
("checked", "0"),
],
storage,
)?;
let vertical = vertical_alignment_str((ps.attr1 >> 20) & 0x03);
let break_non_latin = if (ps.attr1 >> 7) & 1 == 1 {
"KEEP_WORD"
} else {
"BREAK_WORD"
};
let break_latin = ps
.break_latin_word
.as_deref()
.unwrap_or_else(|| latin_break_from_attr1((ps.attr1 >> 5) & 0x03));
let widow_orphan = xml_value(storage, (ps.attr1 >> 16) & 1)?;
let keep_with_next = xml_value(storage, (ps.attr1 >> 17) & 1)?;
let keep_lines = xml_value(storage, (ps.attr1 >> 18) & 1)?;
let page_break_before = xml_value(storage, (ps.attr1 >> 19) & 1)?;
let auto_space_kr_en = xml_value(storage, (ps.attr2 >> 4) & 1)?;
let auto_space_kr_num = xml_value(storage, (ps.attr2 >> 5) & 1)?;
empty_tag(
w,
"hh:align",
&[
("horizontal", alignment_str(ps.alignment)),
("vertical", vertical),
],
storage,
)?;
let heading = [
("type", head_type_str(ps.head_type)),
("idRef", &xml_value(storage, ps.numbering_id)?),
("level", &xml_value(storage, ps.para_level)?),
];
if ps.para_level < 7 {
empty_tag(w, "hh:heading", &heading, storage)?;
} else {
start_tag(w, "hp:switch", storage)?;
start_tag_attrs(
w,
"hp:case",
&[(
"hp:required-namespace",
crate::parser::hwpx::header::HWPML_2016_PARAGRAPH_NS,
)],
storage,
)?;
empty_tag(w, "hh:heading", &heading, storage)?;
end_tag(w, "hp:case", storage)?;
start_tag(w, "hp:default", storage)?;
empty_tag(
w,
"hh:heading",
&[("type", "NONE"), ("idRef", "0"), ("level", "0")],
storage,
)?;
end_tag(w, "hp:default", storage)?;
end_tag(w, "hp:switch", storage)?;
}
empty_tag(
w,
"hh:breakSetting",
&[
("breakLatinWord", break_latin),
("breakNonLatinWord", break_non_latin),
("widowOrphan", &widow_orphan),
("keepWithNext", &keep_with_next),
("keepLines", &keep_lines),
("pageBreakBefore", &page_break_before),
("lineWrap", para_line_wrap_str(ps.attr2)),
],
storage,
)?;
empty_tag(
w,
"hh:autoSpacing",
&[
("eAsianEng", &auto_space_kr_en),
("eAsianNum", &auto_space_kr_num),
],
storage,
)?;
if ps.hwpx_plain_para_margin {
write_para_margin(w, ps, ps.hwpx_plain_para_margin_physical, storage)?;
write_para_line_spacing(w, ps, ps.hwpx_plain_para_margin_physical, storage)?;
} else {
write_para_margin_switch(w, ps, storage)?;
}
let border_connect = if (ps.attr1 >> 28) & 1 != 0 { "1" } else { "0" };
let border_ignore_margin = if (ps.attr1 >> 29) & 1 != 0 { "1" } else { "0" };
empty_tag(
w,
"hh:border",
&[
("borderFillIDRef", &xml_value(storage, ps.border_fill_id)?),
("offsetLeft", &xml_value(storage, ps.border_spacing[0])?),
("offsetRight", &xml_value(storage, ps.border_spacing[1])?),
("offsetTop", &xml_value(storage, ps.border_spacing[2])?),
("offsetBottom", &xml_value(storage, ps.border_spacing[3])?),
("connect", border_connect),
("ignoreMargin", border_ignore_margin),
],
storage,
)?;
end_tag(w, "hh:paraPr", storage)?;
Ok(())
}
fn write_para_margin_switch<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
ps: &ParaShape,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
start_tag(w, "hp:switch", storage)?;
start_tag_attrs(
w,
"hp:case",
&[(
"hp:required-namespace",
"http://www.hancom.co.kr/hwpml/2016/HwpUnitChar",
)],
storage,
)?;
write_para_margin(w, ps, true, storage)?;
write_para_line_spacing(w, ps, true, storage)?;
end_tag(w, "hp:case", storage)?;
start_tag(w, "hp:default", storage)?;
write_para_margin(w, ps, false, storage)?;
write_para_line_spacing(w, ps, false, storage)?;
end_tag(w, "hp:default", storage)?;
end_tag(w, "hp:switch", storage)?;
Ok(())
}
fn write_para_margin<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
ps: &ParaShape,
half: bool,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
start_tag(w, "hh:margin", storage)?;
write_margin_child(w, "hc:intent", ps.indent, half, storage)?;
write_margin_child(w, "hc:left", ps.margin_left, half, storage)?;
write_margin_child(w, "hc:right", ps.margin_right, half, storage)?;
write_margin_child(w, "hc:prev", ps.spacing_before, half, storage)?;
write_margin_child(w, "hc:next", ps.spacing_after, half, storage)?;
end_tag(w, "hh:margin", storage)?;
Ok(())
}
fn write_para_line_spacing<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
ps: &ParaShape,
case: bool,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let value = if case && !matches!(ps.line_spacing_type, LineSpacingType::Percent) {
ps.line_spacing / 2
} else {
ps.line_spacing
};
empty_tag(
w,
"hh:lineSpacing",
&[
("type", line_spacing_type_str(ps.line_spacing_type)),
("value", &xml_value(storage, value)?),
("unit", "HWPUNIT"),
],
storage,
)
}
fn write_margin_child<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
name: &str,
stored: i32,
half: bool,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
if !half {
return empty_tag(
w,
name,
&[("value", &xml_value(storage, stored)?), ("unit", "HWPUNIT")],
storage,
);
}
let odd = stored % 2 != 0;
let value = if odd { (stored - 1) / 2 } else { stored / 2 };
empty_tag(
w,
name,
&[
("value", &xml_value(storage, value)?),
("unit", if odd { "CHAR" } else { "HWPUNIT" }),
],
storage,
)
}
fn alignment_str(a: Alignment) -> &'static str {
use Alignment::*;
match a {
Justify => "JUSTIFY",
Left => "LEFT",
Right => "RIGHT",
Center => "CENTER",
Distribute => "DISTRIBUTE",
Split => "DISTRIBUTE_SPACE",
}
}
fn vertical_alignment_str(bits: u32) -> &'static str {
match bits {
1 => "TOP",
2 => "CENTER",
3 => "BOTTOM",
_ => "BASELINE",
}
}
fn latin_break_from_attr1(bits: u32) -> &'static str {
match bits {
1 => "HYPHENATION",
2 => "BREAK_WORD",
_ => "KEEP_WORD",
}
}
fn head_type_str(h: HeadType) -> &'static str {
use HeadType::*;
match h {
None => "NONE",
Outline => "OUTLINE",
Number => "NUMBER",
Bullet => "BULLET",
}
}
fn line_spacing_type_str(t: LineSpacingType) -> &'static str {
use LineSpacingType::*;
match t {
Percent => "PERCENT",
Fixed => "FIXED",
SpaceOnly => "BETWEEN_LINES",
Minimum => "AT_LEAST",
}
}
fn write_styles<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
doc_info: &DocInfo,
ctx: &SerializeContext,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let _ = ctx;
if doc_info.styles.is_empty() {
return Ok(());
}
start_tag_attrs(
w,
"hh:styles",
&[("itemCnt", &xml_value(storage, doc_info.styles.len())?)],
storage,
)?;
for (idx, st) in doc_info.styles.iter().enumerate() {
write_style(w, idx as u16, st, storage)?;
}
end_tag(w, "hh:styles", storage)?;
Ok(())
}
fn write_style<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
id: u16,
st: &Style,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let type_str = if st.style_type == 1 { "CHAR" } else { "PARA" };
empty_tag(
w,
"hh:style",
&[
("id", &xml_value(storage, id)?),
("type", type_str),
("name", &st.local_name),
("engName", &st.english_name),
("paraPrIDRef", &xml_value(storage, st.para_shape_id)?),
("charPrIDRef", &xml_value(storage, st.char_shape_id)?),
("nextStyleIDRef", &xml_value(storage, st.next_style_id)?),
("langID", &xml_value(storage, st.lang_id)?),
("lockForm", bool01(st.lock_form)),
],
storage,
)
}
fn write_compatible_document<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
start_tag_attrs(
w,
"hh:compatibleDocument",
&[("targetProgram", "HWP201X")],
storage,
)?;
empty_tag(w, "hh:layoutCompatibility", &[], storage)?;
end_tag(w, "hh:compatibleDocument", storage)?;
Ok(())
}
fn write_doc_option<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
start_tag(w, "hh:docOption", storage)?;
empty_tag(
w,
"hh:linkinfo",
&[("path", ""), ("pageInherit", "0"), ("footnoteInherit", "0")],
storage,
)?;
end_tag(w, "hh:docOption", storage)?;
Ok(())
}
fn write_track_change_config<W: Write, S: crate::storage::Storage>(
w: &mut Writer<W>,
flags: u32,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
empty_tag(
w,
"hh:trackchageConfig",
&[("flags", &xml_value(storage, flags)?)],
storage,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn track_change_flags_come_from_the_original_record() {
use crate::model::document::RawRecord;
let mut info = DocInfo::default();
assert_eq!(
info.track_change_flags(),
56,
"레코드가 없으면 한컴이 쓰는 값(56)으로 떨어진다 — 00000·00001 실측"
);
info.extra_records.push(RawRecord {
tag_id: tags::HWPTAG_TRACKCHANGE,
level: 0,
data: 60_u32.to_le_bytes().to_vec(),
});
assert_eq!(info.track_change_flags(), 60, "원본 값을 그대로 옮긴다");
}
#[test]
fn truncated_track_change_record_falls_back_to_the_default() {
use crate::model::document::RawRecord;
let mut info = DocInfo::default();
info.extra_records.push(RawRecord {
tag_id: tags::HWPTAG_TRACKCHANGE,
level: 0,
data: vec![0x38, 0x00],
});
assert_eq!(info.track_change_flags(), 56);
}
use crate::parser::hwpx::parse_hwpx;
#[test]
fn write_style_emits_ir_lang_id() {
let st = Style {
lang_id: 1033,
..Default::default()
};
let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
write_style(&mut w, 0, &st, &crate::storage::Unbounded).expect("write_style");
let xml = String::from_utf8(w.into_inner()).unwrap();
assert!(
xml.contains(r#"langID="1033""#),
"Style.lang_id 가 방출돼야 함: {xml}"
);
}
#[test]
fn write_style_emits_ir_lock_form() {
let st = Style {
lock_form: true,
..Default::default()
};
let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
write_style(&mut w, 0, &st, &crate::storage::Unbounded).expect("write_style");
let xml = String::from_utf8(w.into_inner()).unwrap();
assert!(
xml.contains(r#"lockForm="1""#),
"Style.lock_form 이 방출돼야 함: {xml}"
);
}
#[test]
fn task_m100_shadow_type_str_reserved_value_maps_to_none() {
assert_eq!(shadow_type_str(0), "NONE");
assert_eq!(shadow_type_str(1), "DROP");
assert_eq!(shadow_type_str(2), "CONTINUOUS");
assert_eq!(shadow_type_str(3), "NONE");
assert_eq!(shadow_type_str(99), "NONE");
}
#[test]
fn write_header_runs_on_empty_document() {
let doc = Document::default();
let ctx = SerializeContext::collect_from_document(&doc);
let bytes = write_header(&doc, &ctx).expect("write_header");
let xml = std::str::from_utf8(&bytes).unwrap();
assert!(xml.contains("<hh:head"));
assert!(xml.contains("</hh:head>"));
assert!(
xml.contains(r#"xmlns:hwpunitchar="http://www.hancom.co.kr/hwpml/2016/HwpUnitChar""#),
"hh:head 에 xmlns:hwpunitchar 선언이 있어야 함"
);
assert!(xml.contains(r#"version="1.2""#), "기본 버전 폴백은 1.2");
}
#[test]
fn write_header_seccnt_matches_section_count() {
use crate::model::document::Section;
let mut doc = Document::default();
doc.sections = vec![Section::default(), Section::default(), Section::default()];
doc.doc_properties.section_count = 1; let ctx = SerializeContext::collect_from_document(&doc);
let xml = String::from_utf8(write_header(&doc, &ctx).expect("write_header")).unwrap();
assert!(
xml.contains(r#"secCnt="3""#),
"secCnt 가 섹션 수(3)와 일치해야 함(붕괴 회귀 가드)"
);
}
#[test]
fn write_header_emits_preserved_hwpml_version() {
let mut doc = Document::default();
doc.doc_info.hwpml_version = Some("1.5".to_string());
let ctx = SerializeContext::collect_from_document(&doc);
let xml = String::from_utf8(write_header(&doc, &ctx).expect("write_header")).unwrap();
assert!(
xml.contains(r#"version="1.5""#),
"보존된 hwpml_version=1.5 가 방출되어야 함"
);
assert!(
!xml.contains(r#"version="1.2""#),
"하드코딩 1.2 가 남아있으면 안 됨"
);
}
#[test]
fn write_header_preserves_memo_properties_roundtrip() {
let bytes = include_bytes!("../../../samples/hwpx/aift.hwpx");
let doc = parse_hwpx(bytes).expect("parse aift.hwpx");
assert!(
doc.doc_info.memo_properties_xml.is_some(),
"파서가 memoProperties 원문을 보존해야 함"
);
let ctx = SerializeContext::collect_from_document(&doc);
let header_xml =
String::from_utf8(write_header(&doc, &ctx).expect("write header")).unwrap();
assert!(
header_xml.contains("<hh:memoProperties"),
"재직렬화된 header.xml에 memoProperties가 있어야 함: {header_xml}"
);
assert!(
header_xml.contains(r#"lineType="SOLID""#)
&& header_xml.contains(r##"fillColor="#CBFF99""##),
"memoPr 원본 속성(lineType/fillColor 등)이 그대로 보존돼야 함: {header_xml}"
);
}
#[test]
fn write_header_preserves_char_shape_count() {
let bytes = include_bytes!("../../../samples/hwpx/ref/ref_empty.hwpx");
let doc = parse_hwpx(bytes).expect("parse ref_empty");
let ctx = SerializeContext::collect_from_document(&doc);
let header_bytes = write_header(&doc, &ctx).expect("write header");
let xml = std::str::from_utf8(&header_bytes).unwrap();
let expected = doc.doc_info.char_shapes.len();
let actual = xml.matches("<hh:charPr ").count();
assert_eq!(actual, expected, "charPr count mismatch");
}
#[test]
fn write_header_splices_doc_settings_tail_verbatim() {
let bytes = include_bytes!("../../../samples/hwpx/ref/ref_empty.hwpx");
let mut doc = parse_hwpx(bytes).expect("parse");
doc.doc_info.hwpx_head_tail = Some(
r#"<hh:compatibleDocument targetProgram="HWP201X"><hh:layoutCompatibility/></hh:compatibleDocument><hh:docOption><hh:linkinfo path="" pageInherit="1" footnoteInherit="0"/></hh:docOption><hh:trackchageConfig flags="56"/>"#
.to_string(),
);
let ctx = SerializeContext::collect_from_document(&doc);
let xml = String::from_utf8(write_header(&doc, &ctx).unwrap()).unwrap();
assert!(
xml.contains("<hh:layoutCompatibility/></hh:compatibleDocument>"),
"원본의 빈 layoutCompatibility 가 그대로 보존되어야 함: {xml}"
);
assert!(xml.contains(r#"pageInherit="1""#), "pageInherit=1 보존");
assert!(
xml.contains(r#"<hh:trackchageConfig flags="56"/>"#),
"trackchange flags=56 보존"
);
assert!(
!xml.contains("<hh:char/><hh:paragraph/>"),
"하드코딩 layoutCompatibility 자식이 없어야 함"
);
}
#[test]
fn write_header_falls_back_to_hardcoded_tail_when_absent() {
let bytes = include_bytes!("../../../samples/hwpx/ref/ref_empty.hwpx");
let mut doc = parse_hwpx(bytes).expect("parse");
doc.doc_info.hwpx_head_tail = None;
let ctx = SerializeContext::collect_from_document(&doc);
let xml = String::from_utf8(write_header(&doc, &ctx).unwrap()).unwrap();
assert!(
xml.contains("<hh:layoutCompatibility/></hh:compatibleDocument>"),
"원본 부재 시 폴백도 한컴 산출물과 같은 자기닫힘이어야 함: {xml}"
);
assert!(
!xml.contains("<hh:char/>"),
"폴백에 HWPX 요소가 아닌 자식(<hh:char/> 등)이 없어야 함: {xml}"
);
assert!(
xml.contains(r#"<hh:trackchageConfig flags="56"/>"#),
"폴백은 한컴 기본값 56 이어야 한다: {xml}"
);
}
#[test]
fn write_header_emits_seven_fontfaces_when_populated() {
let bytes = include_bytes!("../../../samples/hwpx/ref/ref_empty.hwpx");
let doc = parse_hwpx(bytes).expect("parse");
let ctx = SerializeContext::collect_from_document(&doc);
let xml = String::from_utf8(write_header(&doc, &ctx).unwrap()).unwrap();
assert_eq!(xml.matches("<hh:fontface ").count(), 7);
}
#[test]
fn write_font_type_info_is_inverse_of_parser_layout() {
let ti = [2u8, 3, 6, 0, 0, 1, 1, 1, 1, 1];
let mut writer = Writer::new(Vec::new());
write_font_type_info(&mut writer, &ti, &crate::storage::Unbounded).expect("write typeInfo");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert_eq!(
xml,
r#"<hh:typeInfo familyType="FCAT_GOTHIC" weight="6" proportion="0" contrast="0" strokeVariation="1" armStyle="1" letterform="1" midline="1" xHeight="1"/>"#,
"typeInfo 9개 속성이 원본 순서/값으로 복원되어야 함"
);
assert!(!xml.contains("serif"));
}
#[test]
fn write_subst_font_emits_all_four_attributes_in_order() {
let sf = SubstFont {
face: "한컴바탕".to_string(),
font_type: 1,
is_embedded: false,
bin_item_id_ref: String::new(),
resolved_bin_data_id: None,
};
let mut writer = Writer::new(Vec::new());
write_subst_font(
&mut writer,
&sf,
&SerializeContext::default(),
&crate::storage::Unbounded,
)
.expect("write substFont");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert_eq!(
xml,
r#"<hh:substFont face="한컴바탕" type="TTF" isEmbedded="0" binaryItemIDRef=""/>"#,
"substFont 4개 속성이 원본 순서/값으로 복원되어야 함(비임베드도 빈 binaryItemIDRef 출력)"
);
}
#[test]
fn write_fontfaces_emits_subst_font_before_type_info() {
let mut doc_info = DocInfo::default();
doc_info.font_faces = vec![Vec::new(); 7];
doc_info.font_faces[0].push(Font {
name: "바탕".to_string(),
alt_type: 1,
type_info: Some([2, 3, 6, 0, 0, 1, 1, 1, 1, 1]),
subst_font: Some(SubstFont {
face: "한컴바탕".to_string(),
font_type: 1,
is_embedded: false,
bin_item_id_ref: String::new(),
resolved_bin_data_id: None,
}),
..Default::default()
});
let mut writer = Writer::new(Vec::new());
write_fontfaces(
&mut writer,
&doc_info,
&SerializeContext::default(),
&crate::storage::Unbounded,
)
.expect("write fontfaces");
let xml = String::from_utf8(writer.into_inner()).unwrap();
let sub = xml.find("<hh:substFont ").expect("substFont present");
let ti = xml.find("<hh:typeInfo ").expect("typeInfo present");
assert!(sub < ti, "substFont 가 typeInfo 보다 먼저 와야 함: {xml}");
assert!(
xml.contains(
r#"<hh:font id="0" face="바탕" type="TTF" isEmbedded="0"><hh:substFont face="한컴바탕""#
),
"substFont 가 font 의 첫 자식이어야 함: {xml}"
);
}
#[test]
fn write_fontfaces_emits_type_info_child_only_when_present() {
let mut doc_info = DocInfo::default();
doc_info.font_faces = vec![Vec::new(); 7];
doc_info.font_faces[0].push(Font {
name: "굴림".to_string(),
alt_type: 1,
..Default::default()
});
doc_info.font_faces[0].push(Font {
name: "바탕".to_string(),
alt_type: 1,
type_info: Some([2, 3, 6, 0, 0, 1, 1, 1, 1, 1]),
..Default::default()
});
let mut writer = Writer::new(Vec::new());
write_fontfaces(
&mut writer,
&doc_info,
&SerializeContext::default(),
&crate::storage::Unbounded,
)
.expect("write fontfaces");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r#"<hh:font id="0" face="굴림" type="TTF" isEmbedded="0"/>"#),
"typeInfo 없는 글꼴은 self-closing: {xml}"
);
assert!(
xml.contains(
r#"<hh:font id="1" face="바탕" type="TTF" isEmbedded="0"><hh:typeInfo familyType="FCAT_GOTHIC""#
),
"typeInfo 있는 글꼴은 자식 복원: {xml}"
);
assert_eq!(xml.matches("<hh:typeInfo ").count(), 1);
}
#[test]
fn embedded_font_references_use_the_serialized_manifest_id() {
use crate::model::bin_data::BinDataContent;
let mut doc = Document::default();
doc.bin_data_content.push(BinDataContent {
id: 2,
data: vec![0, 1, 2].into(),
extension: "ttf".to_string(),
});
doc.doc_info.font_faces = vec![Vec::new(); 7];
doc.doc_info.font_faces[0].push(Font {
name: "Embedded Face".to_string(),
is_embedded: true,
bin_item_id_ref: "font-resource-alpha".to_string(),
resolved_bin_data_id: Some(2),
subst_font: Some(SubstFont {
face: "Embedded Substitute".to_string(),
font_type: 1,
is_embedded: true,
bin_item_id_ref: "font-resource-beta".to_string(),
resolved_bin_data_id: Some(2),
}),
..Default::default()
});
let ctx = SerializeContext::collect_from_document(&doc);
assert_eq!(ctx.resolve_bin_id(2), Some("image2"));
let xml = String::from_utf8(write_header(&doc, &ctx).unwrap()).unwrap();
assert_eq!(xml.matches(r#"binaryItemIDRef="image2""#).count(), 2);
assert!(!xml.contains("font-resource-alpha"));
assert!(!xml.contains("font-resource-beta"));
}
#[test]
fn embedded_font_reference_to_missing_bin_data_is_an_error() {
let mut doc = Document::default();
doc.doc_info.font_faces = vec![Vec::new(); 7];
doc.doc_info.font_faces[0].push(Font {
name: "Missing Embedded Face".to_string(),
is_embedded: true,
bin_item_id_ref: "stale-font-ref".to_string(),
resolved_bin_data_id: Some(9),
..Default::default()
});
let ctx = SerializeContext::collect_from_document(&doc);
let error = write_header(&doc, &ctx).expect_err("dangling font reference must fail");
assert!(error.to_string().contains("missing BinData id 9"));
assert!(!error.to_string().contains("stale-font-ref"));
}
#[test]
fn canonical_attr_order_charpr() {
let bytes = include_bytes!("../../../samples/hwpx/ref/ref_empty.hwpx");
let doc = parse_hwpx(bytes).expect("parse");
let ctx = SerializeContext::collect_from_document(&doc);
let xml = String::from_utf8(write_header(&doc, &ctx).unwrap()).unwrap();
let snippet = xml
.find("<hh:charPr ")
.and_then(|i| {
let end = xml[i..].find('>').map(|e| i + e)?;
Some(&xml[i..=end])
})
.expect("charPr tag");
let ip = snippet.find("id=").unwrap();
let hp = snippet.find("height=").unwrap();
let tc = snippet.find("textColor=").unwrap();
let sc = snippet.find("shadeColor=").unwrap();
let uf = snippet.find("useFontSpace=").unwrap();
let uk = snippet.find("useKerning=").unwrap();
let sm = snippet.find("symMark=").unwrap();
let bf = snippet.find("borderFillIDRef=").unwrap();
assert!(ip < hp && hp < tc && tc < sc && sc < uf && uf < uk && uk < sm && sm < bf);
}
#[test]
fn write_border_fill_preserves_slash_and_backslash_shape_types() {
let mut bf = BorderFill::default();
bf.attr = (0b010 << 2) | (0b011 << 5);
let mut writer = Writer::new(Vec::new());
write_border_fill(
&mut writer,
0,
&bf,
&SerializeContext::collect_from_document(&Default::default()),
&crate::storage::Unbounded,
)
.expect("write borderFill");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r#"<hh:slash type="CENTER" Crooked="0" isCounter="0"/>"#),
"slash 방향 비트가 CENTER로 보존되어야 함: {xml}"
);
assert!(
xml.contains(r#"<hh:backSlash type="CENTER_BELOW" Crooked="0" isCounter="0"/>"#),
"backSlash 방향 비트가 CENTER_BELOW로 보존되어야 함: {xml}"
);
}
#[test]
fn write_border_fill_uses_hwpx_dash_dot_contract() {
let mut bf = BorderFill::default();
bf.borders[0].line_type = BorderLineType::Dash;
bf.borders[1].line_type = BorderLineType::Dot;
let mut writer = Writer::new(Vec::new());
write_border_fill(
&mut writer,
0,
&bf,
&SerializeContext::collect_from_document(&Default::default()),
&crate::storage::Unbounded,
)
.expect("write borderFill");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r#"<hh:leftBorder type="DOT""#),
"HWP5 code 2(Dash)는 HWPX DOT으로 방출돼야 함: {xml}"
);
assert!(
xml.contains(r#"<hh:rightBorder type="DASH""#),
"HWP5 code 3(Dot)는 HWPX DASH로 방출돼야 함: {xml}"
);
}
#[test]
fn write_border_fill_preserves_three_d_and_shadow_bits() {
let mut bf = BorderFill::default();
bf.attr = 0b11;
let mut writer = Writer::new(Vec::new());
write_border_fill(
&mut writer,
0,
&bf,
&SerializeContext::collect_from_document(&Default::default()),
&crate::storage::Unbounded,
)
.expect("write borderFill");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r#"threeD="1""#) && xml.contains(r#"shadow="1""#),
"attr bit0/bit1 이 threeD/shadow 로 방출돼야 함: {xml}"
);
}
#[test]
fn write_border_fill_preserves_center_line_type() {
let mut bf = BorderFill::default();
bf.center_line = CenterLine::Vertical;
let mut writer = Writer::new(Vec::new());
write_border_fill(
&mut writer,
0,
&bf,
&SerializeContext::collect_from_document(&Default::default()),
&crate::storage::Unbounded,
)
.expect("write borderFill");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r#"centerLine="VERTICAL""#),
"centerLine 방향이 보존되어야 함: {xml}"
);
assert!(
xml.contains(r#"<hh:slash type="NONE" Crooked="3" isCounter="0"/>"#),
"VERTICAL 중심선의 HWP attr 보조 비트가 Crooked=3 으로 보존되어야 함: {xml}"
);
}
#[test]
fn write_border_fill_preserves_slash_crooked_two_bit_value() {
let mut bf = BorderFill::default();
bf.attr = (2 << 8) | (0b010 << 5);
let mut writer = Writer::new(Vec::new());
write_border_fill(
&mut writer,
0,
&bf,
&SerializeContext::collect_from_document(&Default::default()),
&crate::storage::Unbounded,
)
.expect("write borderFill");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r#"<hh:slash type="NONE" Crooked="2" isCounter="0"/>"#),
"slash Crooked=2 가 보존되어야 함: {xml}"
);
assert!(
xml.contains(r#"<hh:backSlash type="CENTER" Crooked="0" isCounter="0"/>"#),
"backSlash CENTER 가 보존되어야 함: {xml}"
);
}
#[test]
fn write_border_fill_serializes_solid_winbrush_not_empty() {
use crate::model::style::{Fill, SolidFill};
let mut bf = BorderFill::default();
bf.fill = Fill {
fill_type: FillType::Solid,
solid: Some(SolidFill {
background_color: 0x00D6_D6D6, pattern_color: 0x0000_0000, pattern_type: -1,
}),
alpha: 0,
..Default::default()
};
let mut writer = Writer::new(Vec::new());
write_border_fill(
&mut writer,
5,
&bf,
&SerializeContext::collect_from_document(&Default::default()),
&crate::storage::Unbounded,
)
.expect("write borderFill");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(
r##"<hc:fillBrush><hc:winBrush faceColor="#D6D6D6" hatchColor="#000000" alpha="0"/></hc:fillBrush>"##
),
"Solid 배경색이 winBrush 로 직렬화되어야 함(빈 fillBrush 아님): {xml}"
);
}
#[test]
fn write_border_fill_omits_fillbrush_when_none() {
let bf = BorderFill::default();
let mut writer = Writer::new(Vec::new());
write_border_fill(
&mut writer,
0,
&bf,
&SerializeContext::collect_from_document(&Default::default()),
&crate::storage::Unbounded,
)
.expect("write borderFill");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
!xml.contains("fillBrush"),
"FillType::None + solid 없음 은 fillBrush 미출력: {xml}"
);
}
#[test]
fn write_border_fill_restores_empty_winbrush_when_none_with_solid() {
use crate::model::style::{Fill, SolidFill};
let mut bf = BorderFill::default();
bf.fill = Fill {
fill_type: FillType::None,
solid: Some(SolidFill {
background_color: 0xFFFF_FFFF, pattern_color: 0xFF00_0000, pattern_type: -1,
}),
alpha: 0,
..Default::default()
};
let mut writer = Writer::new(Vec::new());
write_border_fill(
&mut writer,
1,
&bf,
&SerializeContext::collect_from_document(&Default::default()),
&crate::storage::Unbounded,
)
.expect("write borderFill");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(
r##"<hc:fillBrush><hc:winBrush faceColor="#FFFFFFFF" hatchColor="#FF000000" alpha="0"/></hc:fillBrush>"##
),
"보존된 빈 winBrush 가 한글 2018 호환 색 없음 값으로 복원되어야 함: {xml}"
);
let header = format!(
r#"<hh:head xmlns:hh="http://www.hancom.co.kr/hwpml/2011/head" xmlns:hc="http://www.hancom.co.kr/hwpml/2011/core"><hh:refList><hh:borderFills itemCnt="1">{xml}</hh:borderFills></hh:refList></hh:head>"#
);
let (parsed, _) = crate::parser::hwpx::header::parse_hwpx_header(&header).unwrap();
assert_eq!(parsed.border_fills[0].fill.fill_type, FillType::None);
assert_eq!(
parsed.border_fills[0]
.fill
.solid
.as_ref()
.unwrap()
.background_color,
0xffff_ffff
);
}
#[test]
fn write_tab_pr_emits_tab_item_switch_case_default() {
use crate::model::style::{TabDef, TabItem};
let mut td = TabDef::default();
td.tabs = vec![TabItem {
position: 3288,
tab_type: 0,
fill_type: 0,
}];
let mut writer = Writer::new(Vec::new());
write_tab_pr(&mut writer, 2, &td, &crate::storage::Unbounded).expect("write tabPr");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(
r#"<hp:case hp:required-namespace="http://www.hancom.co.kr/hwpml/2016/HwpUnitChar"><hh:tabItem pos="1644" type="LEFT" leader="NONE" unit="HWPUNIT"/></hp:case>"#
),
"case 는 절반값(1644) + unit=HWPUNIT: {xml}"
);
assert!(
xml.contains(
r#"<hp:default><hh:tabItem pos="3288" type="LEFT" leader="NONE"/></hp:default>"#
),
"default 는 저장값(3288), unit 없음: {xml}"
);
assert_eq!(
xml.matches("<hp:switch>").count(),
1,
"탭 1개당 switch 1개: {xml}"
);
}
#[test]
fn write_para_pr_emits_margin_switch_case_default() {
let mut ps = ParaShape::default();
ps.indent = -2620; ps.line_spacing = 130;
ps.line_spacing_type = LineSpacingType::Percent;
let mut writer = Writer::new(Vec::new());
write_para_pr(&mut writer, 1, &ps, &crate::storage::Unbounded).expect("write paraPr");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(
r#"<hp:case hp:required-namespace="http://www.hancom.co.kr/hwpml/2016/HwpUnitChar"><hh:margin><hc:intent value="-1310" unit="HWPUNIT"/>"#
),
"case 는 HwpUnitChar + intent 절반(-1310) + hc: 네임스페이스: {xml}"
);
assert!(
xml.contains(r#"<hp:default><hh:margin><hc:intent value="-2620" unit="HWPUNIT"/>"#),
"default 는 저장값(-2620): {xml}"
);
assert_eq!(
xml.matches(r#"<hh:lineSpacing type="PERCENT" value="130" unit="HWPUNIT"/>"#)
.count(),
2,
"PERCENT lineSpacing 은 case/default 양쪽에 동일 값: {xml}"
);
let auto = xml.find("autoSpacing").unwrap();
let sw = xml.find("<hp:switch>").unwrap();
let border = xml.find("<hh:border ").unwrap();
assert!(
auto < sw && sw < border,
"순서 autoSpacing<switch<border: {xml}"
);
assert!(
!xml.contains("<hh:intent"),
"margin 자식이 hh: 네임스페이스로 남으면 안 됨: {xml}"
);
}
#[test]
fn write_para_pr_emits_align_and_break_from_preserved_bits() {
let mut ps = ParaShape::default();
ps.break_latin_word = Some("HYPHENATION".to_string());
ps.attr1 = (2 << 20) | (1 << 16) | (1 << 19); ps.attr1 &= !(1 << 7); ps.attr2 = 1 << 5;
let mut writer = Writer::new(Vec::new());
write_para_pr(&mut writer, 1, &ps, &crate::storage::Unbounded).expect("write paraPr");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r#"vertical="CENTER""#),
"vertical 은 보존 비트(CENTER)에서 와야 함: {xml}"
);
assert!(
xml.contains(r#"breakLatinWord="HYPHENATION""#),
"breakLatinWord 는 HWPX 원문 보존값에서 와야 함: {xml}"
);
assert!(
xml.contains(r#"breakNonLatinWord="BREAK_WORD""#),
"breakNonLatinWord 는 보존 비트(BREAK_WORD)에서 와야 함: {xml}"
);
assert!(
xml.contains(r#"widowOrphan="1" keepWithNext="0" keepLines="0" pageBreakBefore="1""#),
"widowOrphan/pageBreakBefore 보존 비트 역매핑: {xml}"
);
assert!(
xml.contains(r#"<hh:autoSpacing eAsianEng="0" eAsianNum="1""#),
"autoSpacing은 attr2 4/5에서 역매핑해야 함: {xml}"
);
}
#[test]
fn write_para_pr_does_not_treat_auto_spacing_num_as_widow_orphan() {
let mut ps = ParaShape::default();
ps.attr2 = 1 << 5;
let mut writer = Writer::new(Vec::new());
write_para_pr(&mut writer, 1, &ps, &crate::storage::Unbounded).expect("write paraPr");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r#"widowOrphan="0""#),
"attr2 bit 5는 widowOrphan으로 해석되면 안 됨: {xml}"
);
assert!(
xml.contains(r#"<hh:autoSpacing eAsianEng="0" eAsianNum="1""#),
"attr2 bit 5는 eAsianNum으로만 방출해야 함: {xml}"
);
}
#[test]
fn write_para_pr_default_vertical_is_baseline() {
let ps = ParaShape::default();
let mut writer = Writer::new(Vec::new());
write_para_pr(&mut writer, 0, &ps, &crate::storage::Unbounded).expect("write paraPr");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r#"vertical="BASELINE""#),
"기본 vertical=BASELINE: {xml}"
);
}
#[test]
fn write_char_pr_always_emits_underline_strikeout_outline_shadow() {
let cs = CharShape::default();
let mut writer = Writer::new(Vec::new());
write_char_pr(&mut writer, 0, &cs, &crate::storage::Unbounded).expect("write charPr");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r##"<hh:underline type="NONE" shape="SOLID" color="#000000"/>"##),
"underline NONE 항상 출력: {xml}"
);
assert!(
xml.contains(r##"<hh:strikeout shape="NONE" color="#000000"/>"##),
"strikeout 은 비활성 시 shape=NONE: {xml}"
);
assert!(
xml.contains(r#"<hh:outline type="NONE"/>"#),
"outline NONE 항상 출력: {xml}"
);
assert!(
xml.contains(r#"<hh:shadow type="NONE""#),
"shadow NONE 항상 출력: {xml}"
);
}
#[test]
fn write_char_pr_preserves_opaque_black_shade() {
let cs = CharShape {
shade_color: 0x0000_0000,
..Default::default()
};
let xml = write_single_char_pr(&cs);
assert!(
xml.contains(r##"shadeColor="#000000""##),
"실제 검정 음영은 none 으로 소거하면 안 된다: {xml}"
);
assert!(
!xml.contains(r#"shadeColor="none""#),
"0x00000000은 음영 없음 sentinel 이 아니다: {xml}"
);
}
fn parse_single_char_pr(child: &str) -> CharShape {
let xml = format!(
r##"<?xml version="1.0" encoding="UTF-8"?>
<hh:head xmlns:hh="http://www.hancom.co.kr/hwpml/2011/head">
<hh:refList>
<hh:charProperties itemCnt="1">
<hh:charPr id="0" height="1000" textColor="#000000" shadeColor="none">
<hh:fontRef hangul="0" latin="0" hanja="0" japanese="0" other="0" symbol="0" user="0"/>
{child}
</hh:charPr>
</hh:charProperties>
</hh:refList>
</hh:head>"##
);
let (doc_info, _) =
crate::parser::hwpx::header::parse_hwpx_header(&xml).expect("parse hh:head");
doc_info.char_shapes[0].clone()
}
fn write_single_char_pr(cs: &CharShape) -> String {
let mut writer = Writer::new(Vec::new());
write_char_pr(&mut writer, 0, cs, &crate::storage::Unbounded).expect("write charPr");
String::from_utf8(writer.into_inner()).unwrap()
}
#[test]
fn char_pr_outline_type_roundtrips_all_eight_values() {
for (name, expected) in [
("NONE", 0u8),
("SOLID", 1),
("DASH", 2),
("DOT", 3),
("DASH_DOT", 4),
("DASH_DOT_DOT", 5),
("LONG_DASH", 6),
("CIRCLE", 7),
] {
let cs = parse_single_char_pr(&format!(r#"<hh:outline type="{name}"/>"#));
assert_eq!(
cs.outline_type, expected,
"outline type={name} 은 IR {expected} 로 파싱돼야 함"
);
let xml = write_single_char_pr(&cs);
assert!(
xml.contains(&format!(r#"<hh:outline type="{name}"/>"#)),
"outline_type={expected} 은 type=\"{name}\" 으로 방출돼야 함: {xml}"
);
}
}
#[test]
fn char_pr_shadow_drop_survives_roundtrip_with_offsets() {
let cs = parse_single_char_pr(
r##"<hh:shadow type="DROP" color="#C0C0C0" offsetX="10" offsetY="-7"/>"##,
);
assert_eq!(cs.shadow_type, 1, "DROP 은 IR 1(비연속)");
assert_eq!(cs.shadow_offset_x, 10);
assert_eq!(cs.shadow_offset_y, -7);
let xml = write_single_char_pr(&cs);
assert!(
xml.contains(r#"<hh:shadow type="DROP""#),
"shadow_type=1 은 type=\"DROP\" 으로 방출돼야 함: {xml}"
);
assert!(
xml.contains(r#"offsetX="10" offsetY="-7""#),
"오프셋도 함께 보존돼야 함: {xml}"
);
}
#[test]
fn char_pr_shadow_continuous_is_ir_two_not_one() {
let cs = parse_single_char_pr(r##"<hh:shadow type="CONTINUOUS" color="#808080"/>"##);
assert_eq!(cs.shadow_type, 2, "CONTINUOUS 는 IR 2(연속)");
let xml = write_single_char_pr(&cs);
assert!(
xml.contains(r#"<hh:shadow type="CONTINUOUS""#),
"shadow_type=2 는 type=\"CONTINUOUS\" 로 방출돼야 함: {xml}"
);
}
#[test]
fn write_para_pr_emits_condense_fontlineheight_snaptogrid_from_attr1() {
let mut ps = ParaShape::default();
ps.attr1 = (20 << 9) | (1 << 22);
let mut writer = Writer::new(Vec::new());
write_para_pr(&mut writer, 0, &ps, &crate::storage::Unbounded).expect("write paraPr");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r#"condense="20""#),
"condense=20 가 attr1 에서 직렬화되어야 함: {xml}"
);
assert!(
xml.contains(r#"fontLineHeight="1""#),
"fontLineHeight=1: {xml}"
);
assert!(
xml.contains(r#"snapToGrid="0""#),
"snapToGrid=0(bit8 clear): {xml}"
);
ps.attr1 = 1 << 8;
let mut writer = Writer::new(Vec::new());
write_para_pr(&mut writer, 0, &ps, &crate::storage::Unbounded).expect("write paraPr");
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r#"snapToGrid="1""#) && xml.contains(r#"condense="0""#),
"snapToGrid=1 + condense=0: {xml}"
);
}
#[test]
fn diagonal_shape_type_matches_hwpx_parser_codes() {
assert_eq!(diagonal_shape_type(0), "NONE");
assert_eq!(diagonal_shape_type(0b010), "CENTER");
assert_eq!(diagonal_shape_type(0b011), "CENTER_BELOW");
assert_eq!(diagonal_shape_type(0b110), "CENTER_ABOVE");
assert_eq!(diagonal_shape_type(0b111), "ALL");
}
#[test]
fn write_diagonal_omits_when_none_and_restores_type_from_code() {
let none = DiagonalLine::default();
let mut w = Writer::new(Vec::new());
write_diagonal(&mut w, &none, &crate::storage::Unbounded).expect("write");
assert_eq!(
String::from_utf8(w.into_inner()).unwrap(),
"",
"대각선 없음(code 0)은 미출력이어야 함"
);
let solid = DiagonalLine {
diagonal_type: 1,
width: 0,
color: 0,
};
let mut w = Writer::new(Vec::new());
write_diagonal(&mut w, &solid, &crate::storage::Unbounded).expect("write");
assert_eq!(
String::from_utf8(w.into_inner()).unwrap(),
r##"<hh:diagonal type="SOLID" width="0.1 mm" color="#000000"/>"##,
"SOLID 대각선은 type 코드 복원 + width 무변질"
);
}
#[test]
fn write_char_pr_use_font_space_roundtrip() {
let mut doc = Document::default();
doc.doc_info.char_shapes.push(CharShape {
use_font_space: true,
..Default::default()
});
doc.doc_info.char_shapes.push(CharShape {
use_font_space: false,
..Default::default()
});
let ctx = SerializeContext::collect_from_document(&doc);
let xml = String::from_utf8(write_header(&doc, &ctx).unwrap()).unwrap();
let first = xml.find("useFontSpace=").expect("useFontSpace attribute");
assert!(
xml[first..].starts_with(r#"useFontSpace="1""#),
"use_font_space=true → useFontSpace=\"1\": {xml}"
);
let second = xml[first + 1..]
.find("useFontSpace=")
.expect("second useFontSpace");
let second_abs = first + 1 + second;
assert!(
xml[second_abs..].starts_with(r#"useFontSpace="0""#),
"use_font_space=false → useFontSpace=\"0\": {xml}"
);
}
#[test]
fn write_numbering_splices_raw_para_heads_verbatim() {
let inner = r##"<hh:paraHead start="1" level="1" numFormat="DIGIT" charPrIDRef="4294967295" checkable="0">^1.</hh:paraHead><hh:paraHead start="1" level="8" useInstWidth="0" charPrIDRef="0"/>"##;
let n = Numbering {
start_number: 0,
raw_para_heads: Some(inner.to_string()),
..Numbering::default()
};
let mut writer = Writer::new(Vec::new());
write_numbering(&mut writer, 0, &n, &crate::storage::Unbounded).unwrap();
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert_eq!(
xml,
format!(r##"<hh:numbering id="1" start="0">{inner}</hh:numbering>"##)
);
}
#[test]
fn write_numbering_falls_back_to_skeleton_when_no_raw() {
let n = Numbering::default();
let mut writer = Writer::new(Vec::new());
write_numbering(&mut writer, 0, &n, &crate::storage::Unbounded).unwrap();
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert_eq!(xml.matches("<hh:paraHead").count(), 10);
assert!(xml.starts_with(r#"<hh:numbering id="1" start="0">"#));
}
#[test]
fn write_numbering_skeleton_emits_level_format_string_as_text() {
let mut n = Numbering::default();
n.level_formats[0] = "^1.".to_string();
n.level_formats[1] = "(^2)".to_string();
let mut writer = Writer::new(Vec::new());
write_numbering(&mut writer, 0, &n, &crate::storage::Unbounded).unwrap();
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(">^1.</hh:paraHead>"),
"level 1 형식 문자열이 텍스트 내용으로 나가야 한다: {xml}"
);
assert!(
xml.contains(">(^2)</hh:paraHead>"),
"level 2 형식 문자열이 텍스트 내용으로 나가야 한다: {xml}"
);
assert!(
xml.contains("checkable=\"0\"/>"),
"형식이 없는 수준은 자기닫힘을 유지해야 한다: {xml}"
);
}
#[test]
fn write_numbering_skeleton_uses_number_format_not_hardcoded_digit() {
let mut n = Numbering::default();
n.heads[0].number_format = 2;
let mut writer = Writer::new(Vec::new());
write_numbering(&mut writer, 0, &n, &crate::storage::Unbounded).unwrap();
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r#"numFormat="ROMAN_CAPITAL""#),
"level 1 paraHead 는 number_format=2 를 ROMAN_CAPITAL 로 방출해야 한다: {xml}"
);
}
#[test]
fn write_numbering_skeleton_preserves_text_distance_and_char_shape_id() {
let mut n = Numbering::default();
n.heads[0].text_distance = 130;
n.heads[0].char_shape_id = 7;
let mut writer = Writer::new(Vec::new());
write_numbering(&mut writer, 0, &n, &crate::storage::Unbounded).unwrap();
let xml = String::from_utf8(writer.into_inner()).unwrap();
assert!(
xml.contains(r#"textOffset="130""#),
"text_distance 유실: {xml}"
);
assert!(
xml.contains(r#"charPrIDRef="7""#),
"char_shape_id 유실: {xml}"
);
}
#[test]
fn tab_leader_str_emits_double_and_triple_line_types() {
assert_eq!(tab_leader_str(9), "SLIM_THICK");
assert_eq!(tab_leader_str(10), "THICK_SLIM");
assert_eq!(tab_leader_str(11), "SLIM_THICK_SLIM");
assert_eq!(tab_leader_str(8), "DOUBLE_SLIM");
}
}