use super::bin_data::{BinData, BinDataContent};
use super::footnote::FootnoteShape;
use super::header_footer::MasterPage;
use super::page::{PageBorderFill, PageDef};
use super::paragraph::Paragraph;
use super::style::{BorderFill, Bullet, CharShape, Font, Numbering, ParaShape, Style, TabDef};
use super::*;
pub const HWP5_ORIGIN_HWPX_MARKER_PATH: &str = "META-INF/rhwp-hwp5-origin";
pub const HWP5_ORIGIN_HWPX_PARAGRAPH_AXIS: &[u8] = b"2:paragraph-utf16";
pub const HWP3_ORIGIN_HWPX_MARKER_PATH: &str = "META-INF/rhwp-hwp3-origin";
pub const HWP3_ORIGIN_HWPX_PARAGRAPH_AXIS_PATH: &str = "META-INF/rhwp-hwp3-paragraph-axis";
pub const HWP3_EXTERNAL_REALIGN_STREAM_PATH: &str = "/RhwpHwp3ExternalRealign";
pub const HWP3_EXTERNAL_REALIGN_HWPX_PATH: &str = "META-INF/rhwp-hwp3-external-realign";
pub const HWPX_ORIGIN_STREAM_PATH: &str = "/RhwpHwpxOrigin";
pub const HWPX_ORIGIN_SOURCE_LINES: &[u8] = b"2";
pub const HWP3_ORIGIN_STREAM_PATH: &str = "/RhwpHwp3Origin";
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct RawRecord {
pub tag_id: u16,
pub level: u16,
pub data: Vec<u8>,
}
#[derive(Debug, Clone, Default)]
pub struct Document {
pub header: FileHeader,
pub doc_properties: DocProperties,
pub doc_info: DocInfo,
pub sections: Vec<Section>,
pub preview: Option<Preview>,
pub bin_data_content: Vec<BinDataContent>,
pub extra_streams: Vec<(String, Vec<u8>)>,
pub hwpx_aux_entries: Vec<(String, Vec<u8>)>,
pub is_hwp3_variant: bool,
pub is_hwpx_variant: bool,
pub provenance: crate::model::provenance::SourceProvenance,
}
#[derive(Debug, Clone, Default)]
pub struct Preview {
pub image: Option<PreviewImage>,
pub text: Option<String>,
}
#[derive(Debug, Clone)]
pub struct PreviewImage {
pub format: PreviewImageFormat,
pub data: Vec<u8>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PreviewImageFormat {
Png,
Bmp,
Gif,
Unknown,
}
#[derive(Debug, Clone, Default)]
pub struct FileHeader {
pub version: HwpVersion,
pub flags: u32,
pub compressed: bool,
pub encrypted: bool,
pub distribution: bool,
pub raw_data: Option<Vec<u8>>,
}
#[derive(Debug, Clone, Default)]
pub struct HwpVersion {
pub major: u8,
pub minor: u8,
pub build: u8,
pub revision: u8,
}
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct DocProperties {
pub raw_data: Option<Vec<u8>>,
pub section_count: u16,
pub page_start_num: u16,
pub footnote_start_num: u16,
pub endnote_start_num: u16,
pub picture_start_num: u16,
pub table_start_num: u16,
pub equation_start_num: u16,
pub caret_list_id: u32,
pub caret_para_id: u32,
pub caret_char_pos: u32,
}
#[derive(Debug, Clone, Default)]
pub struct DocInfo {
pub bin_data_list: Vec<BinData>,
pub font_faces: Vec<Vec<Font>>,
pub border_fills: Vec<BorderFill>,
pub char_shapes: Vec<CharShape>,
pub tab_defs: Vec<TabDef>,
pub numberings: Vec<Numbering>,
pub bullets: Vec<Bullet>,
pub para_shapes: Vec<ParaShape>,
pub styles: Vec<Style>,
pub extra_records: Vec<RawRecord>,
pub print_method: Option<u32>,
pub raw_stream: Option<Vec<u8>>,
pub bullet_count: u32,
pub memo_shape_count: u32,
pub memo_properties_xml: Option<String>,
pub distribute_doc_data_removed: bool,
pub raw_stream_dirty: bool,
pub hwpx_head_tail: Option<String>,
pub hwpml_version: Option<String>,
pub raw_provenance: Option<crate::model::raw_provenance::DocInfoSeal>,
}
impl DocInfo {
pub fn track_change_flags(&self) -> u32 {
self.extra_records
.iter()
.find(|r| r.tag_id == crate::parser::tags::HWPTAG_TRACKCHANGE)
.and_then(|r| r.data.get(..4))
.map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
.unwrap_or(TRACK_CHANGE_FLAGS_DEFAULT)
}
}
pub const TRACK_CHANGE_FLAGS_DEFAULT: u32 = 56;
pub const HWP5_DOC_DATA_KEY_PRINT_METHOD: u32 = 0x0006_4006;
pub fn print_method_implies_nup(print_method: Option<u32>) -> bool {
matches!(print_method, Some(4) | Some(5))
}
#[derive(Debug, Clone, Default)]
pub struct Section {
pub section_def: SectionDef,
pub paragraphs: Vec<Paragraph>,
pub trailing_lists: Option<crate::model::section_tail::SectionTail>,
pub raw_stream: Option<Vec<u8>>,
pub raw_provenance: Option<crate::model::raw_provenance::SectionSeal>,
}
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct SectionDef {
pub flags: u32,
pub column_spacing: HwpUnit16,
pub line_grid: HwpUnit16,
pub char_grid: HwpUnit16,
pub default_tab_spacing: HwpUnit,
pub page_num: u16,
pub page_num_type: u8,
pub picture_num: u16,
pub table_num: u16,
pub equation_num: u16,
pub page_def: PageDef,
pub footnote_shape: FootnoteShape,
pub endnote_shape: FootnoteShape,
pub page_border_fill: PageBorderFill,
pub hide_header: bool,
pub hide_footer: bool,
pub hide_master_page: bool,
pub hide_border: bool,
pub hide_fill: bool,
pub first_page_border: bool,
pub first_page_fill: bool,
pub hide_empty_line: bool,
pub text_direction: u8,
pub outline_numbering_id: u16,
pub memo_shape_id: u16,
pub raw_ctrl_extra: Vec<u8>,
pub extra_page_border_fills: Vec<PageBorderFill>,
pub extra_child_records: Vec<RawRecord>,
pub master_pages: Vec<MasterPage>,
}
impl SectionDef {
pub const WONGOJI_FORMAT: u32 = 1 << 22;
pub fn wonggoji_format(&self) -> bool {
self.flags & Self::WONGOJI_FORMAT != 0
}
pub fn set_wonggoji_format(&mut self, on: bool) {
if on {
self.flags |= Self::WONGOJI_FORMAT;
} else {
self.flags &= !Self::WONGOJI_FORMAT;
}
}
pub fn cell_grid(&self) -> Option<crate::model::paragraph::CellGrid> {
(self.wonggoji_format() && self.line_grid > 0 && self.char_grid > 0).then(|| {
crate::model::paragraph::CellGrid {
line: i32::from(self.line_grid),
cell: i32::from(self.char_grid),
}
})
}
}
impl Document {
pub(crate) fn hwpx_print_crop_mark(settings: &[u8]) -> Option<bool> {
let xml = std::str::from_utf8(settings).ok()?;
let start = xml.find(r#"name="PrintCropMark""#)?;
let value_start = start + xml[start..].find('>')? + 1;
let value_end = value_start + xml[value_start..].find('<')?;
match xml[value_start..value_end].trim() {
"0" => Some(false),
"1" => Some(true),
_ => None,
}
}
pub(crate) fn print_crop_marks(&self) -> bool {
if let Some(settings) = self.hwpx_aux_entry("settings.xml") {
return Self::hwpx_print_crop_mark(settings).unwrap_or(false);
}
self.doc_info.extra_records.iter().any(|record| {
record.tag_id == 27
&& record.data.chunks_exact(8).any(|pair| {
u32::from_le_bytes(pair[..4].try_into().unwrap()) == 0x0006_401a
&& u32::from_le_bytes(pair[4..].try_into().unwrap()) == 1
})
})
}
pub fn hwpx_aux_entry(&self, path: &str) -> Option<&[u8]> {
self.hwpx_aux_entries
.iter()
.find(|(p, _)| p == path)
.map(|(_, d)| d.as_slice())
}
pub fn hwpx_origin_keeps_source_lines(&self) -> bool {
self.extra_streams.iter().any(|(path, value)| {
path == HWPX_ORIGIN_STREAM_PATH && value == HWPX_ORIGIN_SOURCE_LINES
})
}
pub fn layout_profile(&self) -> crate::model::provenance::LayoutCompatibilityProfile {
use crate::model::provenance::SourceFormat;
let hwp5_container = self.provenance.format == SourceFormat::Hwp5;
let hwp5_origin_hwpx = self.hwpx_aux_entry(HWP5_ORIGIN_HWPX_MARKER_PATH).is_some();
let native_hwp3_hwpx = self.provenance.format == SourceFormat::Hwpx
&& self.hwpx_aux_entry(HWP3_ORIGIN_HWPX_MARKER_PATH).is_some()
&& !hwp5_origin_hwpx;
crate::model::provenance::LayoutCompatibilityProfile::new(
self.provenance.hwp3_lineage
&& !native_hwp3_hwpx
&& !hwp5_container
&& !hwp5_origin_hwpx,
self.provenance.format == SourceFormat::Hwp3 || native_hwp3_hwpx,
(self.provenance.format == SourceFormat::Hwpx
&& !hwp5_origin_hwpx
&& !native_hwp3_hwpx)
|| self.provenance.hwpx_lineage,
self.provenance.format == SourceFormat::Hwpx && !native_hwp3_hwpx,
hwp5_origin_hwpx,
hwp5_container && !self.provenance.hwpx_lineage,
)
.with_hwp5_container(hwp5_container)
.with_hwp3_external_realign(
self.extra_streams
.iter()
.any(|(path, value)| path == HWP3_EXTERNAL_REALIGN_STREAM_PATH && value == b"1")
|| self.hwpx_aux_entry(HWP3_EXTERNAL_REALIGN_HWPX_PATH) == Some(b"1"),
)
.with_hwp3_password_layout(
self.provenance.format == SourceFormat::Hwp3 && self.header.encrypted,
)
.with_stored_rows_before_hancom_2020(self.provenance.stored_rows_before_hancom_2020)
.with_session_edited(
self.provenance.format == SourceFormat::Hwp5
&& self
.sections
.iter()
.any(|s| s.raw_provenance.is_some() && s.raw_stream.is_none()),
)
}
pub(crate) fn external_image_loaded(&self, bin_data_id: u16) -> bool {
if bin_data_id == 0 {
return false;
}
if let Some(content) = self.bin_data_content.get((bin_data_id - 1) as usize) {
return !content.data.is_empty();
}
self.bin_data_content
.iter()
.any(|content| content.id == bin_data_id && !content.data.is_empty())
}
pub(crate) fn next_bin_data_storage_id(&self) -> u16 {
let max_content = self
.bin_data_content
.iter()
.map(|c| c.id)
.max()
.unwrap_or(0);
let max_storage = self
.doc_info
.bin_data_list
.iter()
.map(|b| b.storage_id)
.max()
.unwrap_or(0);
max_content.max(max_storage).saturating_add(1)
}
pub(crate) fn inject_external_image_data(
&mut self,
bin_data_id: u16,
data: Vec<u8>,
extension: String,
) -> bool {
if bin_data_id == 0 {
return false;
}
let idx = (bin_data_id as usize).saturating_sub(1);
if idx < self.bin_data_content.len() {
self.bin_data_content[idx].id = bin_data_id;
self.bin_data_content[idx].data =
crate::model::bin_data::BinDataBytes::from_shared(data);
self.bin_data_content[idx].extension = extension;
} else {
self.bin_data_content
.push(crate::model::bin_data::BinDataContent {
id: bin_data_id,
data: crate::model::bin_data::BinDataBytes::from_shared(data),
extension,
});
}
true
}
pub(crate) fn update_external_image_display_path(
&mut self,
bin_data_id: u16,
display_path: &str,
) {
for section in &mut self.sections {
for para in &mut section.paragraphs {
for ctrl in &mut para.controls {
let pic = match ctrl {
crate::model::control::Control::Picture(p) => p,
crate::model::control::Control::Shape(s) => match s.as_mut() {
crate::model::shape::ShapeObject::Picture(p) => p,
_ => continue,
},
_ => continue,
};
if pic.image_attr.bin_data_id == bin_data_id
&& pic.image_attr.external_path.is_some()
{
pic.image_attr.external_path = Some(display_path.to_string());
}
}
}
}
}
pub fn convert_to_editable(&mut self) -> bool {
if !self.header.distribution {
return false;
}
self.header.distribution = false;
self.header.flags &= !0x04; self.header.raw_data = None;
const TAG_DISTRIBUTE_DOC_DATA: u16 = 0x01C;
self.doc_info
.extra_records
.retain(|r| r.tag_id != TAG_DISTRIBUTE_DOC_DATA);
self.doc_info.distribute_doc_data_removed = true;
true
}
pub fn find_or_create_char_shape(
&mut self,
base_id: u32,
mods: &super::style::CharShapeMods,
) -> u32 {
let base = self
.doc_info
.char_shapes
.get(base_id as usize)
.cloned()
.unwrap_or_default();
let modified = mods.apply_to(&base);
for (i, cs) in self.doc_info.char_shapes.iter().enumerate() {
if *cs == modified {
return i as u32;
}
}
let new_id = self.doc_info.char_shapes.len() as u32;
self.doc_info.char_shapes.push(modified);
self.doc_info.raw_stream_dirty = true;
new_id
}
pub(crate) fn modified_char_shape_ids(
&mut self,
base_ids: Vec<u32>,
mods: &super::style::CharShapeMods,
) -> std::collections::HashMap<u32, u32> {
let mut ids = std::collections::HashMap::new();
for base_id in base_ids {
ids.entry(base_id)
.or_insert_with(|| self.find_or_create_char_shape(base_id, mods));
}
ids
}
pub fn find_or_create_para_shape(
&mut self,
base_id: u16,
mods: &super::style::ParaShapeMods,
) -> u16 {
let base = self
.doc_info
.para_shapes
.get(base_id as usize)
.cloned()
.unwrap_or_default();
let modified = mods.apply_to(&base);
for (i, ps) in self.doc_info.para_shapes.iter().enumerate() {
if *ps == modified {
return i as u16;
}
}
let new_id = self.doc_info.para_shapes.len() as u16;
self.doc_info.para_shapes.push(modified);
self.doc_info.raw_stream_dirty = true;
new_id
}
pub fn find_or_create_tab_def(&mut self, new_td: super::style::TabDef) -> u16 {
for (i, td) in self.doc_info.tab_defs.iter().enumerate() {
if *td == new_td {
return i as u16;
}
}
let new_id = self.doc_info.tab_defs.len() as u16;
self.doc_info.tab_defs.push(new_td);
self.doc_info.raw_stream_dirty = true;
new_id
}
#[cfg(not(target_arch = "wasm32"))]
pub fn populate_external_images_from_dir(&mut self, base_dir: &std::path::Path) -> usize {
use crate::model::control::Control;
use crate::model::shape::ShapeObject;
use std::collections::BTreeMap;
let mut loaded = 0;
let mut to_load: BTreeMap<u16, (String, String)> = BTreeMap::new();
for section in &self.sections {
for para in §ion.paragraphs {
for ctrl in ¶.controls {
let pic = match ctrl {
Control::Picture(p) => p,
Control::Shape(s) => match s.as_ref() {
ShapeObject::Picture(p) => p,
_ => continue,
},
_ => continue,
};
if let Some(ref path) = pic.image_attr.external_path {
let id = pic.image_attr.bin_data_id;
if self.external_image_loaded(id) {
continue;
}
let basename = path
.rsplit(|c| c == '/' || c == '\\')
.next()
.unwrap_or(path);
let ext = std::path::Path::new(basename)
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_string();
to_load.entry(id).or_insert((basename.to_string(), ext));
}
}
}
}
for (id, (basename, ext)) in to_load {
let full_path = base_dir.join(&basename);
let data = (|| {
use std::io::Read;
let limit = super::bin_data::MAX_BIN_DATA_BYTES;
let metadata = std::fs::metadata(&full_path).ok()?;
if !metadata.is_file() || metadata.len() > limit as u64 {
return None;
}
let file = std::fs::File::open(&full_path).ok()?;
let metadata = file.metadata().ok()?;
if !metadata.is_file() || metadata.len() > limit as u64 {
return None;
}
let mut data = Vec::new();
file.take(limit as u64 + 1).read_to_end(&mut data).ok()?;
if data.len() > limit {
return None;
}
let mime = crate::renderer::image_resolver::detect_image_mime_type(&data);
if mime == "application/octet-stream" {
return None;
}
if mime == "image/svg+xml" {
let xml = std::str::from_utf8(&data).ok()?;
let svg = roxmltree::Document::parse(xml).ok()?;
if !svg.root_element().has_tag_name("svg") {
return None;
}
}
Some(data)
})();
if let Some(data) = data {
if !self.inject_external_image_data(id, data, ext) {
continue;
}
loaded += 1;
let resolved = full_path.to_string_lossy().to_string();
self.update_external_image_display_path(id, &resolved);
}
}
loaded
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_document_default() {
let doc = Document::default();
assert_eq!(doc.sections.len(), 0);
assert_eq!(doc.doc_properties.section_count, 0);
}
#[test]
fn hwp3_native_layout_matches_legacy_version_and_lineage_expression() {
use crate::model::provenance::SourceFormat;
let build = |format: SourceFormat, hwp3_lineage: bool, major: u8| {
let mut doc = Document::default();
doc.provenance.format = format;
doc.provenance.hwp3_lineage = hwp3_lineage;
doc.header.version.major = major;
doc
};
let cases = [
(SourceFormat::Hwp3, false, 3, true), (SourceFormat::Hwp5, true, 5, false), (SourceFormat::Hwp5, false, 5, false), (SourceFormat::Hwpx, false, 5, false), ];
for (format, lineage, major, expected) in cases {
let doc = build(format, lineage, major);
let legacy = doc.header.version.major == 3 && !doc.layout_profile().hwp3_layout();
let refactored = doc.layout_profile().hwp3_native_layout();
assert_eq!(legacy, refactored, "{format:?}/{lineage}/{major}");
assert_eq!(refactored, expected, "{format:?}/{lineage}/{major}");
}
}
#[test]
fn hwp3_password_layout_requires_native_hwp3_and_encrypted_origin() {
use crate::model::provenance::SourceFormat;
let mut hwp3 = Document::default();
hwp3.provenance.format = SourceFormat::Hwp3;
assert!(
!hwp3.layout_profile().hwp3_password_layout(),
"평문 HWP3에는 암호 원본 전용 레이아웃 계약을 적용하지 않는다"
);
hwp3.header.encrypted = true;
assert!(
hwp3.layout_profile().hwp3_password_layout(),
"복호화 뒤에도 보존한 HWP3 암호 플래그가 레이아웃 계약을 선택한다"
);
hwp3.provenance.format = SourceFormat::Hwpx;
assert!(
!hwp3.layout_profile().hwp3_password_layout(),
"HWPX 암호 문서는 HWP3 전용 계약을 사용하지 않는다"
);
}
#[test]
fn test_hwp_version() {
let ver = HwpVersion {
major: 5,
minor: 0,
build: 3,
revision: 0,
};
assert_eq!(ver.major, 5);
}
#[test]
fn test_convert_to_editable_clears_distribution() {
let mut doc = Document {
header: FileHeader {
flags: 0x05, distribution: true,
compressed: true,
..Default::default()
},
doc_info: DocInfo {
extra_records: vec![
RawRecord {
tag_id: 28,
level: 0,
data: vec![0u8; 256],
}, RawRecord {
tag_id: 99,
level: 0,
data: vec![1, 2, 3],
}, ],
..Default::default()
},
..Default::default()
};
let converted = doc.convert_to_editable();
assert!(converted);
assert!(!doc.header.distribution);
assert_eq!(doc.header.flags, 0x01); assert!(doc.header.raw_data.is_none());
assert!(doc.doc_info.raw_stream.is_none());
assert_eq!(doc.doc_info.extra_records.len(), 1);
assert_eq!(doc.doc_info.extra_records[0].tag_id, 99);
}
#[test]
fn test_convert_to_editable_noop_for_normal() {
let mut doc = Document {
header: FileHeader {
flags: 0x01, distribution: false,
compressed: true,
..Default::default()
},
..Default::default()
};
let converted = doc.convert_to_editable();
assert!(!converted);
assert_eq!(doc.header.flags, 0x01); }
#[test]
fn test_find_or_create_char_shape_reuse() {
use super::style::{CharShape, CharShapeMods};
let mut doc = Document::default();
let mut cs = CharShape::default();
cs.bold = false;
doc.doc_info.char_shapes.push(cs.clone());
let mods = CharShapeMods {
bold: Some(true),
..Default::default()
};
let id1 = doc.find_or_create_char_shape(0, &mods);
assert_eq!(id1, 1);
assert_eq!(doc.doc_info.char_shapes.len(), 2);
let id2 = doc.find_or_create_char_shape(0, &mods);
assert_eq!(id2, 1);
assert_eq!(doc.doc_info.char_shapes.len(), 2); }
#[test]
fn test_find_or_create_para_shape_reuse() {
use super::style::{Alignment, ParaShape, ParaShapeMods};
let mut doc = Document::default();
doc.doc_info.para_shapes.push(ParaShape::default());
let mods = ParaShapeMods {
alignment: Some(Alignment::Center),
..Default::default()
};
let id1 = doc.find_or_create_para_shape(0, &mods);
assert_eq!(id1, 1);
let id2 = doc.find_or_create_para_shape(0, &mods);
assert_eq!(id2, 1);
assert_eq!(doc.doc_info.para_shapes.len(), 2);
}
}