#![allow(dead_code)]
use super::section::is_hwpx_inline_slot;
use crate::model::document::Document;
use crate::parser::hwpx::parse_hwpx;
use crate::serializer::hwpx::serialize_hwpx;
use crate::serializer::SerializeError;
mod export_cache;
pub(crate) use export_cache::project_paragraphs as project_exported_line_caches;
pub use export_cache::{diff_exported_hwp_documents, diff_exported_hwpx_documents};
#[derive(Debug, Default)]
pub struct IrDiff {
pub differences: Vec<IrDifference>,
}
impl IrDiff {
pub fn is_empty(&self) -> bool {
self.differences.is_empty()
}
pub fn push(&mut self, d: IrDifference) {
self.differences.push(d);
}
pub fn allowed(&self, _allow: IrDiffAllow) -> bool {
self.is_empty()
}
}
#[derive(Debug, Default, Clone, Copy)]
pub struct IrDiffAllow {
pub shape_raw: bool,
}
#[derive(Debug, Clone)]
pub enum IrDifference {
SectionCount {
expected: usize,
actual: usize,
},
ParagraphCount {
section: usize,
expected: usize,
actual: usize,
},
CharShapeCount {
expected: usize,
actual: usize,
},
ParaShapeCount {
expected: usize,
actual: usize,
},
BorderFillCount {
expected: usize,
actual: usize,
},
TabDefCount {
expected: usize,
actual: usize,
},
NumberingCount {
expected: usize,
actual: usize,
},
StyleCount {
expected: usize,
actual: usize,
},
BinDataContentCount {
expected: usize,
actual: usize,
},
ParagraphCharShapes {
section: usize,
paragraph: usize,
path: String,
expected: String,
actual: String,
},
ParagraphControls {
section: usize,
paragraph: usize,
path: String,
expected: String,
actual: String,
},
ParagraphLinesegs {
section: usize,
paragraph: usize,
path: String,
detail: String,
},
SectionPageDef {
section: usize,
detail: String,
},
SectionVisibility {
section: usize,
detail: String,
},
TableCaption {
section: usize,
paragraph: usize,
path: String,
detail: String,
},
ObjectCaption {
section: usize,
paragraph: usize,
path: String,
detail: String,
},
ObjectComment {
section: usize,
paragraph: usize,
path: String,
detail: String,
},
FieldContent {
section: usize,
paragraph: usize,
path: String,
detail: String,
},
PictureSize {
section: usize,
paragraph: usize,
path: String,
detail: String,
},
TablePageBreak {
section: usize,
paragraph: usize,
path: String,
detail: String,
},
ObjectHoldAnchor {
section: usize,
paragraph: usize,
path: String,
detail: String,
},
ObjectFlowWithText {
section: usize,
paragraph: usize,
path: String,
detail: String,
},
}
impl std::fmt::Display for IrDifference {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use IrDifference::*;
match self {
SectionCount { expected, actual } => {
write!(f, "section count: expected={} actual={}", expected, actual)
}
ParagraphCount {
section,
expected,
actual,
} => write!(
f,
"section[{}] paragraph count: expected={} actual={}",
section, expected, actual
),
CharShapeCount { expected, actual } => write!(
f,
"char_shapes count: expected={} actual={}",
expected, actual
),
ParaShapeCount { expected, actual } => write!(
f,
"para_shapes count: expected={} actual={}",
expected, actual
),
BorderFillCount { expected, actual } => write!(
f,
"border_fills count: expected={} actual={}",
expected, actual
),
TabDefCount { expected, actual } => {
write!(f, "tab_defs count: expected={} actual={}", expected, actual)
}
NumberingCount { expected, actual } => write!(
f,
"numberings count: expected={} actual={}",
expected, actual
),
StyleCount { expected, actual } => {
write!(f, "styles count: expected={} actual={}", expected, actual)
}
BinDataContentCount { expected, actual } => write!(
f,
"bin_data_content count: expected={} actual={}",
expected, actual
),
ParagraphCharShapes {
section,
paragraph,
path,
expected,
actual,
} => write!(
f,
"section[{}] paragraph[{}]{} char_shapes: expected={} actual={}",
section, paragraph, path, expected, actual
),
ParagraphControls {
section,
paragraph,
path,
expected,
actual,
} => write!(
f,
"section[{}] paragraph[{}]{} controls: expected={} actual={}",
section, paragraph, path, expected, actual
),
ParagraphLinesegs {
section,
paragraph,
path,
detail,
} => write!(
f,
"section[{}] paragraph[{}]{} linesegs: {}",
section, paragraph, path, detail
),
SectionPageDef { section, detail } => {
write!(f, "section[{}] page_def: {}", section, detail)
}
SectionVisibility { section, detail } => {
write!(f, "section[{}] visibility: {}", section, detail)
}
TableCaption {
section,
paragraph,
path,
detail,
} => write!(
f,
"section[{}] paragraph[{}]{} caption: {}",
section, paragraph, path, detail
),
ObjectCaption {
section,
paragraph,
path,
detail,
} => write!(
f,
"section[{}] paragraph[{}]{} caption: {}",
section, paragraph, path, detail
),
ObjectComment {
section,
paragraph,
path,
detail,
} => write!(
f,
"section[{}] paragraph[{}]{} comment: {}",
section, paragraph, path, detail
),
FieldContent {
section,
paragraph,
path,
detail,
} => write!(
f,
"section[{}] paragraph[{}]{} field: {}",
section, paragraph, path, detail
),
PictureSize {
section,
paragraph,
path,
detail,
} => write!(
f,
"section[{}] paragraph[{}]{} pic_size: {}",
section, paragraph, path, detail
),
TablePageBreak {
section,
paragraph,
path,
detail,
} => write!(
f,
"section[{}] paragraph[{}]{} tbl page_break: {}",
section, paragraph, path, detail
),
ObjectHoldAnchor {
section,
paragraph,
path,
detail,
} => write!(
f,
"section[{}] paragraph[{}]{} holdAnchorAndSO: {}",
section, paragraph, path, detail
),
ObjectFlowWithText {
section,
paragraph,
path,
detail,
} => write!(
f,
"section[{}] paragraph[{}]{} flowWithText: {}",
section, paragraph, path, detail
),
}
}
}
fn diff_picture_size(
a: &crate::model::image::Picture,
b: &crate::model::image::Picture,
) -> Option<String> {
let mut parts: Vec<String> = Vec::new();
if a.shape_attr.current_width != b.shape_attr.current_width
|| a.shape_attr.current_height != b.shape_attr.current_height
{
parts.push(format!(
"curSz: expected={}x{} actual={}x{}",
a.shape_attr.current_width,
a.shape_attr.current_height,
b.shape_attr.current_width,
b.shape_attr.current_height
));
}
if a.border_x != b.border_x || a.border_y != b.border_y {
parts.push(format!(
"imgRect: expected={:?}/{:?} actual={:?}/{:?}",
a.border_x, a.border_y, b.border_x, b.border_y
));
}
if a.img_dim != b.img_dim {
parts.push(format!(
"imgDim: expected={:?} actual={:?}",
a.img_dim, b.img_dim
));
}
if a.shape_attr.offset_x != b.shape_attr.offset_x
|| a.shape_attr.offset_y != b.shape_attr.offset_y
{
parts.push(format!(
"offset: expected=({}, {}) actual=({}, {})",
a.shape_attr.offset_x,
a.shape_attr.offset_y,
b.shape_attr.offset_x,
b.shape_attr.offset_y
));
}
if parts.is_empty() {
None
} else {
Some(parts.join("; "))
}
}
fn diff_object_comment(a: &str, b: &str) -> Option<String> {
if a == b {
None
} else {
Some(format!("expected={:?} actual={:?}", a, b))
}
}
fn diff_hold_anchor(
a: &crate::model::shape::CommonObjAttr,
b: &crate::model::shape::CommonObjAttr,
) -> Option<String> {
if a.prevent_page_break == b.prevent_page_break {
None
} else {
Some(format!(
"expected={} actual={}",
a.prevent_page_break, b.prevent_page_break
))
}
}
fn diff_flow_with_text(
a: &crate::model::shape::CommonObjAttr,
b: &crate::model::shape::CommonObjAttr,
) -> Option<String> {
if a.flow_with_text == b.flow_with_text {
None
} else {
Some(format!(
"expected={} actual={}",
a.flow_with_text, b.flow_with_text
))
}
}
pub fn roundtrip_ir_diff(hwpx_bytes: &[u8]) -> Result<IrDiff, SerializeError> {
let doc1 = parse_hwpx(hwpx_bytes)
.map_err(|e| SerializeError::XmlError(format!("원본 HWPX 파싱 실패: {}", e)))?;
let out = serialize_hwpx(&doc1)?;
let doc2 = parse_hwpx(&out)
.map_err(|e| SerializeError::XmlError(format!("재직렬화 HWPX 파싱 실패: {}", e)))?;
Ok(diff_documents(&doc1, &doc2))
}
pub fn strip_cross_format_noise(diff: IrDiff) -> IrDiff {
IrDiff {
differences: diff
.differences
.into_iter()
.filter(|d| !is_cross_format_incomparable(d))
.collect(),
}
}
pub fn strip_hwp_to_hwpx_noise(diff: IrDiff) -> IrDiff {
IrDiff {
differences: diff
.differences
.into_iter()
.filter(|d| !is_hwp_to_hwpx_incomparable(d))
.collect(),
}
}
pub fn strip_hwp3_to_hwpx_noise(
expected_document: &Document,
actual_document: &Document,
diff: IrDiff,
) -> IrDiff {
let mut diff = strip_hwp_to_hwpx_noise(diff);
diff.differences.retain(|difference| {
!is_hwp3_to_hwpx_incomparable(expected_document, actual_document, difference)
});
diff
}
pub fn strip_hwpx_to_hwp_noise(diff: IrDiff) -> IrDiff {
let mut diff = strip_cross_format_noise(diff);
diff.differences
.retain(|difference| !is_hwpx_to_hwp_incomparable(difference));
diff
}
fn is_cross_format_incomparable(d: &IrDifference) -> bool {
match d {
IrDifference::FieldContent { detail, .. } => {
detail.contains("parameters:") && detail.contains("actual=None")
}
IrDifference::PictureSize { detail, .. } => {
detail.starts_with("imgDim: expected=(0, 0)") && !detail.contains(';')
}
_ => false,
}
}
fn is_hwp_to_hwpx_incomparable(d: &IrDifference) -> bool {
match d {
IrDifference::FieldContent { detail, .. } => {
const PREFIX: &str = r#"parameters: expected=None actual=Some("<hp:parameters cnt=\"1\" name=\"\"><hp:stringParam name=\"Command\">"#;
const SUFFIX: &str = r#"</hp:stringParam></hp:parameters>")"#;
if detail.starts_with(PREFIX) && detail.ends_with(SUFFIX) {
return true;
}
const MEMO_PREFIX: &str = r#"parameters: expected=None actual=Some("<hp:parameters cnt=\"6\" name=\"\"><hp:integerParam name=\"Prop\">0</hp:integerParam><hp:stringParam name=\"Command\">MEMO/"#;
if detail.starts_with(MEMO_PREFIX) {
return true;
}
detail == "memo paragraphs: expected=0 actual=1"
}
_ => false,
}
}
fn is_hwp3_to_hwpx_incomparable(
expected_document: &Document,
actual_document: &Document,
d: &IrDifference,
) -> bool {
match d {
IrDifference::ParagraphControls {
section,
paragraph,
path,
expected,
actual,
} => {
expected == "[]"
&& actual == "[field]"
&& is_hwp3_top_level_hyperlink_field_materialization(
expected_document,
actual_document,
*section,
*paragraph,
path,
)
}
IrDifference::PictureSize { detail, .. } => is_hwp3_zero_img_rect_materialization(detail),
_ => false,
}
}
fn is_hwp3_top_level_hyperlink_field_materialization(
expected_document: &Document,
actual_document: &Document,
section: usize,
paragraph: usize,
path: &str,
) -> bool {
if !path.is_empty() {
return false;
}
let Some(expected) = expected_document
.sections
.get(section)
.and_then(|section| section.paragraphs.get(paragraph))
else {
return false;
};
let Some(actual) = actual_document
.sections
.get(section)
.and_then(|section| section.paragraphs.get(paragraph))
else {
return false;
};
expected
.controls
.iter()
.any(|control| matches!(control, crate::model::control::Control::Hyperlink(_)))
&& actual.controls.iter().any(|control| {
matches!(
control,
crate::model::control::Control::Field(field)
if field.field_type == crate::model::control::FieldType::Hyperlink
)
})
}
fn is_hwp3_zero_img_rect_materialization(detail: &str) -> bool {
const PREFIX: &str = "imgRect: expected=[0, 0, 0, 0]/[0, 0, 0, 0] actual=";
if !detail.starts_with(PREFIX) || detail.contains(';') {
return false;
}
let Some((x_part, y_part)) = detail[PREFIX.len()..].split_once('/') else {
return false;
};
let x: Vec<i32> = x_part
.strip_prefix('[')
.unwrap_or_default()
.strip_suffix(']')
.unwrap_or_default()
.split(", ")
.filter_map(|value| value.parse().ok())
.collect();
let y: Vec<i32> = y_part
.strip_prefix('[')
.unwrap_or_default()
.strip_suffix(']')
.unwrap_or_default()
.split(", ")
.filter_map(|value| value.parse().ok())
.collect();
matches!(
(x.as_slice(), y.as_slice()),
([0, 0, width, 0], [same_width, height, 0, same_height])
if *width > 0
&& *height > 0
&& width == same_width
&& height == same_height
)
}
fn is_hwpx_to_hwp_incomparable(d: &IrDifference) -> bool {
match d {
IrDifference::PictureSize { detail, .. } => {
detail.starts_with("imgDim: expected=(")
&& detail.ends_with(" actual=(0, 0)")
&& !detail.contains(';')
}
_ => false,
}
}
pub fn hwpx_export_expected_document(doc: &Document) -> Document {
let mut expected = doc.clone();
for section in &mut expected.sections {
for para in &mut section.paragraphs {
normalize_paragraph_like_hwpx_export(para);
}
}
expected
}
fn normalize_paragraph_like_hwpx_export(para: &mut crate::model::paragraph::Paragraph) {
use crate::model::control::Control;
for control in &mut para.controls {
match control {
Control::Table(table) => {
for cell in &mut table.cells {
cell.paragraphs
.iter_mut()
.for_each(normalize_paragraph_like_hwpx_export);
}
if let Some(caption) = &mut table.caption {
caption
.paragraphs
.iter_mut()
.for_each(normalize_paragraph_like_hwpx_export);
}
}
Control::Picture(picture) => {
if let Some(caption) = &mut picture.caption {
caption
.paragraphs
.iter_mut()
.for_each(normalize_paragraph_like_hwpx_export);
}
}
Control::Shape(shape) => {
if let Some(text_box) = shape_text_box_mut(shape) {
text_box
.paragraphs
.iter_mut()
.for_each(normalize_paragraph_like_hwpx_export);
}
if let Some(caption) = shape_caption_mut(shape) {
caption
.paragraphs
.iter_mut()
.for_each(normalize_paragraph_like_hwpx_export);
}
}
Control::Footnote(note) => note
.paragraphs
.iter_mut()
.for_each(normalize_paragraph_like_hwpx_export),
Control::Endnote(note) => note
.paragraphs
.iter_mut()
.for_each(normalize_paragraph_like_hwpx_export),
Control::Header(header) => header
.paragraphs
.iter_mut()
.for_each(normalize_paragraph_like_hwpx_export),
Control::Footer(footer) => footer
.paragraphs
.iter_mut()
.for_each(normalize_paragraph_like_hwpx_export),
_ => {}
}
}
for index in super::section::hwpx_collapsed_page_number_pos_indices(para)
.into_iter()
.rev()
{
para.remove_control_slot_like_hwpx_export(index);
}
if super::section::line_segs_are_all_synthetic(¶.line_segs) {
para.line_segs.clear();
}
}
fn shape_text_box_mut(
s: &mut crate::model::shape::ShapeObject,
) -> Option<&mut crate::model::shape::TextBox> {
use crate::model::shape::ShapeObject::*;
match s {
Line(x) => x.drawing.text_box.as_mut(),
Rectangle(x) => x.drawing.text_box.as_mut(),
Ellipse(x) => x.drawing.text_box.as_mut(),
Arc(x) => x.drawing.text_box.as_mut(),
Polygon(x) => x.drawing.text_box.as_mut(),
Curve(x) => x.drawing.text_box.as_mut(),
Chart(x) => x.drawing.text_box.as_mut(),
Ole(x) => x.drawing.text_box.as_mut(),
Group(_) | Picture(_) => None,
}
}
fn shape_caption_mut(
s: &mut crate::model::shape::ShapeObject,
) -> Option<&mut crate::model::shape::Caption> {
use crate::model::shape::ShapeObject::*;
match s {
Line(x) => x.drawing.caption.as_mut(),
Rectangle(x) => x.drawing.caption.as_mut(),
Ellipse(x) => x.drawing.caption.as_mut(),
Arc(x) => x.drawing.caption.as_mut(),
Polygon(x) => x.drawing.caption.as_mut(),
Curve(x) => x.drawing.caption.as_mut(),
Chart(x) => x.caption.as_mut(),
Ole(x) => x.caption.as_mut(),
Group(x) => x.caption.as_mut(),
Picture(x) => x.caption.as_mut(),
}
}
pub fn diff_documents(a: &Document, b: &Document) -> IrDiff {
let mut diff = IrDiff::default();
if a.sections.len() != b.sections.len() {
diff.push(IrDifference::SectionCount {
expected: a.sections.len(),
actual: b.sections.len(),
});
}
let pairs = a.sections.len().min(b.sections.len());
for i in 0..pairs {
let ap = a.sections[i].paragraphs.len();
let bp = b.sections[i].paragraphs.len();
if ap != bp {
diff.push(IrDifference::ParagraphCount {
section: i,
expected: ap,
actual: bp,
});
}
if let Some(detail) = diff_page_def(
&a.sections[i].section_def.page_def,
&b.sections[i].section_def.page_def,
) {
diff.push(IrDifference::SectionPageDef { section: i, detail });
}
if let Some(detail) =
diff_visibility(&a.sections[i].section_def, &b.sections[i].section_def)
{
diff.push(IrDifference::SectionVisibility { section: i, detail });
}
let pp = ap.min(bp);
for j in 0..pp {
diff_paragraph_char_shapes(
&mut diff,
i,
j,
"",
&a.sections[i].paragraphs[j],
&b.sections[i].paragraphs[j],
);
}
}
if a.doc_info.char_shapes.len() != b.doc_info.char_shapes.len() {
diff.push(IrDifference::CharShapeCount {
expected: a.doc_info.char_shapes.len(),
actual: b.doc_info.char_shapes.len(),
});
}
if a.doc_info.para_shapes.len() != b.doc_info.para_shapes.len() {
diff.push(IrDifference::ParaShapeCount {
expected: a.doc_info.para_shapes.len(),
actual: b.doc_info.para_shapes.len(),
});
}
if a.doc_info.border_fills.len() != b.doc_info.border_fills.len() {
diff.push(IrDifference::BorderFillCount {
expected: a.doc_info.border_fills.len(),
actual: b.doc_info.border_fills.len(),
});
}
if a.doc_info.tab_defs.len() != b.doc_info.tab_defs.len() {
diff.push(IrDifference::TabDefCount {
expected: a.doc_info.tab_defs.len(),
actual: b.doc_info.tab_defs.len(),
});
}
if a.doc_info.numberings.len() != b.doc_info.numberings.len() {
diff.push(IrDifference::NumberingCount {
expected: a.doc_info.numberings.len(),
actual: b.doc_info.numberings.len(),
});
}
if a.doc_info.styles.len() != b.doc_info.styles.len() {
diff.push(IrDifference::StyleCount {
expected: a.doc_info.styles.len(),
actual: b.doc_info.styles.len(),
});
}
let non_empty = |d: &Document| -> usize {
d.bin_data_content
.iter()
.filter(|c| !c.data.is_empty())
.count()
};
if non_empty(a) != non_empty(b) {
diff.push(IrDifference::BinDataContentCount {
expected: non_empty(a),
actual: non_empty(b),
});
}
for d in diff_linesegs(a, b) {
diff.push(IrDifference::ParagraphLinesegs {
section: d.section,
paragraph: d.paragraph,
path: d.path,
detail: d.kind.to_string(),
});
}
diff
}
fn diff_table_caption(
a: &Option<crate::model::shape::Caption>,
b: &Option<crate::model::shape::Caption>,
) -> Option<String> {
let (a, b) = match (a, b) {
(None, None) => return None,
(Some(_), None) => return Some("missing: expected=Some actual=None".to_string()),
(None, Some(_)) => return Some("synthetic: expected=None actual=Some".to_string()),
(Some(a), Some(b)) => (a, b),
};
let mut parts: Vec<String> = Vec::new();
if a.direction != b.direction {
parts.push(format!(
"side: expected={:?} actual={:?}",
a.direction, b.direction
));
}
if a.include_margin != b.include_margin {
parts.push(format!(
"fullSz: expected={} actual={}",
a.include_margin, b.include_margin
));
}
if a.width != b.width {
parts.push(format!("width: expected={} actual={}", a.width, b.width));
}
if a.spacing != b.spacing {
parts.push(format!("gap: expected={} actual={}", a.spacing, b.spacing));
}
if a.max_width != b.max_width {
parts.push(format!(
"lastWidth: expected={} actual={}",
a.max_width, b.max_width
));
}
if a.paragraphs.len() != b.paragraphs.len() {
parts.push(format!(
"paragraphs: expected={} actual={}",
a.paragraphs.len(),
b.paragraphs.len()
));
}
if parts.is_empty() {
None
} else {
Some(parts.join("; "))
}
}
fn diff_page_def(
a: &crate::model::page::PageDef,
b: &crate::model::page::PageDef,
) -> Option<String> {
let mut parts: Vec<String> = Vec::new();
macro_rules! cmp_field {
($field:ident) => {
if a.$field != b.$field {
parts.push(format!(
"{}: expected={} actual={}",
stringify!($field),
a.$field,
b.$field
));
}
};
}
cmp_field!(width);
cmp_field!(height);
cmp_field!(margin_left);
cmp_field!(margin_right);
cmp_field!(margin_top);
cmp_field!(margin_bottom);
cmp_field!(margin_header);
cmp_field!(margin_footer);
cmp_field!(margin_gutter);
cmp_field!(landscape);
if a.binding != b.binding {
parts.push(format!(
"binding: expected={:?} actual={:?}",
a.binding, b.binding
));
}
if parts.is_empty() {
None
} else {
Some(parts.join("; "))
}
}
fn diff_visibility(
a: &crate::model::document::SectionDef,
b: &crate::model::document::SectionDef,
) -> Option<String> {
let mut parts: Vec<String> = Vec::new();
macro_rules! cmp_field {
($field:ident) => {
if a.$field != b.$field {
parts.push(format!(
"{}: expected={} actual={}",
stringify!($field),
a.$field,
b.$field
));
}
};
}
cmp_field!(hide_header);
cmp_field!(hide_footer);
cmp_field!(hide_master_page);
cmp_field!(hide_border);
cmp_field!(hide_fill);
cmp_field!(first_page_border);
cmp_field!(first_page_fill);
cmp_field!(hide_empty_line);
if parts.is_empty() {
None
} else {
Some(parts.join("; "))
}
}
#[derive(Debug, Clone)]
pub struct LinesegDiff {
pub section: usize,
pub paragraph: usize,
pub path: String,
pub kind: LinesegDiffKind,
}
#[derive(Debug, Clone)]
pub enum LinesegDiffKind {
CountMismatch { expected: usize, actual: usize },
ValueMismatch {
index: usize,
field: &'static str,
expected: i64,
actual: i64,
},
}
impl std::fmt::Display for LinesegDiffKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
LinesegDiffKind::CountMismatch { expected, actual } => {
write!(f, "count: expected={} actual={}", expected, actual)
}
LinesegDiffKind::ValueMismatch {
index,
field,
expected,
actual,
} => write!(
f,
"[{}].{}: expected={} actual={}",
index, field, expected, actual
),
}
}
}
pub fn diff_linesegs(a: &Document, b: &Document) -> Vec<LinesegDiff> {
let mut out = Vec::new();
let pairs = a.sections.len().min(b.sections.len());
for i in 0..pairs {
let pp = a.sections[i]
.paragraphs
.len()
.min(b.sections[i].paragraphs.len());
for j in 0..pp {
diff_paragraph_linesegs(
&mut out,
i,
j,
"",
&a.sections[i].paragraphs[j],
&b.sections[i].paragraphs[j],
);
}
}
out
}
fn axis_comparable_line_segs(
para: &crate::model::paragraph::Paragraph,
axis_end: u32,
) -> &[crate::model::paragraph::LineSeg] {
if axis_end == 0 {
return ¶.line_segs;
}
crate::serializer::body_text::line_segs_within_text_axis(¶.line_segs, axis_end)
}
fn axis_rebase_cap(pa: &crate::model::paragraph::Paragraph) -> u32 {
use crate::model::control::Control;
8 * pa
.controls
.iter()
.filter(|c| matches!(c, Control::SectionDef(_) | Control::ColumnDef(_)))
.count() as u32
}
fn diff_paragraph_linesegs(
out: &mut Vec<LinesegDiff>,
section: usize,
paragraph: usize,
path: &str,
pa: &crate::model::paragraph::Paragraph,
pb: &crate::model::paragraph::Paragraph,
) {
diff_paragraph_linesegs_with_axis(
out,
section,
paragraph,
path,
pa,
pb,
pa.char_count,
pb.char_count,
);
}
fn diff_paragraph_linesegs_with_axis(
out: &mut Vec<LinesegDiff>,
section: usize,
paragraph: usize,
path: &str,
pa: &crate::model::paragraph::Paragraph,
pb: &crate::model::paragraph::Paragraph,
a_axis_end: u32,
b_axis_end: u32,
) {
use crate::model::control::Control;
let comparable_axis_end = a_axis_end.max(b_axis_end);
let la = axis_comparable_line_segs(pa, comparable_axis_end);
let lb = axis_comparable_line_segs(pb, comparable_axis_end);
if la.len() != lb.len() {
out.push(LinesegDiff {
section,
paragraph,
path: path.to_string(),
kind: LinesegDiffKind::CountMismatch {
expected: la.len(),
actual: lb.len(),
},
});
}
let axis_rebase_cap = axis_rebase_cap(pa);
for (idx, (sa, sb)) in la.iter().zip(lb.iter()).enumerate() {
let ta = pa.line_seg_text_start_of(sa.text_start);
let tb = pb.line_seg_text_start_of(sb.text_start);
let shift = ta.checked_sub(tb).unwrap_or(u32::MAX);
let text_start_a = if shift > 0 && shift.is_multiple_of(8) && shift <= axis_rebase_cap {
tb
} else {
ta
};
let fields: [(&'static str, i64, i64); 9] = [
("textpos", text_start_a as i64, tb as i64),
("vertpos", sa.vertical_pos as i64, sb.vertical_pos as i64),
("vertsize", sa.line_height as i64, sb.line_height as i64),
("textheight", sa.text_height as i64, sb.text_height as i64),
(
"baseline",
sa.baseline_distance as i64,
sb.baseline_distance as i64,
),
("spacing", sa.line_spacing as i64, sb.line_spacing as i64),
("horzpos", sa.column_start as i64, sb.column_start as i64),
("horzsize", sa.segment_width as i64, sb.segment_width as i64),
("flags", sa.tag as i64, sb.tag as i64),
];
for (field, ea, eb) in fields {
if ea != eb {
out.push(LinesegDiff {
section,
paragraph,
path: path.to_string(),
kind: LinesegDiffKind::ValueMismatch {
index: idx,
field,
expected: ea,
actual: eb,
},
});
}
}
}
for (ci, (ctrl_a, ctrl_b)) in pa.controls.iter().zip(pb.controls.iter()).enumerate() {
match (ctrl_a, ctrl_b) {
(Control::Table(ta), Control::Table(tb)) => {
for (cell_i, (cea, ceb)) in ta.cells.iter().zip(tb.cells.iter()).enumerate() {
for (k, (qa, qb)) in
cea.paragraphs.iter().zip(ceb.paragraphs.iter()).enumerate()
{
let p = format!("{path}/ctrl[{ci}]tbl.cell[{cell_i}].p[{k}]");
diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
}
}
if let (Some(ca), Some(cb)) = (&ta.caption, &tb.caption) {
for (k, (qa, qb)) in ca.paragraphs.iter().zip(cb.paragraphs.iter()).enumerate()
{
let p = format!("{path}/ctrl[{ci}]tbl.caption.p[{k}]");
diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
}
}
}
(Control::Picture(pia), Control::Picture(pib)) => {
if let (Some(ca), Some(cb)) = (&pia.caption, &pib.caption) {
for (k, (qa, qb)) in ca.paragraphs.iter().zip(cb.paragraphs.iter()).enumerate()
{
let p = format!("{path}/ctrl[{ci}]pic.caption.p[{k}]");
diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
}
}
}
(Control::Shape(sa), Control::Shape(sb)) => {
let p = format!("{path}/ctrl[{ci}]shape");
diff_shape_linesegs(out, section, paragraph, &p, sa, sb);
}
(Control::Footnote(na), Control::Footnote(nb)) => {
for (k, (qa, qb)) in na.paragraphs.iter().zip(nb.paragraphs.iter()).enumerate() {
let p = format!("{path}/ctrl[{ci}]fn.p[{k}]");
diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
}
}
(Control::Endnote(na), Control::Endnote(nb)) => {
for (k, (qa, qb)) in na.paragraphs.iter().zip(nb.paragraphs.iter()).enumerate() {
let p = format!("{path}/ctrl[{ci}]en.p[{k}]");
diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
}
}
(Control::Field(fa), Control::Field(fb)) => {
for (k, (qa, qb)) in fa
.memo_paragraphs
.iter()
.zip(fb.memo_paragraphs.iter())
.enumerate()
{
let p = format!("{path}/ctrl[{ci}]field.memo.p[{k}]");
diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
}
}
_ => {}
}
}
}
fn diff_shape_linesegs(
out: &mut Vec<LinesegDiff>,
section: usize,
paragraph: usize,
path: &str,
sa: &crate::model::shape::ShapeObject,
sb: &crate::model::shape::ShapeObject,
) {
use crate::model::shape::ShapeObject;
if let (Some(ta), Some(tb)) = (shape_text_box(sa), shape_text_box(sb)) {
for (k, (qa, qb)) in ta.paragraphs.iter().zip(tb.paragraphs.iter()).enumerate() {
let p = format!("{path}.tb.p[{k}]");
diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
}
}
if let (Some(ca), Some(cb)) = (shape_caption(sa), shape_caption(sb)) {
for (k, (qa, qb)) in ca.paragraphs.iter().zip(cb.paragraphs.iter()).enumerate() {
let p = format!("{path}.caption.p[{k}]");
diff_paragraph_linesegs(out, section, paragraph, &p, qa, qb);
}
}
if let (ShapeObject::Group(ga), ShapeObject::Group(gb)) = (sa, sb) {
for (k, (c1, c2)) in ga.children.iter().zip(gb.children.iter()).enumerate() {
let p = format!("{path}.child[{k}]");
diff_shape_linesegs(out, section, paragraph, &p, c1, c2);
}
}
}
fn diff_paragraph_char_shapes(
diff: &mut IrDiff,
section: usize,
paragraph: usize,
path: &str,
pa: &crate::model::paragraph::Paragraph,
pb: &crate::model::paragraph::Paragraph,
) {
use crate::model::control::Control;
let ca = &pa.char_shapes;
let cb = &pb.char_shapes;
let same = ca.len() == cb.len()
&& ca
.iter()
.zip(cb.iter())
.all(|(x, y)| x.start_pos == y.start_pos && x.char_shape_id == y.char_shape_id);
if !same {
diff.push(IrDifference::ParagraphCharShapes {
section,
paragraph,
path: path.to_string(),
expected: format_char_shapes(ca),
actual: format_char_shapes(cb),
});
}
let sa: Vec<&Control> = pa
.controls
.iter()
.filter(|c| is_hwpx_inline_slot(c))
.collect();
let sb: Vec<&Control> = pb
.controls
.iter()
.filter(|c| is_hwpx_inline_slot(c))
.collect();
let ctrl_same = sa.len() == sb.len()
&& sa
.iter()
.zip(sb.iter())
.all(|(x, y)| control_type_name(x) == control_type_name(y));
if !ctrl_same {
diff.push(IrDifference::ParagraphControls {
section,
paragraph,
path: path.to_string(),
expected: format_control_types(&sa),
actual: format_control_types(&sb),
});
}
for (ci, (ctrl_a, ctrl_b)) in pa.controls.iter().zip(pb.controls.iter()).enumerate() {
match (ctrl_a, ctrl_b) {
(Control::Table(ta), Control::Table(tb)) => {
if ta.page_break != tb.page_break {
diff.push(IrDifference::TablePageBreak {
section,
paragraph,
path: format!("{path}/ctrl[{ci}]tbl"),
detail: format!("expected={:?} actual={:?}", ta.page_break, tb.page_break),
});
}
if let Some(detail) = diff_hold_anchor(&ta.common, &tb.common) {
diff.push(IrDifference::ObjectHoldAnchor {
section,
paragraph,
path: format!("{path}/ctrl[{ci}]tbl"),
detail,
});
}
if let Some(detail) = diff_flow_with_text(&ta.common, &tb.common) {
diff.push(IrDifference::ObjectFlowWithText {
section,
paragraph,
path: format!("{path}/ctrl[{ci}]tbl"),
detail,
});
}
for (cell_i, (cea, ceb)) in ta.cells.iter().zip(tb.cells.iter()).enumerate() {
for (k, (qa, qb)) in
cea.paragraphs.iter().zip(ceb.paragraphs.iter()).enumerate()
{
let p = format!("{path}/ctrl[{ci}]tbl.cell[{cell_i}].p[{k}]");
diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
}
}
if let Some(detail) = diff_table_caption(&ta.caption, &tb.caption) {
diff.push(IrDifference::TableCaption {
section,
paragraph,
path: format!("{path}/ctrl[{ci}]tbl.caption"),
detail,
});
}
if let (Some(ca), Some(cb)) = (&ta.caption, &tb.caption) {
for (k, (qa, qb)) in ca.paragraphs.iter().zip(cb.paragraphs.iter()).enumerate()
{
let p = format!("{path}/ctrl[{ci}]tbl.caption.p[{k}]");
diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
}
}
}
(Control::Picture(pia), Control::Picture(pib)) => {
if let Some(detail) = diff_picture_size(pia, pib) {
diff.push(IrDifference::PictureSize {
section,
paragraph,
path: format!("{path}/ctrl[{ci}]pic"),
detail,
});
}
if let Some(detail) = diff_table_caption(&pia.caption, &pib.caption) {
diff.push(IrDifference::ObjectCaption {
section,
paragraph,
path: format!("{path}/ctrl[{ci}]pic.caption"),
detail,
});
}
if let Some(detail) =
diff_object_comment(&pia.common.description, &pib.common.description)
{
diff.push(IrDifference::ObjectComment {
section,
paragraph,
path: format!("{path}/ctrl[{ci}]pic"),
detail,
});
}
if let Some(detail) = diff_hold_anchor(&pia.common, &pib.common) {
diff.push(IrDifference::ObjectHoldAnchor {
section,
paragraph,
path: format!("{path}/ctrl[{ci}]pic"),
detail,
});
}
if let (Some(ca), Some(cb)) = (&pia.caption, &pib.caption) {
for (k, (qa, qb)) in ca.paragraphs.iter().zip(cb.paragraphs.iter()).enumerate()
{
let p = format!("{path}/ctrl[{ci}]pic.caption.p[{k}]");
diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
}
}
}
(Control::Equation(ea), Control::Equation(eb)) => {
if let Some(detail) =
diff_object_comment(&ea.common.description, &eb.common.description)
{
diff.push(IrDifference::ObjectComment {
section,
paragraph,
path: format!("{path}/ctrl[{ci}]eq"),
detail,
});
}
if let Some(detail) = diff_hold_anchor(&ea.common, &eb.common) {
diff.push(IrDifference::ObjectHoldAnchor {
section,
paragraph,
path: format!("{path}/ctrl[{ci}]eq"),
detail,
});
}
if let Some(detail) = diff_flow_with_text(&ea.common, &eb.common) {
diff.push(IrDifference::ObjectFlowWithText {
section,
paragraph,
path: format!("{path}/ctrl[{ci}]eq"),
detail,
});
}
}
(Control::Shape(sa), Control::Shape(sb)) => {
let p = format!("{path}/ctrl[{ci}]shape");
diff_shape_char_shapes(diff, section, paragraph, &p, sa, sb);
}
(Control::Footnote(na), Control::Footnote(nb)) => {
for (k, (qa, qb)) in na.paragraphs.iter().zip(nb.paragraphs.iter()).enumerate() {
let p = format!("{path}/ctrl[{ci}]fn.p[{k}]");
diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
}
}
(Control::Endnote(na), Control::Endnote(nb)) => {
for (k, (qa, qb)) in na.paragraphs.iter().zip(nb.paragraphs.iter()).enumerate() {
let p = format!("{path}/ctrl[{ci}]en.p[{k}]");
diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
}
}
(Control::Field(fa), Control::Field(fb)) => {
if fa.raw_parameters_xml != fb.raw_parameters_xml {
diff.push(IrDifference::FieldContent {
section,
paragraph,
path: format!("{path}/ctrl[{ci}]field"),
detail: format!(
"parameters: expected={:?} actual={:?}",
fa.raw_parameters_xml, fb.raw_parameters_xml
),
});
}
if fa.memo_paragraphs.len() != fb.memo_paragraphs.len() {
diff.push(IrDifference::FieldContent {
section,
paragraph,
path: format!("{path}/ctrl[{ci}]field"),
detail: format!(
"memo paragraphs: expected={} actual={}",
fa.memo_paragraphs.len(),
fb.memo_paragraphs.len()
),
});
}
for (k, (qa, qb)) in fa
.memo_paragraphs
.iter()
.zip(fb.memo_paragraphs.iter())
.enumerate()
{
let p = format!("{path}/ctrl[{ci}]field.memo.p[{k}]");
diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
}
}
_ => {}
}
}
}
fn diff_shape_char_shapes(
diff: &mut IrDiff,
section: usize,
paragraph: usize,
path: &str,
sa: &crate::model::shape::ShapeObject,
sb: &crate::model::shape::ShapeObject,
) {
use crate::model::shape::ShapeObject;
if let (Some(ta), Some(tb)) = (shape_text_box(sa), shape_text_box(sb)) {
for (k, (qa, qb)) in ta.paragraphs.iter().zip(tb.paragraphs.iter()).enumerate() {
let p = format!("{path}.tb.p[{k}]");
diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
}
}
let (capa, capb) = (shape_caption(sa), shape_caption(sb));
if let Some(detail) = diff_table_caption(capa, capb) {
diff.push(IrDifference::ObjectCaption {
section,
paragraph,
path: format!("{path}.caption"),
detail,
});
}
if let (Some(ca), Some(cb)) = (capa, capb) {
for (k, (qa, qb)) in ca.paragraphs.iter().zip(cb.paragraphs.iter()).enumerate() {
let p = format!("{path}.caption.p[{k}]");
diff_paragraph_char_shapes(diff, section, paragraph, &p, qa, qb);
}
}
if let Some(detail) =
diff_object_comment(&shape_common(sa).description, &shape_common(sb).description)
{
diff.push(IrDifference::ObjectComment {
section,
paragraph,
path: path.to_string(),
detail,
});
}
if let (ShapeObject::Group(ga), ShapeObject::Group(gb)) = (sa, sb) {
for (k, (c1, c2)) in ga.children.iter().zip(gb.children.iter()).enumerate() {
let p = format!("{path}.child[{k}]");
diff_shape_char_shapes(diff, section, paragraph, &p, c1, c2);
}
}
}
fn shape_common(s: &crate::model::shape::ShapeObject) -> &crate::model::shape::CommonObjAttr {
use crate::model::shape::ShapeObject::*;
match s {
Line(x) => &x.common,
Rectangle(x) => &x.common,
Ellipse(x) => &x.common,
Arc(x) => &x.common,
Polygon(x) => &x.common,
Curve(x) => &x.common,
Chart(x) => &x.common,
Ole(x) => &x.common,
Group(x) => &x.common,
Picture(x) => &x.common,
}
}
fn shape_text_box(s: &crate::model::shape::ShapeObject) -> Option<&crate::model::shape::TextBox> {
use crate::model::shape::ShapeObject::*;
match s {
Line(x) => x.drawing.text_box.as_ref(),
Rectangle(x) => x.drawing.text_box.as_ref(),
Ellipse(x) => x.drawing.text_box.as_ref(),
Arc(x) => x.drawing.text_box.as_ref(),
Polygon(x) => x.drawing.text_box.as_ref(),
Curve(x) => x.drawing.text_box.as_ref(),
Chart(x) => x.drawing.text_box.as_ref(),
Ole(x) => x.drawing.text_box.as_ref(),
Group(_) | Picture(_) => None,
}
}
fn shape_caption(s: &crate::model::shape::ShapeObject) -> &Option<crate::model::shape::Caption> {
use crate::model::shape::ShapeObject::*;
match s {
Line(x) => &x.drawing.caption,
Rectangle(x) => &x.drawing.caption,
Ellipse(x) => &x.drawing.caption,
Arc(x) => &x.drawing.caption,
Polygon(x) => &x.drawing.caption,
Curve(x) => &x.drawing.caption,
Chart(x) => &x.caption,
Ole(x) => &x.caption,
Group(x) => &x.caption,
Picture(x) => &x.caption,
}
}
fn control_type_name(c: &crate::model::control::Control) -> &'static str {
use crate::model::control::Control::*;
match c {
Table(_) => "tbl",
Picture(_) => "pic",
Shape(_) => "shape",
Equation(_) => "eq",
Footnote(_) => "fn",
Endnote(_) => "en",
Field(_) => "field",
Form(_) => "form",
Header(_) => "header",
Footer(_) => "footer",
AutoNumber(_) => "autoNum",
PageHide(_) => "pageHide",
PageNumberPos(_) => "pageNumPos",
NewNumber(_) => "newNum",
CharOverlap(_) => "charOverlap",
Ruby(_) => "ruby",
_ => "other",
}
}
fn format_control_types(controls: &[&crate::model::control::Control]) -> String {
let inner = controls
.iter()
.map(|c| control_type_name(c))
.collect::<Vec<_>>()
.join(",");
format!("[{}]", inner)
}
fn format_char_shapes(refs: &[crate::model::paragraph::CharShapeRef]) -> String {
let inner = refs
.iter()
.map(|r| format!("({},{})", r.start_pos, r.char_shape_id))
.collect::<Vec<_>>()
.join(",");
format!("[{}]", inner)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::paragraph::{CharShapeRef, Paragraph};
fn doc_with_char_shapes(refs: &[(u32, u32)]) -> Document {
let mut para = Paragraph::default();
para.char_shapes = refs
.iter()
.map(|&(start_pos, char_shape_id)| CharShapeRef {
start_pos,
char_shape_id,
})
.collect();
let mut doc = Document::default();
let mut section: crate::model::document::Section = Default::default();
section.paragraphs.push(para);
doc.sections.push(section);
doc
}
#[test]
fn ir_diff_empty_default() {
let diff = IrDiff::default();
assert!(diff.is_empty());
}
#[test]
fn diff_documents_empty_is_empty() {
let a = Document::default();
let b = Document::default();
let diff = diff_documents(&a, &b);
assert!(diff.is_empty(), "empty vs empty must have no diff");
}
#[test]
fn diff_documents_same_char_shapes_is_empty() {
let a = doc_with_char_shapes(&[(0, 5), (3, 2), (10, 5)]);
let b = doc_with_char_shapes(&[(0, 5), (3, 2), (10, 5)]);
assert!(diff_documents(&a, &b).is_empty());
}
#[test]
fn diff_documents_detects_flattened_char_shapes() {
let a = doc_with_char_shapes(&[(0, 5), (3, 2)]);
let b = doc_with_char_shapes(&[(0, 5)]);
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1);
match &diff.differences[0] {
IrDifference::ParagraphCharShapes {
section,
paragraph,
path,
expected,
actual,
} => {
assert_eq!(*section, 0);
assert_eq!(*paragraph, 0);
assert_eq!(path, "");
assert_eq!(expected, "[(0,5),(3,2)]");
assert_eq!(actual, "[(0,5)]");
}
other => panic!("ParagraphCharShapes 여야 함: {:?}", other),
}
}
#[test]
fn diff_documents_detects_char_shape_pos_change() {
let a = doc_with_char_shapes(&[(0, 5), (3, 2)]);
let b = doc_with_char_shapes(&[(0, 5), (4, 2)]);
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1);
assert!(matches!(
diff.differences[0],
IrDifference::ParagraphCharShapes { .. }
));
}
fn to_refs(refs: &[(u32, u32)]) -> Vec<CharShapeRef> {
refs.iter()
.map(|&(start_pos, char_shape_id)| CharShapeRef {
start_pos,
char_shape_id,
})
.collect()
}
fn doc_with_control(ctrl: crate::model::control::Control) -> Document {
let mut para = Paragraph::default();
para.controls.push(ctrl);
let mut doc = Document::default();
let mut section: crate::model::document::Section = Default::default();
section.paragraphs.push(para);
doc.sections.push(section);
doc
}
fn table_control(cell_refs: &[(u32, u32)]) -> crate::model::control::Control {
use crate::model::table::{Cell, Table};
let mut cell_para = Paragraph::default();
cell_para.char_shapes = to_refs(cell_refs);
let mut cell = Cell::default();
cell.col_span = 1;
cell.row_span = 1;
cell.paragraphs.push(cell_para);
let mut t = Table::default();
t.row_count = 1;
t.col_count = 1;
t.cells.push(cell);
t.rebuild_grid();
crate::model::control::Control::Table(Box::new(t))
}
fn textbox_control(refs: &[(u32, u32)]) -> crate::model::control::Control {
use crate::model::shape::{RectangleShape, ShapeObject, TextBox};
let mut p = Paragraph::default();
p.char_shapes = to_refs(refs);
let mut tb = TextBox::default();
tb.paragraphs.push(p);
let mut rect = RectangleShape::default();
rect.drawing.text_box = Some(tb);
crate::model::control::Control::Shape(Box::new(ShapeObject::Rectangle(rect)))
}
fn footnote_control(refs: &[(u32, u32)]) -> crate::model::control::Control {
let mut p = Paragraph::default();
p.char_shapes = to_refs(refs);
let mut note = crate::model::footnote::Footnote::default();
note.paragraphs.push(p);
crate::model::control::Control::Footnote(Box::new(note))
}
fn assert_single_char_shapes_diff(diff: &IrDiff, expected_path: &str) {
assert_eq!(diff.differences.len(), 1, "차이 1건이어야 함: {:?}", diff);
match &diff.differences[0] {
IrDifference::ParagraphCharShapes { path, .. } => {
assert_eq!(path, expected_path);
}
other => panic!("ParagraphCharShapes 여야 함: {:?}", other),
}
}
#[test]
fn diff_documents_detects_cell_char_shapes() {
let a = doc_with_control(table_control(&[(0, 1), (3, 2)]));
let b = doc_with_control(table_control(&[(0, 1)]));
assert_single_char_shapes_diff(&diff_documents(&a, &b), "/ctrl[0]tbl.cell[0].p[0]");
}
#[test]
fn diff_documents_same_cell_char_shapes_is_empty() {
let a = doc_with_control(table_control(&[(0, 1), (3, 2)]));
let b = doc_with_control(table_control(&[(0, 1), (3, 2)]));
assert!(diff_documents(&a, &b).is_empty());
}
#[test]
fn diff_documents_detects_textbox_char_shapes() {
let a = doc_with_control(textbox_control(&[(0, 1), (3, 2)]));
let b = doc_with_control(textbox_control(&[(0, 1)]));
assert_single_char_shapes_diff(&diff_documents(&a, &b), "/ctrl[0]shape.tb.p[0]");
}
#[test]
fn diff_documents_detects_footnote_char_shapes() {
let a = doc_with_control(footnote_control(&[(0, 1), (3, 2)]));
let b = doc_with_control(footnote_control(&[(0, 1)]));
assert_single_char_shapes_diff(&diff_documents(&a, &b), "/ctrl[0]fn.p[0]");
}
fn roundtrip_doc_with_control(ctrl: crate::model::control::Control) -> Document {
use crate::model::style::CharShape;
let p0 = Paragraph::default();
let mut p1 = Paragraph::default();
p1.char_count = 9; p1.char_shapes = to_refs(&[(0, 1)]);
p1.controls.push(ctrl);
let mut doc = Document::default();
doc.doc_info.char_shapes = vec![
CharShape::default(),
CharShape::default(),
CharShape::default(),
];
doc.doc_info.para_shapes = vec![Default::default()];
doc.doc_info.styles = vec![Default::default()];
let mut section: crate::model::document::Section = Default::default();
section.paragraphs.push(p0);
section.paragraphs.push(p1);
doc.sections.push(section);
doc
}
fn shapes_of(p: &Paragraph) -> Vec<(u32, u32)> {
p.char_shapes
.iter()
.map(|r| (r.start_pos, r.char_shape_id))
.collect()
}
#[test]
fn serialize_parse_roundtrip_preserves_cell_char_shapes() {
let mut doc = roundtrip_doc_with_control(table_control(&[(0, 1), (2, 2)]));
if let crate::model::control::Control::Table(t) =
&mut doc.sections[0].paragraphs[1].controls[0]
{
let para = &mut t.cells[0].paragraphs[0];
para.text = "abcd".to_string();
para.char_offsets = vec![0, 1, 2, 3];
para.char_count = 5;
} else {
panic!("Table 컨트롤이어야 함");
}
let bytes = serialize_hwpx(&doc).expect("serialize");
let doc2 = parse_hwpx(&bytes).expect("parse");
let cell_para = match &doc2.sections[0].paragraphs[1].controls[0] {
crate::model::control::Control::Table(t) => &t.cells[0].paragraphs[0],
other => panic!("Table 컨트롤이어야 함: {:?}", other),
};
assert_eq!(shapes_of(cell_para), vec![(0, 1), (2, 2)], "셀 문단");
}
#[test]
fn task2784_table_affect_line_spacing_roundtrips() {
let mut doc = roundtrip_doc_with_control(table_control(&[(0, 1)]));
if let crate::model::control::Control::Table(t) =
&mut doc.sections[0].paragraphs[1].controls[0]
{
t.common.affect_line_spacing = true;
} else {
panic!("Table 컨트롤이어야 함");
}
let bytes = serialize_hwpx(&doc).expect("serialize");
let doc2 = parse_hwpx(&bytes).expect("parse");
let preserved = match &doc2.sections[0].paragraphs[1].controls[0] {
crate::model::control::Control::Table(t) => t.common.affect_line_spacing,
other => panic!("Table 컨트롤이어야 함: {:?}", other),
};
assert!(preserved, "표 affectLSpacing 이 왕복 보존돼야 함");
}
#[test]
fn serialize_parse_roundtrip_preserves_textbox_char_shapes() {
let mut doc = roundtrip_doc_with_control(textbox_control(&[(0, 1), (2, 2)]));
if let crate::model::control::Control::Shape(s) =
&mut doc.sections[0].paragraphs[1].controls[0]
{
if let crate::model::shape::ShapeObject::Rectangle(r) = s.as_mut() {
let para = &mut r.drawing.text_box.as_mut().unwrap().paragraphs[0];
para.text = "abcd".to_string();
para.char_offsets = vec![0, 1, 2, 3];
para.char_count = 5;
} else {
panic!("Rectangle 이어야 함");
}
} else {
panic!("Shape 컨트롤이어야 함");
}
let bytes = serialize_hwpx(&doc).expect("serialize");
let doc2 = parse_hwpx(&bytes).expect("parse");
let tb_para = match &doc2.sections[0].paragraphs[1].controls[0] {
crate::model::control::Control::Shape(s) => match s.as_ref() {
crate::model::shape::ShapeObject::Rectangle(r) => {
&r.drawing.text_box.as_ref().expect("text_box").paragraphs[0]
}
other => panic!("Rectangle 이어야 함: {:?}", other),
},
other => panic!("Shape 컨트롤이어야 함: {:?}", other),
};
assert_eq!(shapes_of(tb_para), vec![(0, 1), (2, 2)], "글상자 문단");
}
fn table_control_with_cell_controls(
ctrls: Vec<crate::model::control::Control>,
) -> crate::model::control::Control {
use crate::model::table::{Cell, Table};
let mut cell_para = Paragraph::default();
cell_para.controls = ctrls;
let mut cell = Cell::default();
cell.col_span = 1;
cell.row_span = 1;
cell.paragraphs.push(cell_para);
let mut t = Table::default();
t.row_count = 1;
t.col_count = 1;
t.cells.push(cell);
t.rebuild_grid();
crate::model::control::Control::Table(Box::new(t))
}
fn picture_control() -> crate::model::control::Control {
crate::model::control::Control::Picture(Box::default())
}
fn assert_single_controls_diff(diff: &IrDiff, path0: &str, exp: &str, act: &str) {
assert_eq!(diff.differences.len(), 1, "차이 1건이어야 함: {:?}", diff);
match &diff.differences[0] {
IrDifference::ParagraphControls {
path,
expected,
actual,
..
} => {
assert_eq!(path, path0);
assert_eq!(expected, exp);
assert_eq!(actual, act);
}
other => panic!("ParagraphControls 여야 함: {:?}", other),
}
}
#[test]
fn diff_documents_detects_body_control_loss() {
let a = doc_with_control(picture_control());
let mut b = Document::default();
let mut section: crate::model::document::Section = Default::default();
section.paragraphs.push(Paragraph::default());
b.sections.push(section);
assert_single_controls_diff(&diff_documents(&a, &b), "", "[pic]", "[]");
}
#[test]
fn diff_documents_detects_cell_control_loss() {
let a = doc_with_control(table_control_with_cell_controls(vec![picture_control()]));
let b = doc_with_control(table_control_with_cell_controls(vec![]));
assert_single_controls_diff(
&diff_documents(&a, &b),
"/ctrl[0]tbl.cell[0].p[0]",
"[pic]",
"[]",
);
}
#[test]
fn diff_documents_detects_control_type_change() {
let a = doc_with_control(table_control_with_cell_controls(vec![picture_control()]));
let b = doc_with_control(table_control_with_cell_controls(vec![
crate::model::control::Control::Equation(Box::default()),
]));
assert_single_controls_diff(
&diff_documents(&a, &b),
"/ctrl[0]tbl.cell[0].p[0]",
"[pic]",
"[eq]",
);
}
#[test]
fn diff_documents_bookmark_not_compared_as_control() {
let mut a = doc_with_control(crate::model::control::Control::Bookmark(
crate::model::control::Bookmark {
name: "b".to_string(),
},
));
a.sections[0].paragraphs[0].controls.push(picture_control());
let b = doc_with_control(picture_control());
assert!(diff_documents(&a, &b).is_empty());
}
#[test]
fn issue4388_diff_documents_hyperlink_not_compared_as_control() {
use crate::model::control::{Control, Hyperlink};
let mut a = doc_with_control(Control::Hyperlink(Hyperlink {
url: "http://example.com".to_string(),
text: "example".to_string(),
}));
a.sections[0].paragraphs[0].controls.push(picture_control());
let b = doc_with_control(picture_control());
assert!(
diff_documents(&a, &b).is_empty(),
"Hyperlink 손실은 diff_documents 비교에서 제외되어야 함(is_hwpx_inline_slot 미등록)"
);
}
#[test]
fn issue4388_diff_documents_unknown_not_compared_as_control() {
use crate::model::control::{Control, UnknownControl};
let mut a = doc_with_control(Control::Unknown(UnknownControl {
ctrl_id: 0x1234_5678,
}));
a.sections[0].paragraphs[0].controls.push(picture_control());
let b = doc_with_control(picture_control());
assert!(
diff_documents(&a, &b).is_empty(),
"Unknown 손실은 diff_documents 비교에서 제외되어야 함(is_hwpx_inline_slot 미등록)"
);
}
#[test]
fn diff_documents_same_cell_controls_is_empty() {
let a = doc_with_control(table_control_with_cell_controls(vec![picture_control()]));
let b = doc_with_control(table_control_with_cell_controls(vec![picture_control()]));
assert!(diff_documents(&a, &b).is_empty());
}
#[test]
fn diff_documents_detects_section_count() {
let a = Document::default();
let mut b = Document::default();
b.sections.push(Default::default());
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1);
assert!(matches!(
diff.differences[0],
IrDifference::SectionCount {
expected: 0,
actual: 1
}
));
}
use crate::model::paragraph::LineSeg;
fn doc_with_linesegs(segs: Vec<LineSeg>) -> Document {
let mut para = Paragraph::default();
para.line_segs = segs;
let mut doc = Document::default();
let mut section: crate::model::document::Section = Default::default();
section.paragraphs.push(para);
doc.sections.push(section);
doc
}
fn seg(vertical_pos: i32, line_height: i32) -> LineSeg {
LineSeg {
vertical_pos,
line_height,
text_height: 1000,
baseline_distance: 850,
line_spacing: 600,
segment_width: 42520,
tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
..Default::default()
}
}
#[test]
fn diff_linesegs_equal_is_empty() {
let a = doc_with_linesegs(vec![seg(0, 1200), seg(1200, 1200)]);
let b = doc_with_linesegs(vec![seg(0, 1200), seg(1200, 1200)]);
assert!(diff_linesegs(&a, &b).is_empty());
}
#[test]
fn diff_linesegs_detects_value_mismatch() {
let a = doc_with_linesegs(vec![seg(0, 21974)]);
let b = doc_with_linesegs(vec![seg(0, 19924)]);
let diffs = diff_linesegs(&a, &b);
assert_eq!(diffs.len(), 1, "{diffs:?}");
match &diffs[0].kind {
LinesegDiffKind::ValueMismatch {
index,
field,
expected,
actual,
} => {
assert_eq!(*index, 0);
assert_eq!(*field, "vertsize");
assert_eq!(*expected, 21974);
assert_eq!(*actual, 19924);
}
other => panic!("ValueMismatch 여야 함: {other:?}"),
}
assert_eq!(diffs[0].path, "");
}
#[test]
fn diff_linesegs_detects_count_mismatch_and_compares_common() {
let a = doc_with_linesegs(vec![seg(0, 1200), seg(1200, 1200)]);
let b = doc_with_linesegs(vec![seg(0, 1000)]);
let diffs = diff_linesegs(&a, &b);
assert!(
diffs.iter().any(|d| matches!(
d.kind,
LinesegDiffKind::CountMismatch {
expected: 2,
actual: 1
}
)),
"{diffs:?}"
);
assert!(
diffs.iter().any(|d| matches!(
d.kind,
LinesegDiffKind::ValueMismatch {
index: 0,
field: "vertsize",
..
}
)),
"{diffs:?}"
);
}
#[test]
fn diff_linesegs_recurses_into_cell() {
let make = |lh: i32| {
let mut doc = doc_with_control(table_control(&[(0, 1)]));
if let crate::model::control::Control::Table(t) =
&mut doc.sections[0].paragraphs[0].controls[0]
{
t.cells[0].paragraphs[0].line_segs = vec![seg(0, lh)];
}
doc
};
let a = make(1200);
let b = make(1000);
let diffs = diff_linesegs(&a, &b);
assert_eq!(diffs.len(), 1, "{diffs:?}");
assert_eq!(diffs[0].path, "/ctrl[0]tbl.cell[0].p[0]");
assert!(matches!(
diffs[0].kind,
LinesegDiffKind::ValueMismatch {
field: "vertsize",
..
}
));
}
#[test]
fn task1380_lineseg_in_gate() {
let a = doc_with_linesegs(vec![seg(0, 21974)]);
let b = doc_with_linesegs(vec![seg(0, 19924)]);
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::ParagraphLinesegs {
section,
paragraph,
path,
detail,
} => {
assert_eq!(*section, 0);
assert_eq!(*paragraph, 0);
assert_eq!(path, "");
assert_eq!(detail, "[0].vertsize: expected=21974 actual=19924");
}
other => panic!("ParagraphLinesegs 여야 함: {other:?}"),
}
}
#[test]
fn task1380_gate_detects_synthetic_lineseg_asymmetry() {
let a = doc_with_linesegs(vec![]);
let b = doc_with_linesegs(vec![seg(0, 1000)]);
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::ParagraphLinesegs { detail, .. } => {
assert_eq!(detail, "count: expected=0 actual=1");
}
other => panic!("ParagraphLinesegs 여야 함: {other:?}"),
}
}
#[test]
fn task1380_two_round_stable_with_empty_linesegs() {
let bytes = std::fs::read("samples/hwpx/business_overview.hwpx").expect("샘플 읽기");
let doc1 = parse_hwpx(&bytes).expect("parse 원본");
assert!(
doc1.sections
.iter()
.flat_map(|s| &s.paragraphs)
.any(|p| p.line_segs.is_empty()),
"픽스처 전제: linesegarray 부재(빈 line_segs) 문단이 있어야 한다"
);
let out1 = serialize_hwpx(&doc1).expect("serialize r1");
let doc2 = parse_hwpx(&out1).expect("parse r1");
let d1 = diff_documents(&doc1, &doc2);
assert!(d1.is_empty(), "round1: {:?}", d1.differences);
let out2 = serialize_hwpx(&doc2).expect("serialize r2");
let doc3 = parse_hwpx(&out2).expect("parse r2");
let d2 = diff_documents(&doc2, &doc3);
assert!(d2.is_empty(), "round2: {:?}", d2.differences);
}
fn caption_with_paras(n: usize) -> crate::model::shape::Caption {
let mut c = crate::model::shape::Caption::default();
for _ in 0..n {
c.paragraphs.push(Paragraph::default());
}
c
}
fn table_with_caption(
cap: Option<crate::model::shape::Caption>,
) -> crate::model::control::Control {
match table_control(&[]) {
crate::model::control::Control::Table(mut t) => {
t.caption = cap;
crate::model::control::Control::Table(t)
}
_ => unreachable!(),
}
}
#[test]
fn task1387_caption_loss_in_gate() {
let a = doc_with_control(table_with_caption(Some(caption_with_paras(1))));
let b = doc_with_control(table_with_caption(None));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::TableCaption { path, detail, .. } => {
assert_eq!(path, "/ctrl[0]tbl.caption");
assert_eq!(detail, "missing: expected=Some actual=None");
}
other => panic!("TableCaption 여야 함: {other:?}"),
}
}
#[test]
fn task1387_caption_attr_mismatch_in_gate() {
let mut ca = caption_with_paras(1);
ca.spacing = 850;
let mut cb = caption_with_paras(1);
cb.spacing = 0;
cb.direction = crate::model::shape::CaptionDirection::Top;
let a = doc_with_control(table_with_caption(Some(ca)));
let b = doc_with_control(table_with_caption(Some(cb)));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::TableCaption { detail, .. } => {
assert_eq!(
detail,
"side: expected=Bottom actual=Top; gap: expected=850 actual=0"
);
}
other => panic!("TableCaption 여야 함: {other:?}"),
}
}
#[test]
fn task1387_caption_paragraph_recursed_in_gate() {
let mut ca = caption_with_paras(1);
ca.paragraphs[0].char_shapes = to_refs(&[(0, 6)]);
let mut cb = caption_with_paras(1);
cb.paragraphs[0].char_shapes = to_refs(&[(0, 7)]);
let a = doc_with_control(table_with_caption(Some(ca)));
let b = doc_with_control(table_with_caption(Some(cb)));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::ParagraphCharShapes { path, .. } => {
assert_eq!(path, "/ctrl[0]tbl.caption.p[0]");
}
other => panic!("ParagraphCharShapes 여야 함: {other:?}"),
}
}
#[test]
fn task1387_ta_pic_001_r_roundtrip_caption_gate_zero() {
let bytes = std::fs::read("samples/hwpx/ta-pic-001-r.hwpx").expect("샘플 읽기");
let doc1 = parse_hwpx(&bytes).expect("parse 원본");
let out = serialize_hwpx(&doc1).expect("serialize");
let doc2 = parse_hwpx(&out).expect("reparse");
let diff = diff_documents(&doc1, &doc2);
assert!(diff.is_empty(), "{:?}", diff.differences);
}
fn doc_with_page_def(pd: crate::model::page::PageDef) -> Document {
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
section.section_def.page_def = pd;
doc.sections.push(section);
doc
}
#[test]
fn task1388_page_def_in_gate() {
let mut a_pd = crate::model::page::PageDef::default();
a_pd.margin_left = 7086;
a_pd.margin_right = 14173;
a_pd.binding = crate::model::page::BindingMethod::DuplexSided;
let mut b_pd = a_pd.clone();
b_pd.margin_left = 8504;
b_pd.margin_right = 8504;
b_pd.binding = crate::model::page::BindingMethod::SingleSided;
let diff = diff_documents(&doc_with_page_def(a_pd), &doc_with_page_def(b_pd));
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::SectionPageDef { section, detail } => {
assert_eq!(*section, 0);
assert_eq!(
detail,
"margin_left: expected=7086 actual=8504; \
margin_right: expected=14173 actual=8504; \
binding: expected=DuplexSided actual=SingleSided"
);
}
other => panic!("SectionPageDef 여야 함: {other:?}"),
}
}
#[test]
fn task1388_page_def_equal_is_empty() {
let mut a_pd = crate::model::page::PageDef::default();
a_pd.margin_left = 7086;
let mut b_pd = a_pd.clone();
b_pd.attr = 0xFF;
b_pd.pagination_bottom_tolerance = 100;
let diff = diff_documents(&doc_with_page_def(a_pd), &doc_with_page_def(b_pd));
assert!(diff.is_empty(), "{:?}", diff.differences);
}
#[test]
fn task1388_roundtrip_preserves_page_def() {
let bytes = std::fs::read("samples/hwpx/ta-pic-001-r.hwpx").expect("샘플 읽기");
let doc1 = parse_hwpx(&bytes).expect("parse 원본");
let pd = &doc1.sections[0].section_def.page_def;
assert!(
pd.margin_left != 8504 || pd.margin_right != 8504,
"픽스처 전제: 템플릿 고정값과 다른 여백이어야 한다 (left={} right={})",
pd.margin_left,
pd.margin_right
);
let out = serialize_hwpx(&doc1).expect("serialize");
let doc2 = parse_hwpx(&out).expect("reparse");
let diff = diff_documents(&doc1, &doc2);
assert!(diff.is_empty(), "{:?}", diff.differences);
}
fn doc_with_visibility(hide_empty_line: bool, hide_header: bool) -> Document {
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
section.section_def.hide_empty_line = hide_empty_line;
section.section_def.hide_header = hide_header;
doc.sections.push(section);
doc
}
#[test]
fn task1637_visibility_in_gate() {
let a = doc_with_visibility(true, false);
let b = doc_with_visibility(false, false);
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::SectionVisibility { section, detail } => {
assert_eq!(*section, 0);
assert_eq!(detail, "hide_empty_line: expected=true actual=false");
}
other => panic!("SectionVisibility 여야 함: {other:?}"),
}
}
#[test]
fn task1637_visibility_equal_is_empty() {
let diff = diff_documents(
&doc_with_visibility(true, true),
&doc_with_visibility(true, true),
);
assert!(diff.is_empty(), "{:?}", diff.differences);
}
#[test]
fn task1637_roundtrip_preserves_hide_empty_line() {
let doc = doc_with_visibility(true, true);
let out = serialize_hwpx(&doc).expect("serialize");
let doc2 = parse_hwpx(&out).expect("reparse");
assert!(
doc2.sections[0].section_def.hide_empty_line,
"hide_empty_line=1 이 roundtrip 에서 보존되어야 한다"
);
assert!(
doc2.sections[0].section_def.hide_header,
"hide_header=1 이 roundtrip 에서 보존되어야 한다"
);
assert!(
diff_visibility(&doc.sections[0].section_def, &doc2.sections[0].section_def).is_none(),
"visibility roundtrip 차이가 없어야 한다"
);
}
#[test]
fn task1637_table_flow_with_text_in_gate() {
use crate::model::table::Table;
let mut ta = Table::default();
ta.common.flow_with_text = false;
let mut tb = Table::default();
tb.common.flow_with_text = true;
let a = doc_with_control(crate::model::control::Control::Table(Box::new(ta)));
let b = doc_with_control(crate::model::control::Control::Table(Box::new(tb)));
let diff = diff_documents(&a, &b);
assert!(
diff.differences
.iter()
.any(|d| matches!(d, IrDifference::ObjectFlowWithText { .. })),
"표 flowWithText 차이는 게이트에서 검출되어야 한다: {:?}",
diff.differences
);
}
#[test]
fn task1655_equation_flow_with_text_in_gate() {
let mut ea = crate::model::control::Equation::default();
ea.common.flow_with_text = false;
let mut eb = crate::model::control::Equation::default();
eb.common.flow_with_text = true;
let a = doc_with_control(crate::model::control::Control::Equation(Box::new(ea)));
let b = doc_with_control(crate::model::control::Control::Equation(Box::new(eb)));
let diff = diff_documents(&a, &b);
assert!(
diff.differences
.iter()
.any(|d| matches!(d, IrDifference::ObjectFlowWithText { .. })),
"수식 flowWithText 차이는 게이트에서 검출되어야 한다: {:?}",
diff.differences
);
}
#[test]
fn task1403_pic_caption_lineseg_recursed_in_gate() {
let mut ca = caption_with_paras(1);
ca.paragraphs[0].line_segs = vec![seg(0, 1000)];
let mut cb = caption_with_paras(1);
cb.paragraphs[0].line_segs = vec![seg(0, 2000)];
let mut pa = crate::model::image::Picture::default();
pa.caption = Some(ca);
let mut pb = crate::model::image::Picture::default();
pb.caption = Some(cb);
let a = doc_with_control(crate::model::control::Control::Picture(Box::new(pa)));
let b = doc_with_control(crate::model::control::Control::Picture(Box::new(pb)));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::ParagraphLinesegs { path, detail, .. } => {
assert_eq!(path, "/ctrl[0]pic.caption.p[0]");
assert_eq!(detail, "[0].vertsize: expected=1000 actual=2000");
}
other => panic!("ParagraphLinesegs 여야 함: {other:?}"),
}
}
#[test]
fn task1403_shape_caption_lineseg_recursed_in_gate() {
let mk = |vs: i32| {
let mut cap = caption_with_paras(1);
cap.paragraphs[0].line_segs = vec![seg(0, vs)];
let mut el = crate::model::shape::EllipseShape::default();
el.drawing.caption = Some(cap);
doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Ellipse(el),
)))
};
let diff = diff_documents(&mk(1000), &mk(2000));
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::ParagraphLinesegs { path, .. } => {
assert_eq!(path, "/ctrl[0]shape.caption.p[0]");
}
other => panic!("ParagraphLinesegs 여야 함: {other:?}"),
}
}
#[test]
fn task1403_pic_caption_loss_in_gate() {
let mut pa = crate::model::image::Picture::default();
pa.caption = Some(caption_with_paras(1));
let pb = crate::model::image::Picture::default();
let a = doc_with_control(crate::model::control::Control::Picture(Box::new(pa)));
let b = doc_with_control(crate::model::control::Control::Picture(Box::new(pb)));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::ObjectCaption { path, detail, .. } => {
assert_eq!(path, "/ctrl[0]pic.caption");
assert_eq!(detail, "missing: expected=Some actual=None");
}
other => panic!("ObjectCaption 여야 함: {other:?}"),
}
}
#[test]
fn task1403_line_caption_loss_in_gate() {
let mut la = crate::model::shape::LineShape::default();
la.drawing.caption = Some(caption_with_paras(1));
let lb = crate::model::shape::LineShape::default();
let a = doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Line(la),
)));
let b = doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Line(lb),
)));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::ObjectCaption { path, detail, .. } => {
assert_eq!(path, "/ctrl[0]shape.caption");
assert_eq!(detail, "missing: expected=Some actual=None");
}
other => panic!("ObjectCaption 여야 함: {other:?}"),
}
}
#[test]
fn task1403_legacy_shape_caption_roundtrips() {
let mut cap = caption_with_paras(1);
cap.width = 8504;
cap.paragraphs[0].text = "타원 캡션".to_string();
cap.paragraphs[0].char_shapes = to_refs(&[(0, 0)]);
let mut el = crate::model::shape::EllipseShape::default();
el.drawing.caption = Some(cap);
let mut a = roundtrip_doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Ellipse(el),
)));
a.sections[0].paragraphs[0].char_shapes = to_refs(&[(0, 0)]);
let out = serialize_hwpx(&a).expect("serialize");
let b = parse_hwpx(&out).expect("reparse");
let diff = diff_documents(&a, &b);
assert!(diff.is_empty(), "{:?}", diff.differences);
match &b.sections[0].paragraphs[1].controls[0] {
crate::model::control::Control::Shape(s) => match s.as_ref() {
crate::model::shape::ShapeObject::Ellipse(e2) => {
let c2 = e2.drawing.caption.as_ref().expect("캡션 보존");
assert_eq!(c2.paragraphs[0].text, "타원 캡션");
}
other => panic!("Ellipse 여야 함: {other:?}"),
},
other => panic!("Shape 여야 함: {other:?}"),
}
}
#[test]
fn task1403_group_caption_loss_in_gate() {
let mut ga = crate::model::shape::GroupShape::default();
ga.caption = Some(caption_with_paras(1));
let gb = crate::model::shape::GroupShape::default();
let a = doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Group(ga),
)));
let b = doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Group(gb),
)));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::ObjectCaption { path, detail, .. } => {
assert_eq!(path, "/ctrl[0]shape.caption");
assert_eq!(detail, "missing: expected=Some actual=None");
}
other => panic!("ObjectCaption 여야 함: {other:?}"),
}
}
#[test]
fn issue4319_ole_caption_loss_in_gate() {
let mut oa = crate::model::shape::OleShape::default();
oa.caption = Some(caption_with_paras(1));
let ob = crate::model::shape::OleShape::default();
let a = doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Ole(Box::new(oa)),
)));
let b = doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Ole(Box::new(ob)),
)));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::ObjectCaption { path, detail, .. } => {
assert_eq!(path, "/ctrl[0]shape.caption");
assert_eq!(detail, "missing: expected=Some actual=None");
}
other => panic!("ObjectCaption 여야 함: {other:?}"),
}
}
#[test]
fn issue4319_chart_caption_loss_in_gate() {
let mut oa = crate::model::shape::OleShape::default();
oa.chart_id_ref = Some("Chart/chart1.xml".to_string());
oa.caption = Some(caption_with_paras(1));
let mut ob = crate::model::shape::OleShape::default();
ob.chart_id_ref = Some("Chart/chart1.xml".to_string());
let a = doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Ole(Box::new(oa)),
)));
let b = doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Ole(Box::new(ob)),
)));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::ObjectCaption { path, detail, .. } => {
assert_eq!(path, "/ctrl[0]shape.caption");
assert_eq!(detail, "missing: expected=Some actual=None");
}
other => panic!("ObjectCaption 여야 함: {other:?}"),
}
}
#[test]
fn issue4319_ole_caption_roundtrips() {
let mut cap = caption_with_paras(1);
cap.paragraphs[0].text = "OLE 캡션".to_string();
cap.paragraphs[0].char_shapes = to_refs(&[(0, 0)]);
let mut ole = crate::model::shape::OleShape::default();
ole.caption = Some(cap);
let mut a = roundtrip_doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Ole(Box::new(ole)),
)));
a.sections[0].paragraphs[0].char_shapes = to_refs(&[(0, 0)]);
let out = serialize_hwpx(&a).expect("serialize");
let b = parse_hwpx(&out).expect("reparse");
let diff = diff_documents(&a, &b);
assert!(diff.is_empty(), "{:?}", diff.differences);
match &b.sections[0].paragraphs[1].controls[0] {
crate::model::control::Control::Shape(s) => match s.as_ref() {
crate::model::shape::ShapeObject::Ole(o2) => {
let c2 = o2.caption.as_ref().expect("캡션 보존 (#4319)");
assert_eq!(c2.paragraphs[0].text, "OLE 캡션");
}
other => panic!("Ole 여야 함: {other:?}"),
},
other => panic!("Shape 여야 함: {other:?}"),
}
}
#[test]
fn issue4319_chart_caption_roundtrips() {
let mut cap = caption_with_paras(1);
cap.paragraphs[0].text = "차트 캡션".to_string();
cap.paragraphs[0].char_shapes = to_refs(&[(0, 0)]);
let mut ole = crate::model::shape::OleShape::default();
ole.chart_id_ref = Some("Chart/chart1.xml".to_string());
ole.bin_data_id = 60001;
ole.caption = Some(cap);
let mut a = roundtrip_doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Ole(Box::new(ole)),
)));
a.sections[0].paragraphs[0].char_shapes = to_refs(&[(0, 0)]);
let out = serialize_hwpx(&a).expect("serialize");
let b = parse_hwpx(&out).expect("reparse");
let diff = diff_documents(&a, &b);
assert!(diff.is_empty(), "{:?}", diff.differences);
match &b.sections[0].paragraphs[1].controls[0] {
crate::model::control::Control::Shape(s) => match s.as_ref() {
crate::model::shape::ShapeObject::Ole(o2) => {
let c2 = o2.caption.as_ref().expect("캡션 보존 (#4319)");
assert_eq!(c2.paragraphs[0].text, "차트 캡션");
}
other => panic!("Ole(chart) 여야 함: {other:?}"),
},
other => panic!("Shape 여야 함: {other:?}"),
}
}
#[test]
fn task1392_pic_comment_loss_in_gate() {
let mut pa = crate::model::image::Picture::default();
pa.common.description = "그림입니다.".to_string();
let pb = crate::model::image::Picture::default();
let a = doc_with_control(crate::model::control::Control::Picture(Box::new(pa)));
let b = doc_with_control(crate::model::control::Control::Picture(Box::new(pb)));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::ObjectComment { path, detail, .. } => {
assert_eq!(path, "/ctrl[0]pic");
assert_eq!(detail, "expected=\"그림입니다.\" actual=\"\"");
}
other => panic!("ObjectComment 여야 함: {other:?}"),
}
}
#[test]
fn task1392_equation_comment_loss_in_gate() {
let mut ea = crate::model::control::Equation::default();
ea.common.description = "수식 설명".to_string();
let eb = crate::model::control::Equation::default();
let a = doc_with_control(crate::model::control::Control::Equation(Box::new(ea)));
let b = doc_with_control(crate::model::control::Control::Equation(Box::new(eb)));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::ObjectComment { path, .. } => assert_eq!(path, "/ctrl[0]eq"),
other => panic!("ObjectComment 여야 함: {other:?}"),
}
}
#[test]
fn task1392_shape_comment_loss_in_gate() {
let mut el = crate::model::shape::EllipseShape::default();
el.common.description = "타원 설명".to_string();
let a = doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Ellipse(el),
)));
let b = doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Ellipse(crate::model::shape::EllipseShape::default()),
)));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::ObjectComment { path, .. } => assert_eq!(path, "/ctrl[0]shape"),
other => panic!("ObjectComment 여야 함: {other:?}"),
}
}
#[test]
fn task1392_equal_comment_no_diff() {
let mut pa = crate::model::image::Picture::default();
pa.common.description = "동일".to_string();
let mut pb = crate::model::image::Picture::default();
pb.common.description = "동일".to_string();
let a = doc_with_control(crate::model::control::Control::Picture(Box::new(pa)));
let b = doc_with_control(crate::model::control::Control::Picture(Box::new(pb)));
assert!(diff_documents(&a, &b).is_empty());
}
#[test]
fn task1451_legacy_shape_comment_serialize_roundtrip() {
let mut poly = crate::model::shape::PolygonShape::default();
poly.common.description = "다각형입니다.".to_string();
let doc = roundtrip_doc_with_control(crate::model::control::Control::Shape(Box::new(
crate::model::shape::ShapeObject::Polygon(poly),
)));
let bytes = serialize_hwpx(&doc).expect("serialize");
let doc2 = parse_hwpx(&bytes).expect("parse");
let desc = match &doc2.sections[0].paragraphs[1].controls[0] {
crate::model::control::Control::Shape(s) => match s.as_ref() {
crate::model::shape::ShapeObject::Polygon(p) => &p.common.description,
other => panic!("Polygon 이어야 함: {other:?}"),
},
other => panic!("Shape 컨트롤이어야 함: {other:?}"),
};
assert_eq!(desc, "다각형입니다.", "polygon shapeComment 왕복 보존");
}
#[test]
fn task1391_field_parameters_loss_in_gate() {
let mut fa = crate::model::control::Field::default();
fa.raw_parameters_xml = Some("<hp:parameters cnt=\"1\"></hp:parameters>".into());
let fb = crate::model::control::Field::default();
let a = doc_with_control(crate::model::control::Control::Field(fa));
let b = doc_with_control(crate::model::control::Control::Field(fb));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::FieldContent { path, detail, .. } => {
assert_eq!(path, "/ctrl[0]field");
assert!(detail.starts_with("parameters: expected="), "{detail}");
}
other => panic!("FieldContent 여야 함: {other:?}"),
}
}
#[test]
fn task1391_memo_paragraph_loss_in_gate() {
let mut fa = crate::model::control::Field::default();
fa.field_type = crate::model::control::FieldType::Memo;
fa.memo_paragraphs.push(Paragraph::default());
let mut fb = crate::model::control::Field::default();
fb.field_type = crate::model::control::FieldType::Memo;
let a = doc_with_control(crate::model::control::Control::Field(fa));
let b = doc_with_control(crate::model::control::Control::Field(fb));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::FieldContent { detail, .. } => {
assert_eq!(detail, "memo paragraphs: expected=1 actual=0");
}
other => panic!("FieldContent 여야 함: {other:?}"),
}
}
#[test]
fn task1391_aift_memo_roundtrips() {
let bytes = std::fs::read("samples/hwpx/aift.hwpx").expect("샘플 읽기");
let doc1 = parse_hwpx(&bytes).expect("parse 원본");
let memo_count = doc1
.sections
.iter()
.flat_map(|s| &s.paragraphs)
.flat_map(|p| &p.controls)
.filter(|c| {
matches!(c, crate::model::control::Control::Field(f)
if f.field_type == crate::model::control::FieldType::Memo)
})
.count();
assert_eq!(memo_count, 2, "aift MEMO 2건");
let out = serialize_hwpx(&doc1).expect("serialize");
let doc2 = parse_hwpx(&out).expect("reparse");
let diff = diff_documents(&doc1, &doc2);
assert!(diff.is_empty(), "{:?}", diff.differences);
}
#[test]
fn task1389_picture_size_diff_in_gate() {
let mut pa = crate::model::image::Picture::default();
pa.shape_attr.current_width = 1366;
pa.img_dim = (49380, 45840);
let pb = crate::model::image::Picture::default(); let a = doc_with_control(crate::model::control::Control::Picture(Box::new(pa)));
let b = doc_with_control(crate::model::control::Control::Picture(Box::new(pb)));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::PictureSize { path, detail, .. } => {
assert_eq!(path, "/ctrl[0]pic");
assert!(
detail.contains("curSz") && detail.contains("imgDim"),
"{detail}"
);
}
other => panic!("PictureSize 여야 함: {other:?}"),
}
}
#[test]
fn issue4668_picture_offset_diff_in_gate() {
let mut pa = crate::model::image::Picture::default();
pa.shape_attr.offset_x = 5250;
pa.shape_attr.offset_y = -4332;
let pb = crate::model::image::Picture::default(); let a = doc_with_control(crate::model::control::Control::Picture(Box::new(pa)));
let b = doc_with_control(crate::model::control::Control::Picture(Box::new(pb)));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::PictureSize { path, detail, .. } => {
assert_eq!(path, "/ctrl[0]pic");
assert!(
detail.contains("offset: expected=(5250, -4332) actual=(0, 0)"),
"{detail}"
);
}
other => panic!("PictureSize 여야 함: {other:?}"),
}
}
#[test]
fn hwpx_to_hwp_zero_img_dim_sentinel_is_not_a_layout_loss() {
let diff = IrDiff {
differences: vec![
IrDifference::PictureSize {
section: 0,
paragraph: 0,
path: "/ctrl[0]pic".to_string(),
detail: "imgDim: expected=(76800, 42240) actual=(0, 0)".to_string(),
},
IrDifference::PictureSize {
section: 0,
paragraph: 1,
path: "/ctrl[1]pic".to_string(),
detail: "curSz: expected=2400x1800 actual=0x0; imgDim: expected=(76800, 42240) actual=(0, 0)".to_string(),
},
],
};
let filtered = strip_hwpx_to_hwp_noise(diff);
assert_eq!(
filtered.differences.len(),
1,
"실제 기하 손실은 남겨야 한다"
);
assert!(matches!(
&filtered.differences[0],
IrDifference::PictureSize { detail, .. } if detail.starts_with("curSz:")
));
}
#[test]
fn issue_3739_hwp_to_hwpx_generated_command_parameters_are_incomparable() {
let diff = IrDiff {
differences: vec![
IrDifference::FieldContent {
section: 0,
paragraph: 0,
path: "/ctrl[0]field".to_string(),
detail: r#"parameters: expected=None actual=Some("<hp:parameters cnt=\"1\" name=\"\"><hp:stringParam name=\"Command\">https://example.test</hp:stringParam></hp:parameters>")"#.to_string(),
},
IrDifference::FieldContent {
section: 0,
paragraph: 1,
path: "/ctrl[1]field".to_string(),
detail: r#"parameters: expected=None actual=Some("<hp:parameters cnt=\"2\" name=\"\"><hp:stringParam name=\"Command\">keep</hp:stringParam><hp:stringParam name=\"Direction\">keep</hp:stringParam></hp:parameters>")"#.to_string(),
},
IrDifference::CharShapeCount {
expected: 1,
actual: 2,
},
],
};
let filtered = strip_hwp_to_hwpx_noise(diff);
assert_eq!(
filtered.differences.len(),
2,
"합성 Command 단일 parameters 외 차이는 남겨야 한다"
);
assert!(matches!(
&filtered.differences[0],
IrDifference::FieldContent { detail, .. } if detail.contains("cnt=\\\"2\\\"")
));
assert!(matches!(
&filtered.differences[1],
IrDifference::CharShapeCount { .. }
));
}
#[test]
fn issue_3739_hwp3_to_hwpx_materializes_hyperlink_and_empty_img_rect_only() {
use crate::model::control::{Control, Field, FieldType, Hyperlink};
let mut expected_document = Document::default();
let mut actual_document = Document::default();
let mut expected_section: crate::model::document::Section = Default::default();
let mut actual_section: crate::model::document::Section = Default::default();
for index in 0..4 {
let mut expected = Paragraph::default();
let mut actual = Paragraph::default();
if index == 0 {
expected.controls.push(Control::Hyperlink(Hyperlink {
url: "https://example.test".to_string(),
text: "example".to_string(),
}));
actual.controls.push(Control::Field(Field {
field_type: FieldType::Hyperlink,
command: "https://example.test".to_string(),
..Default::default()
}));
}
expected_section.paragraphs.push(expected);
actual_section.paragraphs.push(actual);
}
expected_document.sections.push(expected_section);
actual_document.sections.push(actual_section);
let diff = IrDiff {
differences: vec![
IrDifference::ParagraphControls {
section: 0,
paragraph: 0,
path: String::new(),
expected: "[]".to_string(),
actual: "[field]".to_string(),
},
IrDifference::PictureSize {
section: 0,
paragraph: 1,
path: "/ctrl[0]pic".to_string(),
detail: "imgRect: expected=[0, 0, 0, 0]/[0, 0, 0, 0] actual=[0, 0, 2228, 0]/[2228, 2372, 0, 2372]".to_string(),
},
IrDifference::ParagraphControls {
section: 0,
paragraph: 2,
path: String::new(),
expected: "[pic]".to_string(),
actual: "[field]".to_string(),
},
IrDifference::PictureSize {
section: 0,
paragraph: 3,
path: "/ctrl[0]pic".to_string(),
detail: "curSz: expected=1x1 actual=2x2; imgRect: expected=[0, 0, 0, 0]/[0, 0, 0, 0] actual=[0, 0, 2, 0]/[2, 2, 0, 2]".to_string(),
},
],
};
let filtered = strip_hwp3_to_hwpx_noise(&expected_document, &actual_document, diff);
assert_eq!(
filtered.differences.len(),
2,
"실제 control/기하 차이는 남겨야 한다"
);
assert!(matches!(
&filtered.differences[0],
IrDifference::ParagraphControls { expected, actual, .. }
if expected == "[pic]" && actual == "[field]"
));
assert!(matches!(
&filtered.differences[1],
IrDifference::PictureSize { detail, .. } if detail.starts_with("curSz:")
));
}
#[test]
fn task1389_ta_pic_size_roundtrips() {
let bytes = std::fs::read("samples/hwpx/ta-pic-001-r.hwpx").expect("샘플 읽기");
let doc1 = parse_hwpx(&bytes).expect("parse 원본");
let has_dim = doc1
.sections
.iter()
.flat_map(|s| &s.paragraphs)
.flat_map(|p| &p.controls)
.any(|c| matches!(c, crate::model::control::Control::Table(t)
if t.cells.iter().flat_map(|ce| &ce.paragraphs).flat_map(|q| &q.controls)
.any(|cc| matches!(cc, crate::model::control::Control::Picture(pic) if pic.img_dim.0 > 0))));
assert!(has_dim, "셀 내 pic img_dim 적재 전제");
let out = serialize_hwpx(&doc1).expect("serialize");
let doc2 = parse_hwpx(&out).expect("reparse");
let diff = diff_documents(&doc1, &doc2);
assert!(diff.is_empty(), "{:?}", diff.differences);
}
#[test]
fn task1393_table_page_break_diff_in_gate() {
use crate::model::table::TablePageBreak;
fn tbl(pb: TablePageBreak) -> crate::model::control::Control {
match table_control(&[]) {
crate::model::control::Control::Table(mut t) => {
t.page_break = pb;
crate::model::control::Control::Table(t)
}
_ => unreachable!(),
}
}
let a = doc_with_control(tbl(TablePageBreak::RowBreak));
let b = doc_with_control(tbl(TablePageBreak::CellBreak));
let diff = diff_documents(&a, &b);
assert_eq!(diff.differences.len(), 1, "{:?}", diff.differences);
match &diff.differences[0] {
IrDifference::TablePageBreak { path, detail, .. } => {
assert_eq!(path, "/ctrl[0]tbl");
assert_eq!(detail, "expected=RowBreak actual=CellBreak");
}
other => panic!("TablePageBreak 여야 함: {other:?}"),
}
}
#[test]
fn task1393_form_002_page_break_roundtrips() {
let bytes = std::fs::read("samples/hwpx/form-002.hwpx").expect("샘플 읽기");
let doc1 = parse_hwpx(&bytes).expect("parse 원본");
let out = serialize_hwpx(&doc1).expect("serialize");
let doc2 = parse_hwpx(&out).expect("reparse");
let diff = diff_documents(&doc1, &doc2);
assert!(diff.is_empty(), "{:?}", diff.differences);
}
}