pub mod canonical_defaults;
pub mod char_shape_tables;
pub mod char_shapes;
pub mod content;
pub mod context;
pub mod field;
pub mod fixtures;
pub mod form;
pub mod header;
pub mod master_page;
pub mod package_check;
pub mod picture;
pub mod roundtrip;
pub mod section;
pub mod shape;
pub mod static_assets;
pub mod table;
pub mod utils;
pub mod writer;
use std::collections::HashSet;
use std::fmt::Write as _;
use crate::model::bin_data::MAX_BIN_DATA_BYTES;
use crate::model::document::{Document, HWP5_ORIGIN_HWPX_MARKER_PATH};
use crate::serializer::content_loss::{ContentLoss, ContentLossReason, SerializedDocument};
use super::SerializeError;
use content::BinDataEntry as ContentBinDataEntry;
use context::SerializeContext;
use writer::HwpxZipWriter;
fn reusable_deflate(
data: &crate::model::bin_data::BinDataBytes,
payload: &[u8],
) -> Option<crate::model::bin_data::DeflatedZipEntry> {
let crc32 = || {
let mut crc = flate2::Crc::new();
crc.update(payload);
crc.sum()
};
if let Some(entry) = data.load_deflated_zip_entry() {
return (entry.uncompressed_size == payload.len() as u64 && entry.crc32 == crc32())
.then_some(entry);
}
let stored = data.load_raw().filter(|stored| stored.compressed)?;
let mut inflated =
flate2::CrcReader::new(flate2::read::DeflateDecoder::new(stored.bytes.as_slice()));
let inflated_size = std::io::copy(
&mut std::io::Read::take(&mut inflated, payload.len() as u64 + 1),
&mut std::io::sink(),
)
.ok()?;
let crc = crc32();
(inflated_size == payload.len() as u64 && inflated.crc().sum() == crc).then_some(
crate::model::bin_data::DeflatedZipEntry {
crc32: crc,
uncompressed_size: payload.len() as u64,
compressed_bytes: stored.bytes,
},
)
}
pub fn serialize_hwpx(doc: &Document) -> Result<Vec<u8>, SerializeError> {
let serialized = serialize_hwpx_with_report(doc)?;
serialized.content_loss().write_warnings_to_stderr();
Ok(serialized.into_bytes())
}
pub fn serialize_hwpx_with_report(doc: &Document) -> Result<SerializedDocument, SerializeError> {
let (writer, report) =
serialize_hwpx_into(doc, HwpxZipWriter::new(), &crate::storage::Unbounded, None)?;
Ok(SerializedDocument::new(writer.into_inner(), report))
}
#[cfg(feature = "pdf-import")]
pub(crate) fn serialize_hwpx_with_storage<S: crate::storage::Storage>(
doc: &Document,
storage: &S,
maximum: usize,
reservation: std::sync::Arc<dyn crate::storage::Reservation>,
) -> Result<Vec<u8>, SerializeError>
where
S::Error: std::fmt::Display,
{
let writer = super::budget_cursor::BudgetCursor::new(storage, maximum);
let (writer, report) = serialize_hwpx_into(
doc,
HwpxZipWriter::with_writer(writer),
storage,
Some(reservation),
)?;
report.write_warnings_to_stderr();
Ok(writer.into_inner())
}
fn serialize_hwpx_into<W: std::io::Write + std::io::Seek, S: crate::storage::Storage>(
doc: &Document,
mut z: HwpxZipWriter<W>,
storage: &S,
reservation: Option<std::sync::Arc<dyn crate::storage::Reservation>>,
) -> Result<(W, crate::serializer::ContentLossReport), SerializeError>
where
S::Error: std::fmt::Display,
{
use static_assets::*;
let mut ctx = SerializeContext::try_collect_from_document(doc, storage, reservation)?;
z.write_stored("mimetype", b"application/hwp+zip")?;
z.write_deflated(
"version.xml",
doc.hwpx_aux_entry("version.xml")
.unwrap_or_else(|| VERSION_XML.as_bytes()),
)?;
let header_xml = header::write_header_with_storage(doc, &ctx, storage)?;
z.write_deflated("Contents/header.xml", &header_xml)?;
let mut hwp3_page_ownership =
crate::model::hwp3_page_ownership::PageOwnership::for_document(doc, &header_xml);
if let Some(bytes) =
crate::model::native_font_program::encode_with_storage(&doc.doc_info, &header_xml, storage)
.map_err(SerializeError::UnsupportedInput)?
{
z.write_deflated(crate::model::native_font_program::HWPX_ENTRY, &bytes)?;
}
let mut section_hrefs = storage
.vec(doc.sections.len())
.map_err(context::context_error)?;
for i in 0..doc.sections.len() {
section_hrefs.push(
storage
.display(&format_args!("Contents/section{}.xml", i))
.map_err(context::context_error)?,
);
}
for (i, sec) in doc.sections.iter().enumerate() {
let xml = section::write_section_with_storage(sec, doc, i, &mut ctx, storage)?;
ctx.check_storage()?;
if let Some(ownership) = &mut hwp3_page_ownership {
ownership.push_section(sec, &xml);
}
z.write_deflated(§ion_hrefs[i], &xml)?;
}
let mut master_items: Vec<(usize, String, String)> = Vec::new();
let mut mp_global = 0usize;
for (section_idx, sec) in doc.sections.iter().enumerate() {
for mp in &sec.section_def.master_pages {
let id = storage
.display(&format_args!("masterpage{}", mp_global))
.map_err(context::context_error)?;
let href = storage
.display(&format_args!("Contents/masterpage{}.xml", mp_global))
.map_err(context::context_error)?;
let xml = master_page::render_master_page_xml_with_storage(mp, &id, &mut ctx, storage)?;
ctx.check_storage()?;
z.write_deflated(&href, xml.as_bytes())?;
storage
.push(&mut master_items, (section_idx, id, href))
.map_err(context::context_error)?;
mp_global += 1;
}
}
z.write_deflated(
"Preview/PrvText.txt",
doc.hwpx_aux_entry("Preview/PrvText.txt")
.unwrap_or(PRV_TEXT),
)?;
z.write_deflated(
"Preview/PrvImage.png",
doc.hwpx_aux_entry("Preview/PrvImage.png")
.unwrap_or(PRV_IMAGE_PNG),
)?;
const CROP_SETTINGS_XML: &str = concat!(
r#"<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>"#,
r#"<ha:HWPApplicationSetting xmlns:ha="http://www.hancom.co.kr/hwpml/2011/app" xmlns:config="urn:oasis:names:tc:opendocument:xmlns:config:1.0">"#,
r#"<ha:CaretPosition listIDRef="0" paraIDRef="0" pos="16"/>"#,
r#"<config:config-item-set name="PrintInfo"><config:config-item name="PrintCropMark" type="short">1</config:config-item></config:config-item-set>"#,
"</ha:HWPApplicationSetting>",
);
z.write_deflated(
"settings.xml",
doc.hwpx_aux_entry("settings.xml").unwrap_or_else(|| {
if doc.print_crop_marks() {
CROP_SETTINGS_XML.as_bytes()
} else {
SETTINGS_XML.as_bytes()
}
}),
)?;
for (path, bytes) in &doc.hwpx_aux_entries {
if path.starts_with("Scripts/") {
z.write_deflated(path, bytes)?;
}
}
let mut converted_script_items = Vec::new();
if !doc
.hwpx_aux_entries
.iter()
.any(|(path, _)| path.starts_with("Scripts/"))
&& doc.extra_streams.iter().any(|(path, bytes)| {
path.trim_start_matches('/') == "Scripts/DefaultJScript" && !bytes.is_empty()
})
{
let (header, source) = crate::model::form_script::script_sources_from_streams(doc)
.map_err(|error| SerializeError::UnsupportedInput(error.to_string()))?;
if !header.is_empty() || !source.is_empty() {
for (id, path, text) in [
("rhwpHeaderScript", "Scripts/headerScripts", header),
("rhwpSourceScript", "Scripts/sourceScripts", source),
] {
let bytes: Vec<u8> = text.encode_utf16().flat_map(u16::to_le_bytes).collect();
z.write_deflated(path, &bytes)?;
converted_script_items.push((id, path));
}
}
}
if let Some(bytes) = ctx
.table_row_grids
.encode_with_storage(storage)
.map_err(SerializeError::UnsupportedInput)?
{
z.write_deflated(crate::model::table_row_grid::HWPX_ENTRY, &bytes)?;
ctx.content_loss
.record_with_storage(
crate::model::table_row_grid::native_grid_loss_with_storage(storage)
.map_err(context::context_error)?,
storage,
)
.map_err(context::context_error)?;
}
if let Some(bytes) = crate::model::border_paint::encode_with_storage(doc, storage)
.map_err(SerializeError::UnsupportedInput)?
{
z.write_deflated(crate::model::border_paint::HWPX_ENTRY, &bytes)?;
ctx.content_loss
.record_with_storage(
crate::model::border_paint::native_editing_loss_with_storage(storage)
.map_err(context::context_error)?,
storage,
)
.map_err(context::context_error)?;
}
if let Some(bytes) = crate::model::text_clip::encode_with_storage(doc, storage)
.map_err(SerializeError::UnsupportedInput)?
{
z.write_deflated(crate::model::text_clip::HWPX_ENTRY, &bytes)?;
ctx.content_loss
.record_with_storage(
crate::model::text_clip::native_visibility_loss_with_storage(storage)
.map_err(context::context_error)?,
storage,
)
.map_err(context::context_error)?;
}
if let Some(bytes) = crate::model::text_paint::encode_with_storage(doc, storage)
.map_err(SerializeError::UnsupportedInput)?
{
z.write_deflated(crate::model::text_paint::HWPX_ENTRY, &bytes)?;
ctx.content_loss
.record_with_storage(
crate::model::text_paint::native_visibility_loss_with_storage(storage)
.map_err(context::context_error)?,
storage,
)
.map_err(context::context_error)?;
}
if let Some(bytes) = crate::model::hyperlink_format::encode_with_storage(doc, storage)
.map_err(SerializeError::UnsupportedInput)?
{
z.write_deflated(crate::model::hyperlink_format::HWPX_ENTRY, &bytes)?;
}
let container_rdf = write_container_rdf(§ion_hrefs);
z.write_deflated("META-INF/container.rdf", container_rdf.as_bytes())?;
ctx.check_storage()?;
let bin_entries = ctx.try_bin_data_entries(storage)?;
let mut zip_bin_entries: HashSet<String> = HashSet::new();
for entry in &bin_entries {
if !entry.is_embedded {
continue;
}
let data = doc
.bin_data_content
.iter()
.find(|b| b.id == entry.bin_data_id)
.ok_or_else(|| {
SerializeError::XmlError(format!(
"BinDataContent 누락: bin_data_id={}",
entry.bin_data_id
))
})?;
let bytes = match storage
.bin_data(&data.data, MAX_BIN_DATA_BYTES)
.map_err(|error| SerializeError::ZipError(error.to_string()))?
{
Some(bytes) => bytes,
None => {
ctx.content_loss
.record_with_storage(
ContentLoss::binary_content_emptied(
entry.bin_data_id,
storage
.string(&entry.href)
.map_err(context::context_error)?,
ContentLossReason::ResourceReadFailedOrLimitExceeded,
),
storage,
)
.map_err(context::context_error)?;
Vec::new()
}
};
const CFB_MAGIC: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
let payload: Vec<u8> = if data.extension.eq_ignore_ascii_case("ole")
&& bytes.len() >= 8
&& bytes[..8] == CFB_MAGIC
{
let mut v = storage
.vec(bytes.len() + 4)
.map_err(context::context_error)?;
v.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
v.extend_from_slice(&bytes);
v
} else {
bytes
};
match reusable_deflate(&data.data, &payload) {
Some(raw) => z.write_precompressed_deflated(
&entry.href,
raw.crc32,
raw.uncompressed_size,
&raw.compressed_bytes,
)?,
None => z.write_deflated(&entry.href, &payload)?,
}
let href = storage
.string(&entry.href)
.map_err(context::context_error)?;
storage
.reserve_set(&mut zip_bin_entries, 1)
.map_err(context::context_error)?;
zip_bin_entries.insert(href);
}
let mut chart_losses = Vec::new();
for entry in &ctx.chart_entries {
let data = doc
.bin_data_content
.iter()
.find(|b| b.id == entry.bin_data_id)
.ok_or_else(|| {
SerializeError::XmlError(format!(
"차트 BinDataContent 누락: bin_data_id={}",
entry.bin_data_id
))
})?;
let chart_bytes = match storage
.bin_data(&data.data, MAX_BIN_DATA_BYTES)
.map_err(|error| SerializeError::ZipError(error.to_string()))?
{
Some(bytes) => bytes,
None => {
storage
.push(
&mut chart_losses,
ContentLoss::binary_content_emptied(
entry.bin_data_id,
storage
.string(&entry.href)
.map_err(context::context_error)?,
ContentLossReason::ResourceReadFailedOrLimitExceeded,
),
)
.map_err(context::context_error)?;
Vec::new()
}
};
z.write_deflated(&entry.href, &chart_bytes)?;
}
for loss in chart_losses {
ctx.content_loss
.record_with_storage(loss, storage)
.map_err(context::context_error)?;
}
let mut content_bin_entries = storage
.vec(bin_entries.len())
.map_err(context::context_error)?;
for entry in &bin_entries {
content_bin_entries.push(ContentBinDataEntry {
id: storage
.string(&entry.manifest_id)
.map_err(context::context_error)?,
href: storage
.string(&entry.href)
.map_err(context::context_error)?,
media_type: storage
.string(&entry.media_type)
.map_err(context::context_error)?,
is_embedded: entry.is_embedded,
});
}
let content_hpf = content::write_content_hpf_with_scripts(
§ion_hrefs,
&content_bin_entries,
&master_items,
doc.hwpx_aux_entry("Contents/content.hpf"),
&converted_script_items,
)?;
z.write_deflated("Contents/content.hpf", &content_hpf)?;
z.write_deflated("META-INF/container.xml", META_INF_CONTAINER_XML.as_bytes())?;
z.write_deflated("META-INF/manifest.xml", META_INF_MANIFEST_XML.as_bytes())?;
if let Some(marker) = doc.hwpx_aux_entry(HWP5_ORIGIN_HWPX_MARKER_PATH) {
z.write_deflated(HWP5_ORIGIN_HWPX_MARKER_PATH, marker)?;
}
if let Some(marker) = doc.hwpx_aux_entry(crate::model::document::HWP3_ORIGIN_HWPX_MARKER_PATH) {
let encoded = hwp3_page_ownership
.as_ref()
.map(crate::model::hwp3_page_ownership::PageOwnership::encode)
.transpose()
.map_err(|error| SerializeError::XmlError(error.to_string()))?;
z.write_deflated(
crate::model::document::HWP3_ORIGIN_HWPX_MARKER_PATH,
encoded.as_deref().unwrap_or(marker),
)?;
z.write_deflated(
crate::model::document::HWP3_ORIGIN_HWPX_PARAGRAPH_AXIS_PATH,
crate::model::document::HWP5_ORIGIN_HWPX_PARAGRAPH_AXIS,
)?;
}
if doc.layout_profile().hwp3_external_realign() {
z.write_deflated(
crate::model::document::HWP3_EXTERNAL_REALIGN_HWPX_PATH,
b"1",
)?;
}
ctx.try_assert_all_refs_resolved(storage)?;
assert_bin_data_3way(&bin_entries, &zip_bin_entries, storage)?;
let writer = z.finish_writer()?;
Ok((writer, ctx.content_loss))
}
pub fn serialize_hwpx_with_password(
doc: &Document,
password: &[u8],
) -> Result<Vec<u8>, SerializeError> {
let serialized = serialize_hwpx_with_report(doc)?;
let (plain, content_loss) = serialized.into_parts();
let bytes = encrypt_hwpx_bytes(&plain, password)?;
content_loss.write_warnings_to_stderr();
Ok(bytes)
}
pub fn serialize_hwpx_with_password_and_report(
doc: &Document,
password: &[u8],
) -> Result<SerializedDocument, SerializeError> {
let serialized = serialize_hwpx_with_report(doc)?;
let (plain, content_loss) = serialized.into_parts();
let bytes = encrypt_hwpx_bytes(&plain, password)?;
Ok(SerializedDocument::new(bytes, content_loss))
}
fn encrypt_hwpx_bytes(plain: &[u8], password: &[u8]) -> Result<Vec<u8>, SerializeError> {
crate::password_crypto::encrypt_hwpx_package(plain, password)
.map_err(|error| SerializeError::CryptoError(error.to_string()))
}
fn write_container_rdf(section_hrefs: &[String]) -> String {
const PKG_NS: &str = "http://www.hancom.co.kr/hwpml/2016/meta/pkg#";
let mut out = String::new();
out.push_str(r#"<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>"#);
out.push_str(r#"<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">"#);
out.push_str(r#"<rdf:Description rdf:about="">"#);
let _ = write!(
out,
r#"<ns0:hasPart xmlns:ns0="{PKG_NS}" rdf:resource="Contents/header.xml"/>"#
);
out.push_str(r#"</rdf:Description>"#);
out.push_str(r#"<rdf:Description rdf:about="Contents/header.xml">"#);
let _ = write!(out, r#"<rdf:type rdf:resource="{PKG_NS}HeaderFile"/>"#);
out.push_str(r#"</rdf:Description>"#);
for href in section_hrefs {
out.push_str(r#"<rdf:Description rdf:about="">"#);
let _ = write!(
out,
r#"<ns0:hasPart xmlns:ns0="{PKG_NS}" rdf:resource="{href}"/>"#
);
out.push_str(r#"</rdf:Description>"#);
let _ = write!(out, r#"<rdf:Description rdf:about="{href}">"#);
let _ = write!(out, r#"<rdf:type rdf:resource="{PKG_NS}SectionFile"/>"#);
out.push_str(r#"</rdf:Description>"#);
}
out.push_str(r#"<rdf:Description rdf:about="">"#);
let _ = write!(out, r#"<rdf:type rdf:resource="{PKG_NS}Document"/>"#);
out.push_str(r#"</rdf:Description>"#);
out.push_str(r#"</rdf:RDF>"#);
out
}
fn assert_bin_data_3way<S: crate::storage::Storage>(
bin_entries: &[context::BinDataEntry],
zip_entries: &HashSet<String>,
storage: &S,
) -> Result<(), SerializeError>
where
S::Error: std::fmt::Display,
{
let mut ctx_hrefs = HashSet::new();
for entry in bin_entries.iter().filter(|entry| entry.is_embedded) {
if !ctx_hrefs.contains(entry.href.as_str()) {
storage
.reserve_set(&mut ctx_hrefs, 1)
.map_err(context::context_error)?;
ctx_hrefs.insert(entry.href.as_str());
}
}
if ctx_hrefs.len() != zip_entries.len()
|| ctx_hrefs.iter().any(|href| !zip_entries.contains(*href))
{
let missing_zip = storage
.collect(
ctx_hrefs
.iter()
.copied()
.filter(|href| !zip_entries.contains(*href)),
)
.map_err(context::context_error)?;
let orphan_zip = storage
.collect(
zip_entries
.iter()
.map(String::as_str)
.filter(|href| !ctx_hrefs.contains(*href)),
)
.map_err(context::context_error)?;
return Err(SerializeError::XmlError(storage.display(&format_args!("3-way BinData 불일치: ctx(href) vs zip_entries — ctx에만 있음: {:?}, zip에만 있음: {:?}", missing_zip, orphan_zip)).map_err(context::context_error)?));
}
Ok(())
}
#[cfg(test)]
mod tests {
use std::io::Read;
use super::*;
use crate::parser::hwpx::parse_hwpx;
#[test]
fn serialize_empty_doc_parses_back() {
let doc = Document::default();
let bytes = serialize_hwpx(&doc).expect("serialize empty");
let parsed = parse_hwpx(&bytes).expect("parse back");
assert_eq!(parsed.sections.len(), 0);
assert!(parsed.bin_data_content.is_empty());
}
#[test]
fn aux_entries_passthrough_verbatim() {
let mut doc = Document::default();
let custom: &[(&str, &[u8])] = &[
("version.xml", b"<custom-version platform=\"Mac\"/>"),
("settings.xml", b"<custom-settings printInfo=\"on\"/>"),
("Preview/PrvText.txt", b"preview body text"),
("Preview/PrvImage.png", &[0x89, b'P', b'N', b'G', 1, 2, 3]),
];
doc.hwpx_aux_entries = custom
.iter()
.map(|(p, d)| (p.to_string(), d.to_vec()))
.collect();
let bytes = serialize_hwpx(&doc).expect("serialize");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
for (path, expected) in custom {
let mut entry = archive
.by_name(path)
.unwrap_or_else(|_| panic!("missing entry {path}"));
let mut got = Vec::new();
std::io::Read::read_to_end(&mut entry, &mut got).expect("read");
assert_eq!(&got, expected, "{path} not passed through verbatim");
}
}
#[test]
fn aux_entries_fallback_to_constants() {
let doc = Document::default();
let bytes = serialize_hwpx(&doc).expect("serialize");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut entry = archive.by_name("version.xml").expect("version.xml");
let mut got = Vec::new();
std::io::Read::read_to_end(&mut entry, &mut got).expect("read");
assert_eq!(got, static_assets::VERSION_XML.as_bytes());
}
#[test]
fn version_xml_declares_the_owpml_revision_that_hangul_lays_out_with() {
assert!(
static_assets::VERSION_XML.contains(r#"xmlVersion="1.5""#),
"xmlVersion 은 1.5 여야 한다: {}",
static_assets::VERSION_XML
);
}
#[test]
fn serialize_with_one_section_parses_back() {
let mut doc = Document::default();
doc.sections
.push(crate::model::document::Section::default());
let bytes = serialize_hwpx(&doc).expect("serialize one-section");
let parsed = parse_hwpx(&bytes).expect("parse back");
assert_eq!(parsed.sections.len(), 1);
}
#[test]
fn master_pages_are_serialized_as_package_parts() {
use crate::model::document::Section;
use crate::model::header_footer::{HeaderFooterApply, MasterPage};
use crate::model::paragraph::Paragraph;
use crate::serializer::hwpx::package_check::check_package;
let mut doc = Document::default();
let mut section0 = Section::default();
let mut section1 = Section::default();
let mut first_master_para = Paragraph::default();
first_master_para.text = "first master".to_string();
section0.section_def.master_pages.push(MasterPage {
apply_to: HeaderFooterApply::Both,
text_width: 10_000,
text_height: 10_000,
text_ref: 1,
paragraphs: vec![first_master_para],
..Default::default()
});
let mut second_master_para = Paragraph::default();
second_master_para.text = "second master".to_string();
section1.section_def.master_pages.push(MasterPage {
apply_to: HeaderFooterApply::Odd,
text_width: 12_000,
text_height: 8_000,
text_ref: 1,
paragraphs: vec![second_master_para],
..Default::default()
});
doc.sections.push(section0);
doc.sections.push(section1);
let bytes = serialize_hwpx(&doc).expect("serialize master pages");
let report = check_package(&bytes, &doc);
assert!(report.is_ok(), "problems: {}", report.summary());
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
for name in ["Contents/masterpage0.xml", "Contents/masterpage1.xml"] {
archive
.by_name(name)
.unwrap_or_else(|_| panic!("missing {name}"));
}
let mut content_hpf = String::new();
archive
.by_name("Contents/content.hpf")
.expect("content.hpf")
.read_to_string(&mut content_hpf)
.expect("read content.hpf");
assert!(content_hpf.contains(r#"id="masterpage0""#));
assert!(content_hpf.contains(r#"href="Contents/masterpage1.xml""#));
let mut section1_xml = String::new();
archive
.by_name("Contents/section1.xml")
.expect("section1")
.read_to_string(&mut section1_xml)
.expect("read section1");
assert!(section1_xml.contains(r#"masterPageCnt="1""#));
assert!(section1_xml.contains(r#"idRef="masterpage1""#));
drop(archive);
let parsed = parse_hwpx(&bytes).expect("parse back");
assert_eq!(parsed.sections[0].section_def.master_pages.len(), 1);
assert_eq!(parsed.sections[1].section_def.master_pages.len(), 1);
assert_eq!(
parsed.sections[1].section_def.master_pages[0].apply_to,
HeaderFooterApply::Odd
);
}
#[test]
fn container_rdf_lists_every_section() {
let mut doc = Document::default();
for _ in 0..3 {
doc.sections
.push(crate::model::document::Section::default());
}
let bytes = serialize_hwpx(&doc).expect("serialize");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut container_rdf = String::new();
archive
.by_name("META-INF/container.rdf")
.expect("container.rdf")
.read_to_string(&mut container_rdf)
.expect("read container.rdf");
assert!(container_rdf.contains(r#"rdf:resource="Contents/header.xml""#));
for i in 0..3 {
let href = format!("Contents/section{i}.xml");
assert!(
container_rdf.contains(&format!(r#"rdf:resource="{href}""#)),
"missing hasPart for {href}: {container_rdf}"
);
assert!(
container_rdf.contains(&format!(r#"rdf:about="{href}""#)),
"missing type description for {href}: {container_rdf}"
);
}
}
#[test]
fn header_footer_ids_are_preserved() {
use crate::model::control::Control;
use crate::model::document::Section;
use crate::model::header_footer::{Footer, Header, HeaderFooterApply};
use crate::model::paragraph::Paragraph;
let mut doc = Document::default();
let mut section = Section::default();
let mut para = Paragraph::default();
para.controls.push(Control::Footer(Box::new(Footer {
raw_ctrl_extra: 2u32.to_le_bytes().to_vec(),
apply_to: HeaderFooterApply::Even,
..Default::default()
})));
para.controls.push(Control::Header(Box::new(Header {
raw_ctrl_extra: 1u32.to_le_bytes().to_vec(),
apply_to: HeaderFooterApply::Odd,
..Default::default()
})));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize header/footer ids");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut section0_xml = String::new();
archive
.by_name("Contents/section0.xml")
.expect("section0")
.read_to_string(&mut section0_xml)
.expect("read section0");
assert!(
section0_xml.contains(r#"<hp:footer id="2" applyPageType="EVEN">"#),
"footer id not preserved: {section0_xml}"
);
assert!(
section0_xml.contains(r#"<hp:header id="1" applyPageType="ODD">"#),
"header id not preserved: {section0_xml}"
);
}
#[test]
fn serialize_text_paragraph_roundtrip() {
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "안녕 Hello 123".to_string();
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize text");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("valid zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
assert!(
xml.contains("<hp:t>안녕 Hello 123</hp:t>"),
"text not injected into section0.xml"
);
drop(sec0);
let parsed = parse_hwpx(&bytes).expect("parse back");
assert_eq!(parsed.sections.len(), 1);
let p0 = &parsed.sections[0].paragraphs[0];
assert!(
p0.text.contains("안녕 Hello 123"),
"text roundtrip failed: {:?}",
p0.text
);
}
#[test]
fn issue4387_unequal_column_widths_roundtrip() {
use crate::model::control::Control;
use crate::model::document::Section;
use crate::model::page::{ColumnDef, ColumnType};
use crate::model::paragraph::Paragraph;
let mut cd = ColumnDef::default();
cd.column_type = ColumnType::Normal;
cd.column_count = 2;
cd.same_width = false;
cd.widths = vec![4000, 6000];
cd.gaps = vec![500, 0];
let mut para = Paragraph::default();
para.text = "x".to_string();
para.controls.push(Control::ColumnDef(cd));
let mut section = Section::default();
section.paragraphs.push(para);
let mut doc = Document::default();
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize unequal columns");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("valid zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
sec0.read_to_string(&mut xml).expect("read");
assert!(
xml.contains(r#"sameSz="0""#),
"sameSz=false 가 방출돼야 함: {}",
&xml[..900.min(xml.len())]
);
assert!(
xml.contains(r#"<hp:colSz width="4000" gap="500"/>"#)
&& xml.contains(r#"<hp:colSz width="6000" gap="0"/>"#),
"colSz 요소가 방출돼야 함(#4387): {}",
&xml[..900.min(xml.len())]
);
drop(sec0);
let parsed = parse_hwpx(&bytes).expect("parse back");
let p0 = &parsed.sections[0].paragraphs[0];
let cd2 = p0
.controls
.iter()
.find_map(|c| match c {
Control::ColumnDef(cd) => Some(cd),
_ => None,
})
.expect("ColumnDef control roundtrips");
assert!(!cd2.same_width);
assert_eq!(
cd2.widths,
vec![4000, 6000],
"단별 너비가 왕복에서 보존돼야 함(#4387)"
);
assert_eq!(
cd2.gaps,
vec![500, 0],
"단별 간격이 왕복에서 보존돼야 함(#4387)"
);
assert!(
cd2.proportional_widths,
"한컴 HWPX colSz의 비례 너비 해석이 왕복에서 보존돼야 함"
);
}
#[test]
fn tab_and_linebreak_emitted_inline() {
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "A\tB\nC".to_string();
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
assert!(
xml.contains(
r#"<hp:t>A<hp:tab width="0" leader="0" type="1"/>B<hp:lineBreak/>C</hp:t>"#
),
"mixed content not rendered: {}",
xml
);
}
#[test]
fn equation_control_roundtrip_preserves_script() {
use crate::model::control::{Control, Equation};
use crate::model::shape::{
CommonObjAttr, HorzAlign, HorzRelTo, TextWrap, VertAlign, VertRelTo,
};
use crate::model::Padding;
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "AB".to_string();
para.char_offsets = vec![0, 9];
para.char_count = 11;
para.controls.push(Control::Equation(Box::new(Equation {
common: CommonObjAttr {
instance_id: 7,
z_order: 3,
width: 2400,
height: 1200,
vertical_offset: 80,
horizontal_offset: 160,
margin: Padding {
left: 10,
right: 20,
top: 30,
bottom: 40,
},
treat_as_char: true,
text_wrap: TextWrap::TopAndBottom,
vert_rel_to: VertRelTo::Para,
horz_rel_to: HorzRelTo::Para,
vert_align: VertAlign::Bottom,
horz_align: HorzAlign::Center,
..Default::default()
},
attr: 0,
script: "x < y & z".to_string(),
font_size: 1000,
color: 0x000000FF,
baseline: 120,
unknown: 0,
eqedit: 0,
font_name: "HYhwpEQ".to_string(),
version_info: "Equation Version 60".to_string(),
raw_ctrl_data: Vec::new(),
raw_ctrl_seal: None,
unpositioned_host_frame_seal: None,
legacy_source_frame_seal: None,
})));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize equation");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
assert!(
xml.contains("<hp:equation "),
"equation XML missing: {}",
xml
);
assert!(
xml.contains("<hp:script>x < y & z</hp:script>"),
"script XML missing: {}",
xml
);
drop(sec0);
let parsed = parse_hwpx(&bytes).expect("parse back");
let parsed_para = &parsed.sections[0].paragraphs[0];
assert_eq!(parsed_para.text, "AB");
let parsed_eq = parsed_para.controls.iter().find_map(|ctrl| match ctrl {
Control::Equation(eq) => Some(eq),
_ => None,
});
match parsed_eq {
Some(eq) => {
assert_eq!(eq.script, "x < y & z");
assert_eq!(eq.font_size, 1000);
assert_eq!(eq.color, 0x000000FF);
assert_eq!(eq.baseline, 120);
assert_eq!(eq.font_name, "HYhwpEQ");
assert_eq!(eq.version_info, "Equation Version 60");
assert!(eq.common.treat_as_char);
assert_eq!(eq.common.width, 2400);
assert_eq!(eq.common.height, 1200);
assert_eq!(eq.common.instance_id, 7);
assert_eq!(eq.common.z_order, 3);
assert_eq!(eq.common.vertical_offset, 80);
assert_eq!(eq.common.horizontal_offset, 160);
assert_eq!(eq.common.margin.left, 10);
assert_eq!(eq.common.margin.right, 20);
assert_eq!(eq.common.margin.top, 30);
assert_eq!(eq.common.margin.bottom, 40);
assert_eq!(eq.common.text_wrap, TextWrap::TopAndBottom);
assert_eq!(eq.common.vert_rel_to, VertRelTo::Para);
assert_eq!(eq.common.horz_rel_to, HorzRelTo::Para);
assert_eq!(eq.common.vert_align, VertAlign::Bottom);
assert_eq!(eq.common.horz_align, HorzAlign::Center);
}
None => panic!("expected equation control, got {:?}", parsed_para.controls),
}
}
#[test]
fn task1655_equation_flow_with_text_roundtrips() {
use crate::model::control::{Control, Equation};
use crate::model::shape::CommonObjAttr;
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "A".to_string();
para.char_offsets = vec![0];
para.char_count = 9;
para.controls.push(Control::Equation(Box::new(Equation {
common: CommonObjAttr {
width: 1600,
height: 900,
treat_as_char: true,
flow_with_text: false,
..Default::default()
},
script: "a+b".to_string(),
font_size: 1000,
..Default::default()
})));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize equation");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
assert!(
xml.contains(r#"flowWithText="0""#),
"수식 flowWithText=false 는 0으로 방출되어야 한다: {}",
xml
);
drop(sec0);
let parsed = parse_hwpx(&bytes).expect("parse back");
let parsed_eq = parsed.sections[0].paragraphs[0]
.controls
.iter()
.find_map(|ctrl| match ctrl {
Control::Equation(eq) => Some(eq),
_ => None,
})
.expect("equation control");
assert!(
!parsed_eq.common.flow_with_text,
"수식 flowWithText=false 는 재파싱 뒤에도 보존되어야 한다"
);
}
#[test]
fn equation_control_between_text_runs_roundtrips_position() {
use crate::model::control::{Control, Equation};
use crate::model::page::ColumnDef;
use crate::model::shape::CommonObjAttr;
use crate::model::table::Table;
let mut doc = Document::default();
doc.doc_info
.border_fills
.push(crate::model::style::BorderFill::default());
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "ACB".to_string();
para.char_offsets = vec![0, 9, 18];
para.char_count = 20;
para.controls.push(Control::ColumnDef(ColumnDef::default()));
para.controls.push(Control::Table(Box::default()));
para.controls.push(Control::Equation(Box::new(Equation {
common: CommonObjAttr {
width: 1000,
height: 1000,
treat_as_char: true,
..Default::default()
},
script: "a+b".to_string(),
font_size: 1000,
..Default::default()
})));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize equation");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
let a_pos = xml.find("<hp:t>A</hp:t>").expect("A text run");
let c_pos = xml.find("<hp:t>C</hp:t>").expect("C text run");
let eq_pos = xml.find("<hp:equation ").expect("equation");
let b_pos = xml.find("<hp:t>B</hp:t>").expect("B text run");
assert!(
a_pos < c_pos && c_pos < eq_pos && eq_pos < b_pos,
"equation must stay after non-equation inline slots: {}",
xml
);
}
#[test]
fn task1587_ruby_control_roundtrips() {
use crate::model::control::{Control, Ruby};
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "ab".to_string();
para.char_offsets = vec![0, 9];
para.char_count = 11; para.controls.push(Control::Ruby(Ruby {
main_text: "기준글".to_string(),
ruby_text: "덧말".to_string(),
pos_type: 1, align: 3, sz_ratio: 80,
option: 3,
style_id_ref: 5,
}));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize ruby");
let doc2 = crate::parser::hwpx::parse_hwpx(&bytes).expect("parse");
let rubies: Vec<_> = doc2.sections[0].paragraphs[0]
.controls
.iter()
.filter_map(|c| match c {
Control::Ruby(r) => Some(r),
_ => None,
})
.collect();
assert_eq!(
rubies.len(),
1,
"Ruby 컨트롤이 roundtrip 후 보존돼야 한다 (현재 드롭): {:?}",
doc2.sections[0].paragraphs[0].controls
);
let r = rubies[0];
assert_eq!(r.main_text, "기준글", "mainText 보존");
assert_eq!(r.ruby_text, "덧말", "subText(덧말) 보존");
assert_eq!(r.pos_type, 1, "posType(BOTTOM) 보존");
assert_eq!(r.align, 3, "align(CENTER) 보존");
assert_eq!(r.sz_ratio, 80, "szRatio 보존");
assert_eq!(r.option, 3, "option 보존");
assert_eq!(r.style_id_ref, 5, "styleIDRef 보존");
}
#[test]
fn issue4388_hyperlink_control_drop_is_not_silent() {
use crate::model::control::{Control, Hyperlink};
use crate::model::paragraph::CharShapeRef;
use crate::model::style::CharShape;
let mut doc = Document::default();
doc.doc_info.char_shapes.push(CharShape::default());
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "ab".to_string();
para.char_offsets = vec![0, 9];
para.char_count = 11; para.char_shapes = vec![CharShapeRef {
start_pos: 0,
char_shape_id: 0,
}];
para.controls.push(Control::Hyperlink(Hyperlink {
url: "http://example.com".to_string(),
text: "example".to_string(),
}));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize hyperlink");
let doc2 = crate::parser::hwpx::parse_hwpx(&bytes).expect("parse");
let hyperlinks_after: Vec<_> = doc2.sections[0].paragraphs[0]
.controls
.iter()
.filter(|c| matches!(c, Control::Hyperlink(_)))
.collect();
assert!(
hyperlinks_after.is_empty(),
"Hyperlink 는 HWPX 로 안전하게 변환할 대응 표현이 없어 드롭되는 것이 현재 계약이다: {:?}",
doc2.sections[0].paragraphs[0].controls
);
assert!(
!crate::serializer::hwpx::section::is_hwpx_inline_slot(&Control::Hyperlink(
Hyperlink::default()
)),
"Hyperlink 는 is_hwpx_inline_slot 에 등록되면 안 됨(#4388 후속 회귀 참조)"
);
}
#[test]
fn issue4388_unknown_control_drop_is_not_silent() {
use crate::model::control::{Control, UnknownControl};
use crate::model::paragraph::CharShapeRef;
use crate::model::style::CharShape;
let mut doc = Document::default();
doc.doc_info.char_shapes.push(CharShape::default());
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "a\u{fffc}b".to_string();
para.char_offsets = vec![0, 1, 9];
para.char_count = 11; para.char_shapes = vec![CharShapeRef {
start_pos: 0,
char_shape_id: 0,
}];
para.controls.push(Control::Unknown(UnknownControl {
ctrl_id: 0x1234_5678,
}));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize unknown");
let doc2 = crate::parser::hwpx::parse_hwpx(&bytes).expect("parse");
let unknowns_after: Vec<_> = doc2.sections[0].paragraphs[0]
.controls
.iter()
.filter(|c| matches!(c, Control::Unknown(_)))
.collect();
assert!(
unknowns_after.is_empty(),
"Unknown 컨트롤은 HWPX 로 변환할 대응 표현·원본 바이트가 없어 드롭되는 것이 \
현재 계약이다: {:?}",
doc2.sections[0].paragraphs[0].controls
);
assert!(
!crate::serializer::hwpx::section::is_hwpx_inline_slot(&Control::Unknown(
UnknownControl::default()
)),
"Unknown 은 is_hwpx_inline_slot 에 등록되면 안 됨(#4388 후속 회귀 참조)"
);
}
#[test]
fn task1591_bookmark_not_hoisted_before_slot() {
use crate::model::control::{Bookmark, Control};
use crate::model::style::BorderFill;
use crate::model::table::Table;
let mut doc = Document::default();
doc.doc_info.border_fills.push(BorderFill::default());
let mut section = crate::model::document::Section::default();
section
.paragraphs
.push(crate::model::paragraph::Paragraph::default()); let mut p = crate::model::paragraph::Paragraph::default();
p.text = "AB".to_string();
p.char_offsets = vec![0, 9]; p.char_count = 11;
p.controls.push(Control::Table(Box::<Table>::default()));
p.controls.push(Control::Bookmark(Bookmark {
name: "bm".to_string(),
}));
section.paragraphs.push(p);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize");
let doc2 = crate::parser::hwpx::parse_hwpx(&bytes).expect("parse");
let ctrls: Vec<&str> = doc2.sections[0].paragraphs[1]
.controls
.iter()
.map(|c| match c {
Control::Table(_) => "tbl",
Control::Bookmark(_) => "bm",
_ => "?",
})
.collect();
assert_eq!(
ctrls,
vec!["tbl", "bm"],
"북마크가 표 뒤 위치를 보존해야 한다 (hoisting 시 [bm,tbl] 로 뒤바뀜)"
);
}
#[test]
fn task1591v2_first_para_hidden_slot_char_shape_position() {
use crate::model::control::{Bookmark, Control, PageNumberPos};
use crate::model::document::SectionDef;
use crate::model::page::ColumnDef;
use crate::model::paragraph::CharShapeRef;
use crate::model::style::{BorderFill, CharShape};
use crate::model::table::Table;
let mut doc = Document::default();
doc.doc_info.border_fills.push(BorderFill::default());
doc.doc_info.char_shapes.push(CharShape::default()); doc.doc_info.char_shapes.push(CharShape::default()); let mut section = crate::model::document::Section::default();
let mut p = crate::model::paragraph::Paragraph::default();
p.text = String::new();
p.char_count = 41;
p.char_shapes = vec![
CharShapeRef {
start_pos: 0,
char_shape_id: 0,
},
CharShapeRef {
start_pos: 24,
char_shape_id: 1,
},
];
p.controls
.push(Control::SectionDef(Box::<SectionDef>::default()));
p.controls.push(Control::ColumnDef(ColumnDef::default()));
p.controls.push(Control::Table(Box::<Table>::default()));
p.controls
.push(Control::PageNumberPos(PageNumberPos::default()));
p.controls.push(Control::Bookmark(Bookmark {
name: "별첨 1".to_string(),
}));
section.paragraphs.push(p);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize");
let doc2 = crate::parser::hwpx::parse_hwpx(&bytes).expect("parse");
let p2 = &doc2.sections[0].paragraphs[0];
let positions: Vec<u32> = p2.char_shapes.iter().map(|cs| cs.start_pos).collect();
assert_eq!(
positions,
vec![0, 24],
"char_shape 경계가 24 에 보존돼야 한다 (mismatch 폴백 시 +8 → 32)"
);
let ctrls: Vec<&str> = p2
.controls
.iter()
.map(|c| match c {
Control::SectionDef(_) => "secd",
Control::ColumnDef(_) => "cold",
Control::Table(_) => "tbl",
Control::PageNumberPos(_) => "pagenum",
Control::Bookmark(_) => "bm",
_ => "?",
})
.collect();
assert_eq!(
ctrls,
vec!["secd", "cold", "tbl", "pagenum", "bm"],
"컨트롤 순서(표·pageNum 뒤 북마크) 보존"
);
}
#[test]
fn task1593_first_para_same_para_field_end_preserved() {
use crate::model::control::{Bookmark, Control, Field};
use crate::model::document::SectionDef;
use crate::model::page::ColumnDef;
use crate::model::paragraph::{CharShapeRef, FieldRange};
use crate::model::style::CharShape;
let mut doc = Document::default();
doc.doc_info.char_shapes.push(CharShape::default()); doc.doc_info.char_shapes.push(CharShape::default()); let mut section = crate::model::document::Section::default();
let mut p = crate::model::paragraph::Paragraph::default();
p.text = "AB".to_string();
p.char_offsets = vec![32, 41];
p.char_count = 43;
p.char_shapes = vec![
CharShapeRef {
start_pos: 0,
char_shape_id: 0,
},
CharShapeRef {
start_pos: 41,
char_shape_id: 1,
},
];
p.controls
.push(Control::SectionDef(Box::<SectionDef>::default()));
p.controls.push(Control::ColumnDef(ColumnDef::default()));
p.controls.push(Control::Field(Field::default()));
p.controls.push(Control::Bookmark(Bookmark {
name: "bm".to_string(),
}));
p.field_ranges = vec![FieldRange {
start_char_idx: 0,
end_char_idx: 1,
control_idx: 2,
..Default::default()
}];
section.paragraphs.push(p);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize");
let doc2 = crate::parser::hwpx::parse_hwpx(&bytes).expect("parse");
let p2 = &doc2.sections[0].paragraphs[0];
assert_eq!(
p2.field_ranges.len(),
1,
"same-para 균형 필드(fieldBegin/End 1/1)가 보존돼야 한다 (종전: fieldEnd 드롭)"
);
assert_eq!(
p2.char_count, 43,
"fieldEnd 8유닛 + 책갈피 8유닛(#4677) 보존"
);
let positions: Vec<u32> = p2.char_shapes.iter().map(|cs| cs.start_pos).collect();
assert_eq!(
positions,
vec![0, 41],
"후속 char_shape 경계 보존 (종전 −8)"
);
}
#[test]
fn task1592_empty_paragraph_no_spurious_charshape() {
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
let mut p0 = crate::model::paragraph::Paragraph::default();
p0.text = "본문".to_string();
section.paragraphs.push(p0);
section
.paragraphs
.push(crate::model::paragraph::Paragraph::default());
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize");
let doc2 = crate::parser::hwpx::parse_hwpx(&bytes).expect("parse");
let cs = &doc2.sections[0].paragraphs[1].char_shapes;
assert!(
cs.is_empty(),
"빈 문단은 char_shapes 가 비어야 한다 (spurious (0,0) 금지): {:?}",
cs.iter()
.map(|c| (c.start_pos, c.char_shape_id))
.collect::<Vec<_>>()
);
}
#[test]
fn equation_control_does_not_consume_unmapped_control_gap() {
use crate::model::control::{Control, Equation};
use crate::model::shape::CommonObjAttr;
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "ACB".to_string();
para.char_offsets = vec![0, 9, 18];
para.char_count = 20;
para.controls.push(Control::Equation(Box::new(Equation {
common: CommonObjAttr {
width: 1000,
height: 1000,
treat_as_char: true,
..Default::default()
},
script: "a+b".to_string(),
font_size: 1000,
..Default::default()
})));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize equation");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
let text_pos = xml.find("<hp:t>ACB</hp:t>").expect("text run");
let eq_pos = xml.find("<hp:equation ").expect("equation");
assert!(
text_pos < eq_pos,
"ambiguous control gap must not move equation before text: {}",
xml
);
}
#[test]
fn equation_roundtrip_from_hancom_origin_hwp_sample() {
use crate::model::control::{Control, Equation};
use crate::parser::parse_hwp;
let bytes = std::fs::read("samples/equation-lim.hwp")
.expect("samples/equation-lim.hwp must be readable");
let original = parse_hwp(&bytes).expect("parse hancom origin hwp");
let collect_equations = |doc: &Document| -> Vec<Equation> {
doc.sections
.iter()
.flat_map(|s| s.paragraphs.iter())
.flat_map(|p| p.controls.iter())
.filter_map(|c| match c {
Control::Equation(eq) => Some((**eq).clone()),
_ => None,
})
.collect()
};
let original_eqs = collect_equations(&original);
assert!(
!original_eqs.is_empty(),
"한컴 origin 샘플에 수식이 존재해야 회귀 비교가 의미있음"
);
let hwpx_bytes = serialize_hwpx(&original).expect("serialize to hwpx");
let reparsed = parse_hwpx(&hwpx_bytes).expect("parse hwpx back");
let reparsed_eqs = collect_equations(&reparsed);
assert_eq!(
reparsed_eqs.len(),
original_eqs.len(),
"수식 컨트롤 개수가 hwpx 라운드트립에서 유지되어야 함"
);
for (i, (orig, rep)) in original_eqs.iter().zip(reparsed_eqs.iter()).enumerate() {
assert_eq!(
rep.script, orig.script,
"[#{}] script must roundtrip through hwpx",
i
);
assert_eq!(
rep.font_size, orig.font_size,
"[#{}] font_size must roundtrip",
i
);
assert_eq!(
rep.baseline, orig.baseline,
"[#{}] baseline must roundtrip",
i
);
assert_eq!(
rep.font_name, orig.font_name,
"[#{}] font_name must roundtrip",
i
);
assert_eq!(rep.color, orig.color, "[#{}] color must roundtrip", i);
assert_eq!(
rep.common.width, orig.common.width,
"[#{}] common.width must roundtrip",
i
);
assert_eq!(
rep.common.height, orig.common.height,
"[#{}] common.height must roundtrip",
i
);
assert_eq!(
rep.common.treat_as_char, orig.common.treat_as_char,
"[#{}] common.treat_as_char must roundtrip",
i
);
}
}
#[test]
fn linesegs_from_ir_emitted_per_linebreak() {
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "A\nB\nC".to_string();
for (textpos, vertpos) in [(0u32, 0i32), (2, 1600), (4, 3200)] {
para.line_segs.push(crate::model::paragraph::LineSeg {
text_start: textpos,
vertical_pos: vertpos,
line_height: 1000,
text_height: 1000,
baseline_distance: 850,
line_spacing: 600,
tag: crate::model::paragraph::LineSeg::TAG_SINGLE_SEGMENT_LINE,
..Default::default()
});
}
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
let count = xml.matches("<hp:lineseg ").count();
assert_eq!(count, 3, "expected 3 linesegs, got {}: {}", count, xml);
assert!(xml.contains(r#"textpos="0" vertpos="0""#));
assert!(xml.contains(r#"textpos="2" vertpos="1600""#));
assert!(xml.contains(r#"textpos="4" vertpos="3200""#));
}
#[test]
fn task1380_no_linesegarray_when_ir_has_none() {
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "A\nB\nC".to_string();
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
assert!(!xml.contains("<hp:linesegarray"), "got: {}", xml);
}
#[test]
fn multi_paragraph_emits_multiple_hp_p() {
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
for t in ["첫째 줄", "둘째", "끝"] {
let mut p = crate::model::paragraph::Paragraph::default();
p.text = t.to_string();
section.paragraphs.push(p);
}
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
let p_count = xml.matches("<hp:p ").count();
assert_eq!(p_count, 3, "expected 3 <hp:p>, got {}", p_count);
assert!(xml.contains("<hp:t>첫째 줄</hp:t>"));
assert!(xml.contains("<hp:t>둘째</hp:t>"));
assert!(xml.contains("<hp:t>끝</hp:t>"));
}
#[test]
fn xml_escape_applied_to_section_text() {
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "a & b < c".to_string();
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
assert!(xml.contains("a & b < c"), "escape missing: {}", xml);
}
#[test]
fn mimetype_is_first_entry() {
let doc = Document::default();
let bytes = serialize_hwpx(&doc).expect("serialize");
assert_eq!(&bytes[0..4], b"PK\x03\x04", "ZIP signature");
let name_len = u16::from_le_bytes([bytes[26], bytes[27]]) as usize;
let name = &bytes[30..30 + name_len];
assert_eq!(name, b"mimetype");
}
#[test]
fn mimetype_stored_not_deflated() {
let doc = Document::default();
let bytes = serialize_hwpx(&doc).expect("serialize");
let method = u16::from_le_bytes([bytes[8], bytes[9]]);
assert_eq!(method, 0, "mimetype must be STORED (method=0)");
}
#[test]
fn hancom_required_files_present() {
let mut doc = Document::default();
doc.sections
.push(crate::model::document::Section::default());
let bytes = serialize_hwpx(&doc).expect("serialize");
let cursor = std::io::Cursor::new(&bytes);
let archive = zip::ZipArchive::new(cursor).expect("valid zip");
let names: Vec<String> = archive
.file_names()
.map(|name| name.expect("ZIP 엔트리 이름").into_owned())
.collect();
let required = [
"mimetype",
"version.xml",
"Contents/header.xml",
"Contents/section0.xml",
"Contents/content.hpf",
"Preview/PrvText.txt",
"Preview/PrvImage.png",
"settings.xml",
"META-INF/container.xml",
"META-INF/container.rdf",
"META-INF/manifest.xml",
];
for r in &required {
assert!(names.iter().any(|n| n == r), "missing required file: {}", r);
}
}
#[test]
fn picture_bindata_roundtrip() {
use crate::model::bin_data::BinDataContent;
use crate::model::control::Control;
use crate::model::image::{ImageAttr, Picture};
use crate::model::shape::CommonObjAttr;
let fake_png = b"\x89PNG\r\n\x1a\nfake_image_data_for_test";
let mut doc = Document::default();
doc.bin_data_content.push(BinDataContent {
id: 1,
data: fake_png.to_vec().into(),
extension: "png".to_string(),
});
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "A".to_string();
para.char_offsets = vec![8];
para.char_count = 10;
para.controls.push(Control::Picture(Box::new(Picture {
common: CommonObjAttr {
width: 5000,
height: 3000,
treat_as_char: true,
..Default::default()
},
image_attr: ImageAttr {
bin_data_id: 1,
..Default::default()
},
..Default::default()
})));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize picture");
let cursor = std::io::Cursor::new(&bytes);
let archive = zip::ZipArchive::new(cursor).expect("zip");
let names: Vec<String> = archive
.file_names()
.map(|name| name.expect("ZIP 엔트리 이름").into_owned())
.collect();
assert!(
names.iter().any(|n| n.starts_with("BinData/")),
"BinData/ ZIP entry missing: {:?}",
names
);
drop(archive);
let cursor2 = std::io::Cursor::new(&bytes);
let mut archive2 = zip::ZipArchive::new(cursor2).expect("zip");
let mut sec0 = archive2.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
assert!(
xml.contains("binaryItemIDRef"),
"binaryItemIDRef missing in section XML: {}",
xml
);
drop(sec0);
let cursor3 = std::io::Cursor::new(&bytes);
let mut archive3 = zip::ZipArchive::new(cursor3).expect("zip");
let mut content_hpf = archive3
.by_name("Contents/content.hpf")
.expect("content.hpf");
let mut content_xml = String::new();
std::io::Read::read_to_string(&mut content_hpf, &mut content_xml).expect("read");
assert!(
content_xml.contains(r#"isEmbeded="1""#),
"embedded BinData manifest item must include isEmbeded=1: {}",
content_xml
);
drop(content_hpf);
let parsed = parse_hwpx(&bytes).expect("parse back");
assert_eq!(parsed.bin_data_content.len(), 1);
assert_eq!(&parsed.bin_data_content[0].data.load()[..], fake_png);
assert_eq!(parsed.bin_data_content[0].extension, "png");
}
#[test]
fn issue1917_bindata_load_failure_preserves_pic_control() {
use crate::model::bin_data::BinDataContent;
use crate::model::control::Control;
use crate::model::image::{ImageAttr, Picture};
use crate::model::shape::CommonObjAttr;
fn count_pics(doc: &Document) -> usize {
doc.sections
.iter()
.flat_map(|s| s.paragraphs.iter())
.flat_map(|p| p.controls.iter())
.filter(|c| matches!(c, Control::Picture(_)))
.count()
}
let mut doc = Document::default();
doc.doc_info
.char_shapes
.push(crate::model::style::CharShape::default());
doc.bin_data_content.push(BinDataContent {
id: 1,
data: b"BMfake_bmp_data".to_vec().into(),
extension: "bmp".to_string(),
});
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "A".to_string();
para.char_offsets = vec![8];
para.char_count = 10;
para.controls.push(Control::Picture(Box::new(Picture {
common: CommonObjAttr {
width: 5000,
height: 3000,
treat_as_char: true,
..Default::default()
},
image_attr: ImageAttr {
bin_data_id: 1,
..Default::default()
},
..Default::default()
})));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize picture");
let stripped = {
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).expect("zip open");
let mut out = std::io::Cursor::new(Vec::<u8>::new());
let mut zw = zip::ZipWriter::new(&mut out);
let opts = zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Deflated);
for i in 0..archive.len() {
let mut f = archive.by_index(i).expect("entry");
let name = f.name().expect("ZIP 엔트리 이름").to_string();
if name.starts_with("BinData/") {
continue;
}
let mut data = Vec::new();
f.read_to_end(&mut data).expect("read entry");
zw.start_file(name, opts).expect("start_file");
std::io::Write::write_all(&mut zw, &data).expect("write entry");
}
zw.finish().expect("finish");
out.into_inner()
};
let doc2 = parse_hwpx(&stripped).expect("parse stripped");
assert_eq!(
doc2.bin_data_content.len(),
1,
"로드 실패한 BinData 도 placeholder 로 등록되어야 한다"
);
assert!(
doc2.bin_data_content[0].data.is_empty(),
"placeholder 데이터는 빈 값이어야 한다"
);
assert_eq!(
doc2.bin_data_content[0].extension, "bmp",
"placeholder 확장자는 manifest 기준으로 보존"
);
assert_eq!(count_pics(&doc2), 1, "pic 컨트롤이 보존되어야 한다");
let bytes2 = serialize_hwpx(&doc2).expect("re-serialize with placeholder");
let doc3 = parse_hwpx(&bytes2).expect("parse re-serialized");
assert_eq!(count_pics(&doc3), 1, "재직렬화 왕복 후에도 pic 보존");
}
#[test]
fn issue1452_hwpx_preserves_alpha_png_bindata_bytes() {
use crate::model::bin_data::BinDataContent;
use crate::model::control::Control;
use crate::model::image::{ImageAttr, Picture};
use crate::model::shape::CommonObjAttr;
let alpha_png = vec![
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48,
0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x04, 0x00, 0x00,
0x00, 0xb5, 0x1c, 0x0c, 0x02, 0x00, 0x00, 0x00, 0x0b, 0x49, 0x44, 0x41, 0x54, 0x78,
0xda, 0x63, 0x60, 0x60, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x2b, 0x09, 0x4d, 0x84,
0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
];
let mut doc = Document::default();
doc.bin_data_content.push(BinDataContent {
id: 1,
data: alpha_png.clone().into(),
extension: "png".to_string(),
});
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "A".to_string();
para.char_offsets = vec![8];
para.char_count = 10;
para.controls.push(Control::Picture(Box::new(Picture {
common: CommonObjAttr {
width: 5000,
height: 5000,
treat_as_char: true,
..Default::default()
},
image_attr: ImageAttr {
bin_data_id: 1,
..Default::default()
},
..Default::default()
})));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize alpha png picture");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let bin_name = archive
.file_names()
.map(|name| name.expect("ZIP 엔트리 이름"))
.find(|name| name.starts_with("BinData/") && name.ends_with(".png"))
.map(|name| name.into_owned())
.expect("png BinData entry");
let mut bin = archive.by_name(&bin_name).expect("read png BinData");
let mut actual = Vec::new();
std::io::Read::read_to_end(&mut bin, &mut actual).expect("read");
assert_eq!(
actual, alpha_png,
"알파 채널이 있는 PNG BinData 바이트는 HWPX ZIP 안에서도 그대로 보존되어야 한다"
);
}
#[test]
fn issue_1345_picture_effects_shadow_roundtrip() {
use crate::model::control::Control;
use crate::model::shape::ShapeObject;
fn count_shape_picture_shadows(shape: &ShapeObject) -> usize {
match shape {
ShapeObject::Picture(pic) => usize::from(pic.effects.shadow.is_some()),
ShapeObject::Group(group) => {
group.children.iter().map(count_shape_picture_shadows).sum()
}
_ => 0,
}
}
fn count_picture_shadows(control: &Control) -> usize {
match control {
Control::Picture(pic) => usize::from(pic.effects.shadow.is_some()),
Control::Shape(shape) => count_shape_picture_shadows(shape),
_ => 0,
}
}
let bytes = std::fs::read("samples/hwpx/aift.hwpx")
.expect("samples/hwpx/aift.hwpx must be readable");
let original = parse_hwpx(&bytes).expect("parse original");
let parsed_shadow_count: usize = original
.sections
.iter()
.flat_map(|section| §ion.paragraphs)
.flat_map(|para| ¶.controls)
.map(count_picture_shadows)
.sum();
assert!(
parsed_shadow_count > 0,
"parser must preserve at least one picture shadow effect"
);
let serialized = serialize_hwpx(&original).expect("serialize roundtrip");
let mut archive =
zip::ZipArchive::new(std::io::Cursor::new(serialized)).expect("roundtrip zip");
let section_names: Vec<String> = archive
.file_names()
.map(|name| name.expect("ZIP 엔트리 이름"))
.filter(|name| name.starts_with("Contents/section") && name.ends_with(".xml"))
.map(|name| name.into_owned())
.collect();
let mut section_xml = String::new();
for name in section_names {
let mut section = archive.by_name(&name).expect("roundtrip section");
std::io::Read::read_to_string(&mut section, &mut section_xml).expect("read section");
}
for needle in ["<hp:shadow ", "<hp:scale ", "<hp:effectsColor ", "<hp:rgb "] {
assert!(
section_xml.contains(needle),
"roundtrip section XML must preserve {needle}"
);
}
}
#[test]
fn table_control_roundtrip() {
use crate::model::control::Control;
use crate::model::table::Table;
let mut doc = Document::default();
doc.doc_info
.border_fills
.push(crate::model::style::BorderFill::default());
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "A".to_string();
para.char_offsets = vec![8];
para.char_count = 10;
para.controls.push(Control::Table(Box::default()));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize table");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
assert!(
xml.contains("<hp:tbl ") || xml.contains("<hp:tbl>"),
"table element missing in section XML: {}",
xml
);
drop(sec0);
let parsed = parse_hwpx(&bytes).expect("parse back");
let has_table = parsed.sections[0].paragraphs[0]
.controls
.iter()
.any(|c| matches!(c, Control::Table(_)));
assert!(has_table, "table control missing after roundtrip");
}
#[test]
fn footnote_endnote_roundtrip() {
use crate::model::control::Control;
use crate::model::footnote::{Endnote, Footnote};
use crate::model::paragraph::Paragraph;
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "본문".to_string();
para.char_offsets = vec![8, 17];
para.char_count = 20;
let mut fn_para = Paragraph::default();
fn_para.text = "각주 텍스트".to_string();
para.controls.push(Control::Footnote(Box::new(Footnote {
number: 1,
paragraphs: vec![fn_para],
after_decoration_letter: 0x0029,
..Default::default()
})));
let mut en_para = Paragraph::default();
en_para.text = "미주 텍스트".to_string();
para.controls.push(Control::Endnote(Box::new(Endnote {
number: 1,
paragraphs: vec![en_para],
after_decoration_letter: 0x0029,
..Default::default()
})));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize notes");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
assert!(xml.contains("<hp:footNote"), "footNote missing: {}", xml);
assert!(xml.contains("<hp:endNote"), "endNote missing: {}", xml);
assert!(
xml.contains("각주 텍스트"),
"footnote text missing: {}",
xml
);
assert!(xml.contains("미주 텍스트"), "endnote text missing: {}", xml);
drop(sec0);
let parsed = parse_hwpx(&bytes).expect("parse back");
let ctrls = &parsed.sections[0].paragraphs[0].controls;
let has_fn = ctrls.iter().any(|c| matches!(c, Control::Footnote(_)));
let has_en = ctrls.iter().any(|c| matches!(c, Control::Endnote(_)));
assert!(has_fn, "footnote missing after roundtrip");
assert!(has_en, "endnote missing after roundtrip");
let fn_ctrl = ctrls.iter().find_map(|c| match c {
Control::Footnote(f) => Some(f),
_ => None,
});
assert!(
fn_ctrl.unwrap().paragraphs[0].text.contains("각주 텍스트"),
"footnote paragraph text not preserved"
);
}
#[test]
fn footnote_endnote_decoration_attrs_roundtrip() {
use crate::model::control::Control;
use crate::model::footnote::{Endnote, Footnote};
use crate::model::paragraph::Paragraph;
let mut doc = Document::default();
let mut section = crate::model::document::Section::default();
let mut para = crate::model::paragraph::Paragraph::default();
para.text = "본문".to_string();
para.char_offsets = vec![8, 17];
para.char_count = 20;
let mut fn_para = Paragraph::default();
fn_para.text = "각주 본문".to_string();
para.controls.push(Control::Footnote(Box::new(Footnote {
number: 1,
paragraphs: vec![fn_para],
before_decoration_letter: 47928, after_decoration_letter: 65289, number_shape: 3211264, instance_id: 1085612573,
..Default::default()
})));
let mut en_para = Paragraph::default();
en_para.text = "미주 본문".to_string();
para.controls.push(Control::Endnote(Box::new(Endnote {
number: 2,
paragraphs: vec![en_para],
before_decoration_letter: 0,
after_decoration_letter: 0,
number_shape: 0,
instance_id: 7,
..Default::default()
})));
section.paragraphs.push(para);
doc.sections.push(section);
let bytes = serialize_hwpx(&doc).expect("serialize notes");
let cursor = std::io::Cursor::new(&bytes);
let mut archive = zip::ZipArchive::new(cursor).expect("zip");
let mut sec0 = archive.by_name("Contents/section0.xml").expect("section0");
let mut xml = String::new();
std::io::Read::read_to_string(&mut sec0, &mut xml).expect("read");
drop(sec0);
assert!(
xml.contains(
r#"<hp:footNote flag="3211264" number="1" prefixChar="47928" suffixChar="65289" instId="1085612573">"#
),
"footNote 속성이 한컴 계약대로 방출되지 않음: {}",
xml
);
assert!(
xml.contains(r#"<hp:endNote number="2" suffixChar="0" instId="7">"#),
"endNote 생략 규칙(flag/prefixChar 생략, suffixChar 항상)이 어긋남: {}",
xml
);
let parsed = parse_hwpx(&bytes).expect("parse back");
let ctrls = &parsed.sections[0].paragraphs[0].controls;
let fn_ctrl = ctrls
.iter()
.find_map(|c| match c {
Control::Footnote(f) => Some(f),
_ => None,
})
.expect("footnote ctrl");
assert_eq!(
fn_ctrl.before_decoration_letter, 47928,
"footNote prefixChar"
);
assert_eq!(
fn_ctrl.after_decoration_letter, 65289,
"footNote suffixChar"
);
assert_eq!(fn_ctrl.number_shape, 3211264, "footNote flag");
assert_eq!(fn_ctrl.instance_id, 1085612573, "footNote instId");
let en_ctrl = ctrls
.iter()
.find_map(|c| match c {
Control::Endnote(e) => Some(e),
_ => None,
})
.expect("endnote ctrl");
assert_eq!(
en_ctrl.before_decoration_letter, 0,
"endNote prefixChar 없음"
);
assert_eq!(
en_ctrl.after_decoration_letter, 0,
"endNote suffixChar 0 이 ')' 로 오염됨"
);
assert_eq!(en_ctrl.number_shape, 0, "endNote flag 없음");
assert_eq!(en_ctrl.instance_id, 7, "endNote instId");
}
#[test]
fn tac_img_sample_has_pictures_and_bindata() {
use crate::model::control::Control;
let bytes = std::fs::read("samples/tac-img-02.hwpx")
.expect("samples/tac-img-02.hwpx must be readable");
let original = parse_hwpx(&bytes).expect("parse original");
assert!(
!original.bin_data_content.is_empty(),
"sample must contain BinData"
);
let pic_count = original
.sections
.iter()
.flat_map(|s| s.paragraphs.iter())
.flat_map(|p| p.controls.iter())
.filter(|c| matches!(c, Control::Picture(_)))
.count();
assert!(pic_count > 0, "sample must contain Picture controls");
}
}