repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/document/bodytext/list_header.rs | crates/hwp-core/src/viewer/markdown/document/bodytext/list_header.rs | //! ListHeader conversion to Markdown
//! ListHeader๋ฅผ ๋งํฌ๋ค์ด์ผ๋ก ๋ณํํ๋ ๋ชจ๋
//!
//! ์คํ ๋ฌธ์ ๋งคํ: ํ 57 - ๋ณธ๋ฌธ์ ๋ฐ์ดํฐ ๋ ์ฝ๋, LIST_HEADER (HWPTAG_BEGIN + 56)
//! Spec mapping: Table 57 - BodyText data records, LIST_HEADER (HWPTAG_BEGIN + 56)
//!
//! Note: ์ค์ ๋ณํ์ convert_paragraph_to_markdown์์ ์ฒ๋ฆฌ๋๋ฏ๋ก
//! ์ด ๋ชจ๋์ ํฅํ ํ์ฅ์ ์ํด ์ค๋น๋์์ต๋๋ค.
//! Note: Actual conversion is handled in convert_paragraph_to_markdown,
//! so this module is prepared for future expansion.
//!
//! This module is currently empty but reserved for future ListHeader-specific conversion logic.
//! ์ด ๋ชจ๋์ ํ์ฌ ๋น์ด์์ง๋ง ํฅํ ListHeader ์ ์ฉ ๋ณํ ๋ก์ง์ ์ํด ์์ฝ๋์ด ์์ต๋๋ค.
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/document/bodytext/paragraph.rs | crates/hwp-core/src/viewer/markdown/document/bodytext/paragraph.rs | /// Paragraph conversion to Markdown
/// ๋ฌธ๋จ์ ๋งํฌ๋ค์ด์ผ๋ก ๋ณํํ๋ ๋ชจ๋
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 57 - ๋ณธ๋ฌธ์ ๋ฐ์ดํฐ ๋ ์ฝ๋
/// Spec mapping: Table 57 - BodyText data records
use crate::document::bodytext::CharShapeInfo;
use crate::document::CharShape;
use crate::document::{HwpDocument, Paragraph, ParagraphRecord};
use crate::viewer::markdown::collect::collect_text_and_images_from_paragraph;
use crate::viewer::markdown::document::bodytext::para_text::{
convert_para_text_to_markdown, convert_para_text_to_markdown_with_char_shapes,
};
use crate::viewer::markdown::document::bodytext::shape_component::convert_shape_component_children_to_markdown;
use crate::viewer::markdown::document::bodytext::shape_component_picture::convert_shape_component_picture_to_markdown;
use crate::viewer::markdown::document::bodytext::table::convert_table_to_markdown;
use crate::viewer::markdown::utils::{
convert_to_outline_with_number, is_text_part, OutlineNumberTracker,
};
use crate::viewer::markdown::MarkdownOptions;
/// Convert a paragraph to markdown
/// ๋ฌธ๋จ์ ๋งํฌ๋ค์ด์ผ๋ก ๋ณํ
pub fn convert_paragraph_to_markdown(
paragraph: &Paragraph,
document: &HwpDocument,
options: &MarkdownOptions,
tracker: &mut OutlineNumberTracker,
) -> String {
if paragraph.records.is_empty() {
return String::new();
}
let mut parts = Vec::new();
let mut text_parts = Vec::new(); // ๊ฐ์ ๋ฌธ๋จ ๋ด์ ํ
์คํธ ๋ ์ฝ๋๋ค์ ๋ชจ์ / Collect text records in the same paragraph
let mut char_shapes: Vec<CharShapeInfo> = Vec::new(); // ๋ฌธ๋จ์ ๊ธ์ ๋ชจ์ ์ ๋ณด ์์ง / Collect character shape information for paragraph
// ๋จผ์ ParaCharShape ๋ ์ฝ๋๋ฅผ ์์ง / First collect ParaCharShape records
for record in ¶graph.records {
if let ParagraphRecord::ParaCharShape { shapes } = record {
char_shapes.extend(shapes.clone());
}
}
// CharShape๋ฅผ ๊ฐ์ ธ์ค๋ ํด๋ก์ / Closure to get CharShape
let get_char_shape = |shape_id: u32| -> Option<&CharShape> {
document.doc_info.char_shapes.get(shape_id as usize)
};
// Process all records in order / ๋ชจ๋ ๋ ์ฝ๋๋ฅผ ์์๋๋ก ์ฒ๋ฆฌ
for record in ¶graph.records {
match record {
ParagraphRecord::ParaText {
text,
control_char_positions,
inline_control_params: _,
..
} => {
// ParaText ๋ณํ / Convert ParaText
// ํ ์
๋ด๋ถ์ ํ
์คํธ๋ ์ด๋ฏธ Table.cells์ ํฌํจ๋์ด convert_table_to_markdown์์ ์ฒ๋ฆฌ๋๋ฏ๋ก
// ์ฌ๊ธฐ์๋ ํ ์๋ค์ ์ผ๋ฐ ํ
์คํธ๋ ์ ์์ ์ผ๋ก ์ฒ๋ฆฌ๋จ
// Text inside table cells is already included in Table.cells and processed in convert_table_to_markdown,
// so regular text before/after tables is also processed normally here
let text_md = if !char_shapes.is_empty() {
convert_para_text_to_markdown_with_char_shapes(
text,
control_char_positions,
&char_shapes,
Some(&get_char_shape),
)
} else {
convert_para_text_to_markdown(text, control_char_positions)
};
if let Some(text_md) = text_md {
// ๊ฐ์ ๋ฌธ๋จ ๋ด์ ํ
์คํธ๋ ๋์ค์ ํฉ์นจ / Text in the same paragraph will be combined later
text_parts.push(text_md);
}
}
ParagraphRecord::ShapeComponent {
shape_component: _,
children,
} => {
// SHAPE_COMPONENT์ children์ ์ฌ๊ท์ ์ผ๋ก ์ฒ๋ฆฌ / Recursively process SHAPE_COMPONENT's children
let shape_parts = convert_shape_component_children_to_markdown(
children,
document,
options.image_output_dir.as_deref(),
tracker,
);
parts.extend(shape_parts);
}
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
// ShapeComponentPicture ๋ณํ / Convert ShapeComponentPicture
if let Some(image_md) = convert_shape_component_picture_to_markdown(
shape_component_picture,
document,
options.image_output_dir.as_deref(),
) {
parts.push(image_md);
}
}
ParagraphRecord::CtrlHeader {
header,
children,
paragraphs: ctrl_paragraphs,
..
} => {
// ๋งํฌ๋ค์ด์ผ๋ก ํํํ ์ ์๋ ์ปจํธ๋กค ํค๋๋ ๊ฑด๋๋ / Skip control headers that cannot be expressed in markdown
use crate::viewer::markdown::utils::should_process_control_header;
if !should_process_control_header(header) {
// CTRL_HEADER ๋ด๋ถ์ ์ง์ ๋ฌธ๋จ ์ฒ๋ฆฌ / Process direct paragraphs inside CTRL_HEADER
for para in ctrl_paragraphs {
let para_md =
convert_paragraph_to_markdown(para, document, options, tracker);
if !para_md.is_empty() {
parts.push(para_md);
}
}
// CTRL_HEADER์ children ์ฒ๋ฆฌ (์: SHAPE_COMPONENT_PICTURE) / Process CTRL_HEADER's children (e.g., SHAPE_COMPONENT_PICTURE)
for child in children {
match child {
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
if let Some(image_md) = convert_shape_component_picture_to_markdown(
shape_component_picture,
document,
options.image_output_dir.as_deref(),
) {
parts.push(image_md);
}
}
_ => {
// ๊ธฐํ ์์ ๋ ์ฝ๋๋ ๋ฌด์ (์ด๋ฏธ ์ฒ๋ฆฌ๋ ๊ฒฝ์ฐ๋ง ๋๋ฌ) / Ignore other child records (only reached if already processed)
}
}
}
continue; // ์ด ์ปจํธ๋กค ํค๋๋ ๋ ์ด์ ์ฒ๋ฆฌํ์ง ์์ / Don't process this control header further
}
// ์ปจํธ๋กค ํค๋์ ์์ ๋ ์ฝ๋ ์ฒ๋ฆฌ (๋ ๋ฒจ 2, ์: ํ
์ด๋ธ, ๊ทธ๋ฆผ ๋ฑ) / Process control header children (level 2, e.g., table, images, etc.)
let mut has_table = false;
// ํ ์
๋ด๋ถ์ ํ
์คํธ์ ์ด๋ฏธ์ง๋ฅผ ์์งํ์ฌ ์
๋ด๋ถ ๋ฌธ๋จ์ธ์ง ํ์ธ
// Collect text and images from paragraphs in Table.cells to check if they are cell content
// ํฌ์ธํฐ ๋น๊ต๋ ๋ณต์ฌ๋ ๊ฐ์ฒด์์ ์คํจํ ์ ์์ผ๋ฏ๋ก ํ
์คํธ ๋ด์ฉ๊ณผ ์ด๋ฏธ์ง ID๋ก ๋น๊ต
// Pointer comparison may fail with copied objects, so compare by text content and image ID
let mut table_cell_texts: std::collections::HashSet<String> =
std::collections::HashSet::new();
let mut table_cell_image_ids: std::collections::HashSet<u16> =
std::collections::HashSet::new();
let mut table_cell_para_ids: std::collections::HashSet<u32> =
std::collections::HashSet::new(); // ํ ์
๋ด๋ถ ๋ฌธ๋จ์ instance_id ์์ง
let mut table_opt: Option<&crate::document::bodytext::Table> = None;
let mut table_index: Option<usize> = None;
let is_table_control = header.ctrl_id == crate::document::CtrlId::TABLE;
// ๋จผ์ TABLE์ ์ฐพ์์ table_opt์ ์ ์ฅ / First find TABLE and store in table_opt
let children_slice: &[ParagraphRecord] = children;
for (idx, child) in children_slice.iter().enumerate() {
if let ParagraphRecord::Table { table } = child {
table_opt = Some(table);
table_index = Some(idx);
break;
}
}
if let Some(table) = table_opt {
for cell in &table.cells {
for para in &cell.paragraphs {
// ๋ฌธ๋จ์ instance_id ์์ง (0์ด ์๋ ๊ฒฝ์ฐ๋ง) / Collect paragraph instance_id (only if not 0)
if para.para_header.instance_id != 0 {
table_cell_para_ids.insert(para.para_header.instance_id);
}
// ParaText์ ํ
์คํธ๋ฅผ ์์ง / Collect text from ParaText
// ์ฌ๊ท์ ์ผ๋ก ๋ชจ๋ ๋ ์ฝ๋๋ฅผ ํ์ธํ์ฌ ์ด๋ฏธ์ง ID ์์ง / Recursively check all records to collect image IDs
collect_text_and_images_from_paragraph(
para,
&mut table_cell_texts,
&mut table_cell_image_ids,
);
}
}
}
// libhwp ๋ฐฉ์: ํ์ ๋จ๊ณ์์ TABLE ์ด์ /์ดํ์ LIST_HEADER๋ฅผ children์ ์ถ๊ฐํ์ง ์์ผ๋ฏ๋ก
// ์ฌ๊ธฐ์๋ ์ฒ๋ฆฌํ์ง ์์
// libhwp approach: LIST_HEADERs (before/after TABLE) are not added to children in parser stage,
// so we don't process them here
// TABLE ์ด์ ์ LIST_HEADER๋ ์บก์
์ผ๋ก ๋ณ๋ ์ฒ๋ฆฌ๋๊ณ ,
// TABLE ์ดํ์ LIST_HEADER๋ ์
๋ก๋ง ์ฒ๋ฆฌ๋จ
// LIST_HEADERs before TABLE are processed as captions separately,
// and LIST_HEADERs after TABLE are only processed as cells
// ์ปจํธ๋กค ํค๋์ ์์ ๋ ์ฝ๋๋ค์ ์ํํ๋ฉฐ ์ฒ๋ฆฌ / Iterate through control header's child records and process them
let mut index = 0;
let children_slice: &[ParagraphRecord] = children;
let is_shape_object = header.ctrl_id == crate::document::CtrlId::SHAPE_OBJECT;
while index < children_slice.len() {
let child = &children_slice[index];
match child {
ParagraphRecord::Table { table } => {
// ํ ๋ณํ / Convert table
let table_md =
convert_table_to_markdown(table, document, options, tracker);
if !table_md.is_empty() {
parts.push(table_md);
has_table = true;
}
index += 1;
}
ParagraphRecord::ListHeader { paragraphs, .. } => {
// LIST_HEADER ์ฒ๋ฆฌ (ํ ์๋ ์บก์
๋ฑ) / Process LIST_HEADER (caption below, etc.)
// libhwp ๋ฐฉ์: TABLE ์ดํ์ LIST_HEADER๋ Table.cells์ ํฌํจ๋์ด ์์ผ๋ฏ๋ก children์์ ์ฒ๋ฆฌํ์ง ์์
// libhwp approach: LIST_HEADERs after TABLE are included in Table.cells, so don't process in children
if let Some(table_idx) = table_index {
if index > table_idx && is_table_control {
// TABLE ์ดํ์ LIST_HEADER๋ ์ด๋ฏธ Table.cells์ ํฌํจ๋์ด ์์ผ๋ฏ๋ก ๊ฑด๋๋
// LIST_HEADERs after TABLE are already included in Table.cells, so skip
// libhwp๋ TABLE ์ดํ์ LIST_HEADER๋ฅผ children์์ ์ฒ๋ฆฌํ์ง ์๊ณ ,
// TABLE์ ์ฝ์ ํ ๋ช
์์ ์ผ๋ก ๊ฐ ์
์ ์ํํ๋ฉฐ ์ฒ๋ฆฌํจ
// libhwp doesn't process LIST_HEADERs after TABLE in children,
// but processes them explicitly when iterating through cells after reading TABLE
} else {
// ํ ์์ LIST_HEADER๋ ์ด๋ฏธ ์ฒ๋ฆฌ๋จ / LIST_HEADER before table is already processed
// ํ๊ฐ ์๊ฑฐ๋ ํ ์
๋ด๋ถ๊ฐ ์๋ ๊ฒฝ์ฐ ์ผ๋ฐ ์ฒ๋ฆฌ / General processing if no table or not inside table cell
for para in paragraphs {
let para_md = convert_paragraph_to_markdown(
para, document, options, tracker,
);
if !para_md.is_empty() {
parts.push(para_md);
}
}
}
} else {
// ํ๊ฐ ์๋ ๊ฒฝ์ฐ ์ผ๋ฐ ์ฒ๋ฆฌ / General processing if no table
for para in paragraphs {
let para_md = convert_paragraph_to_markdown(
para, document, options, tracker,
);
if !para_md.is_empty() {
parts.push(para_md);
}
}
}
index += 1;
}
ParagraphRecord::ShapeComponent {
shape_component: _,
children: shape_children,
} => {
// SHAPE_COMPONENT์ children ์ฒ๋ฆฌ (SHAPE_COMPONENT_PICTURE ๋ฑ) / Process SHAPE_COMPONENT's children (SHAPE_COMPONENT_PICTURE, etc.)
// ๋จผ์ ํ ์
๋ด๋ถ์ ์ด๋ฏธ์ง์ธ์ง ํ์ธ / First check if images are inside table cells
let mut shape_parts_to_output = Vec::new();
let mut has_image_in_shape = false;
for child in shape_children {
match child {
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
// ํ ์
๋ด๋ถ์ ์ด๋ฏธ์ง์ธ์ง ํ์ธ (bindata_id๋ก ์ง์ ๋น๊ต) / Check if image is inside table cell (direct comparison by bindata_id)
let is_table_cell_image = table_cell_image_ids.contains(
&shape_component_picture.picture_info.bindata_id,
);
if is_table_cell_image {
// ํ ์
๋ด๋ถ์ ์ด๋ฏธ์ง๋ ํ ์
์ ์ด๋ฏธ ํฌํจ๋๋ฏ๋ก ์ฌ๊ธฐ์๋ ํ์ํ์ง ์์
// Images inside table cells are already included in table cells, so don't display here
has_image_in_shape = true;
} else {
// ํ ์
๋ด๋ถ๊ฐ ์๋ ๊ฒฝ์ฐ ์ด๋ฏธ์ง ๋ณํ / Convert image if not inside table cell
if let Some(image_md) =
convert_shape_component_picture_to_markdown(
shape_component_picture,
document,
options.image_output_dir.as_deref(),
)
{
shape_parts_to_output.push(image_md);
has_image_in_shape = true;
}
}
}
ParagraphRecord::ListHeader { paragraphs, .. } => {
// LIST_HEADER์ paragraphs ์ฒ๋ฆฌ (๊ธ์์ ํ
์คํธ) / Process LIST_HEADER's paragraphs (textbox text)
for para in paragraphs {
let para_md = convert_paragraph_to_markdown(
para, document, options, tracker,
);
if !para_md.is_empty() {
shape_parts_to_output.push(para_md);
}
}
}
_ => {}
}
}
// ๋ณํ๋ ๋ถ๋ถ๋ค์ ์ถ๋ ฅ / Output converted parts
for shape_part in shape_parts_to_output {
if has_table && has_image_in_shape {
// ํ๊ฐ ์๊ณ ์ด๋ฏธ์ง๊ฐ ์๋ ๊ฒฝ์ฐ, ์ด๋ฏธ์ง๊ฐ ํ ์
๋ด๋ถ๊ฐ ์๋๋ฏ๋ก ์ถ๋ ฅ
// If table exists and image exists, image is not inside table cell, so output
parts.push(shape_part);
} else if is_shape_object {
// SHAPE_OBJECT์ ๊ฒฝ์ฐ ํ ๋ฐ์์๋ ์ด๋ฏธ์ง๋ฅผ ์ฒ๋ฆฌ
// For SHAPE_OBJECT, process image even outside table
parts.push(shape_part);
} else {
// ๊ธฐํ ๊ฒฝ์ฐ์๋ ์ถ๋ ฅ
// For other cases, output
parts.push(shape_part);
}
}
index += 1;
}
ParagraphRecord::ShapeComponentPicture {
shape_component_picture,
} => {
// ShapeComponentPicture ๋ณํ / Convert ShapeComponentPicture
// ํ ์
๋ด๋ถ์ ์ด๋ฏธ์ง์ธ์ง ํ์ธ / Check if image is inside table cell
let is_table_cell_image = table_cell_image_ids
.contains(&shape_component_picture.picture_info.bindata_id);
// ํ ์
๋ด๋ถ์ ์ด๋ฏธ์ง๋ ํ ์
์ ์ด๋ฏธ ํฌํจ๋๋ฏ๋ก ์ฌ๊ธฐ์๋ ํ์ํ์ง ์์
// Images inside table cells are already included in table cells, so don't display here
if !is_table_cell_image {
if let Some(image_md) = convert_shape_component_picture_to_markdown(
shape_component_picture,
document,
options.image_output_dir.as_deref(),
) {
if has_table {
// ํ๊ฐ ์์ง๋ง ์
๋ด๋ถ๊ฐ ์๋ ๊ฒฝ์ฐ (ํ ์/์๋ ์ด๋ฏธ์ง ๋ฑ)
// Table exists but not inside cell (e.g., image above/below table)
parts.push(image_md);
} else if is_shape_object {
// SHAPE_OBJECT์ ๊ฒฝ์ฐ ํ ๋ฐ์์๋ ์ด๋ฏธ์ง๋ฅผ ์ฒ๋ฆฌ
// For SHAPE_OBJECT, process image even outside table
parts.push(image_md);
} else {
// ๊ธฐํ ๊ฒฝ์ฐ์๋ ์ถ๋ ฅ
// For other cases, output
parts.push(image_md);
}
}
}
index += 1;
}
_ => {
// ๊ธฐํ ๋ ์ฝ๋๋ ๋ฌด์ / Ignore other records
// CtrlHeader๋ ์ด๋ฏธ ์์์ ์ฒ๋ฆฌ๋จ / CtrlHeader is already processed above
index += 1;
}
}
}
// CTRL_HEADER ๋ด๋ถ์ ์ง์ ๋ฌธ๋จ ์ฒ๋ฆฌ / Process direct paragraphs inside CTRL_HEADER
for para in ctrl_paragraphs {
// ํ ์
๋ด๋ถ์ ๋ฌธ๋จ์ธ์ง ํ์ธ / Check if paragraph is inside table cell
let is_table_cell = if is_table_control && table_opt.is_some() {
// ๋จผ์ instance_id๋ก ํ์ธ (๊ฐ์ฅ ์ ํ, 0์ด ์๋ ๊ฒฝ์ฐ๋ง) / First check by instance_id (most accurate, only if not 0)
let is_table_cell_by_id = !table_cell_para_ids.is_empty()
&& para.para_header.instance_id != 0
&& table_cell_para_ids.contains(¶.para_header.instance_id);
// instance_id๋ก ํ์ธ๋์ง ์์ผ๋ฉด ํ
์คํธ์ ์ด๋ฏธ์ง๋ก ํ์ธ / If not found by instance_id, check by text and images
if is_table_cell_by_id {
true
} else {
// ์ฌ๊ท์ ์ผ๋ก ๋ฌธ๋จ์์ ํ
์คํธ์ ์ด๋ฏธ์ง๋ฅผ ์์งํ์ฌ ํ ์
๋ด๋ถ์ธ์ง ํ์ธ
// Recursively collect text and images from paragraph to check if inside table cell
let mut para_texts = std::collections::HashSet::new();
let mut para_image_ids = std::collections::HashSet::new();
collect_text_and_images_from_paragraph(
para,
&mut para_texts,
&mut para_image_ids,
);
// ์์งํ ํ
์คํธ๋ ์ด๋ฏธ์ง๊ฐ ํ ์
๋ด๋ถ์ ํฌํจ๋์ด ์๋์ง ํ์ธ
// Check if collected text or images are included in table cells
(!para_texts.is_empty()
&& para_texts
.iter()
.any(|text| table_cell_texts.contains(text)))
|| (!para_image_ids.is_empty()
&& para_image_ids
.iter()
.any(|id| table_cell_image_ids.contains(id)))
}
} else {
false
};
// ํ ์
๋ด๋ถ๊ฐ ์๋ ๊ฒฝ์ฐ์๋ง ์ฒ๋ฆฌ / Only process if not inside table cell
if !is_table_cell {
let para_md =
convert_paragraph_to_markdown(para, document, options, tracker);
if !para_md.is_empty() {
parts.push(para_md);
}
}
}
}
_ => {
// ๊ธฐํ ๋ ์ฝ๋๋ ๋ฌด์ / Ignore other records
}
}
}
// ๊ฐ์ ๋ฌธ๋จ ๋ด์ ํ
์คํธ๋ฅผ ํฉ์นจ / Combine text in the same paragraph
if !text_parts.is_empty() {
let combined_text = text_parts.join("");
// ๊ฐ์ ๋ ๋ฒจ ํ์ธ ๋ฐ ๊ฐ์ ๋ฒํธ ์ถ๊ฐ / Check outline level and add outline number
let outline_md = convert_to_outline_with_number(
&combined_text,
¶graph.para_header,
document,
tracker,
);
parts.push(outline_md);
}
// ๋งํฌ๋ค์ด ๋ฌธ๋ฒ์ ๋ง๊ฒ ๊ฐํ ์ฒ๋ฆฌ / Handle line breaks according to markdown syntax
// ํ
์คํธ๊ฐ ์ฐ์์ผ๋ก ๋์ฌ ๋๋ ์คํ์ด์ค 2๊ฐ + ๊ฐํ, ๋ธ๋ก ์์ ์ฌ์ด๋ ๋น ์ค
// For consecutive text: two spaces + newline, for block elements: blank line
if parts.is_empty() {
return String::new();
}
if parts.len() == 1 {
return parts[0].clone();
}
let mut result = String::new();
for (i, part) in parts.iter().enumerate() {
if i > 0 {
// ์ด์ part๊ฐ ํ
์คํธ์ด๊ณ ํ์ฌ part๋ ํ
์คํธ์ธ ๊ฒฝ์ฐ: ์คํ์ด์ค 2๊ฐ + ๊ฐํ
// If previous part is text and current part is also text: two spaces + newline
if is_text_part(&parts[i - 1]) && is_text_part(part) {
result.push_str(" \n");
}
// ๋ธ๋ก ์์๊ฐ ํฌํจ๋ ๊ฒฝ์ฐ: ๋น ์ค
// When block elements are involved, use blank line
else {
result.push_str("\n\n");
}
}
result.push_str(part);
}
result
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/viewer/markdown/document/bodytext/para_text.rs | crates/hwp-core/src/viewer/markdown/document/bodytext/para_text.rs | /// ParaText conversion to Markdown
/// ParaText๋ฅผ ๋งํฌ๋ค์ด์ผ๋ก ๋ณํํ๋ ๋ชจ๋
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 57 - ๋ณธ๋ฌธ์ ๋ฐ์ดํฐ ๋ ์ฝ๋, PARA_TEXT (HWPTAG_BEGIN + 51)
/// Spec mapping: Table 57 - BodyText data records, PARA_TEXT (HWPTAG_BEGIN + 51)
use crate::document::bodytext::{CharShapeInfo, ControlChar, ControlCharPosition};
use crate::document::CharShape;
/// ์๋ฏธ ์๋ ํ
์คํธ์ธ์ง ํ์ธํฉ๋๋ค. / Check if text is meaningful.
///
/// ๊ณต๋ฐฑ๋ง ์๋ ํ
์คํธ๋ ์๋ฏธ ์๋ค๊ณ ํ๋จํฉ๋๋ค.
/// Text containing only whitespace is considered meaningless.
///
/// # Arguments / ๋งค๊ฐ๋ณ์
/// * `text` - ์ ์ด ๋ฌธ์๊ฐ ์ด๋ฏธ ์ ๊ฑฐ๋ ํ
์คํธ / Text with control characters already removed
/// * `control_positions` - ์ ์ด ๋ฌธ์ ์์น ์ ๋ณด (ํ์ฌ๋ ์ฌ์ฉ๋์ง ์์) / Control character positions (currently unused)
///
/// # Returns / ๋ฐํ๊ฐ
/// ์๋ฏธ ์๋ ํ
์คํธ์ด๋ฉด `true`, ๊ทธ๋ ์ง ์์ผ๋ฉด `false` / `true` if meaningful, `false` otherwise
///
/// # Note
/// ์ ์ด ๋ฌธ์๋ ์ด๋ฏธ ํ์ฑ ๋จ๊ณ์์ text์์ ์ ๊ฑฐ๋์์ผ๋ฏ๋ก,
/// ํ
์คํธ๊ฐ ๋น์ด์์ง ์์์ง๋ง ํ์ธํฉ๋๋ค.
/// Control characters are already removed from text during parsing,
/// so we only check if text is not empty.
pub(crate) fn is_meaningful_text(text: &str, _control_positions: &[ControlCharPosition]) -> bool {
!text.trim().is_empty()
}
/// Convert ParaText to markdown
/// ParaText๋ฅผ ๋งํฌ๋ค์ด์ผ๋ก ๋ณํ
///
/// # Arguments / ๋งค๊ฐ๋ณ์
/// * `text` - ํ
์คํธ ๋ด์ฉ / Text content
/// * `control_positions` - ์ ์ด ๋ฌธ์ ์์น ์ ๋ณด / Control character positions
///
/// # Returns / ๋ฐํ๊ฐ
/// ๋งํฌ๋ค์ด ๋ฌธ์์ด / Markdown string
/// Convert character index to byte index in UTF-8 string
/// UTF-8 ๋ฌธ์์ด์์ ๋ฌธ์ ์ธ๋ฑ์ค๋ฅผ ๋ฐ์ดํธ ์ธ๋ฑ์ค๋ก ๋ณํ
fn char_index_to_byte_index(text: &str, char_idx: usize) -> Option<usize> {
text.char_indices()
.nth(char_idx)
.map(|(byte_idx, _)| byte_idx)
}
/// CharShape ์ ๋ณด๋ฅผ ์ฌ์ฉํ์ฌ ํ
์คํธ๋ฅผ ๊ตฌ๊ฐ๋ณ๋ก ๋๋๊ณ ๋งํฌ๋ค์ด ์คํ์ผ์ ์ ์ฉ
/// Divide text into segments by CharShape information and apply markdown styles
fn convert_text_with_char_shapes<'a>(
text: &str,
control_positions: &[ControlCharPosition],
char_shapes: &[CharShapeInfo],
get_char_shape: &'a dyn Fn(u32) -> Option<&'a CharShape>,
) -> Option<String> {
if text.trim().is_empty() {
return None;
}
let text_chars: Vec<char> = text.chars().collect();
let text_len = text_chars.len();
// CharShape ์ ๋ณด๋ฅผ position ๊ธฐ์ค์ผ๋ก ์ ๋ ฌ / Sort CharShape info by position
let mut sorted_shapes: Vec<_> = char_shapes.iter().collect();
sorted_shapes.sort_by_key(|shape| shape.position);
let mut result = String::new();
let mut segments: Vec<(usize, usize, Option<&CharShape>)> = Vec::new();
// ๊ตฌ๊ฐ ์ ์ / Define segments
let mut positions = vec![0];
for shape_info in &sorted_shapes {
let pos = shape_info.position as usize;
if pos <= text_len {
positions.push(pos);
}
}
positions.push(text_len);
positions.sort();
positions.dedup();
// ๊ฐ ๊ตฌ๊ฐ์ ๋ํ CharShape ์ฐพ๊ธฐ / Find CharShape for each segment
for i in 0..positions.len() - 1 {
let start = positions[i];
let end = positions[i + 1];
// ์ด ๊ตฌ๊ฐ์ ์ ์ฉํ CharShape ์ฐพ๊ธฐ / Find CharShape to apply to this segment
// start ์์น์์ ์์ํ๋ ๊ฐ์ฅ ๊ฐ๊น์ด CharShape๋ฅผ ์ฐพ์ / Find the closest CharShape starting at start position
let char_shape = sorted_shapes
.iter()
.find(|shape| (shape.position as usize) == start)
.or_else(|| {
// ์ ํํ ์ผ์นํ๋ ๊ฒ์ด ์์ผ๋ฉด, start๋ณด๋ค ์์ position ์ค ๊ฐ์ฅ ํฐ ๊ฒ์ ์ฐพ์
// If no exact match, find the largest position less than start
sorted_shapes
.iter()
.rev()
.find(|shape| (shape.position as usize) < start)
})
.and_then(|shape| get_char_shape(shape.shape_id));
segments.push((start, end, char_shape));
}
// PARA_BREAK/LINE_BREAK ์์น ์์ง / Collect PARA_BREAK/LINE_BREAK positions
let mut break_positions: Vec<usize> = control_positions
.iter()
.filter(|pos| pos.code == ControlChar::PARA_BREAK || pos.code == ControlChar::LINE_BREAK)
.map(|pos| usize::from(pos.position))
.collect();
break_positions.sort();
// ๊ฐ ๊ตฌ๊ฐ์ ์คํ์ผ ์ ์ฉํ์ฌ ๊ฒฐ๊ณผ ์์ฑ / Generate result by applying styles to each segment
for (start, end, char_shape) in &segments {
if *start < *end && *end <= text_len {
// ์ด ๊ตฌ๊ฐ ๋ด์ PARA_BREAK/LINE_BREAK๊ฐ ์๋์ง ํ์ธ / Check if there are breaks in this segment
let mut segment_breaks: Vec<usize> = break_positions
.iter()
.filter(|&&break_pos| break_pos >= *start && break_pos < *end)
.copied()
.collect();
if segment_breaks.is_empty() {
// ๊ตฌ๊ฐ ๋ด์ break๊ฐ ์์ผ๋ฉด ์ ์ฒด ๊ตฌ๊ฐ์ ์คํ์ผ ์ ์ฉ / No breaks in segment, apply style to entire segment
let segment_text: String = text_chars[*start..*end].iter().collect();
if !segment_text.trim().is_empty() {
if let Some(shape) = char_shape {
let styled = apply_markdown_styles(
&segment_text,
shape.attributes.bold,
shape.attributes.italic,
shape.attributes.strikethrough != 0,
);
result.push_str(&styled);
} else {
result.push_str(&segment_text);
}
}
} else {
// ๊ตฌ๊ฐ ๋ด์ break๊ฐ ์์ผ๋ฉด break ์์น๋ก ๋๋์ด ์ฒ๋ฆฌ / Split segment by breaks
segment_breaks.insert(0, *start);
segment_breaks.push(*end);
for i in 0..segment_breaks.len() - 1 {
let seg_start = segment_breaks[i];
let seg_end = segment_breaks[i + 1];
if seg_start < seg_end && seg_end <= text_len {
let segment_text: String = text_chars[seg_start..seg_end].iter().collect();
if !segment_text.trim().is_empty() {
if let Some(shape) = char_shape {
let styled = apply_markdown_styles(
&segment_text,
shape.attributes.bold,
shape.attributes.italic,
shape.attributes.strikethrough != 0,
);
result.push_str(&styled);
} else {
result.push_str(&segment_text);
}
}
}
// break ๋ค์์ด๋ฉด ๋งํฌ๋ค์ด ๊ฐํ ์ถ๊ฐ / Add markdown line break after break
if i < segment_breaks.len() - 2 {
result.push_str(" \n");
}
}
}
}
}
let trimmed_result = result.trim();
if !trimmed_result.is_empty() {
Some(trimmed_result.to_string())
} else {
None
}
}
/// ํ
์คํธ์ ๋งํฌ๋ค์ด ์คํ์ผ์ ์ ์ฉํฉ๋๋ค. / Apply markdown styles to text.
///
/// # Arguments / ๋งค๊ฐ๋ณ์
/// * `text` - ์๋ณธ ํ
์คํธ / Original text
/// * `bold` - ์งํ๊ฒ ์ฌ๋ถ / Bold
/// * `italic` - ๊ธฐ์ธ์ ์ฌ๋ถ / Italic
/// * `strikethrough` - ๊ฐ์ด๋์ค ์ฌ๋ถ / Strikethrough
///
/// # Returns / ๋ฐํ๊ฐ
/// ๋งํฌ๋ค์ด ์คํ์ผ์ด ์ ์ฉ๋ ํ
์คํธ / Text with markdown styles applied
fn apply_markdown_styles(text: &str, bold: bool, italic: bool, strikethrough: bool) -> String {
if text.is_empty() {
return String::new();
}
let mut result = String::from(text);
// ๋งํฌ๋ค์ด ์คํ์ผ ์ ์ฉ ์์: strikethrough (๊ฐ์ฅ ๋ฐ๊นฅ) -> bold -> italic (๊ฐ์ฅ ์์ชฝ)
// Markdown style application order: strikethrough (outermost) -> bold -> italic (innermost)
// ๊ธฐ์ธ์ ์ ์ฉ (๊ฐ์ฅ ์์ชฝ) / Apply italic (innermost)
if italic {
result = format!("*{}*", result);
}
// ์งํ๊ฒ ์ ์ฉ / Apply bold
if bold {
result = format!("**{}**", result);
}
// ๊ฐ์ด๋์ค ์ ์ฉ (๊ฐ์ฅ ๋ฐ๊นฅ์ชฝ) / Apply strikethrough (outermost)
if strikethrough {
result = format!("~~{}~~", result);
}
result
}
pub fn convert_para_text_to_markdown(
text: &str,
control_positions: &[ControlCharPosition],
) -> Option<String> {
convert_para_text_to_markdown_with_char_shapes(text, control_positions, &[], None)
}
/// CharShape ์ ๋ณด๋ฅผ ์ฌ์ฉํ์ฌ ParaText๋ฅผ ๋งํฌ๋ค์ด์ผ๋ก ๋ณํ
/// Convert ParaText to markdown using CharShape information
///
/// # Arguments / ๋งค๊ฐ๋ณ์
/// * `text` - ํ
์คํธ ๋ด์ฉ / Text content
/// * `control_positions` - ์ ์ด ๋ฌธ์ ์์น ์ ๋ณด / Control character positions
/// * `char_shapes` - ๊ธ์ ๋ชจ์ ์ ๋ณด ๋ฆฌ์คํธ / Character shape information list
/// * `get_char_shape` - shape_id๋ก CharShape๋ฅผ ๊ฐ์ ธ์ค๋ ํจ์ / Function to get CharShape by shape_id
///
/// # Returns / ๋ฐํ๊ฐ
/// ๋งํฌ๋ค์ด ๋ฌธ์์ด / Markdown string
pub fn convert_para_text_to_markdown_with_char_shapes<'a>(
text: &str,
control_positions: &[ControlCharPosition],
char_shapes: &[CharShapeInfo],
get_char_shape: Option<&'a dyn Fn(u32) -> Option<&'a CharShape>>,
) -> Option<String> {
// CharShape ์ ๋ณด๊ฐ ์์ผ๋ฉด ํ
์คํธ๋ฅผ ๊ตฌ๊ฐ๋ณ๋ก ๋๋์ด ์คํ์ผ ์ ์ฉ / If CharShape info exists, divide text into segments and apply styles
if !char_shapes.is_empty() && get_char_shape.is_some() {
return convert_text_with_char_shapes(
text,
control_positions,
char_shapes,
get_char_shape.unwrap(),
);
}
// PARA_BREAK๋ LINE_BREAK๊ฐ ์๋์ง ํ์ธ / Check for PARA_BREAK or LINE_BREAK
let has_breaks = control_positions
.iter()
.any(|pos| pos.code == ControlChar::PARA_BREAK || pos.code == ControlChar::LINE_BREAK);
if !has_breaks {
// ์ ์ด ๋ฌธ์๊ฐ ์์ผ๋ฉด ๊ธฐ์กด ๋ก์ง ์ฌ์ฉ / Use existing logic if no control characters
if is_meaningful_text(text, control_positions) {
let trimmed = text.trim();
if !trimmed.is_empty() {
return Some(trimmed.to_string());
}
}
return None;
}
// PARA_BREAK/LINE_BREAK๊ฐ ์๋ ๊ฒฝ์ฐ ์ฒ๋ฆฌ / Process when PARA_BREAK/LINE_BREAK exists
// ํ์์์ \n์ ์ ๊ฑฐํ์ผ๋ฏ๋ก, control_positions์ ์ ๋ณด๋ง ์ฌ์ฉํ์ฌ ๋งํฌ๋ค์ด ๊ฐํ์ผ๋ก ๋ณํ
// Parser removed \n, so only use control_positions info to convert to markdown line breaks
let mut result = String::new();
let mut last_char_pos = 0;
// control_positions๋ฅผ ์ ๋ ฌํ์ฌ ์์๋๋ก ์ฒ๋ฆฌ / Sort control_positions to process in order
let mut sorted_positions: Vec<_> = control_positions.iter().collect();
sorted_positions.sort_by_key(|pos| pos.position);
for pos in sorted_positions {
// PARA_BREAK๋ LINE_BREAK๋ง ์ฒ๋ฆฌ / Only process PARA_BREAK or LINE_BREAK
if pos.code != ControlChar::PARA_BREAK && pos.code != ControlChar::LINE_BREAK {
continue;
}
// ๋ฌธ์ ์ธ๋ฑ์ค๋ฅผ ๋ฐ์ดํธ ์ธ๋ฑ์ค๋ก ๋ณํ / Convert character index to byte index
let byte_idx = match char_index_to_byte_index(text, pos.position) {
Some(idx) => idx,
None => continue, // ์ ํจํ์ง ์์ ์์น๋ ๊ฑด๋๋ / Skip invalid position
};
let last_byte_idx = char_index_to_byte_index(text, last_char_pos).unwrap_or(0);
// ์ ์ด ๋ฌธ์ ์ด์ ์ ํ
์คํธ ์ถ๊ฐ (ํ์์์ \n์ด ์ ๊ฑฐ๋์์ผ๋ฏ๋ก ๊ทธ๋๋ก ์ฌ์ฉ)
// Add text before control character (parser removed \n, so use as-is)
if byte_idx > last_byte_idx && byte_idx <= text.len() {
let text_part = &text[last_byte_idx..byte_idx];
let trimmed = text_part.trim();
if !trimmed.is_empty() {
result.push_str(trimmed);
}
}
// PARA_BREAK๋ LINE_BREAK๋ฅผ ๋งํฌ๋ค์ด ๊ฐํ(์คํ์ด์ค 2๊ฐ + ๊ฐํ)์ผ๋ก ๋ณํ
// Convert PARA_BREAK or LINE_BREAK to markdown line break (two spaces + newline)
result.push_str(" \n");
// ์ ์ด ๋ฌธ์ ๋ค์ ์์น / Position after control character
last_char_pos = pos.position + 1;
}
// ๋ง์ง๋ง ๋ถ๋ถ์ ํ
์คํธ ์ถ๊ฐ / Add remaining text
let last_byte_idx = char_index_to_byte_index(text, last_char_pos).unwrap_or(0);
if last_byte_idx < text.len() {
let text_part = &text[last_byte_idx..];
let trimmed = text_part.trim();
if !trimmed.is_empty() {
result.push_str(trimmed);
}
}
// trim() ๋์ trim_start()๋ง ์ฌ์ฉํ์ฌ ์ค ๋ ๊ณต๋ฐฑ(๋งํฌ๋ค์ด ๊ฐํ์ฉ)์ ์ ์ง
// Use trim_start() instead of trim() to preserve trailing spaces (for markdown line breaks)
let trimmed_result = result.trim_start();
if !trimmed_result.is_empty() {
Some(trimmed_result.to_string())
} else {
None
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/preview_image.rs | crates/hwp-core/src/document/preview_image.rs | /// PreviewImage ๊ตฌ์กฐ์ฒด / PreviewImage structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: 3.2.7 - ๋ฏธ๋ฆฌ๋ณด๊ธฐ ์ด๋ฏธ์ง / Spec mapping: 3.2.7 - Preview image
///
/// `PrvImage` ์คํธ๋ฆผ์๋ ๋ฏธ๋ฆฌ๋ณด๊ธฐ ์ด๋ฏธ์ง๊ฐ BMP ๋๋ GIF ํ์์ผ๋ก ์ ์ฅ๋ฉ๋๋ค.
/// The `PrvImage` stream contains preview image stored as BMP or GIF format.
use crate::error::HwpError;
use base64::{engine::general_purpose::STANDARD, Engine as _};
use serde::{Deserialize, Serialize};
use std::path::Path;
/// ๋ฏธ๋ฆฌ๋ณด๊ธฐ ์ด๋ฏธ์ง / Preview image
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PreviewImage {
/// Base64๋ก ์ธ์ฝ๋ฉ๋ ์ด๋ฏธ์ง ๋ฐ์ดํฐ / Base64 encoded image data
pub data: String,
/// ์ด๋ฏธ์ง ํ์ ("BMP" ๋๋ "GIF") / Image format ("BMP" or "GIF")
pub format: String,
/// ํ์ผ๋ก ์ ์ฅ๋ ๊ฒฝ์ฐ ํ์ผ ๊ฒฝ๋ก (์ ํ์ ) / File path if saved as file (optional)
#[serde(skip_serializing_if = "Option::is_none")]
pub file_path: Option<String>,
}
impl PreviewImage {
/// PreviewImage๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse PreviewImage from byte array.
///
/// # Arguments
/// * `data` - PrvImage ์คํธ๋ฆผ์ ์์ ๋ฐ์ดํธ ๋ฐ์ดํฐ / Raw byte data of PrvImage stream
/// * `save_to_file` - ํ์ผ๋ก ์ ์ฅํ ๋๋ ํ ๋ฆฌ ๊ฒฝ๋ก (์ ํ์ ) / Optional directory path to save file
///
/// # Returns
/// ํ์ฑ๋ PreviewImage ๊ตฌ์กฐ์ฒด / Parsed PreviewImage structure
///
/// # Note
/// ์คํ ๋ฌธ์ 3.2.7์ ๋ฐ๋ฅด๋ฉด PrvImage ์คํธ๋ฆผ์๋ ๋ฏธ๋ฆฌ๋ณด๊ธฐ ์ด๋ฏธ์ง๊ฐ BMP ๋๋ GIF ํ์์ผ๋ก ์ ์ฅ๋ฉ๋๋ค.
/// According to spec 3.2.7, the PrvImage stream contains preview image stored as BMP or GIF format.
/// ์ด๋ฏธ์ง ํ์์ ํ์ผ ์๊ทธ๋์ฒ๋ฅผ ํ์ธํ์ฌ ๊ฐ์งํฉ๋๋ค.
/// Image format is detected by checking file signature.
/// ์ด๋ฏธ์ง ๋ฐ์ดํฐ๋ ํญ์ base64๋ก ์ธ์ฝ๋ฉ๋์ด ์ ์ฅ๋๋ฉฐ, ์ ํ์ ์ผ๋ก ํ์ผ๋ก๋ ์ ์ฅํ ์ ์์ต๋๋ค.
/// Image data is always stored as base64 encoded string, and optionally saved as file.
pub fn parse(data: &[u8], save_to_file: Option<&str>) -> Result<Self, HwpError> {
if data.is_empty() {
return Err(HwpError::InsufficientData {
field: "PreviewImage data".to_string(),
expected: 1,
actual: 0,
});
}
// ์ด๋ฏธ์ง ํ์ ๊ฐ์ง / Detect image format
// BMP: "BM" (0x42 0x4D)๋ก ์์ / BMP: starts with "BM" (0x42 0x4D)
// GIF: "GIF87a" ๋๋ "GIF89a"๋ก ์์ / GIF: starts with "GIF87a" or "GIF89a"
let format = if data.len() >= 2 && data[0] == 0x42 && data[1] == 0x4D {
"BMP".to_string()
} else if data.len() >= 6 {
let gif_header = &data[0..6];
if gif_header == b"GIF87a" || gif_header == b"GIF89a" {
"GIF".to_string()
} else {
// ์ ์ ์๋ ํ์์ด์ง๋ง ๋ฐ์ดํฐ๋ ์ ์ฅ / Unknown format but store data
"UNKNOWN".to_string()
}
} else {
// ๋ฐ์ดํฐ๊ฐ ๋๋ฌด ์งง์์ ํ์์ ํ์ธํ ์ ์์ / Data too short to determine format
"UNKNOWN".to_string()
};
// Base64 ์ธ์ฝ๋ฉ / Base64 encoding
let base64_data = STANDARD.encode(data);
// ํ์ผ๋ก ์ ์ฅ (์ ํ์ ) / Save to file (optional)
let file_path = if let Some(dir_path) = save_to_file {
let extension = match format.as_str() {
"BMP" => "bmp",
"GIF" => "gif",
_ => "bin",
};
let file_name = format!("preview_image.{}", extension);
let file_path = Path::new(dir_path).join(&file_name);
std::fs::create_dir_all(dir_path).map_err(|e| {
HwpError::Io(format!("Failed to create directory '{}': {}", dir_path, e))
})?;
std::fs::write(&file_path, data).map_err(|e| {
HwpError::Io(format!(
"Failed to write preview image file '{}': {}",
file_path.display(),
e
))
})?;
Some(file_path.to_string_lossy().to_string())
} else {
None
};
Ok(PreviewImage {
data: base64_data,
format,
file_path,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/preview_text.rs | crates/hwp-core/src/document/preview_text.rs | /// PreviewText ๊ตฌ์กฐ์ฒด / PreviewText structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: 3.2.6 - ๋ฏธ๋ฆฌ๋ณด๊ธฐ ํ
์คํธ / Spec mapping: 3.2.6 - Preview text
///
/// `PrvText` ์คํธ๋ฆผ์๋ ๋ฏธ๋ฆฌ๋ณด๊ธฐ ํ
์คํธ๊ฐ ์ ๋์ฝ๋ ๋ฌธ์์ด๋ก ์ ์ฅ๋ฉ๋๋ค.
/// The `PrvText` stream contains preview text stored as Unicode string.
use crate::error::HwpError;
use crate::types::decode_utf16le;
use serde::{Deserialize, Serialize};
/// ๋ฏธ๋ฆฌ๋ณด๊ธฐ ํ
์คํธ / Preview text
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PreviewText {
/// ๋ฏธ๋ฆฌ๋ณด๊ธฐ ํ
์คํธ ๋ด์ฉ (UTF-16LE) / Preview text content (UTF-16LE)
pub text: String,
}
impl PreviewText {
/// PreviewText๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse PreviewText from byte array.
///
/// # Arguments
/// * `data` - PrvText ์คํธ๋ฆผ์ ์์ ๋ฐ์ดํธ ๋ฐ์ดํฐ / Raw byte data of PrvText stream
///
/// # Returns
/// ํ์ฑ๋ PreviewText ๊ตฌ์กฐ์ฒด / Parsed PreviewText structure
///
/// # Note
/// ์คํ ๋ฌธ์ 3.2.6์ ๋ฐ๋ฅด๋ฉด PrvText ์คํธ๋ฆผ์๋ ๋ฏธ๋ฆฌ๋ณด๊ธฐ ํ
์คํธ๊ฐ ์ ๋์ฝ๋ ๋ฌธ์์ด๋ก ์ ์ฅ๋ฉ๋๋ค.
/// According to spec 3.2.6, the PrvText stream contains preview text stored as Unicode string.
/// UTF-16LE ํ์์ผ๋ก ์ ์ฅ๋๋ฏ๋ก decode_utf16le ํจ์๋ฅผ ์ฌ์ฉํ์ฌ ๋์ฝ๋ฉํฉ๋๋ค.
/// Since it's stored in UTF-16LE format, we use decode_utf16le function to decode it.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// UTF-16LE ๋์ฝ๋ฉ / Decode UTF-16LE
let text = decode_utf16le(data)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode preview text: {}", e),
})?;
Ok(PreviewText { text })
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/xml_template.rs | crates/hwp-core/src/document/xml_template.rs | /// XmlTemplate ๊ตฌ์กฐ์ฒด / XmlTemplate structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: 3.2.10 - XML ํ
ํ๋ฆฟ / Spec mapping: 3.2.10 - XML Template
///
/// `XMLTemplate` ์คํ ๋ฆฌ์ง์๋ XML Template ์ ๋ณด๊ฐ ์ ์ฅ๋ฉ๋๋ค.
/// The `XMLTemplate` storage contains XML Template information.
use crate::cfb::CfbParser;
use crate::error::HwpError;
use crate::types::{decode_utf16le, DWORD};
use serde::{Deserialize, Serialize};
/// XML ํ
ํ๋ฆฟ / XML Template
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct XmlTemplate {
/// Schema ์ด๋ฆ (from _SchemaName stream) / Schema name (from _SchemaName stream)
#[serde(skip_serializing_if = "Option::is_none")]
pub schema_name: Option<String>,
/// Schema (from Schema stream) / Schema (from Schema stream)
#[serde(skip_serializing_if = "Option::is_none")]
pub schema: Option<String>,
/// Instance (from Instance stream) / Instance (from Instance stream)
#[serde(skip_serializing_if = "Option::is_none")]
pub instance: Option<String>,
}
impl XmlTemplate {
/// XmlTemplate์ CFB ๊ตฌ์กฐ์์ ํ์ฑํฉ๋๋ค. / Parse XmlTemplate from CFB structure.
///
/// # Arguments
/// * `cfb` - CompoundFile structure (mutable reference required) / CompoundFile ๊ตฌ์กฐ์ฒด (๊ฐ๋ณ ์ฐธ์กฐ ํ์)
///
/// # Returns
/// ํ์ฑ๋ XmlTemplate ๊ตฌ์กฐ์ฒด / Parsed XmlTemplate structure
///
/// # Note
/// ์คํ ๋ฌธ์ 3.2.10์ ๋ฐ๋ฅด๋ฉด XMLTemplate ์คํ ๋ฆฌ์ง์๋ ๋ค์ ์คํธ๋ฆผ์ด ํฌํจ๋ฉ๋๋ค:
/// - _SchemaName: Schema ์ด๋ฆ (ํ 10)
/// - Schema: Schema ๋ฌธ์์ด (ํ 11)
/// - Instance: Instance ๋ฌธ์์ด (ํ 12)
/// According to spec 3.2.10, XMLTemplate storage contains the following streams:
/// - _SchemaName: Schema name (Table 10)
/// - Schema: Schema string (Table 11)
/// - Instance: Instance string (Table 12)
pub fn parse(cfb: &mut cfb::CompoundFile<std::io::Cursor<&[u8]>>) -> Result<Self, HwpError> {
let mut xml_template = XmlTemplate::default();
// Parse _SchemaName stream
// _SchemaName ์คํธ๋ฆผ ํ์ฑ / Parse _SchemaName stream
// ์คํ ๋ฌธ์ ํ 10: Schema ์ด๋ฆ ์ ๋ณด
// Spec Table 10: Schema name information
if let Ok(schema_name_data) =
CfbParser::read_nested_stream(cfb, "XMLTemplate", "_SchemaName")
{
match Self::parse_schema_name(&schema_name_data) {
Ok(schema_name) => {
xml_template.schema_name = Some(schema_name);
}
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("Warning: Failed to parse _SchemaName stream: {}", e);
}
}
}
// Parse Schema stream
// Schema ์คํธ๋ฆผ ํ์ฑ / Parse Schema stream
// ์คํ ๋ฌธ์ ํ 11: Schema ๊ธธ์ด ์ ๋ณด
// Spec Table 11: Schema length information
if let Ok(schema_data) = CfbParser::read_nested_stream(cfb, "XMLTemplate", "Schema") {
match Self::parse_schema(&schema_data) {
Ok(schema) => {
xml_template.schema = Some(schema);
}
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("Warning: Failed to parse Schema stream: {}", e);
}
}
}
// Parse Instance stream
// Instance ์คํธ๋ฆผ ํ์ฑ / Parse Instance stream
// ์คํ ๋ฌธ์ ํ 12: Instance ์ ๋ณด
// Spec Table 12: Instance information
if let Ok(instance_data) = CfbParser::read_nested_stream(cfb, "XMLTemplate", "Instance") {
match Self::parse_instance(&instance_data) {
Ok(instance) => {
xml_template.instance = Some(instance);
}
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("Warning: Failed to parse Instance stream: {}", e);
}
}
}
Ok(xml_template)
}
/// Schema ์ด๋ฆ ํ์ฑ (ํ 10) / Parse schema name (Table 10)
fn parse_schema_name(data: &[u8]) -> Result<String, HwpError> {
if data.len() < 4 {
return Err(HwpError::insufficient_data(
"Schema name data",
4,
data.len(),
));
}
// DWORD Schema ์ด๋ฆ ๊ธธ์ด (4 bytes) / Schema name length (4 bytes)
let len = DWORD::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
// WCHAR array[len] Schema ์ด๋ฆ (2รlen bytes) / Schema name (2รlen bytes)
if data.len() < 4 + (len * 2) {
return Err(HwpError::InsufficientData {
field: "Schema name data".to_string(),
expected: 4 + (len * 2),
actual: data.len(),
});
}
if len > 0 {
let schema_name_bytes = &data[4..4 + (len * 2)];
decode_utf16le(schema_name_bytes).map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode schema name: {}", e),
})
} else {
Ok(String::new())
}
}
/// Schema ํ์ฑ (ํ 11) / Parse schema (Table 11)
fn parse_schema(data: &[u8]) -> Result<String, HwpError> {
if data.len() < 4 {
return Err(HwpError::insufficient_data("Schema data", 4, data.len()));
}
// DWORD Schema ๊ธธ์ด (4 bytes) / Schema length (4 bytes)
let len = DWORD::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
// WCHAR array[len] Schema (2รlen bytes) / Schema (2รlen bytes)
if data.len() < 4 + (len * 2) {
return Err(HwpError::InsufficientData {
field: "Schema data".to_string(),
expected: 4 + (len * 2),
actual: data.len(),
});
}
if len > 0 {
let schema_bytes = &data[4..4 + (len * 2)];
decode_utf16le(schema_bytes).map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode schema: {}", e),
})
} else {
Ok(String::new())
}
}
/// Instance ํ์ฑ (ํ 12) / Parse instance (Table 12)
fn parse_instance(data: &[u8]) -> Result<String, HwpError> {
if data.len() < 4 {
return Err(HwpError::insufficient_data("Instance data", 4, data.len()));
}
// DWORD Instance ๊ธธ์ด (4 bytes) / Instance length (4 bytes)
let len = DWORD::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
// WCHAR array[len] Instance (2รlen bytes) / Instance (2รlen bytes)
if data.len() < 4 + (len * 2) {
return Err(HwpError::InsufficientData {
field: "Instance data".to_string(),
expected: 4 + (len * 2),
actual: data.len(),
});
}
if len > 0 {
let instance_bytes = &data[4..4 + (len * 2)];
decode_utf16le(instance_bytes).map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode instance: {}", e),
})
} else {
Ok(String::new())
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/mod.rs | crates/hwp-core/src/document/mod.rs | pub mod bindata;
pub mod bodytext;
pub mod constants;
pub mod docinfo;
/// HWP Document structure
///
/// This module defines the main document structure for HWP files.
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 2 - ์ ์ฒด ๊ตฌ์กฐ
pub mod fileheader;
pub mod preview_image;
pub mod preview_text;
pub mod scripts;
pub mod summary_information;
pub mod xml_template;
pub use bindata::{BinData, BinaryDataFormat};
pub use bodytext::{
BodyText, ColumnDivideType, CtrlHeader, CtrlHeaderData, CtrlId, PageNumberPosition, Paragraph,
ParagraphRecord, Section,
};
pub use docinfo::{
BinDataRecord, BorderFill, Bullet, CharShape, DocInfo, DocumentProperties, FaceName, FillInfo,
HeaderShapeType, IdMappings, Numbering, ParaShape, Style, TabDef,
};
pub use fileheader::FileHeader;
pub use preview_image::PreviewImage;
pub use preview_text::PreviewText;
pub use scripts::Scripts;
pub use summary_information::SummaryInformation;
pub use xml_template::XmlTemplate;
use serde::{Deserialize, Serialize};
/// Main HWP document structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HwpDocument {
/// File header information
pub file_header: FileHeader,
/// Document information (DocInfo stream)
pub doc_info: DocInfo,
/// Body text (BodyText storage)
pub body_text: BodyText,
/// Binary data (BinData storage)
pub bin_data: BinData,
/// Preview text (PrvText stream)
pub preview_text: Option<PreviewText>,
/// Preview image (PrvImage stream)
pub preview_image: Option<PreviewImage>,
/// Scripts (Scripts storage)
pub scripts: Option<Scripts>,
/// XML Template (XMLTemplate storage)
pub xml_template: Option<XmlTemplate>,
/// Summary Information (\005HwpSummaryInformation stream)
pub summary_information: Option<SummaryInformation>,
}
impl HwpDocument {
/// Create a new empty HWP document
pub fn new(file_header: FileHeader) -> Self {
Self {
file_header,
doc_info: DocInfo::default(),
body_text: BodyText::default(),
bin_data: BinData::default(),
preview_text: None,
preview_image: None,
scripts: None,
xml_template: None,
summary_information: None,
}
}
/// Convert HWP document to Markdown format
/// HWP ๋ฌธ์๋ฅผ ๋งํฌ๋ค์ด ํ์์ผ๋ก ๋ณํ
///
/// # Arguments / ๋งค๊ฐ๋ณ์
/// * `options` - Markdown conversion options / ๋งํฌ๋ค์ด ๋ณํ ์ต์
///
/// # Returns / ๋ฐํ๊ฐ
/// Markdown string representation of the document / ๋ฌธ์์ ๋งํฌ๋ค์ด ๋ฌธ์์ด ํํ
pub fn to_markdown(&self, options: &crate::viewer::markdown::MarkdownOptions) -> String {
crate::viewer::to_markdown(self, options)
}
/// Convert HWP document to Markdown format (๊ธฐ์กด API ํธํ์ฑ)
/// HWP ๋ฌธ์๋ฅผ ๋งํฌ๋ค์ด ํ์์ผ๋ก ๋ณํ (๊ธฐ์กด API ํธํ์ฑ)
///
/// # Arguments / ๋งค๊ฐ๋ณ์
/// * `image_output_dir` - Optional directory path to save images as files. If None, images are embedded as base64 data URIs.
/// ์ด๋ฏธ์ง๋ฅผ ํ์ผ๋ก ์ ์ฅํ ๋๋ ํ ๋ฆฌ ๊ฒฝ๋ก (์ ํ). None์ด๋ฉด base64 ๋ฐ์ดํฐ URI๋ก ์๋ฒ ๋๋ฉ๋๋ค.
///
/// # Returns / ๋ฐํ๊ฐ
/// Markdown string representation of the document / ๋ฌธ์์ ๋งํฌ๋ค์ด ๋ฌธ์์ด ํํ
pub fn to_markdown_with_dir(&self, image_output_dir: Option<&str>) -> String {
let options = crate::viewer::markdown::MarkdownOptions {
image_output_dir: image_output_dir.map(|s| s.to_string()),
use_html: Some(true),
include_version: Some(true),
include_page_info: Some(true),
};
crate::viewer::to_markdown(self, &options)
}
/// Convert HWP document to HTML format
/// HWP ๋ฌธ์๋ฅผ HTML ํ์์ผ๋ก ๋ณํ
///
/// # Arguments / ๋งค๊ฐ๋ณ์
/// * `options` - HTML conversion options / HTML ๋ณํ ์ต์
///
/// # Returns / ๋ฐํ๊ฐ
/// HTML string representation of the document / ๋ฌธ์์ HTML ๋ฌธ์์ด ํํ
pub fn to_html(&self, options: &crate::viewer::html::HtmlOptions) -> String {
crate::viewer::to_html(self, options)
}
/// Resolve derived display texts for control tokens (e.g., AUTO_NUMBER) into `ParaTextRun::Control.display_text`.
///
/// IMPORTANT:
/// - `runs` (control tokens + document settings) are the source of truth.
/// - `display_text` is a derived/cache value for preview/viewers and may be recomputed.
pub fn resolve_display_texts(&mut self) {
use crate::document::bodytext::{ControlChar, ParaTextRun};
use crate::document::ParagraphRecord;
// Footnote/endnote numbering rules are defined by FootnoteShape (spec Table 133/134).
// In practice, two FootnoteShape records appear (footnote, endnote). If only one exists,
// we reuse it for both.
let mut footnote_shape_opt: Option<crate::document::bodytext::FootnoteShape> = None;
let mut endnote_shape_opt: Option<crate::document::bodytext::FootnoteShape> = None;
for section in &self.body_text.sections {
for paragraph in §ion.paragraphs {
for record in ¶graph.records {
if let ParagraphRecord::FootnoteShape { footnote_shape } = record {
if footnote_shape_opt.is_none() {
footnote_shape_opt = Some(footnote_shape.clone());
} else if endnote_shape_opt.is_none() {
endnote_shape_opt = Some(footnote_shape.clone());
}
}
}
}
}
if endnote_shape_opt.is_none() {
endnote_shape_opt = footnote_shape_opt.clone();
}
let mut table_no: u32 = self
.doc_info
.document_properties
.as_ref()
.map(|p| p.table_start_number as u32)
.unwrap_or(1);
let footnote_start: u32 = footnote_shape_opt
.as_ref()
.map(|s| s.start_number as u32)
.or_else(|| {
self.doc_info
.document_properties
.as_ref()
.map(|p| p.footnote_start_number as u32)
})
.unwrap_or(1);
let endnote_start: u32 = endnote_shape_opt
.as_ref()
.map(|s| s.start_number as u32)
.or_else(|| {
self.doc_info
.document_properties
.as_ref()
.map(|p| p.endnote_start_number as u32)
})
.unwrap_or(1);
let footnote_numbering = footnote_shape_opt
.as_ref()
.map(|s| s.attributes.numbering)
.unwrap_or(crate::document::bodytext::footnote_shape::NumberingMethod::Continue);
let endnote_numbering = endnote_shape_opt
.as_ref()
.map(|s| s.attributes.numbering)
.unwrap_or(crate::document::bodytext::footnote_shape::NumberingMethod::Continue);
// NOTE: PerPage is currently treated the same as Continue (requested).
let mut footnote_no: u32 = footnote_start;
let mut endnote_no: u32 = endnote_start;
let mut image_no: u32 = self
.doc_info
.document_properties
.as_ref()
.map(|p| p.image_start_number as u32)
.unwrap_or(1);
let mut formula_no: u32 = self
.doc_info
.document_properties
.as_ref()
.map(|p| p.formula_start_number as u32)
.unwrap_or(1);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AutoNumberKind {
Page = 0,
Footnote = 1,
Endnote = 2,
Image = 3,
Table = 4,
Formula = 5,
Unknown = 255,
}
fn parse_auto_number_kind(attribute: u32) -> AutoNumberKind {
match (attribute & 0x0F) as u8 {
0 => AutoNumberKind::Page,
1 => AutoNumberKind::Footnote,
2 => AutoNumberKind::Endnote,
3 => AutoNumberKind::Image,
4 => AutoNumberKind::Table,
5 => AutoNumberKind::Formula,
_ => AutoNumberKind::Unknown,
}
}
fn parse_number_shape(
attribute: u32,
) -> crate::document::bodytext::footnote_shape::NumberShape {
// spec Table 143 bit 4-11 number shape, mapping uses Table 134 (same as FootnoteShape)
let v = ((attribute >> 4) & 0xFF) as u8;
use crate::document::bodytext::footnote_shape::NumberShape;
match v {
0 => NumberShape::Arabic,
1 => NumberShape::CircledArabic,
2 => NumberShape::RomanUpper,
3 => NumberShape::RomanLower,
4 => NumberShape::AlphaUpper,
5 => NumberShape::AlphaLower,
6 => NumberShape::CircledAlphaUpper,
7 => NumberShape::CircledAlphaLower,
8 => NumberShape::Hangul,
9 => NumberShape::CircledHangul,
10 => NumberShape::HangulJamo,
11 => NumberShape::CircledHangulJamo,
12 => NumberShape::HangulNumber,
13 => NumberShape::ChineseNumber,
14 => NumberShape::CircledChineseNumber,
15 => NumberShape::HeavenlyStem,
16 => NumberShape::HeavenlyStemChinese,
0x80 => NumberShape::FourCharRepeat,
0x81 => NumberShape::CustomCharRepeat,
_ => NumberShape::Arabic,
}
}
fn format_number(
shape: crate::document::bodytext::footnote_shape::NumberShape,
n: u32,
) -> String {
use crate::document::bodytext::footnote_shape::NumberShape;
match shape {
NumberShape::Arabic => n.to_string(),
NumberShape::RomanUpper => to_roman(n).to_uppercase(),
NumberShape::RomanLower => to_roman(n).to_lowercase(),
NumberShape::AlphaUpper => to_alpha(n, true),
NumberShape::AlphaLower => to_alpha(n, false),
NumberShape::CircledArabic => circled_number(n).unwrap_or_else(|| n.to_string()),
NumberShape::CircledAlphaUpper => {
circled_alpha(n, true).unwrap_or_else(|| to_alpha(n, true))
}
NumberShape::CircledAlphaLower => {
circled_alpha(n, false).unwrap_or_else(|| to_alpha(n, false))
}
NumberShape::Hangul => hangul_gana(n).unwrap_or_else(|| n.to_string()),
NumberShape::HangulJamo => hangul_jamo(n).unwrap_or_else(|| n.to_string()),
NumberShape::CircledHangul => circled_hangul_gana(n)
.unwrap_or_else(|| hangul_gana(n).unwrap_or_else(|| n.to_string())),
NumberShape::CircledHangulJamo => circled_hangul_jamo(n)
.unwrap_or_else(|| hangul_jamo(n).unwrap_or_else(|| n.to_string())),
NumberShape::HangulNumber => hangul_number(n).unwrap_or_else(|| n.to_string()),
NumberShape::ChineseNumber => chinese_number(n).unwrap_or_else(|| n.to_string()),
NumberShape::CircledChineseNumber => circled_chinese_number(n)
.unwrap_or_else(|| chinese_number(n).unwrap_or_else(|| n.to_string())),
NumberShape::HeavenlyStem => heavenly_stem(n).unwrap_or_else(|| n.to_string()),
NumberShape::HeavenlyStemChinese => {
heavenly_stem_chinese(n).unwrap_or_else(|| n.to_string())
}
// NOTE: Repeat-based shapes require additional spec-backed inputs (e.g., custom symbol set).
// We intentionally fall back to Arabic until we can resolve the exact behavior from spec/fixtures.
NumberShape::FourCharRepeat | NumberShape::CustomCharRepeat => n.to_string(),
}
}
fn circled_number(n: u32) -> Option<String> {
// โ ..โณ (U+2460..U+2473) for 1..20
if (1..=20).contains(&n) {
let cp = 0x2460 + (n - 1);
return char::from_u32(cp).map(|c| c.to_string());
}
// ใ..ใ (U+3251..U+325F) for 21..35 (circled numbers in a circle)
if (21..=35).contains(&n) {
let cp = 0x3251 + (n - 21);
return char::from_u32(cp).map(|c| c.to_string());
}
None
}
fn circled_alpha(n: u32, upper: bool) -> Option<String> {
// โถ..โ (U+24B6..U+24CF) for 1..26
// โ..โฉ (U+24D0..U+24E9) for 1..26
if !(1..=26).contains(&n) {
return None;
}
let base = if upper { 0x24B6 } else { 0x24D0 };
let cp = base + (n - 1);
char::from_u32(cp).map(|c| c.to_string())
}
fn hangul_gana(n: u32) -> Option<String> {
// ๊ฐ..ํ (14 chars) used commonly for numbering
const LIST: [&str; 14] = [
"๊ฐ", "๋", "๋ค", "๋ผ", "๋ง", "๋ฐ", "์ฌ", "์", "์", "์ฐจ", "์นด", "ํ", "ํ", "ํ",
];
if n == 0 {
return None;
}
let idx = ((n - 1) % (LIST.len() as u32)) as usize;
Some(LIST[idx].to_string())
}
fn circled_hangul_gana(n: u32) -> Option<String> {
// ใฎ..ใป (U+326E..U+327B) for 1..14
if !(1..=14).contains(&n) {
return None;
}
let cp = 0x326E + (n - 1);
char::from_u32(cp).map(|c| c.to_string())
}
fn hangul_jamo(n: u32) -> Option<String> {
// ใฑ ใด ใท ใน ใ
ใ
ใ
ใ
ใ
ใ
ใ
ใ
ใ
ใ
const LIST: [&str; 14] = [
"ใฑ", "ใด", "ใท", "ใน", "ใ
", "ใ
", "ใ
", "ใ
", "ใ
", "ใ
", "ใ
", "ใ
", "ใ
", "ใ
",
];
if n == 0 {
return None;
}
let idx = ((n - 1) % (LIST.len() as u32)) as usize;
Some(LIST[idx].to_string())
}
fn circled_hangul_jamo(n: u32) -> Option<String> {
// ใ ..ใญ (U+3260..U+326D) for 1..14
if !(1..=14).contains(&n) {
return None;
}
let cp = 0x3260 + (n - 1);
char::from_u32(cp).map(|c| c.to_string())
}
fn hangul_number(n: u32) -> Option<String> {
// ์ผ, ์ด, ์ผ ... (up to 99 for now)
if n == 0 || n > 99 {
return None;
}
const DIGITS: [&str; 10] = ["", "์ผ", "์ด", "์ผ", "์ฌ", "์ค", "์ก", "์น ", "ํ", "๊ตฌ"];
if n < 10 {
return Some(DIGITS[n as usize].to_string());
}
if n == 10 {
return Some("์ญ".to_string());
}
let tens = n / 10;
let ones = n % 10;
let mut out = String::new();
if tens > 1 {
out.push_str(DIGITS[tens as usize]);
}
out.push('์ญ');
if ones > 0 {
out.push_str(DIGITS[ones as usize]);
}
Some(out)
}
fn chinese_number(n: u32) -> Option<String> {
// ไธ, ไบ, ไธ ... (up to 99 for now)
if n == 0 || n > 99 {
return None;
}
const DIGITS: [&str; 10] = ["", "ไธ", "ไบ", "ไธ", "ๅ", "ไบ", "ๅ
ญ", "ไธ", "ๅ
ซ", "ไน"];
if n < 10 {
return Some(DIGITS[n as usize].to_string());
}
if n == 10 {
return Some("ๅ".to_string());
}
let tens = n / 10;
let ones = n % 10;
let mut out = String::new();
if tens > 1 {
out.push_str(DIGITS[tens as usize]);
}
out.push('ๅ');
if ones > 0 {
out.push_str(DIGITS[ones as usize]);
}
Some(out)
}
fn circled_chinese_number(n: u32) -> Option<String> {
// ใ..ใ (U+3280..U+3289) for 1..10
if !(1..=10).contains(&n) {
return None;
}
let cp = 0x3280 + (n - 1);
char::from_u32(cp).map(|c| c.to_string())
}
fn heavenly_stem(n: u32) -> Option<String> {
// ๊ฐ, ์, ๋ณ, ์ , ๋ฌด, ๊ธฐ, ๊ฒฝ, ์ , ์, ๊ณ
const LIST: [&str; 10] = ["๊ฐ", "์", "๋ณ", "์ ", "๋ฌด", "๊ธฐ", "๊ฒฝ", "์ ", "์", "๊ณ"];
if n == 0 {
return None;
}
let idx = ((n - 1) % 10) as usize;
Some(LIST[idx].to_string())
}
fn heavenly_stem_chinese(n: u32) -> Option<String> {
// ็ฒ, ไน, ไธ, ไธ, ๆ, ๅทฑ, ๅบ, ่พ, ๅฃฌ, ็ธ
const LIST: [&str; 10] = ["็ฒ", "ไน", "ไธ", "ไธ", "ๆ", "ๅทฑ", "ๅบ", "่พ", "ๅฃฌ", "็ธ"];
if n == 0 {
return None;
}
let idx = ((n - 1) % 10) as usize;
Some(LIST[idx].to_string())
}
fn to_roman(mut n: u32) -> String {
if n == 0 {
return String::new();
}
let mut out = String::new();
let pairs = [
(1000, "M"),
(900, "CM"),
(500, "D"),
(400, "CD"),
(100, "C"),
(90, "XC"),
(50, "L"),
(40, "XL"),
(10, "X"),
(9, "IX"),
(5, "V"),
(4, "IV"),
(1, "I"),
];
for (v, s) in pairs {
while n >= v {
out.push_str(s);
n -= v;
}
}
out
}
fn to_alpha(mut n: u32, upper: bool) -> String {
// 1->A, 26->Z, 27->AA
if n == 0 {
return String::new();
}
let mut buf: Vec<u8> = Vec::new();
while n > 0 {
n -= 1;
let c = (n % 26) as u8;
buf.push(if upper { b'A' + c } else { b'a' + c });
n /= 26;
}
buf.reverse();
String::from_utf8_lossy(&buf).to_string()
}
fn resolve_paragraph_record(
record: &mut ParagraphRecord,
table_no: &mut u32,
footnote_no: &mut u32,
endnote_no: &mut u32,
_image_no: &mut u32,
_formula_no: &mut u32,
) {
match record {
ParagraphRecord::CtrlHeader {
header,
children,
paragraphs,
..
} => {
// Footnote/endnote ctrl headers ("fn " / "en "): assign number to all AUTO_NUMBER tokens in this subtree.
if header.ctrl_id == "fn " || header.ctrl_id == "en " {
let current = if header.ctrl_id == "fn " {
*footnote_no
} else {
*endnote_no
};
fn fill_auto_numbers_in_records(
records: &mut [ParagraphRecord],
value: u32,
) {
for r in records.iter_mut() {
match r {
ParagraphRecord::ParaText { runs, .. } => {
for run in runs.iter_mut() {
if let ParaTextRun::Control {
code, display_text, ..
} = run
{
if *code == ControlChar::AUTO_NUMBER
&& display_text.is_none()
{
*display_text = Some(value.to_string());
}
}
}
}
ParagraphRecord::CtrlHeader {
children,
paragraphs,
..
} => {
fill_auto_numbers_in_records(children, value);
for p in paragraphs.iter_mut() {
fill_auto_numbers_in_records(&mut p.records, value);
}
}
ParagraphRecord::ListHeader { paragraphs, .. } => {
for p in paragraphs.iter_mut() {
fill_auto_numbers_in_records(&mut p.records, value);
}
}
ParagraphRecord::ShapeComponent { children, .. } => {
fill_auto_numbers_in_records(children, value);
}
_ => {}
}
}
}
fill_auto_numbers_in_records(children, current);
for p in paragraphs.iter_mut() {
fill_auto_numbers_in_records(&mut p.records, current);
}
if header.ctrl_id == "fn " {
*footnote_no += 1;
} else {
*endnote_no += 1;
}
}
// Table ctrl header ("tbl "): assign table number to the first AUTO_NUMBER found in caption paragraphs.
if header.ctrl_id == "tbl " {
let mut assigned_for_this_table = false;
for p in paragraphs.iter_mut() {
for r in p.records.iter_mut() {
if let ParagraphRecord::ParaText { runs, .. } = r {
for run in runs.iter_mut() {
if let ParaTextRun::Control {
code, display_text, ..
} = run
{
if *code == ControlChar::AUTO_NUMBER
&& display_text.is_none()
{
*display_text = Some(table_no.to_string());
assigned_for_this_table = true;
break;
}
}
}
}
if assigned_for_this_table {
break;
}
}
if assigned_for_this_table {
break;
}
}
if assigned_for_this_table {
*table_no += 1;
}
}
// Recurse into nested structures for completeness.
for c in children.iter_mut() {
resolve_paragraph_record(
c,
table_no,
footnote_no,
endnote_no,
_image_no,
_formula_no,
);
}
for p in paragraphs.iter_mut() {
for r in p.records.iter_mut() {
resolve_paragraph_record(
r,
table_no,
footnote_no,
endnote_no,
_image_no,
_formula_no,
);
}
}
}
ParagraphRecord::ListHeader { paragraphs, .. } => {
for p in paragraphs.iter_mut() {
for r in p.records.iter_mut() {
resolve_paragraph_record(
r,
table_no,
footnote_no,
endnote_no,
_image_no,
_formula_no,
);
}
}
}
ParagraphRecord::ShapeComponent { children, .. } => {
for c in children.iter_mut() {
resolve_paragraph_record(
c,
table_no,
footnote_no,
endnote_no,
_image_no,
_formula_no,
);
}
}
_ => {}
}
}
for section in self.body_text.sections.iter_mut() {
// Apply "Restart" per section. PerPage is currently treated as Continue.
use crate::document::bodytext::footnote_shape::NumberingMethod;
if matches!(footnote_numbering, NumberingMethod::Restart) {
footnote_no = footnote_start;
}
if matches!(endnote_numbering, NumberingMethod::Restart) {
endnote_no = endnote_start;
}
for paragraph in section.paragraphs.iter_mut() {
// If this paragraph has an AutoNumber/NewNumber ctrl header, use it to resolve AUTO_NUMBER tokens in its ParaText runs.
let mut para_auto_attr: Option<u32> = None;
let mut para_auto_prefix: Option<String> = None;
let mut para_auto_suffix: Option<String> = None;
let mut new_number_attr_and_value: Option<(u32, u16)> = None;
for record in paragraph.records.iter() {
if let ParagraphRecord::CtrlHeader { header, .. } = record {
match &header.data {
crate::document::bodytext::ctrl_header::CtrlHeaderData::AutoNumber {
attribute,
prefix,
suffix,
..
} => {
para_auto_attr = Some(*attribute);
if !prefix.is_empty() {
para_auto_prefix = Some(prefix.clone());
}
if !suffix.is_empty() {
para_auto_suffix = Some(suffix.clone());
}
}
crate::document::bodytext::ctrl_header::CtrlHeaderData::NewNumber {
attribute,
number,
} => {
new_number_attr_and_value = Some((*attribute, *number));
}
_ => {}
}
}
}
// Apply NEW_NUMBER to counters (bit 0-3: kind, number: new value)
if let Some((attr, num)) = new_number_attr_and_value {
match parse_auto_number_kind(attr) {
AutoNumberKind::Footnote => footnote_no = num as u32,
AutoNumberKind::Endnote => endnote_no = num as u32,
AutoNumberKind::Image => image_no = num as u32,
AutoNumberKind::Table => table_no = num as u32,
AutoNumberKind::Formula => formula_no = num as u32,
_ => {}
}
}
// Fill AUTO_NUMBER tokens in this paragraph if we know the kind.
if let Some(attr) = para_auto_attr {
let kind = parse_auto_number_kind(attr);
let shape = parse_number_shape(attr);
let prefix = para_auto_prefix.as_deref().unwrap_or("");
let suffix = para_auto_suffix.as_deref().unwrap_or("");
let next_value = match kind {
AutoNumberKind::Footnote => Some(footnote_no),
AutoNumberKind::Endnote => Some(endnote_no),
AutoNumberKind::Image => Some(image_no),
AutoNumberKind::Table => Some(table_no),
AutoNumberKind::Formula => Some(formula_no),
_ => None,
};
if let Some(v) = next_value {
let formatted = format!("{}{}{}", prefix, format_number(shape, v), suffix);
for record in paragraph.records.iter_mut() {
if let ParagraphRecord::ParaText { runs, .. } = record {
for run in runs.iter_mut() {
if let ParaTextRun::Control {
code, display_text, ..
} = run
{
if *code == ControlChar::AUTO_NUMBER
&& display_text.is_none()
{
*display_text = Some(formatted.clone());
}
}
}
}
}
// Increment the counter once per paragraph auto-number usage.
match kind {
AutoNumberKind::Footnote => footnote_no += 1,
AutoNumberKind::Endnote => endnote_no += 1,
AutoNumberKind::Image => image_no += 1,
AutoNumberKind::Table => table_no += 1,
AutoNumberKind::Formula => formula_no += 1,
_ => {}
}
}
}
for record in paragraph.records.iter_mut() {
resolve_paragraph_record(
record,
&mut table_no,
&mut footnote_no,
&mut endnote_no,
&mut image_no,
&mut formula_no,
);
}
}
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/summary_information.rs | crates/hwp-core/src/document/summary_information.rs | /// SummaryInformation ๊ตฌ์กฐ์ฒด / SummaryInformation structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: 3.2.4 - ๋ฌธ์ ์์ฝ / Spec mapping: 3.2.4 - Document summary
///
/// `\005HwpSummaryInformation` ์คํธ๋ฆผ์๋ ํ๊ธ ๋ฉ๋ด์ "ํ์ผ - ๋ฌธ์ ์ ๋ณด - ๋ฌธ์ ์์ฝ"์์ ์
๋ ฅํ ๋ด์ฉ์ด ์ ์ฅ๋ฉ๋๋ค.
/// The `\005HwpSummaryInformation` stream contains summary information entered from HWP menu "File - Document Info - Document Summary".
///
/// Summary Information์ ๋ํ ์์ธํ ์ค๋ช
์ MSDN์ ์ฐธ๊ณ :
/// For detailed description of Summary Information, refer to MSDN:
/// - The Summary Information Property Set
/// - The DocumentSummaryInformation and UserDefined Property Set
///
/// ์คํ ๋ฌธ์ ํ 7: ๋ฌธ์ ์์ฝ Property ID ์ ์
/// Spec document Table 7: Document summary Property ID definitions
use crate::error::HwpError;
use crate::types::{INT32, UINT32};
use serde::{Deserialize, Serialize};
/// ๋ฌธ์ ์์ฝ ์ ๋ณด / Document summary information
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SummaryInformation {
/// ์ ๋ชฉ / Title (PIDSI_TITLE, 0x00000002)
pub title: Option<String>,
/// ์ฃผ์ / Subject (PIDSI_SUBJECT, 0x00000003)
pub subject: Option<String>,
/// ์์ฑ์ / Author (PIDSI_AUTHOR, 0x00000004)
pub author: Option<String>,
/// ํค์๋ / Keywords (PIDSI_KEYWORDS, 0x00000005)
pub keywords: Option<String>,
/// ์ฃผ์ / Comments (PIDSI_COMMENTS, 0x00000006)
pub comments: Option<String>,
/// ๋ง์ง๋ง ์ ์ฅํ ์ฌ๋ / Last Saved By (PIDSI_LASTAUTHOR, 0x00000008)
pub last_saved_by: Option<String>,
/// ์์ ๋ฒํธ / Revision Number (PIDSI_REVNUMBER, 0x00000009)
pub revision_number: Option<String>,
/// ๋ง์ง๋ง ์ธ์ ์๊ฐ (UTC+9 ISO 8601 ํ์) / Last Printed (PIDSI_LASTPRINTED, 0x0000000B) (UTC+9 ISO 8601 format)
#[serde(skip_serializing_if = "Option::is_none")]
pub last_printed: Option<String>,
/// ์์ฑ ์๊ฐ/๋ ์ง (UTC+9 ISO 8601 ํ์) / Create Time/Date (PIDSI_CREATE_DTM, 0x0000000C) (UTC+9 ISO 8601 format)
#[serde(skip_serializing_if = "Option::is_none")]
pub create_time: Option<String>,
/// ๋ง์ง๋ง ์ ์ฅ ์๊ฐ/๋ ์ง (UTC+9 ISO 8601 ํ์) / Last saved Time/Date (PIDSI_LASTSAVE_DTM, 0x0000000D) (UTC+9 ISO 8601 format)
#[serde(skip_serializing_if = "Option::is_none")]
pub last_saved_time: Option<String>,
/// ํ์ด์ง ์ / Number of Pages (PIDSI_PAGECOUNT, 0x0000000E)
pub page_count: Option<INT32>,
/// ๋ ์ง ๋ฌธ์์ด (์ฌ์ฉ์ ์ ์) / Date String (User define) (HWPPIDSI_DATE_STR, 0x00000014)
pub date_string: Option<String>,
/// ๋ฌธ๋จ ์ (์ฌ์ฉ์ ์ ์) / Para Count (User define) (HWPPIDSI_PARACOUNT, 0x00000015)
pub para_count: Option<INT32>,
}
/// FILETIME ๊ตฌ์กฐ์ฒด (Windows FILETIME ํ์) / FILETIME structure (Windows FILETIME format)
/// 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC)
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct FileTime {
/// Low 32 bits / ํ์ 32๋นํธ
pub low: UINT32,
/// High 32 bits / ์์ 32๋นํธ
pub high: UINT32,
}
impl FileTime {
/// FILETIME์ Unix timestamp (์ด)๋ก ๋ณํ / Convert FILETIME to Unix timestamp (seconds)
pub fn to_unix_timestamp(self) -> i64 {
// FILETIME epoch: January 1, 1601
// Unix epoch: January 1, 1970
// Difference: 11644473600 seconds = 0x019DB1DED53E8000 in 100-nanosecond intervals
let filetime = ((self.high as u64) << 32) | (self.low as u64);
let unix_time = filetime as i64 - 0x019DB1DED53E8000;
unix_time / 10_000_000 // Convert from 100-nanosecond intervals to seconds
}
/// FILETIME์ UTC+9 ์๊ฐ๋์ ISO 8601 ๋ฌธ์์ด๋ก ๋ณํ / Convert FILETIME to ISO 8601 string in UTC+9 timezone
pub fn to_utc9_string(self) -> String {
use std::time::{Duration, UNIX_EPOCH};
let unix_timestamp = self.to_unix_timestamp();
if unix_timestamp < 0 {
return "1970-01-01T00:00:00+09:00".to_string();
}
let duration = Duration::from_secs(unix_timestamp as u64);
let datetime = UNIX_EPOCH + duration;
// UTC+9๋ก ๋ณํ (9์๊ฐ ์ถ๊ฐ)
// Convert to UTC+9 (add 9 hours)
let utc9_datetime = datetime + Duration::from_secs(9 * 3600);
// ISO 8601 ํ์์ผ๋ก ๋ณํ (YYYY-MM-DDTHH:MM:SS+09:00)
// Convert to ISO 8601 format (YYYY-MM-DDTHH:MM:SS+09:00)
let total_secs = utc9_datetime.duration_since(UNIX_EPOCH).unwrap().as_secs();
let days = total_secs / 86400;
let secs_in_day = total_secs % 86400;
let hours = secs_in_day / 3600;
let minutes = (secs_in_day % 3600) / 60;
let seconds = secs_in_day % 60;
// 1970-01-01๋ถํฐ์ ์ผ์๋ก ๋ ์ง ๊ณ์ฐ
// Calculate date from days since 1970-01-01
let mut year = 1970;
let mut day_of_year = days as i32;
loop {
let days_in_year = if is_leap_year(year) { 366 } else { 365 };
if day_of_year < days_in_year {
break;
}
day_of_year -= days_in_year;
year += 1;
}
let mut month = 1;
let mut day = day_of_year + 1;
let days_in_month = [
31,
if is_leap_year(year) { 29 } else { 28 },
31,
30,
31,
30,
31,
31,
30,
31,
30,
31,
];
for &dim in &days_in_month {
if day <= dim {
break;
}
day -= dim;
month += 1;
}
format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}+09:00",
year, month, day, hours, minutes, seconds
)
}
}
fn is_leap_year(year: i32) -> bool {
year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}
/// Property ID ์์ / Property ID constants
mod property_ids {
pub const PID_CODEPAGE: u32 = 0x00000001; // Codepage (VT_I2)
pub const PIDSI_TITLE: u32 = 0x00000002;
pub const PIDSI_SUBJECT: u32 = 0x00000003;
pub const PIDSI_AUTHOR: u32 = 0x00000004;
pub const PIDSI_KEYWORDS: u32 = 0x00000005;
pub const PIDSI_COMMENTS: u32 = 0x00000006;
pub const PIDSI_LASTAUTHOR: u32 = 0x00000008;
pub const PIDSI_REVNUMBER: u32 = 0x00000009;
pub const PIDSI_LASTPRINTED: u32 = 0x0000000B;
pub const PIDSI_CREATE_DTM: u32 = 0x0000000C;
pub const PIDSI_LASTSAVE_DTM: u32 = 0x0000000D;
pub const PIDSI_PAGECOUNT: u32 = 0x0000000E;
pub const HWPPIDSI_DATE_STR: u32 = 0x00000014;
pub const HWPPIDSI_PARACOUNT: u32 = 0x00000015;
}
/// VT (Variant Type) ์์ / VT (Variant Type) constants
/// ๋ด๋ถ ์ฌ์ฉ ์ ์ฉ / Internal use only
const VT_LPSTR: u32 = 0x001E; // 30 (0x1E) - ANSI string
const VT_LPWSTR: u32 = 0x001F; // 31 (0x1F) - Wide string (UTF-16LE)
const VT_FILETIME: u32 = 0x0040; // 64 (0x40)
const VT_I2: u32 = 0x0002; // 2 (16-bit signed integer, used for codepage)
const VT_I4: u32 = 0x0003; // 3
impl SummaryInformation {
/// SummaryInformation์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse SummaryInformation from byte array.
///
/// # Arguments
/// * `data` - \005HwpSummaryInformation ์คํธ๋ฆผ์ ์์ ๋ฐ์ดํธ ๋ฐ์ดํฐ / Raw byte data of \005HwpSummaryInformation stream
///
/// # Returns
/// ํ์ฑ๋ SummaryInformation ๊ตฌ์กฐ์ฒด / Parsed SummaryInformation structure
///
/// # Note
/// MSDN Property Set ํ์์ ํ์ฑํฉ๋๋ค.
/// Parses MSDN Property Set format.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.is_empty() {
return Ok(SummaryInformation::default());
}
let mut result = SummaryInformation::default();
// MSDN Property Set ํ์ ํ์ฑ / Parse MSDN Property Set format
// PropertySetStreamHeader ๊ตฌ์กฐ:
// - ByteOrder (UINT16, 2 bytes)
// - Version (UINT16, 2 bytes)
// - SystemIdentifier (UINT32, 4 bytes) - pyhwp ์ฐธ๊ณ
// - CLSID (16 bytes)
// - propsetDescList (N_ARRAY, ๊ฐ๋ณ ๊ธธ์ด)
// - ๊ฐ PropertySetDesc: FMTID (16 bytes) + Offset (4 bytes) = 20 bytes
// - N_ARRAY๋ ๋จผ์ ๊ฐ์(UINT32, 4 bytes)๋ฅผ ์ฝ๊ณ , ๊ทธ ๋ค์ ํญ๋ชฉ๋ค์ ์ฝ์
if data.len() < 24 {
return Err(HwpError::insufficient_data("Property Set header", 24, data.len()));
}
let mut offset = 0;
// Byte order (2 bytes): 0xFEFF (little-endian) or 0xFFFE (big-endian)
// MSDN Property Set ํ์์์๋ ๋ ๊ฐ์ง ๋ชจ๋ ์ง์
// MSDN Property Set format supports both
// Note: Byte order field is stored as raw bytes, not in a specific endianness
// ์ฃผ์: Byte order ํ๋๋ raw ๋ฐ์ดํธ๋ก ์ ์ฅ๋๋ฉฐ, ํน์ ์๋์ธ์ผ๋ก ์ ์ฅ๋์ง ์์
// 0xFEFF (stored as [0xFE, 0xFF]) means little-endian
// 0xFEFF ([0xFE, 0xFF]๋ก ์ ์ฅ)๋ little-endian์ ์๋ฏธ
// 0xFFFE (stored as [0xFF, 0xFE]) means big-endian
// 0xFFFE ([0xFF, 0xFE]๋ก ์ ์ฅ)๋ big-endian์ ์๋ฏธ
let byte_order_bytes = [data[offset], data[offset + 1]];
// Read as big-endian to get the actual BOM value
// ์ค์ BOM ๊ฐ์ ์ป๊ธฐ ์ํด big-endian์ผ๋ก ์ฝ๊ธฐ
let byte_order = u16::from_be_bytes(byte_order_bytes);
let is_big_endian = byte_order == 0xFFFE;
if byte_order != 0xFEFF && byte_order != 0xFFFE {
return Err(HwpError::UnexpectedValue {
field: "Property Set byte order".to_string(),
expected: "0xFEFF or 0xFFFE".to_string(),
found: format!("0x{:04X}", byte_order),
});
}
offset += 2;
// Version (2 bytes): Usually 0x0000
offset += 2;
// SystemIdentifier (4 bytes): UINT32 (pyhwp ์ฐธ๊ณ )
// ์ค์ ๋ฐ์ดํฐ๋ฅผ ๋ณด๋ฉด [5, 1, 2, 0]์ด SystemIdentifier์ธ ๊ฒ ๊ฐ์ต๋๋ค
// Looking at actual data, [5, 1, 2, 0] seems to be SystemIdentifier
offset += 4;
// CLSID (16 bytes): GUID, skip
offset += 16;
// propsetDescList: N_ARRAY์ด๋ฏ๋ก ๋จผ์ ๊ฐ์ ์ฝ๊ธฐ
// propsetDescList: N_ARRAY, so read count first
// N_ARRAY๋ counttype (UINT32)๋ก ๊ฐ์๋ฅผ ์ฝ์ต๋๋ค
// N_ARRAY reads count using counttype (UINT32)
if offset + 4 > data.len() {
return Err(HwpError::insufficient_data(
"propsetDescList count",
4,
data.len() - offset,
));
}
let num_property_sets = if is_big_endian {
UINT32::from_be_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
])
} else {
UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
])
};
offset += 4;
if num_property_sets == 0 {
return Ok(result);
}
// ์ฒซ ๋ฒ์งธ PropertySetDesc ์ฝ๊ธฐ (์ผ๋ฐ์ ์ผ๋ก ํ๋๋ง ์์)
// Read first PropertySetDesc (usually only one)
// ๊ฐ PropertySetDesc๋ FMTID (16 bytes) + Offset (4 bytes) = 20 bytes
// Each PropertySetDesc is FMTID (16 bytes) + Offset (4 bytes) = 20 bytes
if offset + 20 > data.len() {
return Err(HwpError::InsufficientData {
field: "PropertySetDesc".to_string(),
expected: offset + 20,
actual: data.len(),
});
}
// FMTID (16 bytes) ๊ฑด๋๋ฐ๊ธฐ / Skip FMTID (16 bytes)
offset += 16;
// ์ฒซ ๋ฒ์งธ PropertySetDesc์ offset ์ฝ๊ธฐ
// Read offset of first PropertySetDesc
// PropertySetDesc ๊ตฌ์กฐ: FMTID (16 bytes) + Offset (4 bytes)
// PropertySetDesc structure: FMTID (16 bytes) + Offset (4 bytes)
if offset + 4 > data.len() {
return Err(HwpError::insufficient_data(
"PropertySetDesc offset",
4,
data.len() - offset,
));
}
// PropertySetDesc์ offset์ byte order์ ๋ฐ๋ผ ์ฝ์ด์ผ ํจ
// PropertySetDesc offset should be read according to byte order
// ์ค์ ๋ฐ์ดํฐ๋ฅผ ๋ณด๋ฉด offset 44์์ [48, 0, 0, 0] = 0x00000030 = 48 (little-endian)
// Looking at actual data, at offset 44 we have [48, 0, 0, 0] = 0x00000030 = 48 (little-endian)
let property_set_offset = if is_big_endian {
UINT32::from_be_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]) as usize
} else {
UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]) as usize
};
let property_set_start = property_set_offset;
if property_set_start >= data.len() {
return Err(HwpError::UnexpectedValue {
field: format!("Property Set offset (start={})", property_set_start),
expected: format!("< {}", data.len()),
found: property_set_start.to_string(),
});
}
// Property Set Header: Size (4) + NumProperties (4) + Property entries
if property_set_start + 8 > data.len() {
return Err(HwpError::insufficient_data(
"Property Set header",
8,
data.len() - property_set_start,
));
}
// Size (4 bytes): Size of property set (from current offset to end of property set)
let _property_set_size = if is_big_endian {
UINT32::from_be_bytes([
data[property_set_start],
data[property_set_start + 1],
data[property_set_start + 2],
data[property_set_start + 3],
]) as usize
} else {
UINT32::from_le_bytes([
data[property_set_start],
data[property_set_start + 1],
data[property_set_start + 2],
data[property_set_start + 3],
]) as usize
};
let mut offset = property_set_start + 4;
// NumProperties (4 bytes): Number of properties
let num_properties = if is_big_endian {
UINT32::from_be_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
])
} else {
UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
])
};
offset += 4;
// Property entries: Each entry is Property ID (4) + Offset (4) = 8 bytes
let property_entries_start = offset;
let property_entries_size = (num_properties as usize) * 8;
if offset + property_entries_size > data.len() {
return Err(HwpError::InsufficientData {
field: "property entries".to_string(),
expected: offset + property_entries_size,
actual: data.len(),
});
}
// Parse properties: find codepage first, then parse all properties
// Property ํ์ฑ: ๋จผ์ codepage๋ฅผ ์ฐพ๊ณ , ๊ทธ ๋ค์ ๋ชจ๋ property ํ์ฑ
let mut codepage: u16 = 0xFFFF; // Default: invalid codepage
for i in 0..num_properties {
let entry_offset = property_entries_start + (i as usize * 8);
// Property ID (4 bytes)
let property_id = if is_big_endian {
UINT32::from_be_bytes([
data[entry_offset],
data[entry_offset + 1],
data[entry_offset + 2],
data[entry_offset + 3],
])
} else {
UINT32::from_le_bytes([
data[entry_offset],
data[entry_offset + 1],
data[entry_offset + 2],
data[entry_offset + 3],
])
};
// Offset (4 bytes): Offset from Property Set start (Size field)
let value_offset = if is_big_endian {
UINT32::from_be_bytes([
data[entry_offset + 4],
data[entry_offset + 5],
data[entry_offset + 6],
data[entry_offset + 7],
]) as usize
} else {
UINT32::from_le_bytes([
data[entry_offset + 4],
data[entry_offset + 5],
data[entry_offset + 6],
data[entry_offset + 7],
]) as usize
};
let value_data_offset = property_set_start + value_offset;
if value_data_offset >= data.len() {
continue;
}
// Find codepage first
if property_id == property_ids::PID_CODEPAGE {
if let Ok(cp) = Self::parse_vt_i2(&data[value_data_offset..], is_big_endian) {
codepage = cp as u16;
}
continue;
}
// Parse property value
match property_id {
property_ids::PIDSI_TITLE => {
result.title =
Self::parse_vt_lpstr(&data[value_data_offset..], is_big_endian, codepage)
.ok();
}
property_ids::PIDSI_SUBJECT => {
result.subject =
Self::parse_vt_lpstr(&data[value_data_offset..], is_big_endian, codepage)
.ok();
}
property_ids::PIDSI_AUTHOR => {
result.author =
Self::parse_vt_lpstr(&data[value_data_offset..], is_big_endian, codepage)
.ok();
}
property_ids::PIDSI_KEYWORDS => {
result.keywords =
Self::parse_vt_lpstr(&data[value_data_offset..], is_big_endian, codepage)
.ok();
}
property_ids::PIDSI_COMMENTS => {
result.comments =
Self::parse_vt_lpstr(&data[value_data_offset..], is_big_endian, codepage)
.ok();
}
property_ids::PIDSI_LASTAUTHOR => {
result.last_saved_by =
Self::parse_vt_lpstr(&data[value_data_offset..], is_big_endian, codepage)
.ok();
}
property_ids::PIDSI_REVNUMBER => {
result.revision_number =
Self::parse_vt_lpstr(&data[value_data_offset..], is_big_endian, codepage)
.ok();
}
property_ids::PIDSI_LASTPRINTED => {
result.last_printed =
Self::parse_vt_filetime(&data[value_data_offset..], is_big_endian)
.ok()
.map(|ft| ft.to_utc9_string());
}
property_ids::PIDSI_CREATE_DTM => {
result.create_time =
Self::parse_vt_filetime(&data[value_data_offset..], is_big_endian)
.ok()
.map(|ft| ft.to_utc9_string());
}
property_ids::PIDSI_LASTSAVE_DTM => {
result.last_saved_time =
Self::parse_vt_filetime(&data[value_data_offset..], is_big_endian)
.ok()
.map(|ft| ft.to_utc9_string());
}
property_ids::PIDSI_PAGECOUNT => {
result.page_count =
Self::parse_vt_i4(&data[value_data_offset..], is_big_endian).ok();
}
property_ids::HWPPIDSI_DATE_STR => {
result.date_string =
Self::parse_vt_lpstr(&data[value_data_offset..], is_big_endian, codepage)
.ok();
}
property_ids::HWPPIDSI_PARACOUNT => {
result.para_count =
Self::parse_vt_i4(&data[value_data_offset..], is_big_endian).ok();
}
_ => {
// Unknown property ID, skip
}
}
}
Ok(result)
}
/// VT_I2 ํ์ฑ (16-bit signed integer, codepage์ ์ฌ์ฉ) / Parse VT_I2 (16-bit signed integer, used for codepage)
/// Format: VT type (4 bytes) + Value (2 bytes)
fn parse_vt_i2(data: &[u8], is_big_endian: bool) -> Result<i16, HwpError> {
if data.len() < 6 {
return Err(HwpError::insufficient_data("VT_I2", 6, data.len()));
}
// VT type (4 bytes): Should be VT_I2 (0x0002)
let vt_type = if is_big_endian {
UINT32::from_be_bytes([data[0], data[1], data[2], data[3]])
} else {
UINT32::from_le_bytes([data[0], data[1], data[2], data[3]])
};
if vt_type != VT_I2 {
return Err(HwpError::UnexpectedValue {
field: "VT_I2 type".to_string(),
expected: format!("0x{:08X}", VT_I2),
found: format!("0x{:08X}", vt_type),
});
}
// Value (2 bytes): Signed 16-bit integer
let value = if is_big_endian {
i16::from_be_bytes([data[4], data[5]])
} else {
i16::from_le_bytes([data[4], data[5]])
};
Ok(value)
}
/// VT_LPSTR ๋๋ VT_LPWSTR ํ์ฑ (๋ฌธ์์ด) / Parse VT_LPSTR or VT_LPWSTR (string)
/// Format: VT type (4 bytes) + Length (4 bytes) + String (null-terminated)
/// codepage์ ๋ฐ๋ผ ์ ์ ํ ์ธ์ฝ๋ฉ์ผ๋ก ๋์ฝ๋ฉ / Decode using appropriate encoding based on codepage
fn parse_vt_lpstr(data: &[u8], is_big_endian: bool, codepage: u16) -> Result<String, HwpError> {
if data.len() < 8 {
return Err(HwpError::insufficient_data("VT_LPSTR/VT_LPWSTR", 8, data.len()));
}
// VT type (4 bytes): Should be VT_LPSTR (0x001E) or VT_LPWSTR (0x001F)
let vt_type = if is_big_endian {
UINT32::from_be_bytes([data[0], data[1], data[2], data[3]])
} else {
UINT32::from_le_bytes([data[0], data[1], data[2], data[3]])
};
// VT_LPWSTR (wide string) ์ฒ๋ฆฌ
if vt_type == VT_LPWSTR {
return Self::parse_vt_lpwstr(data, is_big_endian);
}
if vt_type != VT_LPSTR {
return Err(HwpError::UnexpectedValue {
field: "VT_LPSTR/VT_LPWSTR type".to_string(),
expected: format!("0x{:08X} or 0x{:08X}", VT_LPSTR, VT_LPWSTR),
found: format!("0x{:08X}", vt_type),
});
}
// Length (4 bytes): String length in bytes (including null terminator)
// hwplib์ CodePageString์ฒ๋ผ size๋งํผ ์ฝ์
let size = if is_big_endian {
UINT32::from_be_bytes([data[4], data[5], data[6], data[7]]) as usize
} else {
UINT32::from_le_bytes([data[4], data[5], data[6], data[7]]) as usize
};
if data.len() < 8 + size {
return Err(HwpError::InsufficientData {
field: "VT_LPSTR string".to_string(),
expected: 8 + size,
actual: data.len(),
});
}
// String data: size๋งํผ ์ฝ์ (hwplib์ CodePageString์ฒ๋ผ)
let string_data = &data[8..8 + size];
// Decode string based on codepage
// codepage์ ๋ฐ๋ผ ์ ์ ํ ์ธ์ฝ๋ฉ์ผ๋ก ๋์ฝ๋ฉ
Self::decode_string_by_codepage(string_data, codepage)
.map_err(|e| HwpError::EncodingError {
reason: format!(
"Failed to decode VT_LPSTR string with codepage {}: {}",
codepage, e
),
})
}
/// VT_FILETIME ํ์ฑ (๋ ์ง/์๊ฐ) / Parse VT_FILETIME (date/time)
/// Format: VT type (4 bytes) + FILETIME (8 bytes: low 4 bytes + high 4 bytes)
fn parse_vt_filetime(data: &[u8], is_big_endian: bool) -> Result<FileTime, HwpError> {
if data.len() < 12 {
return Err(HwpError::insufficient_data("VT_FILETIME", 12, data.len()));
}
// VT type (4 bytes): Should be VT_FILETIME (0x0040)
let vt_type = if is_big_endian {
UINT32::from_be_bytes([data[0], data[1], data[2], data[3]])
} else {
UINT32::from_le_bytes([data[0], data[1], data[2], data[3]])
};
if vt_type != VT_FILETIME {
return Err(HwpError::UnexpectedValue {
field: "VT_FILETIME type".to_string(),
expected: format!("0x{:08X}", VT_FILETIME),
found: format!("0x{:08X}", vt_type),
});
}
// FILETIME: Low 32 bits (4 bytes) + High 32 bits (4 bytes)
let low = if is_big_endian {
UINT32::from_be_bytes([data[4], data[5], data[6], data[7]])
} else {
UINT32::from_le_bytes([data[4], data[5], data[6], data[7]])
};
let high = if is_big_endian {
UINT32::from_be_bytes([data[8], data[9], data[10], data[11]])
} else {
UINT32::from_le_bytes([data[8], data[9], data[10], data[11]])
};
Ok(FileTime { low, high })
}
/// VT_LPWSTR ํ์ฑ (Wide string, UTF-16LE) / Parse VT_LPWSTR (Wide string, UTF-16LE)
/// Format: VT type (4 bytes) + Length (4 bytes, character count) + String (UTF-16LE, null-terminated)
/// hwplib์ UnicodeString ๊ตฌํ ์ฐธ๊ณ
fn parse_vt_lpwstr(data: &[u8], is_big_endian: bool) -> Result<String, HwpError> {
if data.len() < 8 {
return Err(HwpError::insufficient_data("VT_LPWSTR", 8, data.len()));
}
// VT type (4 bytes): Should be VT_LPWSTR (0x001F)
let vt_type = if is_big_endian {
UINT32::from_be_bytes([data[0], data[1], data[2], data[3]])
} else {
UINT32::from_le_bytes([data[0], data[1], data[2], data[3]])
};
if vt_type != VT_LPWSTR {
return Err(HwpError::UnexpectedValue {
field: "VT_LPWSTR type".to_string(),
expected: format!("0x{:08X}", VT_LPWSTR),
found: format!("0x{:08X}", vt_type),
});
}
// Length (4 bytes): Character count (not byte count)
// hwplib์ UnicodeString์ฒ๋ผ character count๋ฅผ ์ฝ์
let char_count = if is_big_endian {
UINT32::from_be_bytes([data[4], data[5], data[6], data[7]]) as usize
} else {
UINT32::from_le_bytes([data[4], data[5], data[6], data[7]]) as usize
};
if char_count == 0 {
return Ok(String::new());
}
// UTF-16LE: ๊ฐ character๋ 2 bytes
let byte_count = char_count * 2;
if data.len() < 8 + byte_count {
return Err(HwpError::InsufficientData {
field: "VT_LPWSTR string".to_string(),
expected: 8 + byte_count,
actual: data.len(),
});
}
// String data: UTF-16LE bytes
// hwplib์ UnicodeString์ฒ๋ผ length * 2 ๋ฐ์ดํธ๋ฅผ ์ฝ์
let string_bytes = &data[8..8 + byte_count];
// UTF-16LE ๋์ฝ๋ฉ (hwplib์ StringUtil.getFromUnicodeLE์ฒ๋ผ)
let mut chars = Vec::new();
for i in (0..string_bytes.len()).step_by(2) {
if i + 1 < string_bytes.len() {
let code_point = u16::from_le_bytes([string_bytes[i], string_bytes[i + 1]]);
if code_point == 0 {
break; // null terminator
}
if let Some(ch) = char::from_u32(code_point as u32) {
chars.push(ch);
}
}
}
Ok(chars.into_iter().collect())
}
/// Codepage์ ๋ฐ๋ผ ๋ฌธ์์ด ๋์ฝ๋ฉ / Decode string based on codepage
/// hwplib์ CodePageString.getJavaValue() ๋ก์ง ์ฐธ๊ณ
fn decode_string_by_codepage(data: &[u8], codepage: u16) -> Result<String, HwpError> {
use encoding_rs::*;
if data.is_empty() {
return Ok(String::new());
}
// Codepage ์์ (hwplib ์ฐธ๊ณ )
const CP_UTF16: u16 = 1200;
const CP_UTF16_BE: u16 = 1201;
const CP_UTF8: u16 = 65001;
const CP_MS949: u16 = 949;
const CP_WINDOWS_1252: u16 = 1252;
// hwplib์ฒ๋ผ codepage๊ฐ -1 (0xFFFF)์ด๋ฉด ๊ธฐ๋ณธ ์ธ์ฝ๋ฉ ์ฌ์ฉ
let result = if codepage == 0xFFFF {
// Default: try UTF-8, fallback to Windows-1252
String::from_utf8(data.to_vec())
.unwrap_or_else(|_| WINDOWS_1252.decode(data).0.to_string())
} else {
match codepage {
CP_UTF16 => {
let mut chars = Vec::new();
for i in (0..data.len()).step_by(2) {
if i + 1 < data.len() {
let code_point = u16::from_le_bytes([data[i], data[i + 1]]);
if let Some(ch) = char::from_u32(code_point as u32) {
if ch != '\0' {
chars.push(ch);
}
}
}
}
chars.into_iter().collect()
}
CP_UTF16_BE => {
let mut chars = Vec::new();
for i in (0..data.len()).step_by(2) {
if i + 1 < data.len() {
let code_point = u16::from_be_bytes([data[i], data[i + 1]]);
if let Some(ch) = char::from_u32(code_point as u32) {
if ch != '\0' {
chars.push(ch);
}
}
}
}
chars.into_iter().collect()
}
CP_UTF8 => String::from_utf8(data.to_vec())
.map_err(|e| HwpError::EncodingError {
reason: format!("UTF-8 decode error: {}", e),
})?,
CP_MS949 => EUC_KR.decode(data).0.to_string(),
CP_WINDOWS_1252 => WINDOWS_1252.decode(data).0.to_string(),
_ => {
// Unknown codepage: try UTF-8, fallback to Windows-1252
String::from_utf8(data.to_vec())
.unwrap_or_else(|_| WINDOWS_1252.decode(data).0.to_string())
}
}
};
// Remove null terminator (hwplib์ CodePageString.getJavaValue์ฒ๋ผ)
// hwplib๋ null terminator๋ฅผ ์ฐพ์์ substring(0, terminator)๋ฅผ ๋ฐํ
let terminator = result.find('\0');
if let Some(pos) = terminator {
Ok(result[..pos].to_string())
} else {
Ok(result)
}
}
/// VT_I4 ํ์ฑ (32-bit signed integer) / Parse VT_I4 (32-bit signed integer)
/// Format: VT type (4 bytes) + Value (4 bytes)
fn parse_vt_i4(data: &[u8], is_big_endian: bool) -> Result<INT32, HwpError> {
if data.len() < 8 {
return Err(HwpError::insufficient_data("VT_I4", 8, data.len()));
}
// VT type (4 bytes): Should be VT_I4 (0x0003)
let vt_type = if is_big_endian {
UINT32::from_be_bytes([data[0], data[1], data[2], data[3]])
} else {
UINT32::from_le_bytes([data[0], data[1], data[2], data[3]])
};
if vt_type != VT_I4 {
return Err(HwpError::UnexpectedValue {
field: "VT_I4 type".to_string(),
expected: format!("0x{:08X}", VT_I4),
found: format!("0x{:08X}", vt_type),
});
}
// Value (4 bytes): Signed 32-bit integer
let value = if is_big_endian {
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | true |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/constants.rs | crates/hwp-core/src/document/constants.rs | /// ๊ณตํต ํ๊ทธ ์์ ์ ์ / Common tag constants definition
///
/// HWPTAG_BEGIN = 0x10 (ํ๊ธ ๋ด๋ถ ์ฌ์ฉ์ ์ํด ์์ฝ๋ ์์ญ์ ์์) / HWPTAG_BEGIN = 0x10 (start of reserved area for HWP internal use)
/// ๋ฐ์ดํฐ ๋ ์ฝ๋ ์์ ๊ฐ / Data record start value
pub const HWPTAG_BEGIN: u16 = 0x10;
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/scripts/script_version.rs | crates/hwp-core/src/document/scripts/script_version.rs | /// ScriptVersion ๊ตฌ์กฐ์ฒด / ScriptVersion structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 8 - ์คํฌ๋ฆฝํธ ๋ฒ์ / Spec mapping: Table 8 - Script version
use crate::error::HwpError;
use crate::types::DWORD;
use serde::{Deserialize, Serialize};
/// ์คํฌ๋ฆฝํธ ๋ฒ์ / Script version
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScriptVersion {
/// ์คํฌ๋ฆฝํธ ๋ฒ์ HIGH / Script version HIGH
pub high: DWORD,
/// ์คํฌ๋ฆฝํธ ๋ฒ์ LOW / Script version LOW
pub low: DWORD,
}
impl ScriptVersion {
/// ScriptVersion์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ScriptVersion from byte array.
///
/// # Arguments
/// * `data` - JScriptVersion ์คํธ๋ฆผ์ ์์ ๋ฐ์ดํธ ๋ฐ์ดํฐ / Raw byte data of JScriptVersion stream
///
/// # Returns
/// ํ์ฑ๋ ScriptVersion ๊ตฌ์กฐ์ฒด / Parsed ScriptVersion structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 8์ ๋ฐ๋ฅด๋ฉด ์คํฌ๋ฆฝํธ ๋ฒ์ ์ 8๋ฐ์ดํธ์
๋๋ค:
/// - DWORD (4 bytes): ์คํฌ๋ฆฝํธ ๋ฒ์ HIGH
/// - DWORD (4 bytes): ์คํฌ๋ฆฝํธ ๋ฒ์ LOW
/// According to spec Table 8, script version is 8 bytes:
/// - DWORD (4 bytes): Script version HIGH
/// - DWORD (4 bytes): Script version LOW
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 8 {
return Err(HwpError::insufficient_data("ScriptVersion", 8, data.len()));
}
// DWORD ์คํฌ๋ฆฝํธ ๋ฒ์ HIGH (4 bytes) / Script version HIGH (4 bytes)
let high = DWORD::from_le_bytes([data[0], data[1], data[2], data[3]]);
// DWORD ์คํฌ๋ฆฝํธ ๋ฒ์ LOW (4 bytes) / Script version LOW (4 bytes)
let low = DWORD::from_le_bytes([data[4], data[5], data[6], data[7]]);
Ok(ScriptVersion { high, low })
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/scripts/mod.rs | crates/hwp-core/src/document/scripts/mod.rs | /// Scripts parsing module
///
/// This module handles parsing of HWP Scripts storage.
///
/// ์คํ ๋ฌธ์ ๋งคํ: 3.2.9 - ์คํฌ๋ฆฝํธ / Spec mapping: 3.2.9 - Scripts
mod script;
mod script_version;
pub use script::Script;
pub use script_version::ScriptVersion;
use crate::cfb::CfbParser;
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// Scripts structure
/// ์คํฌ๋ฆฝํธ ๊ตฌ์กฐ
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Scripts {
/// Script version (from JScriptVersion stream) / ์คํฌ๋ฆฝํธ ๋ฒ์ (JScriptVersion ์คํธ๋ฆผ)
pub version: Option<ScriptVersion>,
/// Default script (from DefaultJScript stream) / ๊ธฐ๋ณธ ์คํฌ๋ฆฝํธ (DefaultJScript ์คํธ๋ฆผ)
pub default_script: Option<Script>,
}
impl Scripts {
/// Parse Scripts storage from CFB structure
/// CFB ๊ตฌ์กฐ์์ Scripts ์คํ ๋ฆฌ์ง๋ฅผ ํ์ฑํฉ๋๋ค.
///
/// # Arguments
/// * `cfb` - CompoundFile structure (mutable reference required) / CompoundFile ๊ตฌ์กฐ์ฒด (๊ฐ๋ณ ์ฐธ์กฐ ํ์)
///
/// # Returns
/// Parsed Scripts structure / ํ์ฑ๋ Scripts ๊ตฌ์กฐ์ฒด
///
/// # Note
/// ์คํ ๋ฌธ์ 3.2.9์ ๋ฐ๋ฅด๋ฉด Scripts ์คํ ๋ฆฌ์ง์๋ ๋ค์ ์คํธ๋ฆผ์ด ํฌํจ๋ฉ๋๋ค:
/// - JScriptVersion: ์คํฌ๋ฆฝํธ ๋ฒ์ (ํ 8)
/// - DefaultJScript: ์คํฌ๋ฆฝํธ ๋ด์ฉ (ํ 9)
/// According to spec 3.2.9, Scripts storage contains the following streams:
/// - JScriptVersion: Script version (Table 8)
/// - DefaultJScript: Script content (Table 9)
pub fn parse(cfb: &mut cfb::CompoundFile<std::io::Cursor<&[u8]>>) -> Result<Self, HwpError> {
let mut scripts = Scripts::default();
// Parse JScriptVersion stream
// JScriptVersion ์คํธ๋ฆผ ํ์ฑ / Parse JScriptVersion stream
// ์คํ ๋ฌธ์ ํ 8: ์คํฌ๋ฆฝํธ ๋ฒ์ ์ 8๋ฐ์ดํธ (DWORD HIGH + DWORD LOW)
// Spec Table 8: Script version is 8 bytes (DWORD HIGH + DWORD LOW)
if let Ok(version_data) = CfbParser::read_nested_stream(cfb, "Scripts", "JScriptVersion") {
match ScriptVersion::parse(&version_data) {
Ok(version) => {
scripts.version = Some(version);
}
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("Warning: Failed to parse JScriptVersion stream: {}", e);
}
}
}
// Parse DefaultJScript stream
// DefaultJScript ์คํธ๋ฆผ ํ์ฑ / Parse DefaultJScript stream
// ์คํ ๋ฌธ์ ํ 9: ์คํฌ๋ฆฝํธ ๋ด์ฉ์ ๊ฐ๋ณ ๊ธธ์ด
// Spec Table 9: Script content is variable length
if let Ok(script_data) = CfbParser::read_nested_stream(cfb, "Scripts", "DefaultJScript") {
match Script::parse(&script_data) {
Ok(default_script) => {
scripts.default_script = Some(default_script);
}
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("Warning: Failed to parse DefaultJScript stream: {}", e);
}
}
}
Ok(scripts)
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/scripts/script.rs | crates/hwp-core/src/document/scripts/script.rs | /// Script ๊ตฌ์กฐ์ฒด / Script structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 9 - ์คํฌ๋ฆฝํธ / Spec mapping: Table 9 - Script
use crate::error::HwpError;
use crate::types::{decode_utf16le, DWORD};
use serde::{Deserialize, Serialize};
/// ์คํฌ๋ฆฝํธ / Script
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Script {
/// ์คํฌ๋ฆฝํธ ํค๋ / Script header
pub header: String,
/// ์คํฌ๋ฆฝํธ ์์ค / Script source
pub source: String,
/// ์คํฌ๋ฆฝํธ Pre ์์ค / Script pre source
pub pre_source: String,
/// ์คํฌ๋ฆฝํธ Post ์์ค / Script post source
pub post_source: String,
}
impl Script {
/// Script๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse Script from byte array.
///
/// # Arguments
/// * `data` - DefaultJScript ์คํธ๋ฆผ์ ์์ ๋ฐ์ดํธ ๋ฐ์ดํฐ / Raw byte data of DefaultJScript stream
///
/// # Returns
/// ํ์ฑ๋ Script ๊ตฌ์กฐ์ฒด / Parsed Script structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 9์ ๋ฐ๋ฅด๋ฉด ์คํฌ๋ฆฝํธ๋ ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋๋ค:
/// - DWORD (4 bytes): ์คํฌ๋ฆฝํธ ํค๋ ๊ธธ์ด (len1)
/// - WCHAR array[len1] (2รlen1 bytes): ์คํฌ๋ฆฝํธ ํค๋
/// - DWORD (4 bytes): ์คํฌ๋ฆฝํธ ์์ค ๊ธธ์ด (len2)
/// - WCHAR array[len2] (2รlen2 bytes): ์คํฌ๋ฆฝํธ ์์ค
/// - DWORD (4 bytes): ์คํฌ๋ฆฝํธ Pre ์์ค ๊ธธ์ด (len3)
/// - WCHAR array[len3] (2รlen3 bytes): ์คํฌ๋ฆฝํธ Pre ์์ค
/// - DWORD (4 bytes): ์คํฌ๋ฆฝํธ Post ์์ค ๊ธธ์ด (len4)
/// - WCHAR array[len4] (2รlen4 bytes): ์คํฌ๋ฆฝํธ Post ์์ค
/// - DWORD (4 bytes): ์คํฌ๋ฆฝํธ end flag (-1)
/// According to spec Table 9, script has the following structure:
/// - DWORD (4 bytes): Script header length (len1)
/// - WCHAR array[len1] (2รlen1 bytes): Script header
/// - DWORD (4 bytes): Script source length (len2)
/// - WCHAR array[len2] (2รlen2 bytes): Script source
/// - DWORD (4 bytes): Script pre source length (len3)
/// - WCHAR array[len3] (2รlen3 bytes): Script pre source
/// - DWORD (4 bytes): Script post source length (len4)
/// - WCHAR array[len4] (2รlen4 bytes): Script post source
/// - DWORD (4 bytes): Script end flag (-1)
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
let mut offset = 0;
// ์ต์ 20๋ฐ์ดํธ ํ์ (4๊ฐ์ DWORD ๊ธธ์ด ํ๋ + end flag) / Need at least 20 bytes (4 DWORD length fields + end flag)
if data.len() < 20 {
return Err(HwpError::insufficient_data("Script", 20, data.len()));
}
// DWORD ์คํฌ๋ฆฝํธ ํค๋ ๊ธธ์ด (4 bytes) / Script header length (4 bytes)
let header_len = DWORD::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]) as usize;
offset += 4;
// WCHAR array[len1] ์คํฌ๋ฆฝํธ ํค๋ (2รlen1 bytes) / Script header (2รlen1 bytes)
let header = if header_len > 0 {
let header_bytes_len = header_len.saturating_mul(2);
if offset + header_bytes_len <= data.len() {
let header_bytes = &data[offset..offset + header_bytes_len];
decode_utf16le(header_bytes).unwrap_or_default()
} else {
String::new()
}
} else {
String::new()
};
offset = offset.saturating_add(header_len.saturating_mul(2));
// DWORD ์คํฌ๋ฆฝํธ ์์ค ๊ธธ์ด (4 bytes) / Script source length (4 bytes)
if offset + 4 > data.len() {
return Err(HwpError::insufficient_data(
"Script source length",
4,
data.len().saturating_sub(offset),
));
}
let source_len = DWORD::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]) as usize;
offset += 4;
// WCHAR array[len2] ์คํฌ๋ฆฝํธ ์์ค (2รlen2 bytes) / Script source (2รlen2 bytes)
let source = if source_len > 0 {
let source_bytes_len = source_len.saturating_mul(2);
if offset + source_bytes_len <= data.len() {
let source_bytes = &data[offset..offset + source_bytes_len];
decode_utf16le(source_bytes).unwrap_or_default()
} else {
String::new()
}
} else {
String::new()
};
offset = offset.saturating_add(source_len.saturating_mul(2));
// DWORD ์คํฌ๋ฆฝํธ Pre ์์ค ๊ธธ์ด (4 bytes) / Script pre source length (4 bytes)
if offset + 4 > data.len() {
return Err(HwpError::insufficient_data(
"Script pre source length",
4,
data.len().saturating_sub(offset),
));
}
let pre_source_len = DWORD::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]) as usize;
offset += 4;
// WCHAR array[len3] ์คํฌ๋ฆฝํธ Pre ์์ค (2รlen3 bytes) / Script pre source (2รlen3 bytes)
let pre_source = if pre_source_len > 0 {
let pre_source_bytes_len = pre_source_len.saturating_mul(2);
if offset + pre_source_bytes_len <= data.len() {
let pre_source_bytes = &data[offset..offset + pre_source_bytes_len];
decode_utf16le(pre_source_bytes).unwrap_or_default()
} else {
String::new()
}
} else {
String::new()
};
offset = offset.saturating_add(pre_source_len.saturating_mul(2));
// DWORD ์คํฌ๋ฆฝํธ Post ์์ค ๊ธธ์ด (4 bytes) / Script post source length (4 bytes)
if offset + 4 > data.len() {
return Err(HwpError::insufficient_data(
"Script post source length",
4,
data.len().saturating_sub(offset),
));
}
let post_source_len = DWORD::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]) as usize;
offset += 4;
// WCHAR array[len4] ์คํฌ๋ฆฝํธ Post ์์ค (2รlen4 bytes) / Script post source (2รlen4 bytes)
let post_source = if post_source_len > 0 {
let post_source_bytes_len = post_source_len.saturating_mul(2);
if offset + post_source_bytes_len <= data.len() {
let post_source_bytes = &data[offset..offset + post_source_bytes_len];
decode_utf16le(post_source_bytes).unwrap_or_default()
} else {
String::new()
}
} else {
String::new()
};
offset = offset.saturating_add(post_source_len.saturating_mul(2));
// DWORD ์คํฌ๋ฆฝํธ end flag (-1) (4 bytes) / Script end flag (-1) (4 bytes)
// ๊ฒ์ฆ ๋ชฉ์ ์ผ๋ก ์ฝ์ง๋ง ์ฌ์ฉํ์ง ์์ / Read for validation but not used
if offset + 4 <= data.len() {
let end_flag = DWORD::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
if end_flag != 0xFFFFFFFF {
#[cfg(debug_assertions)]
eprintln!(
"Warning: Script end flag is not -1 (0xFFFFFFFF), got 0x{:08X}",
end_flag
);
}
}
Ok(Script {
header,
source,
pre_source,
post_source,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/track_change.rs | crates/hwp-core/src/document/docinfo/track_change.rs | /// TrackChange ๊ตฌ์กฐ์ฒด / TrackChange structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 4 - ๋ณ๊ฒฝ ์ถ์ ์ ๋ณด / Spec mapping: Table 4 - Track change information
/// ์์ธ ๊ตฌ์กฐ๋ ์คํ ๋ฌธ์์ ๋ช
์๋์ง ์์ / Detailed structure not specified in spec
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// ๋ณ๊ฒฝ ์ถ์ ์ ๋ณด / Track change information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrackChange {
/// Raw data (1032๋ฐ์ดํธ) / Raw data (1032 bytes)
#[serde(skip)]
pub raw_data: Vec<u8>,
}
impl TrackChange {
/// TrackChange๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse TrackChange from byte array.
///
/// # Arguments
/// * `data` - TrackChange ๋ฐ์ดํฐ (1032๋ฐ์ดํธ) / TrackChange data (1032 bytes)
///
/// # Returns
/// ํ์ฑ๋ TrackChange ๊ตฌ์กฐ์ฒด / Parsed TrackChange structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 1032 {
return Err(HwpError::insufficient_data("TrackChange", 1032, data.len()));
}
Ok(TrackChange {
raw_data: data[0..1032.min(data.len())].to_vec(),
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/track_change_author.rs | crates/hwp-core/src/document/docinfo/track_change_author.rs | /// TrackChangeAuthor ๊ตฌ์กฐ์ฒด / TrackChangeAuthor structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 4 - ๋ณ๊ฒฝ ์ถ์ ์์ฑ์ / Spec mapping: Table 4 - Track change author
/// ์์ธ ๊ตฌ์กฐ๋ ์คํ ๋ฌธ์์ ๋ช
์๋์ง ์์ / Detailed structure not specified in spec
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// ๋ณ๊ฒฝ ์ถ์ ์์ฑ์ / Track change author
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrackChangeAuthor {
/// Raw data (๊ฐ๋ณ) / Raw data (variable)
#[serde(skip)]
pub raw_data: Vec<u8>,
}
impl TrackChangeAuthor {
/// TrackChangeAuthor๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse TrackChangeAuthor from byte array.
///
/// # Arguments
/// * `data` - TrackChangeAuthor ๋ฐ์ดํฐ (๊ฐ๋ณ) / TrackChangeAuthor data (variable)
///
/// # Returns
/// ํ์ฑ๋ TrackChangeAuthor ๊ตฌ์กฐ์ฒด / Parsed TrackChangeAuthor structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
Ok(TrackChangeAuthor {
raw_data: data.to_vec(),
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/id_mappings.rs | crates/hwp-core/src/document/docinfo/id_mappings.rs | /// ID Mappings ๊ตฌ์กฐ์ฒด / ID Mappings structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 15 - ์์ด๋ ๋งคํ ํค๋ / Spec mapping: Table 15 - ID mappings header
/// Tag ID: HWPTAG_ID_MAPPINGS
/// ์ ์ฒด ๊ธธ์ด: 72 ๋ฐ์ดํธ (18๊ฐ INT32) / Total length: 72 bytes (18 INT32 values)
use crate::error::HwpError;
use crate::types::INT32;
use serde::{Deserialize, Serialize};
/// ID Mappings ๊ตฌ์กฐ์ฒด / ID Mappings structure
///
/// ์คํ ๋ฌธ์ ํ 15์ ๋ฐ๋ฅด๋ฉด, ๊ฐ ํ๋๋ ํด๋น ํ์
์ ๋ ์ฝ๋ ๊ฐ์๋ฅผ ๋ํ๋
๋๋ค.
/// According to spec document Table 15, each field represents the count of records of the corresponding type.
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 15 - ์์ด๋ ๋งคํ ํค๋, ํ 16 - ์์ด๋ ๋งคํ ๊ฐ์ ์ธ๋ฑ์ค
/// Spec mapping: Table 15 - ID mappings header, Table 16 - ID mapping count indices
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IdMappings {
/// ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ ๊ฐ์ (HWPTAG_BIN_DATA ๋ ์ฝ๋ ๊ฐ์, ํ 16 ์ธ๋ฑ์ค 0) / Binary data count (HWPTAG_BIN_DATA record count, Table 16 index 0)
pub binary_data: INT32,
/// ํ๊ธ ๊ธ๊ผด ๊ฐ์ (HWPTAG_FACE_NAME ๋ ์ฝ๋ ๊ฐ์, ํ 16 ์ธ๋ฑ์ค 1) / Korean font count (HWPTAG_FACE_NAME record count, Table 16 index 1)
pub font_korean: INT32,
/// ์์ด ๊ธ๊ผด ๊ฐ์ (HWPTAG_FACE_NAME ๋ ์ฝ๋ ๊ฐ์, ํ 16 ์ธ๋ฑ์ค 2) / English font count (HWPTAG_FACE_NAME record count, Table 16 index 2)
pub font_english: INT32,
/// ํ์ ๊ธ๊ผด ๊ฐ์ (HWPTAG_FACE_NAME ๋ ์ฝ๋ ๊ฐ์, ํ 16 ์ธ๋ฑ์ค 3) / Chinese font count (HWPTAG_FACE_NAME record count, Table 16 index 3)
pub font_chinese: INT32,
/// ์ผ์ด ๊ธ๊ผด ๊ฐ์ (HWPTAG_FACE_NAME ๋ ์ฝ๋ ๊ฐ์, ํ 16 ์ธ๋ฑ์ค 4) / Japanese font count (HWPTAG_FACE_NAME record count, Table 16 index 4)
pub font_japanese: INT32,
/// ๊ธฐํ ๊ธ๊ผด ๊ฐ์ (HWPTAG_FACE_NAME ๋ ์ฝ๋ ๊ฐ์, ํ 16 ์ธ๋ฑ์ค 5) / Other font count (HWPTAG_FACE_NAME record count, Table 16 index 5)
pub font_other: INT32,
/// ๊ธฐํธ ๊ธ๊ผด ๊ฐ์ (HWPTAG_FACE_NAME ๋ ์ฝ๋ ๊ฐ์, ํ 16 ์ธ๋ฑ์ค 6) / Symbol font count (HWPTAG_FACE_NAME record count, Table 16 index 6)
pub font_symbol: INT32,
/// ์ฌ์ฉ์ ๊ธ๊ผด ๊ฐ์ (HWPTAG_FACE_NAME ๋ ์ฝ๋ ๊ฐ์, ํ 16 ์ธ๋ฑ์ค 7) / User font count (HWPTAG_FACE_NAME record count, Table 16 index 7)
pub font_user: INT32,
/// ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ๊ฐ์ (HWPTAG_BORDER_FILL ๋ ์ฝ๋ ๋ฐฐ์ด ํฌ๊ธฐ, ํ 16 ์ธ๋ฑ์ค 8) / Border/fill count (HWPTAG_BORDER_FILL record array size, Table 16 index 8)
pub border_fill: INT32,
/// ๊ธ์ ๋ชจ์ ๊ฐ์ (HWPTAG_CHAR_SHAPE ๋ ์ฝ๋ ๋ฐฐ์ด ํฌ๊ธฐ, ํ 16 ์ธ๋ฑ์ค 9) / Character shape count (HWPTAG_CHAR_SHAPE record array size, Table 16 index 9)
pub char_shape: INT32,
/// ํญ ์ ์ ๊ฐ์ (HWPTAG_TAB_DEF ๋ ์ฝ๋ ๋ฐฐ์ด ํฌ๊ธฐ, ํ 16 ์ธ๋ฑ์ค 10) / Tab definition count (HWPTAG_TAB_DEF record array size, Table 16 index 10)
pub tab_def: INT32,
/// ๋ฌธ๋จ ๋ฒํธ ๊ฐ์ (HWPTAG_NUMBERING ๋ ์ฝ๋ ๋ฐฐ์ด ํฌ๊ธฐ, ํ 16 ์ธ๋ฑ์ค 11) / Paragraph numbering count (HWPTAG_NUMBERING record array size, Table 16 index 11)
pub paragraph_numbering: INT32,
/// ๊ธ๋จธ๋ฆฌํ ๊ฐ์ (HWPTAG_BULLET ๋ ์ฝ๋ ๋ฐฐ์ด ํฌ๊ธฐ, ํ 16 ์ธ๋ฑ์ค 12) / Bullet count (HWPTAG_BULLET record array size, Table 16 index 12)
pub bullet: INT32,
/// ๋ฌธ๋จ ๋ชจ์ ๊ฐ์ (HWPTAG_PARA_SHAPE ๋ ์ฝ๋ ๋ฐฐ์ด ํฌ๊ธฐ, ํ 16 ์ธ๋ฑ์ค 13) / Paragraph shape count (HWPTAG_PARA_SHAPE record array size, Table 16 index 13)
pub paragraph_shape: INT32,
/// ์คํ์ผ ๊ฐ์ (HWPTAG_STYLE ๋ ์ฝ๋ ๋ฐฐ์ด ํฌ๊ธฐ, ํ 16 ์ธ๋ฑ์ค 14) / Style count (HWPTAG_STYLE record array size, Table 16 index 14)
pub style: INT32,
/// ๋ฉ๋ชจ ๋ชจ์ ๊ฐ์ (5.0.2.1 ์ด์, ํ 16 ์ธ๋ฑ์ค 15) / Memo shape count (5.0.2.1 and above, Table 16 index 15)
pub memo_shape: Option<INT32>,
/// ๋ณ๊ฒฝ์ถ์ ๊ฐ์ (5.0.3.2 ์ด์, ํ 16 ์ธ๋ฑ์ค 16) / Track change count (5.0.3.2 and above, Table 16 index 16)
pub track_change: Option<INT32>,
/// ๋ณ๊ฒฝ์ถ์ ์ฌ์ฉ์ ๊ฐ์ (5.0.3.2 ์ด์, ํ 16 ์ธ๋ฑ์ค 17) / Track change author count (5.0.3.2 and above, Table 16 index 17)
pub track_change_author: Option<INT32>,
}
impl IdMappings {
/// IdMappings๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse IdMappings from byte array.
///
/// # Arguments
/// * `data` - ์ต์ 72๋ฐ์ดํธ์ ๋ฐ์ดํฐ (18๊ฐ INT32) / At least 72 bytes of data (18 INT32 values)
/// * `version` - FileHeader์ version (๋ฒ์ ์ ๋ฐ๋ผ ํ๋ ๊ฐ์๊ฐ ๋ค๋ฅผ ์ ์์) / FileHeader version (field count may vary by version)
///
/// # Returns
/// ํ์ฑ๋ IdMappings ๊ตฌ์กฐ์ฒด / Parsed IdMappings structure
pub fn parse(data: &[u8], _version: u32) -> Result<Self, HwpError> {
// ์ต์ 60๋ฐ์ดํธ (15๊ฐ INT32) ํ์ / Need at least 60 bytes (15 INT32 values)
if data.len() < 60 {
return Err(HwpError::insufficient_data("IdMappings", 60, data.len()));
}
let mut offset = 0;
// INT32 ๋ฐฐ์ด ์ฝ๊ธฐ (๊ฐ 4๋ฐ์ดํธ) / Read INT32 array (4 bytes each)
let read_int32 = |offset: &mut usize| -> INT32 {
let value = INT32::from_le_bytes([
data[*offset],
data[*offset + 1],
data[*offset + 2],
data[*offset + 3],
]);
*offset += 4;
value
};
// ๊ธฐ๋ณธ 15๊ฐ ํ๋ (60๋ฐ์ดํธ) / Basic 15 fields (60 bytes)
let binary_data = read_int32(&mut offset);
let font_korean = read_int32(&mut offset);
let font_english = read_int32(&mut offset);
let font_chinese = read_int32(&mut offset);
let font_japanese = read_int32(&mut offset);
let font_other = read_int32(&mut offset);
let font_symbol = read_int32(&mut offset);
let font_user = read_int32(&mut offset);
let border_fill = read_int32(&mut offset);
let char_shape = read_int32(&mut offset);
let tab_def = read_int32(&mut offset);
let paragraph_numbering = read_int32(&mut offset);
let bullet = read_int32(&mut offset);
let paragraph_shape = read_int32(&mut offset);
let style = read_int32(&mut offset);
// ๋ฒ์ ์ ๋ฐ๋ฅธ ์ ํ์ ํ๋ / Optional fields based on version
// ๋ ๊ฑฐ์ ์ฝ๋ ๊ธฐ์ค: version >= 5017์ผ ๋ ๋ฉ๋ชจ ๋ชจ์ ์ถ๊ฐ / Legacy code: memo shape added when version >= 5017
// ์คํ ๋ฌธ์: 5.0.2.1 ์ด์ / Spec document: 5.0.2.1 and above
// ๋ฐ์ดํฐ ํฌ๊ธฐ๋ก ํ๋จ: 64๋ฐ์ดํธ ์ด์์ด๋ฉด ๋ฉ๋ชจ ๋ชจ์ ํ๋ ์กด์ฌ / Determine by data size: memo shape field exists if 64 bytes or more
let memo_shape = if data.len() >= 64 && offset + 4 <= data.len() {
Some(read_int32(&mut offset))
} else {
None
};
// ๋ณ๊ฒฝ์ถ์ : ๋ ๊ฑฐ์ ์ฝ๋ ๊ธฐ์ค version >= 5032 / Track change: legacy code version >= 5032
// ์คํ ๋ฌธ์: 5.0.3.2 ์ด์ / Spec document: 5.0.3.2 and above
// ๋ฐ์ดํฐ ํฌ๊ธฐ๋ก ํ๋จ: 68๋ฐ์ดํธ ์ด์์ด๋ฉด ๋ณ๊ฒฝ์ถ์ ํ๋ ์กด์ฌ / Determine by data size: track change field exists if 68 bytes or more
let track_change = if data.len() >= 68 && offset + 4 <= data.len() {
Some(read_int32(&mut offset))
} else {
None
};
// ๋ณ๊ฒฝ์ถ์ ์ฌ์ฉ์: ๋ ๊ฑฐ์ ์ฝ๋ ๊ธฐ์ค version >= 5032 / Track change author: legacy code version >= 5032
// ๋ฐ์ดํฐ ํฌ๊ธฐ๋ก ํ๋จ: 72๋ฐ์ดํธ ์ด์์ด๋ฉด ๋ณ๊ฒฝ์ถ์ ์ฌ์ฉ์ ํ๋ ์กด์ฌ / Determine by data size: track change author field exists if 72 bytes or more
let track_change_author = if data.len() >= 72 && offset + 4 <= data.len() {
Some(read_int32(&mut offset))
} else {
None
};
Ok(IdMappings {
binary_data,
font_korean,
font_english,
font_chinese,
font_japanese,
font_other,
font_symbol,
font_user,
border_fill,
char_shape,
tab_def,
paragraph_numbering,
bullet,
paragraph_shape,
style,
memo_shape,
track_change,
track_change_author,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/document_properties.rs | crates/hwp-core/src/document/docinfo/document_properties.rs | /// Document Properties ๊ตฌ์กฐ์ฒด / Document Properties structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 14 - ๋ฌธ์ ์์ฑ / Spec mapping: Table 14 - Document properties
/// Tag ID: HWPTAG_DOCUMENT_PROPERTIES
/// ์ ์ฒด ๊ธธ์ด: 26 ๋ฐ์ดํธ / Total length: 26 bytes
use crate::error::HwpError;
use crate::types::{UINT16, UINT32};
use serde::{Deserialize, Serialize};
/// ๋ฌธ์ ์์ฑ ๊ตฌ์กฐ์ฒด / Document properties structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocumentProperties {
/// ๊ตฌ์ญ ๊ฐ์ / Area count
pub area_count: UINT16,
/// ๋ฌธ์ ๋ด ๊ฐ์ข
์์๋ฒํธ์ ๋ํ ์ ๋ณด / Start number information
pub start_number_info: UINT16,
/// ํ์ด์ง ์์ ๋ฒํธ / Page start number
pub page_start_number: UINT16,
/// ๊ฐ์ฃผ ์์ ๋ฒํธ / Footnote start number
pub footnote_start_number: UINT16,
/// ๋ฏธ์ฃผ ์์ ๋ฒํธ / Endnote start number
pub endnote_start_number: UINT16,
/// ๊ทธ๋ฆผ ์์ ๋ฒํธ / Image start number
pub image_start_number: UINT16,
/// ํ ์์ ๋ฒํธ / Table start number
pub table_start_number: UINT16,
/// ์์ ์์ ๋ฒํธ / Formula start number
pub formula_start_number: UINT16,
/// ๋ฌธ์ ๋ด ์บ๋ฟ์ ์์น ์ ๋ณด (๋ฆฌ์คํธ ์์ด๋) / Caret position information in document (list ID)
pub list_id: UINT32,
/// ๋ฌธ๋จ ์์ด๋ / Paragraph ID
pub paragraph_id: UINT32,
/// ๋ฌธ๋จ ๋ด์์์ ๊ธ์ ๋จ์ ์์น / Character position within paragraph
pub character_position: UINT32,
}
impl DocumentProperties {
/// DocumentProperties๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse DocumentProperties from byte array.
///
/// # Arguments
/// * `data` - ์ต์ 26๋ฐ์ดํธ์ ๋ฐ์ดํฐ / At least 26 bytes of data
///
/// # Returns
/// ํ์ฑ๋ DocumentProperties ๊ตฌ์กฐ์ฒด / Parsed DocumentProperties structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ๋ ๊ฑฐ์ ์ฝ๋ ๊ธฐ์ค์ผ๋ก 26๋ฐ์ดํธ๋ฅผ ์ฝ์
// Read 26 bytes based on legacy code
if data.len() < 26 {
return Err(HwpError::insufficient_data("DocumentProperties", 26, data.len()));
}
let mut offset = 0;
// UINT16 ๊ตฌ์ญ ๊ฐ์ / UINT16 area count
let area_count = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT16 ํ์ด์ง ์์ ๋ฒํธ / UINT16 page start number
// Note: ๋ ๊ฑฐ์ ์ฝ๋์์๋ "๋ฌธ์ ๋ด ๊ฐ์ข
์์๋ฒํธ์ ๋ํ ์ ๋ณด" ํ๋๋ฅผ ๊ฑด๋๋ฐ๊ณ ๋ฐ๋ก ํ์ด์ง ์์ ๋ฒํธ๋ฅผ ์ฝ์
// Note: Legacy code skips "start number information" field and reads page_start_number directly
let page_start_number = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT16 ๊ฐ์ฃผ ์์ ๋ฒํธ / UINT16 footnote start number
let footnote_start_number = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT16 ๋ฏธ์ฃผ ์์ ๋ฒํธ / UINT16 endnote start number
let endnote_start_number = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT16 ๊ทธ๋ฆผ ์์ ๋ฒํธ / UINT16 image start number
let image_start_number = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT16 ํ ์์ ๋ฒํธ / UINT16 table start number
let table_start_number = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT16 ์์ ์์ ๋ฒํธ / UINT16 formula start number
let formula_start_number = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT32 ๋ฌธ์ ๋ด ์บ๋ฟ์ ์์น ์ ๋ณด (๋ฆฌ์คํธ ์์ด๋) / UINT32 caret position (list ID)
let list_id = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// UINT32 ๋ฌธ๋จ ์์ด๋ / UINT32 paragraph ID
let paragraph_id = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// UINT32 ๋ฌธ๋จ ๋ด์์์ ๊ธ์ ๋จ์ ์์น / UINT32 character position within paragraph
let character_position = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
Ok(DocumentProperties {
area_count,
start_number_info: 0, // ๋ ๊ฑฐ์ ์ฝ๋์์๋ ์ด ํ๋๋ฅผ ๊ฑด๋๋ / This field is skipped in legacy code
page_start_number,
footnote_start_number,
endnote_start_number,
image_start_number,
table_start_number,
formula_start_number,
list_id,
paragraph_id,
character_position,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/tab_def.rs | crates/hwp-core/src/document/docinfo/tab_def.rs | /// Tab Definition ๊ตฌ์กฐ์ฒด / Tab Definition structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 36 - ํญ ์ ์ / Spec mapping: Table 36 - Tab definition
/// Tag ID: HWPTAG_TAB_DEF
/// ์ ์ฒด ๊ธธ์ด: ๊ฐ๋ณ (8 + 8รcount ๋ฐ์ดํธ) / Total length: variable (8 + 8รcount bytes)
use crate::error::HwpError;
use crate::types::{HWPUNIT, INT16, UINT32, UINT8};
use serde::{Deserialize, Serialize};
/// ํญ ์ข
๋ฅ / Tab type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TabType {
/// ์ผ์ชฝ / Left
Left = 0,
/// ์ค๋ฅธ์ชฝ / Right
Right = 1,
/// ๊ฐ์ด๋ฐ / Center
Center = 2,
/// ์์์ / Decimal
Decimal = 3,
}
impl TabType {
/// UINT8 ๊ฐ์์ TabType ์์ฑ / Create TabType from UINT8 value
fn from_byte(value: UINT8) -> Self {
match value {
1 => TabType::Right,
2 => TabType::Center,
3 => TabType::Decimal,
_ => TabType::Left,
}
}
}
/// ํญ ์ ์ ์์ฑ / Tab definition attributes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TabDefAttributes {
/// ๋ฌธ๋จ ์ผ์ชฝ ๋ ์๋ ํญ(๋ด์ด ์ฐ๊ธฐ์ฉ ์๋ ํญ) ์ ๋ฌด / Auto tab at paragraph left edge (hanging indent)
pub has_left_auto_tab: bool,
/// ๋ฌธ๋จ ์ค๋ฅธ์ชฝ ๋ ์๋ ํญ ์ ๋ฌด / Auto tab at paragraph right edge
pub has_right_auto_tab: bool,
}
/// ํญ ํญ๋ชฉ / Tab item
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TabItem {
/// ํญ์ ์์น / Tab position
pub position: HWPUNIT,
/// ํญ์ ์ข
๋ฅ / Tab type
pub tab_type: TabType,
/// ์ฑ์ ์ข
๋ฅ (ํ 25 ์ฐธ์กฐ) / Fill type (Table 25)
pub fill_type: UINT8,
}
/// Tab Definition ๊ตฌ์กฐ์ฒด / Tab Definition structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TabDef {
/// ์์ฑ (ํ 37) / Attributes (Table 37)
pub attributes: TabDefAttributes,
/// ํญ ๊ฐ์ / Tab count
pub count: INT16,
/// ํญ ํญ๋ชฉ ๋ชฉ๋ก / Tab items list
pub tabs: Vec<TabItem>,
}
impl TabDef {
/// TabDef๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse TabDef from byte array.
///
/// # Arguments
/// * `data` - TabDef ๋ ์ฝ๋ ๋ฐ์ดํฐ / TabDef record data
///
/// # Returns
/// ํ์ฑ๋ TabDef ๊ตฌ์กฐ์ฒด / Parsed TabDef structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ์ต์ 6๋ฐ์ดํธ ํ์ (์์ฑ 4๋ฐ์ดํธ + count 2๋ฐ์ดํธ) / Need at least 6 bytes (attributes 4 bytes + count 2 bytes)
if data.len() < 6 {
return Err(HwpError::insufficient_data("TabDef", 6, data.len()));
}
let mut offset = 0;
// UINT32 ์์ฑ (ํ 37) / UINT32 attributes (Table 37)
let attr_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let attributes = TabDefAttributes {
has_left_auto_tab: (attr_value & 0x00000001) != 0,
has_right_auto_tab: (attr_value & 0x00000002) != 0,
};
// INT16 count / INT16 count
let count = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// ํญ ํญ๋ชฉ ํ์ฑ (๊ฐ 8๋ฐ์ดํธ) / Parse tab items (8 bytes each)
let mut tabs = Vec::new();
for _ in 0..count {
if offset + 8 > data.len() {
return Err(HwpError::InsufficientData {
field: format!("TabDef tab item at offset {}", offset),
expected: offset + 8,
actual: data.len(),
});
}
// HWPUNIT ํญ์ ์์น / HWPUNIT tab position
let position = HWPUNIT(u32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// UINT8 ํญ์ ์ข
๋ฅ / UINT8 tab type
let tab_type = TabType::from_byte(data[offset]);
offset += 1;
// UINT8 ์ฑ์ ์ข
๋ฅ / UINT8 fill type
let fill_type = data[offset];
offset += 1;
// UINT16 ์์ฝ (8๋ฐ์ดํธ ๋ง์ถค์ฉ) / UINT16 reserved (for 8-byte alignment)
offset += 2;
tabs.push(TabItem {
position,
tab_type,
fill_type,
});
}
Ok(TabDef {
attributes,
count,
tabs,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/char_shape.rs | crates/hwp-core/src/document/docinfo/char_shape.rs | /// Character Shape ๊ตฌ์กฐ์ฒด / Character Shape structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 33 - ๊ธ์ ๋ชจ์ / Spec mapping: Table 33 - Character shape
/// Tag ID: HWPTAG_CHAR_SHAPE
/// ์ ์ฒด ๊ธธ์ด: 72 ๋ฐ์ดํธ / Total length: 72 bytes
use crate::error::HwpError;
use crate::types::{COLORREF, INT32, INT8, UINT16, UINT32, UINT8, WORD};
use serde::{Deserialize, Serialize};
/// ์ธ์ด๋ณ ๊ธ๊ผด ์ ๋ณด / Language-specific font information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LanguageFontInfo {
/// ํ๊ธ ๊ธ๊ผด ID / Korean font ID
pub korean: WORD,
/// ์์ด ๊ธ๊ผด ID / English font ID
pub english: WORD,
/// ํ์ ๊ธ๊ผด ID / Chinese font ID
pub chinese: WORD,
/// ์ผ์ด ๊ธ๊ผด ID / Japanese font ID
pub japanese: WORD,
/// ๊ธฐํ ๊ธ๊ผด ID / Other font ID
pub other: WORD,
/// ๊ธฐํธ ๊ธ๊ผด ID / Symbol font ID
pub symbol: WORD,
/// ์ฌ์ฉ์ ๊ธ๊ผด ID / User font ID
pub user: WORD,
}
/// ์ธ์ด๋ณ ๊ธ์ ์์ฑ ์ ๋ณด (UINT8) / Language-specific character attribute information (UINT8)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LanguageCharAttributesU8 {
/// ํ๊ธ / Korean
pub korean: UINT8,
/// ์์ด / English
pub english: UINT8,
/// ํ์ / Chinese
pub chinese: UINT8,
/// ์ผ์ด / Japanese
pub japanese: UINT8,
/// ๊ธฐํ / Other
pub other: UINT8,
/// ๊ธฐํธ / Symbol
pub symbol: UINT8,
/// ์ฌ์ฉ์ / User
pub user: UINT8,
}
/// ์ธ์ด๋ณ ๊ธ์ ์์ฑ ์ ๋ณด (INT8) / Language-specific character attribute information (INT8)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LanguageCharAttributesI8 {
/// ํ๊ธ / Korean
pub korean: INT8,
/// ์์ด / English
pub english: INT8,
/// ํ์ / Chinese
pub chinese: INT8,
/// ์ผ์ด / Japanese
pub japanese: INT8,
/// ๊ธฐํ / Other
pub other: INT8,
/// ๊ธฐํธ / Symbol
pub symbol: INT8,
/// ์ฌ์ฉ์ / User
pub user: INT8,
}
/// ๊ธ์ ๋ชจ์ ์์ฑ / Character shape attributes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CharShapeAttributes {
/// ๊ธฐ์ธ์ ์ฌ๋ถ / Italic
pub italic: bool,
/// ์งํ๊ฒ ์ฌ๋ถ / Bold
pub bold: bool,
/// ๋ฐ์ค ์ข
๋ฅ (0: ์์, 1: ๊ธ์ ์๋, 2: ๊ธ์ ์) / Underline type (0: none, 1: below, 2: above)
pub underline_type: UINT8, // bits 2-3
/// ๋ฐ์ค ๋ชจ์ (0-6) / Underline style (0-6)
pub underline_style: UINT8, // bits 4-7
/// ์ธ๊ณฝ์ ์ข
๋ฅ (0: ์์, 1: ๋น์ฐ์, 2: ์ฐ์) / Outline type (0: none, 1: non-continuous, 2: continuous)
pub outline_type: UINT8, // bits 8-10
/// ๊ทธ๋ฆผ์ ์ข
๋ฅ / Shadow type
pub shadow_type: UINT8, // bits 11-12
/// ์๊ฐ ์ฌ๋ถ / Emboss
pub emboss: bool, // bit 13
/// ์๊ฐ ์ฌ๋ถ / Engrave
pub engrave: bool, // bit 14
/// ์ ์ฒจ์ ์ฌ๋ถ / Superscript
pub superscript: bool, // bit 15
/// ์๋ ์ฒจ์ ์ฌ๋ถ / Subscript
pub subscript: bool, // bit 16
/// ์ทจ์์ ์ฌ๋ถ (0: ์์, 1 ์ด์: ์์) / Strikethrough (0: none, 1+: present)
/// ์คํ ๋ฌธ์ ํ 35: bit 18-20 / Spec Table 35: bit 18-20
pub strikethrough: UINT8,
/// ๊ฐ์กฐ์ ์ข
๋ฅ / Emphasis mark type
pub emphasis_mark: UINT8, // bits 21-24
/// ๊ธ๊ผด์ ์ด์ธ๋ฆฌ๋ ๋น์นธ ์ฌ์ฉ ์ฌ๋ถ / Use font-appropriate spacing
pub use_font_spacing: bool, // bit 25
/// ์ทจ์์ ๋ชจ์ (ํ 25 ์ฐธ์กฐ) / Strikethrough style (Table 25)
pub strikethrough_style: UINT8, // bits 26-29
/// Kerning ์ฌ๋ถ / Kerning
pub kerning: bool, // bit 30
}
/// Character Shape ๊ตฌ์กฐ์ฒด / Character Shape structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CharShape {
/// ์ธ์ด๋ณ ๊ธ๊ผด ID (ํ 34) / Language-specific font IDs (Table 34)
pub font_ids: LanguageFontInfo,
/// ์ธ์ด๋ณ ์ฅํ, 50%~200% / Language-specific font stretch, 50%~200%
pub font_stretch: LanguageCharAttributesU8,
/// ์ธ์ด๋ณ ์๊ฐ, -50%~50% / Language-specific letter spacing, -50%~50%
pub letter_spacing: LanguageCharAttributesI8,
/// ์ธ์ด๋ณ ์๋ ํฌ๊ธฐ, 10%~250% / Language-specific relative size, 10%~250%
pub relative_size: LanguageCharAttributesU8,
/// ์ธ์ด๋ณ ๊ธ์ ์์น, -100%~100% / Language-specific text position, -100%~100%
pub text_position: LanguageCharAttributesI8,
/// ๊ธฐ์ค ํฌ๊ธฐ, 0pt~4096pt / Base size, 0pt~4096pt
pub base_size: INT32,
/// ์์ฑ (ํ 35) / Attributes (Table 35)
pub attributes: CharShapeAttributes,
/// ๊ทธ๋ฆผ์ ๊ฐ๊ฒฉ X, -100%~100% / Shadow spacing X, -100%~100%
pub shadow_spacing_x: INT8,
/// ๊ทธ๋ฆผ์ ๊ฐ๊ฒฉ Y, -100%~100% / Shadow spacing Y, -100%~100%
pub shadow_spacing_y: INT8,
/// ๊ธ์ ์ / Text color
pub text_color: COLORREF,
/// ๋ฐ์ค ์ / Underline color
pub underline_color: COLORREF,
/// ์์ ์ / Shading color
pub shading_color: COLORREF,
/// ๊ทธ๋ฆผ์ ์ / Shadow color
pub shadow_color: COLORREF,
/// ๊ธ์ ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ID (5.0.2.1 ์ด์) / Character border/fill ID (5.0.2.1 and above)
pub border_fill_id: Option<UINT16>,
/// ์ทจ์์ ์ (5.0.3.0 ์ด์) / Strikethrough color (5.0.3.0 and above)
pub strikethrough_color: Option<COLORREF>,
}
impl CharShape {
/// CharShape๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse CharShape from byte array.
///
/// # Arguments
/// * `data` - ์ต์ 66๋ฐ์ดํธ์ ๋ฐ์ดํฐ (๊ธฐ๋ณธ 66๋ฐ์ดํธ, ๋ฒ์ ์ ๋ฐ๋ผ ์ต๋ 72๋ฐ์ดํธ) / At least 66 bytes of data (basic 66 bytes, up to 72 bytes depending on version)
/// * `version` - FileHeader์ version (๋ฒ์ ์ ๋ฐ๋ผ ํ๋ ๊ฐ์๊ฐ ๋ค๋ฅผ ์ ์์) / FileHeader version (field count may vary by version)
///
/// # Returns
/// ํ์ฑ๋ CharShape ๊ตฌ์กฐ์ฒด / Parsed CharShape structure
pub fn parse(data: &[u8], _version: u32) -> Result<Self, HwpError> {
// ์ต์ 66๋ฐ์ดํธ ํ์ / Need at least 66 bytes
if data.len() < 66 {
return Err(HwpError::insufficient_data("CharShape", 66, data.len()));
}
let mut offset = 0;
// WORD array[7] ์ธ์ด๋ณ ๊ธ๊ผด ID / WORD array[7] language-specific font IDs
let font_ids = LanguageFontInfo {
korean: WORD::from_le_bytes([data[offset], data[offset + 1]]),
english: WORD::from_le_bytes([data[offset + 2], data[offset + 3]]),
chinese: WORD::from_le_bytes([data[offset + 4], data[offset + 5]]),
japanese: WORD::from_le_bytes([data[offset + 6], data[offset + 7]]),
other: WORD::from_le_bytes([data[offset + 8], data[offset + 9]]),
symbol: WORD::from_le_bytes([data[offset + 10], data[offset + 11]]),
user: WORD::from_le_bytes([data[offset + 12], data[offset + 13]]),
};
offset += 14;
// UINT8 array[7] ์ธ์ด๋ณ ์ฅํ / UINT8 array[7] language-specific font stretch
let font_stretch = LanguageCharAttributesU8 {
korean: data[offset] as UINT8,
english: data[offset + 1] as UINT8,
chinese: data[offset + 2] as UINT8,
japanese: data[offset + 3] as UINT8,
other: data[offset + 4] as UINT8,
symbol: data[offset + 5] as UINT8,
user: data[offset + 6] as UINT8,
};
offset += 7;
// INT8 array[7] ์ธ์ด๋ณ ์๊ฐ / INT8 array[7] language-specific letter spacing
// u8์ i8๋ก ์บ์คํ
ํ ๋ ๋ถํธ ํ์ฅ์ด ์ ๋๋ก ๋๋๋ก i8::from_le_bytes ์ฌ์ฉ
// Use i8::from_le_bytes to properly handle sign extension when casting u8 to i8
let letter_spacing = LanguageCharAttributesI8 {
korean: i8::from_le_bytes([data[offset]]),
english: i8::from_le_bytes([data[offset + 1]]),
chinese: i8::from_le_bytes([data[offset + 2]]),
japanese: i8::from_le_bytes([data[offset + 3]]),
other: i8::from_le_bytes([data[offset + 4]]),
symbol: i8::from_le_bytes([data[offset + 5]]),
user: i8::from_le_bytes([data[offset + 6]]),
};
offset += 7;
// UINT8 array[7] ์ธ์ด๋ณ ์๋ ํฌ๊ธฐ / UINT8 array[7] language-specific relative size
let relative_size = LanguageCharAttributesU8 {
korean: data[offset] as UINT8,
english: data[offset + 1] as UINT8,
chinese: data[offset + 2] as UINT8,
japanese: data[offset + 3] as UINT8,
other: data[offset + 4] as UINT8,
symbol: data[offset + 5] as UINT8,
user: data[offset + 6] as UINT8,
};
offset += 7;
// INT8 array[7] ์ธ์ด๋ณ ๊ธ์ ์์น / INT8 array[7] language-specific text position
// u8์ i8๋ก ์บ์คํ
ํ ๋ ๋ถํธ ํ์ฅ์ด ์ ๋๋ก ๋๋๋ก i8::from_le_bytes ์ฌ์ฉ
// Use i8::from_le_bytes to properly handle sign extension when casting u8 to i8
let text_position = LanguageCharAttributesI8 {
korean: i8::from_le_bytes([data[offset]]),
english: i8::from_le_bytes([data[offset + 1]]),
chinese: i8::from_le_bytes([data[offset + 2]]),
japanese: i8::from_le_bytes([data[offset + 3]]),
other: i8::from_le_bytes([data[offset + 4]]),
symbol: i8::from_le_bytes([data[offset + 5]]),
user: i8::from_le_bytes([data[offset + 6]]),
};
offset += 7;
// INT32 ๊ธฐ์ค ํฌ๊ธฐ / INT32 base size
let base_size = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// UINT32 ์์ฑ (ํ 35) / UINT32 attributes (Table 35)
let attr_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// UINT32 ์์ฑ ํ์ฑ (ํ 35) / Parse UINT32 attributes (Table 35)
let attributes = CharShapeAttributes {
italic: (attr_value & 0x00000001) != 0,
bold: (attr_value & 0x00000002) != 0,
underline_type: ((attr_value >> 2) & 0x03) as UINT8,
underline_style: ((attr_value >> 4) & 0x0F) as UINT8,
outline_type: ((attr_value >> 8) & 0x07) as UINT8,
shadow_type: ((attr_value >> 11) & 0x03) as UINT8,
emboss: (attr_value & 0x00002000) != 0,
engrave: (attr_value & 0x00004000) != 0,
superscript: (attr_value & 0x00008000) != 0,
subscript: (attr_value & 0x00010000) != 0,
strikethrough: ((attr_value >> 18) & 0x07) as UINT8, // bit 18-20: ์ทจ์์ ์ฌ๋ถ (ํ 35) / bit 18-20: Strikethrough (Table 35)
emphasis_mark: ((attr_value >> 21) & 0x0F) as UINT8,
use_font_spacing: (attr_value & 0x02000000) != 0,
strikethrough_style: ((attr_value >> 26) & 0x0F) as UINT8,
kerning: (attr_value & 0x40000000) != 0,
};
// INT8 ๊ทธ๋ฆผ์ ๊ฐ๊ฒฉ X / INT8 shadow spacing X
let shadow_spacing_x = data[offset] as INT8;
offset += 1;
// INT8 ๊ทธ๋ฆผ์ ๊ฐ๊ฒฉ Y / INT8 shadow spacing Y
let shadow_spacing_y = data[offset] as INT8;
offset += 1;
// COLORREF ๊ธ์ ์ / COLORREF text color
let text_color = COLORREF(u32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// COLORREF ๋ฐ์ค ์ / COLORREF underline color
let underline_color = COLORREF(u32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// COLORREF ์์ ์ / COLORREF shading color
let shading_color = COLORREF(u32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// COLORREF ๊ทธ๋ฆผ์ ์ / COLORREF shadow color
let shadow_color = COLORREF(u32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// UINT16 ๊ธ์ ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ID (5.0.2.1 ์ด์) / UINT16 character border/fill ID (5.0.2.1 and above)
// ๋ฐ์ดํฐ ํฌ๊ธฐ๋ก ํ๋จ: 66๋ฐ์ดํธ ์ด์์ด๋ฉด border_fill_id ํ๋ ์กด์ฌ / Determine by data size: border_fill_id exists if 66 bytes or more
let border_fill_id = if data.len() >= 66 && offset + 2 <= data.len() {
Some(WORD::from_le_bytes([data[offset], data[offset + 1]]))
} else {
None
};
if border_fill_id.is_some() {
offset += 2;
}
// COLORREF ์ทจ์์ ์ (5.0.3.0 ์ด์) / COLORREF strikethrough color (5.0.3.0 and above)
// ๋ฐ์ดํฐ ํฌ๊ธฐ๋ก ํ๋จ: 70๋ฐ์ดํธ ์ด์์ด๋ฉด strikethrough_color ํ๋ ์กด์ฌ / Determine by data size: strikethrough_color exists if 70 bytes or more
let strikethrough_color = if data.len() >= 70 && offset + 4 <= data.len() {
Some(COLORREF(u32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
])))
} else {
None
};
Ok(CharShape {
font_ids,
font_stretch,
letter_spacing,
relative_size,
text_position,
base_size,
attributes,
shadow_spacing_x,
shadow_spacing_y,
text_color,
underline_color,
shading_color,
shadow_color,
border_fill_id,
strikethrough_color,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/border_fill.rs | crates/hwp-core/src/document/docinfo/border_fill.rs | /// Border/Fill ๊ตฌ์กฐ์ฒด / Border/Fill structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 23 - ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์ฑ / Spec mapping: Table 23 - Border/fill properties
/// Tag ID: HWPTAG_BORDER_FILL
use crate::error::HwpError;
use crate::types::{BYTE, COLORREF, INT16, INT32, UINT, UINT16, UINT8};
use serde::{Deserialize, Serialize};
/// ํ
๋๋ฆฌ์ ์ ๋ณด / Border line information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BorderLine {
/// ํ
๋๋ฆฌ์ ์ข
๋ฅ (ํ 25) / Border line type (Table 25)
pub line_type: UINT8,
/// ํ
๋๋ฆฌ์ ๊ตต๊ธฐ (ํ 26) / Border line width (Table 26)
pub width: UINT8,
/// ํ
๋๋ฆฌ์ ์์ / Border line color
pub color: COLORREF,
}
/// ๋๊ฐ์ ์ ๋ณด / Diagonal line information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagonalLine {
/// ๋๊ฐ์ ์ข
๋ฅ (ํ 27) / Diagonal line type (Table 27)
pub line_type: UINT8,
/// ๋๊ฐ์ ๊ตต๊ธฐ / Diagonal line thickness
pub thickness: UINT8,
/// ๋๊ฐ์ ์์ / Diagonal line color
pub color: COLORREF,
}
/// ์ฑ์ฐ๊ธฐ ์ข
๋ฅ / Fill type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum FillType {
/// ์ฑ์ฐ๊ธฐ ์์ / No fill
None = 0x00000000,
/// ๋จ์ ์ฑ์ฐ๊ธฐ / Solid fill
Solid = 0x00000001,
/// ์ด๋ฏธ์ง ์ฑ์ฐ๊ธฐ / Image fill
Image = 0x00000002,
/// ๊ทธ๋ฌ๋ฐ์ด์
์ฑ์ฐ๊ธฐ / Gradient fill
Gradient = 0x00000004,
}
/// ๋จ์ ์ฑ์ฐ๊ธฐ ์ ๋ณด / Solid fill information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SolidFill {
/// ๋ฐฐ๊ฒฝ์ / Background color
pub background_color: COLORREF,
/// ๋ฌด๋ฌ์ / Pattern color
pub pattern_color: COLORREF,
/// ๋ฌด๋ฌ ์ข
๋ฅ (ํ 29) / Pattern type (Table 29)
pub pattern_type: INT32,
}
/// ๊ทธ๋ฌ๋ฐ์ด์
์ฑ์ฐ๊ธฐ ์ ๋ณด / Gradient fill information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GradientFill {
/// ๊ทธ๋ฌ๋ฐ์ด์
์ ํ (ํ 30) / Gradient type (Table 30)
pub gradient_type: INT16,
/// ๊ทธ๋ฌ๋ฐ์ด์
์ ๊ธฐ์ธ์(์์ ๊ฐ) / Gradient angle (start angle)
pub angle: INT16,
/// ๊ทธ๋ฌ๋ฐ์ด์
์ ๊ฐ๋ก ์ค์ฌ(์ค์ฌ X ์ขํ) / Gradient horizontal center (center X coordinate)
pub horizontal_center: INT16,
/// ๊ทธ๋ฌ๋ฐ์ด์
์ ์ธ๋ก ์ค์ฌ(์ค์ฌ Y ์ขํ) / Gradient vertical center (center Y coordinate)
pub vertical_center: INT16,
/// ๊ทธ๋ฌ๋ฐ์ด์
๋ฒ์ง ์ ๋(0-100) / Gradient spread (0-100)
pub spread: INT16,
/// ๊ทธ๋ฌ๋ฐ์ด์
์ ์ ์ / Number of gradient colors
pub color_count: INT16,
/// ์์์ด ๋ฐ๋๋ ๊ณณ์ ์์น (color_count > 2์ผ ๊ฒฝ์ฐ์๋ง) / Color change positions (only if color_count > 2)
pub positions: Option<Vec<INT32>>,
/// ์์ ๋ฐฐ์ด / Color array
pub colors: Vec<COLORREF>,
}
/// ์ด๋ฏธ์ง ์ฑ์ฐ๊ธฐ ์ ๋ณด / Image fill information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageFill {
/// ์ด๋ฏธ์ง ์ฑ์ฐ๊ธฐ ์ ํ (ํ 31) / Image fill type (Table 31)
pub image_fill_type: BYTE,
/// ๊ทธ๋ฆผ ์ ๋ณด (ํ 32) / Image information (Table 32)
pub image_info: Vec<u8>, // 5 bytes
/// ๊ทธ๋ฌ๋ฐ์ด์
๋ฒ์ง์ ๋์ ์ค์ฌ (0..100) / Gradient spread center (0..100)
pub gradient_spread_center: Option<BYTE>,
/// ์ถ๊ฐ ์ฑ์ฐ๊ธฐ ์์ฑ ๊ธธ์ด / Additional fill attribute length
pub additional_attributes_length: Option<UINT>,
/// ์ถ๊ฐ ์ฑ์ฐ๊ธฐ ์์ฑ / Additional fill attributes
pub additional_attributes: Option<Vec<u8>>,
}
/// ์ฑ์ฐ๊ธฐ ์ ๋ณด / Fill information
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "lowercase")]
#[allow(dead_code)]
pub enum FillInfo {
/// ์ฑ์ฐ๊ธฐ ์์ / No fill
None,
/// ๋จ์ ์ฑ์ฐ๊ธฐ / Solid fill
Solid(SolidFill),
/// ์ด๋ฏธ์ง ์ฑ์ฐ๊ธฐ / Image fill
Image(ImageFill),
/// ๊ทธ๋ฌ๋ฐ์ด์
์ฑ์ฐ๊ธฐ / Gradient fill
Gradient(GradientFill),
}
/// ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์ฑ / Border/fill properties
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BorderFill {
/// ์์ฑ (ํ 24) / Attributes (Table 24)
pub attributes: BorderFillAttributes,
/// 4๋ฐฉํฅ ํ
๋๋ฆฌ์ ์ ๋ณด / 4-direction border line information
pub borders: [BorderLine; 4], // [Left, Right, Top, Bottom]
/// ๋๊ฐ์ ์ ๋ณด / Diagonal line information
pub diagonal: DiagonalLine,
/// ์ฑ์ฐ๊ธฐ ์ ๋ณด / Fill information
pub fill: FillInfo,
}
/// ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์ฑ ๋นํธ ํ๋๊ทธ / Border/fill attribute bit flags
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BorderFillAttributes {
/// 3D ํจ๊ณผ์ ์ ๋ฌด / 3D effect presence
pub has_3d_effect: bool,
/// ๊ทธ๋ฆผ์ ํจ๊ณผ์ ์ ๋ฌด / Shadow effect presence
pub has_shadow: bool,
/// Slash ๋๊ฐ์ ๋ชจ์ / Slash diagonal shape
pub slash_shape: u8, // bits 2-4
/// BackSlash ๋๊ฐ์ ๋ชจ์ / BackSlash diagonal shape
pub backslash_shape: u8, // bits 5-7
/// Slash ๋๊ฐ์ ๊บฝ์์ / Slash diagonal broken line
pub slash_broken_line: u8, // bits 8-9
/// BackSlash ๋๊ฐ์ ๊บฝ์์ / BackSlash diagonal broken line
pub backslash_broken_line: bool, // bit 10
/// Slash ๋๊ฐ์ ๋ชจ์ 180๋ ํ์ ์ฌ๋ถ / Slash diagonal 180 degree rotation
pub slash_rotated_180: bool, // bit 11
/// BackSlash ๋๊ฐ์ ๋ชจ์ 180๋ ํ์ ์ฌ๋ถ / BackSlash diagonal 180 degree rotation
pub backslash_rotated_180: bool, // bit 12
/// ์ค์ฌ์ ์ ๋ฌด / Center line presence
pub has_center_line: bool, // bit 13
}
impl BorderFill {
/// BorderFill์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse BorderFill from byte array.
///
/// # Arguments
/// * `data` - BorderFill ๋ ์ฝ๋ ๋ฐ์ดํฐ / BorderFill record data
///
/// # Returns
/// ํ์ฑ๋ BorderFill ๊ตฌ์กฐ์ฒด / Parsed BorderFill structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 32 {
return Err(HwpError::insufficient_data("BorderFill", 32, data.len()));
}
let mut offset = 0;
// UINT16 ์์ฑ (ํ 24) / UINT16 attributes (Table 24)
let attr_value = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let attributes = BorderFillAttributes {
has_3d_effect: (attr_value & 0x0001) != 0,
has_shadow: (attr_value & 0x0002) != 0,
slash_shape: ((attr_value >> 2) & 0x07) as u8,
backslash_shape: ((attr_value >> 5) & 0x07) as u8,
slash_broken_line: ((attr_value >> 8) & 0x03) as u8,
backslash_broken_line: (attr_value & 0x0400) != 0,
slash_rotated_180: (attr_value & 0x0800) != 0,
backslash_rotated_180: (attr_value & 0x1000) != 0,
has_center_line: (attr_value & 0x2000) != 0,
};
// NOTE:
// BorderFill์ ์ค์ ์ ์ฅ ํฌ๋งท์ ๊ตฌํ์ฒด/๋ฒ์ ์ ๋ฐ๋ผ 2๊ฐ์ง๊ฐ ๊ด์ฐฐ๋จ.
// (A) ์คํ(ํ 23): line_types[4] -> widths[4] -> colors[4]
// (B) ๋ ๊ฑฐ์(hwpjs.js): (line_type, width, color) * 4 (Left, Right, Top, Bottom) interleave
// ์ฌ๊ธฐ์๋ ๋ ๋ค ํ์ฑํด๋ณด๊ณ โ๋ ๊ทธ๋ด๋ฏํโ ๊ฒฐ๊ณผ๋ฅผ ์ ํํ๋ค.
if data.len() < offset + 24 + 1 + 1 + 4 {
return Err(HwpError::insufficient_data(
"BorderFill (borders+diagonal)",
offset + 24 + 1 + 1 + 4,
data.len(),
));
}
fn score_borderline(line: &BorderLine) -> i32 {
let mut s = 0;
// width๋ ํ 26: 0..=15
if line.width <= 15 {
s += 3;
} else {
s -= 10;
}
// line_type๋ ํ 25: 0..=16 (์ค๋ฌด์์ ํ์ฅ๊ฐ์ด ์์ ์ ์์ด ์ฝ๊ฐ ์ํ)
if line.line_type <= 32 {
s += 2;
} else {
s -= 5;
}
// color๋ COLORREF์ด๋ฏ๋ก ์ด๋ค ๊ฐ์ด๋ ๊ฐ๋ฅํ์ง๋ง, 0xFFFFFFFF ๊ฐ์ ๊ทน๋จ๊ฐ์ ๊ฐ์
if line.color.0 == 0xFFFFFFFF {
s -= 2;
}
s
}
fn score_borders(borders: &[BorderLine; 4]) -> i32 {
borders.iter().map(score_borderline).sum()
}
let start = offset;
// (B) interleave: (line, width, color) * 4
let mut borders_interleave: [BorderLine; 4] = [
BorderLine {
line_type: 0,
width: 0,
color: COLORREF(0),
},
BorderLine {
line_type: 0,
width: 0,
color: COLORREF(0),
},
BorderLine {
line_type: 0,
width: 0,
color: COLORREF(0),
},
BorderLine {
line_type: 0,
width: 0,
color: COLORREF(0),
},
];
let mut off_i = start;
for i in 0..4 {
let line_type = data[off_i];
off_i += 1;
let width = data[off_i];
off_i += 1;
let color = COLORREF(u32::from_le_bytes([
data[off_i],
data[off_i + 1],
data[off_i + 2],
data[off_i + 3],
]));
off_i += 4;
borders_interleave[i] = BorderLine {
line_type,
width,
color,
};
}
// (A) spec arrays: line_types[4], widths[4], colors[4]
let mut borders_spec: [BorderLine; 4] = borders_interleave.clone();
let mut off_s = start;
let line_types = [
data[off_s],
data[off_s + 1],
data[off_s + 2],
data[off_s + 3],
];
off_s += 4;
let widths = [
data[off_s],
data[off_s + 1],
data[off_s + 2],
data[off_s + 3],
];
off_s += 4;
let mut colors = [COLORREF(0); 4];
for i in 0..4 {
colors[i] = COLORREF(u32::from_le_bytes([
data[off_s],
data[off_s + 1],
data[off_s + 2],
data[off_s + 3],
]));
off_s += 4;
}
for i in 0..4 {
borders_spec[i] = BorderLine {
line_type: line_types[i],
width: widths[i],
color: colors[i],
};
}
// ์ ์ ๋น๊ต๋ก ์ ํ
let score_i = score_borders(&borders_interleave);
let score_s = score_borders(&borders_spec);
let borders = if score_i >= score_s {
offset = off_i;
borders_interleave
} else {
offset = off_s;
borders_spec
};
// debug instrumentation removed
// UINT8 ๋๊ฐ์ ์ข
๋ฅ / UINT8 diagonal line type
let diagonal_type = data[offset];
offset += 1;
// UINT8 ๋๊ฐ์ ๊ตต๊ธฐ / UINT8 diagonal line thickness
let diagonal_thickness = data[offset];
offset += 1;
// COLORREF ๋๊ฐ์ ์๊น / COLORREF diagonal line color
let diagonal_color = COLORREF(u32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
let diagonal = DiagonalLine {
line_type: diagonal_type,
thickness: diagonal_thickness,
color: diagonal_color,
};
// BYTE stream ์ฑ์ฐ๊ธฐ ์ ๋ณด (ํ 28) / BYTE stream fill information (Table 28)
let fill = if offset < data.len() {
Self::parse_fill_info(&data[offset..])?
} else {
FillInfo::None
};
Ok(BorderFill {
attributes,
borders,
diagonal,
fill,
})
}
/// ์ฑ์ฐ๊ธฐ ์ ๋ณด ํ์ฑ / Parse fill information
fn parse_fill_info(data: &[u8]) -> Result<FillInfo, HwpError> {
if data.len() < 4 {
return Ok(FillInfo::None);
}
let mut offset = 0;
// UINT ์ฑ์ฐ๊ธฐ ์ข
๋ฅ / UINT fill type
let fill_type_value = UINT::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let fill_type = if fill_type_value == 0x00000000 {
FillType::None
} else if (fill_type_value & 0x00000001) != 0 {
FillType::Solid
} else if (fill_type_value & 0x00000002) != 0 {
FillType::Image
} else if (fill_type_value & 0x00000004) != 0 {
FillType::Gradient
} else {
return Ok(FillInfo::None);
};
match fill_type {
FillType::None => Ok(FillInfo::None),
FillType::Solid => {
if offset + 12 > data.len() {
return Err(HwpError::insufficient_data(
"Solid fill data",
12,
data.len() - offset,
));
}
let background_color = COLORREF(u32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
let pattern_color = COLORREF(u32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
let pattern_type = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
Ok(FillInfo::Solid(SolidFill {
background_color,
pattern_color,
pattern_type,
}))
}
FillType::Gradient => {
if offset + 12 > data.len() {
return Err(HwpError::insufficient_data(
"Gradient fill data",
12,
data.len() - offset,
));
}
let gradient_type = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let angle = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let horizontal_center = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let vertical_center = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let spread = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let color_count = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let positions = if color_count > 2 {
if offset + (4 * color_count as usize) > data.len() {
return Err(HwpError::insufficient_data(
"Gradient positions data",
4 * color_count as usize,
data.len() - offset,
));
}
let mut pos_vec = Vec::new();
for _ in 0..color_count {
pos_vec.push(INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
}
Some(pos_vec)
} else {
None
};
if offset + (4 * color_count as usize) > data.len() {
return Err(HwpError::insufficient_data(
"Gradient colors data",
4 * color_count as usize,
data.len() - offset,
));
}
let mut colors = Vec::new();
for _ in 0..color_count {
colors.push(COLORREF(u32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
])));
offset += 4;
}
Ok(FillInfo::Gradient(GradientFill {
gradient_type,
angle,
horizontal_center,
vertical_center,
spread,
color_count,
positions,
colors,
}))
}
FillType::Image => {
// ์ด๋ฏธ์ง ์ฑ์ฐ๊ธฐ๋ ๋ณต์กํ๋ฏ๋ก ๊ธฐ๋ณธ ๊ตฌ์กฐ๋ง ํ์ฑ / Image fill is complex, so only parse basic structure
if offset + 1 > data.len() {
return Err(HwpError::insufficient_data(
"Image fill type",
1,
data.len() - offset,
));
}
let image_fill_type = data[offset];
offset += 1;
if offset + 5 > data.len() {
return Err(HwpError::insufficient_data(
"Image info",
5,
data.len() - offset,
));
}
let image_info = data[offset..offset + 5].to_vec();
offset += 5;
// ๋๋จธ์ง๋ ๋ณต์กํ๋ฏ๋ก ์ผ๋จ ๊ธฐ๋ณธ ๊ตฌ์กฐ๋ง / Rest is complex, so only basic structure for now
Ok(FillInfo::Image(ImageFill {
image_fill_type,
image_info,
gradient_spread_center: None,
additional_attributes_length: None,
additional_attributes: None,
}))
}
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/face_name.rs | crates/hwp-core/src/document/docinfo/face_name.rs | /// Face Name (Font) ๊ตฌ์กฐ์ฒด / Face Name (Font) structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 19 - ๊ธ๊ผด / Spec mapping: Table 19 - Font
/// Tag ID: HWPTAG_FACE_NAME
use crate::error::HwpError;
use crate::types::{decode_utf16le, BYTE, WORD};
use serde::{Deserialize, Serialize};
/// ๊ธ๊ผด ์์ฑ ํ๋๊ทธ / Font attribute flags
mod flags {
/// ๋์ฒด ๊ธ๊ผด ์กด์ฌ ์ฌ๋ถ / Alternative font exists
pub const HAS_ALTERNATIVE: u8 = 0x80;
/// ๊ธ๊ผด ์ ํ ์ ๋ณด ์กด์ฌ ์ฌ๋ถ / Font type information exists
pub const HAS_TYPE_INFO: u8 = 0x40;
/// ๊ธฐ๋ณธ ๊ธ๊ผด ์กด์ฌ ์ฌ๋ถ / Default font exists
pub const HAS_DEFAULT: u8 = 0x20;
}
/// ๋์ฒด ๊ธ๊ผด ์ ํ / Alternative font type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum AlternativeFontType {
/// ์๋ ์ข
๋ฅ๋ฅผ ์ ์ ์์ ๋ / Unknown original type
Unknown = 0,
/// ํธ๋ฃจํ์
๊ธ๊ผด(TTF) / TrueType font (TTF)
TTF = 1,
/// ํ๊ธ ์ ์ฉ ๊ธ๊ผด(HFT) / HWP font (HFT)
HFT = 2,
}
impl AlternativeFontType {
/// BYTE ๊ฐ์์ AlternativeFontType ์์ฑ / Create AlternativeFontType from BYTE value
fn from_byte(value: BYTE) -> Self {
match value {
1 => AlternativeFontType::TTF,
2 => AlternativeFontType::HFT,
_ => AlternativeFontType::Unknown,
}
}
}
/// ๊ธ๊ผด ์ ํ ์ ๋ณด / Font type information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FontTypeInfo {
/// ๊ธ๊ผด ๊ณ์ด / Font family
pub font_family: BYTE,
/// ์ธ๋ฆฌํ ์ ํ / Serif type
pub serif: BYTE,
/// ๊ตต๊ธฐ / Boldness
pub bold: BYTE,
/// ๋น๋ก / Proportion
pub proportion: BYTE,
/// ๋์กฐ / Contrast
pub contrast: BYTE,
/// ์คํธ๋กํฌ ํธ์ฐจ / Stroke variation
pub stroke_variation: BYTE,
/// ์ํ ์ ํ / Stroke type
pub stroke_type: BYTE,
/// ๊ธ์ํ / Letter type
pub letter_type: BYTE,
/// ์ค๊ฐ์ / Middle line
pub middle_line: BYTE,
/// X-๋์ด / X-height
pub x_height: BYTE,
}
/// Face Name (Font) ๊ตฌ์กฐ์ฒด / Face Name (Font) structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FaceName {
/// ๊ธ๊ผด ์ด๋ฆ / Font name
pub name: String,
/// ๋์ฒด ๊ธ๊ผด ์ ํ (์์ฑ์ ๋ฐ๋ผ ์กด์ฌ) / Alternative font type (exists based on attribute)
pub alternative_font_type: Option<AlternativeFontType>,
/// ๋์ฒด ๊ธ๊ผด ์ด๋ฆ (์์ฑ์ ๋ฐ๋ผ ์กด์ฌ) / Alternative font name (exists based on attribute)
pub alternative_font_name: Option<String>,
/// ๊ธ๊ผด ์ ํ ์ ๋ณด (์์ฑ์ ๋ฐ๋ผ ์กด์ฌ) / Font type information (exists based on attribute)
pub font_type_info: Option<FontTypeInfo>,
/// ๊ธฐ๋ณธ ๊ธ๊ผด ์ด๋ฆ (์์ฑ์ ๋ฐ๋ผ ์กด์ฌ) / Default font name (exists based on attribute)
pub default_font_name: Option<String>,
}
impl FaceName {
/// FaceName์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse FaceName from byte array.
///
/// # Arguments
/// * `data` - FaceName ๋ ์ฝ๋ ๋ฐ์ดํฐ / FaceName record data
///
/// # Returns
/// ํ์ฑ๋ FaceName ๊ตฌ์กฐ์ฒด / Parsed FaceName structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 3 {
return Err(HwpError::insufficient_data("FaceName", 3, data.len()));
}
let mut offset = 0;
// BYTE ์์ฑ (ํ 20) / BYTE attribute (Table 20)
let attributes = data[offset];
offset += 1;
// WORD ๊ธ๊ผด ์ด๋ฆ ๊ธธ์ด / WORD font name length
let name_length = WORD::from_le_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
// WCHAR array ๊ธ๊ผด ์ด๋ฆ / WCHAR array font name
if offset + (name_length * 2) > data.len() {
return Err(HwpError::InsufficientData {
field: format!("FaceName font name at offset {}", offset),
expected: offset + (name_length * 2),
actual: data.len(),
});
}
let name_bytes = &data[offset..offset + (name_length * 2)];
let name = decode_utf16le(name_bytes)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode font name: {}", e),
})?;
offset += name_length * 2;
// ๋์ฒด ๊ธ๊ผด ์ฒ๋ฆฌ (์์ฑ bit 7์ด 1์ธ ๊ฒฝ์ฐ) / Process alternative font (if attribute bit 7 is 1)
let (alternative_font_type, alternative_font_name) =
if (attributes & flags::HAS_ALTERNATIVE) != 0 {
if offset >= data.len() {
return Err(HwpError::insufficient_data(
"FaceName alternative font type",
1,
0,
));
}
let alt_type_byte = data[offset];
offset += 1;
// WORD ๋์ฒด ๊ธ๊ผด ์ด๋ฆ ๊ธธ์ด / WORD alternative font name length
if offset + 2 > data.len() {
return Err(HwpError::insufficient_data(
"FaceName alternative font name length",
2,
data.len() - offset,
));
}
let alt_name_length =
WORD::from_le_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
// WCHAR array ๋์ฒด ๊ธ๊ผด ์ด๋ฆ / WCHAR array alternative font name
if offset + (alt_name_length * 2) > data.len() {
return Err(HwpError::InsufficientData {
field: format!("FaceName alternative font name at offset {}", offset),
expected: offset + (alt_name_length * 2),
actual: data.len(),
});
}
let alt_name_bytes = &data[offset..offset + (alt_name_length * 2)];
let alt_name = decode_utf16le(alt_name_bytes)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode alternative font name: {}", e),
})?;
offset += alt_name_length * 2;
(
Some(AlternativeFontType::from_byte(alt_type_byte)),
Some(alt_name),
)
} else {
(None, None)
};
// ๊ธ๊ผด ์ ํ ์ ๋ณด ์ฒ๋ฆฌ (์์ฑ bit 6์ด 1์ธ ๊ฒฝ์ฐ) / Process font type info (if attribute bit 6 is 1)
let font_type_info = if (attributes & flags::HAS_TYPE_INFO) != 0 {
if offset + 10 > data.len() {
return Err(HwpError::insufficient_data(
"FaceName font type info",
10,
data.len() - offset,
));
}
Some(FontTypeInfo {
font_family: data[offset],
serif: data[offset + 1],
bold: data[offset + 2],
proportion: data[offset + 3],
contrast: data[offset + 4],
stroke_variation: data[offset + 5],
stroke_type: data[offset + 6],
letter_type: data[offset + 7],
middle_line: data[offset + 8],
x_height: data[offset + 9],
})
} else {
None
};
if font_type_info.is_some() {
offset += 10;
}
// ๊ธฐ๋ณธ ๊ธ๊ผด ์ฒ๋ฆฌ (์์ฑ bit 5๊ฐ 1์ธ ๊ฒฝ์ฐ) / Process default font (if attribute bit 5 is 1)
let default_font_name = if (attributes & flags::HAS_DEFAULT) != 0 {
if offset + 2 > data.len() {
return Err(HwpError::insufficient_data(
"FaceName default font name length",
2,
data.len() - offset,
));
}
let default_name_length =
WORD::from_le_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
if offset + (default_name_length * 2) > data.len() {
return Err(HwpError::InsufficientData {
field: format!("FaceName default font name at offset {}", offset),
expected: offset + (default_name_length * 2),
actual: data.len(),
});
}
let default_name_bytes = &data[offset..offset + (default_name_length * 2)];
let default_name = decode_utf16le(default_name_bytes)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode default font name: {}", e),
})?;
Some(default_name)
} else {
None
};
Ok(FaceName {
name,
alternative_font_type,
alternative_font_name,
font_type_info,
default_font_name,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/memo_shape.rs | crates/hwp-core/src/document/docinfo/memo_shape.rs | /// MemoShape ๊ตฌ์กฐ์ฒด / MemoShape structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 4 - ๋ฉ๋ชจ ๋ชจ์ / Spec mapping: Table 4 - Memo shape
/// ์์ธ ๊ตฌ์กฐ๋ ์คํ ๋ฌธ์์ ๋ช
์๋์ง ์์ / Detailed structure not specified in spec
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// ๋ฉ๋ชจ ๋ชจ์ / Memo shape
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoShape {
/// Raw data (22๋ฐ์ดํธ) / Raw data (22 bytes)
#[serde(skip)]
pub raw_data: Vec<u8>,
}
impl MemoShape {
/// MemoShape๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse MemoShape from byte array.
///
/// # Arguments
/// * `data` - MemoShape ๋ฐ์ดํฐ (22๋ฐ์ดํธ) / MemoShape data (22 bytes)
///
/// # Returns
/// ํ์ฑ๋ MemoShape ๊ตฌ์กฐ์ฒด / Parsed MemoShape structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 22 {
return Err(HwpError::insufficient_data("MemoShape", 22, data.len()));
}
Ok(MemoShape {
raw_data: data[0..22.min(data.len())].to_vec(),
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/bullet.rs | crates/hwp-core/src/document/docinfo/bullet.rs | /// Bullet ๊ตฌ์กฐ์ฒด / Bullet structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 42 - ๊ธ๋จธ๋ฆฌํ / Spec mapping: Table 42 - Bullet
/// Tag ID: HWPTAG_BULLET
/// ์ ์ฒด ๊ธธ์ด: 20๋ฐ์ดํธ (ํ 42) ๋๋ ๊ฐ๋ณ (๋ ๊ฑฐ์ ์ฝ๋ ๊ธฐ์ค) / Total length: 20 bytes (Table 42) or variable (legacy code)
use crate::error::HwpError;
use crate::types::{BYTE, HWPUNIT16, INT32, UINT32, WCHAR};
use serde::{Deserialize, Serialize};
/// ๋ฌธ๋จ ๋จธ๋ฆฌ ์ ๋ณด ์์ฑ / Paragraph header information attributes
///
/// ํ 40 ์ฐธ์กฐ / See Table 40
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BulletHeaderAttributes {
/// ๋ฌธ๋จ์ ์ ๋ ฌ ์ข
๋ฅ / Paragraph alignment type
pub align_type: BulletAlignType,
/// ์ธ์คํด์ค ์ ์ฌ ์ฌ๋ถ (bit 2) / Instance-like flag (bit 2)
pub instance_like: bool,
/// ์๋ ๋ด์ด ์ฐ๊ธฐ ์ฌ๋ถ / Auto outdent flag
pub auto_outdent: bool,
/// ์์ค๋ณ ๋ณธ๋ฌธ๊ณผ์ ๊ฑฐ๋ฆฌ ์ข
๋ฅ / Distance type from body text by level
pub distance_type: BulletDistanceType,
}
/// ๋ฌธ๋จ ์ ๋ ฌ ์ข
๋ฅ / Paragraph alignment type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BulletAlignType {
/// ์ผ์ชฝ / Left
Left = 0,
/// ๊ฐ์ด๋ฐ / Center
Center = 1,
/// ์ค๋ฅธ์ชฝ / Right
Right = 2,
}
impl BulletAlignType {
fn from_bits(bits: u32) -> Self {
match bits & 0x00000003 {
1 => BulletAlignType::Center,
2 => BulletAlignType::Right,
_ => BulletAlignType::Left,
}
}
}
/// ์์ค๋ณ ๋ณธ๋ฌธ๊ณผ์ ๊ฑฐ๋ฆฌ ์ข
๋ฅ / Distance type from body text by level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BulletDistanceType {
/// ๊ธ์ ํฌ๊ธฐ์ ๋ํ ์๋ ๋น์จ / Relative ratio to font size
Ratio = 0,
/// ๊ฐ / Value
Value = 1,
}
impl BulletDistanceType {
fn from_bit(bit: bool) -> Self {
if bit {
BulletDistanceType::Value
} else {
BulletDistanceType::Ratio
}
}
}
/// ์ด๋ฏธ์ง ๊ธ๋จธ๋ฆฌํ ์์ฑ / Image bullet attributes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageBulletAttributes {
/// ๋ช
์ / Brightness
pub brightness: BYTE,
/// ๋ฐ๊ธฐ / Contrast
pub contrast: BYTE,
/// ํจ๊ณผ / Effect
pub effect: BYTE,
/// ID / ID
pub id: BYTE,
}
/// Bullet ๊ตฌ์กฐ์ฒด / Bullet structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Bullet {
/// ์์ฑ (ํ 40) / Attributes (Table 40)
pub attributes: BulletHeaderAttributes,
/// ๋๋น ๋ณด์ ๊ฐ / Width correction value
pub width: HWPUNIT16,
/// ๋ณธ๋ฌธ๊ณผ์ ๊ฑฐ๋ฆฌ / Distance from body text
pub space: HWPUNIT16,
/// ๊ธ์ ๋ชจ์ ์์ด๋ ์ฐธ์กฐ / Character shape ID reference
pub char_shape_id: INT32,
/// ๊ธ๋จธ๋ฆฌํ ๋ฌธ์ / Bullet character
pub bullet_char: WCHAR,
/// ์ด๋ฏธ์ง ๊ธ๋จธ๋ฆฌํ ์กด์ฌ ์ฌ๋ถ(ID) / Image bullet existence (ID)
pub image_bullet_id: INT32,
/// ์ด๋ฏธ์ง ๊ธ๋จธ๋ฆฌํ ์์ฑ (๋ช
์, ๋ฐ๊ธฐ, ํจ๊ณผ, ID) / Image bullet attributes (brightness, contrast, effect, ID)
pub image_bullet_attributes: Option<ImageBulletAttributes>,
/// ์ฒดํฌ ๊ธ๋จธ๋ฆฌํ ๋ฌธ์ / Check bullet character
pub check_bullet_char: WCHAR,
}
impl Bullet {
/// Bullet์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse Bullet from byte array.
///
/// # Arguments
/// * `data` - Bullet ๋ ์ฝ๋ ๋ฐ์ดํฐ / Bullet record data
///
/// # Returns
/// ํ์ฑ๋ Bullet ๊ตฌ์กฐ์ฒด / Parsed Bullet structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ๋ ๊ฑฐ์ ์ฝ๋ ๊ธฐ์ค ์ต์ 12๋ฐ์ดํธ ํ์ (์์ฑ 4 + ๋๋น 2 + ๊ฑฐ๋ฆฌ 2 + ๊ธ์๋ชจ์ID 4) / Need at least 12 bytes based on legacy code
if data.len() < 12 {
return Err(HwpError::insufficient_data("Bullet", 12, data.len()));
}
let mut offset = 0;
// UINT ์์ฑ (ํ 40) - ๋ ๊ฑฐ์ ์ฝ๋ ๊ธฐ์ค / UINT attributes (Table 40) - based on legacy code
let attr_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let attributes = BulletHeaderAttributes {
align_type: BulletAlignType::from_bits(attr_value),
instance_like: (attr_value & 0x00000004) != 0,
auto_outdent: (attr_value & 0x00000008) != 0,
distance_type: BulletDistanceType::from_bit((attr_value & 0x00000010) != 0),
};
// HWPUNIT16 ๋๋น ๋ณด์ ๊ฐ / HWPUNIT16 width correction value
let width = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// HWPUNIT16 ๋ณธ๋ฌธ๊ณผ์ ๊ฑฐ๋ฆฌ / HWPUNIT16 distance from body text
let space = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// INT32 ๊ธ์ ๋ชจ์ ์์ด๋ ์ฐธ์กฐ / INT32 character shape ID reference
let char_shape_id = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// WCHAR ๊ธ๋จธ๋ฆฌํ ๋ฌธ์ / WCHAR bullet character
let bullet_char = if offset + 2 <= data.len() {
WCHAR::from_le_bytes([data[offset], data[offset + 1]])
} else {
0
};
offset += 2;
// INT32 ์ด๋ฏธ์ง ๊ธ๋จธ๋ฆฌํ ์กด์ฌ ์ฌ๋ถ(ID) - ์ต์
/ INT32 image bullet existence (ID) - optional
let image_bullet_id = if offset + 4 <= data.len() {
INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
])
} else {
0
};
offset += 4;
// BYTE stream ์ด๋ฏธ์ง ๊ธ๋จธ๋ฆฌํ ์์ฑ (4๋ฐ์ดํธ) - ์ต์
/ BYTE stream image bullet attributes (4 bytes) - optional
let image_bullet_attributes = if offset + 4 <= data.len() {
Some(ImageBulletAttributes {
brightness: data[offset],
contrast: data[offset + 1],
effect: data[offset + 2],
id: data[offset + 3],
})
} else {
None
};
offset += 4;
// WCHAR ์ฒดํฌ ๊ธ๋จธ๋ฆฌํ ๋ฌธ์ - ์ต์
/ WCHAR check bullet character - optional
let check_bullet_char = if offset + 2 <= data.len() {
WCHAR::from_le_bytes([data[offset], data[offset + 1]])
} else {
0
};
Ok(Bullet {
attributes,
width,
space,
char_shape_id,
bullet_char,
image_bullet_id,
image_bullet_attributes,
check_bullet_char,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/track_change_content.rs | crates/hwp-core/src/document/docinfo/track_change_content.rs | /// TrackChangeContent ๊ตฌ์กฐ์ฒด / TrackChangeContent structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 4 - ๋ณ๊ฒฝ ์ถ์ ๋ด์ฉ ๋ฐ ๋ชจ์ / Spec mapping: Table 4 - Track change content and shape
/// ์์ธ ๊ตฌ์กฐ๋ ์คํ ๋ฌธ์์ ๋ช
์๋์ง ์์ / Detailed structure not specified in spec
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// ๋ณ๊ฒฝ ์ถ์ ๋ด์ฉ ๋ฐ ๋ชจ์ / Track change content and shape
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrackChangeContent {
/// Raw data (๊ฐ๋ณ) / Raw data (variable)
#[serde(skip)]
pub raw_data: Vec<u8>,
}
impl TrackChangeContent {
/// TrackChangeContent๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse TrackChangeContent from byte array.
///
/// # Arguments
/// * `data` - TrackChangeContent ๋ฐ์ดํฐ (๊ฐ๋ณ) / TrackChangeContent data (variable)
///
/// # Returns
/// ํ์ฑ๋ TrackChangeContent ๊ตฌ์กฐ์ฒด / Parsed TrackChangeContent structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
Ok(TrackChangeContent {
raw_data: data.to_vec(),
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/distribute_doc_data.rs | crates/hwp-core/src/document/docinfo/distribute_doc_data.rs | /// DistributeDocData ๊ตฌ์กฐ์ฒด / DistributeDocData structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 53 - ๋ฐฐํฌ์ฉ ๋ฌธ์ ๋ฐ์ดํฐ / Spec mapping: Table 53 - Distribution document data
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// ๋ฐฐํฌ์ฉ ๋ฌธ์ ๋ฐ์ดํฐ (ํ 53) / Distribution document data (Table 53)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DistributeDocData {
/// ๋ฐฐํฌ์ฉ ๋ฌธ์ ๋ฐ์ดํฐ (256๋ฐ์ดํธ) / Distribution document data (256 bytes)
pub data: Vec<u8>,
}
impl DistributeDocData {
/// DistributeDocData๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse DistributeDocData from byte array.
///
/// # Arguments
/// * `data` - DistributeDocData ๋ฐ์ดํฐ (256๋ฐ์ดํธ) / DistributeDocData data (256 bytes)
///
/// # Returns
/// ํ์ฑ๋ DistributeDocData ๊ตฌ์กฐ์ฒด / Parsed DistributeDocData structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 256 {
return Err(HwpError::insufficient_data("DistributeDocData", 256, data.len()));
}
let doc_data = data[0..256].to_vec();
Ok(DistributeDocData { data: doc_data })
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/bin_data.rs | crates/hwp-core/src/document/docinfo/bin_data.rs | /// BinData record structure
///
/// This module handles parsing of HWPTAG_BIN_DATA records from DocInfo.
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 17 - ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ / Spec mapping: Table 17 - Binary data
/// Tag ID: HWPTAG_BIN_DATA
use crate::error::HwpError;
use crate::types::{decode_utf16le, UINT16, WORD};
use serde::{Deserialize, Serialize};
/// ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ ์ ์ฅ ํ์
/ Binary data storage type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum BinDataStorageType {
/// LINK, ๊ทธ๋ฆผ ์ธ๋ถ ํ์ผ ์ฐธ์กฐ / Link, external file reference
Link = 0x0000,
/// EMBEDDING, ๊ทธ๋ฆผ ํ์ผ ํฌํจ / Embedding, embedded file
Embedding = 0x0001,
/// STORAGE, OLE ํฌํจ / Storage, OLE embedded
Storage = 0x0002,
}
impl BinDataStorageType {
/// UINT16 ๊ฐ์์ BinDataStorageType ์์ฑ / Create BinDataStorageType from UINT16 value
fn from_u16(value: UINT16) -> Self {
match value & 0x000F {
0x0000 => BinDataStorageType::Link,
0x0001 => BinDataStorageType::Embedding,
0x0002 => BinDataStorageType::Storage,
_ => BinDataStorageType::Link, // Default fallback
}
}
}
/// ์์ถ ํ์
/ Compression type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CompressionType {
/// ์คํ ๋ฆฌ์ง์ ๋ํดํธ ๋ชจ๋ ๋ฐ๋ผ๊ฐ / Follow storage default mode
StorageDefault = 0x0000,
/// ๋ฌด์กฐ๊ฑด ์์ถ / Always compress
Compress = 0x0010,
/// ๋ฌด์กฐ๊ฑด ์์ถํ์ง ์์ / Never compress
NoCompress = 0x0020,
}
impl CompressionType {
/// UINT16 ๊ฐ์์ CompressionType ์์ฑ / Create CompressionType from UINT16 value
fn from_u16(value: UINT16) -> Self {
match value & 0x0030 {
0x0000 => CompressionType::StorageDefault,
0x0010 => CompressionType::Compress,
0x0020 => CompressionType::NoCompress,
_ => CompressionType::StorageDefault, // Default fallback
}
}
}
/// ์ ๊ทผ ์ํ / Access state
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AccessState {
/// ์์ง access ๋ ์ ์ด ์๋ ์ํ / Never accessed
Never = 0x0000,
/// access์ ์ฑ๊ณตํ์ฌ ํ์ผ์ ์ฐพ์ ์ํ / Successfully accessed, file found
Success = 0x0100,
/// access๊ฐ ์คํจํ ์๋ฌ ์ํ / Access failed with error
Failed = 0x0200,
/// ๋งํฌ access๊ฐ ์คํจํ์ผ๋ ๋ฌด์๋ ์ํ / Link access failed but ignored
FailedIgnored = 0x0300,
}
impl AccessState {
/// UINT16 ๊ฐ์์ AccessState ์์ฑ / Create AccessState from UINT16 value
fn from_u16(value: UINT16) -> Self {
match value & 0x0300 {
0x0000 => AccessState::Never,
0x0100 => AccessState::Success,
0x0200 => AccessState::Failed,
0x0300 => AccessState::FailedIgnored,
_ => AccessState::Never, // Default fallback
}
}
}
/// ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ ์์ฑ / Binary data attributes
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct BinDataAttributes {
/// ์ ์ฅ ํ์
/ Storage type
pub storage_type: BinDataStorageType,
/// ์์ถ ํ์
/ Compression type
pub compression: CompressionType,
/// ์ ๊ทผ ์ํ / Access state
pub access: AccessState,
}
impl BinDataAttributes {
/// UINT16 ๊ฐ์์ BinDataAttributes ์์ฑ / Create BinDataAttributes from UINT16 value
fn from_u16(value: UINT16) -> Self {
Self {
storage_type: BinDataStorageType::from_u16(value),
compression: CompressionType::from_u16(value),
access: AccessState::from_u16(value),
}
}
}
/// LINK ํ์
๋ฐ์ดํฐ / Link type data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BinDataLink {
/// ์ฐ๊ฒฐ ํ์ผ์ ์ ๋ ๊ฒฝ๋ก / Absolute path of linked file
pub absolute_path: String,
/// ์ฐ๊ฒฐ ํ์ผ์ ์๋ ๊ฒฝ๋ก / Relative path of linked file
pub relative_path: String,
}
/// EMBEDDING ํ์
๋ฐ์ดํฐ / Embedding type data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BinDataEmbedding {
/// BINDATASTORAGE์ ์ ์ฅ๋ ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ์ ์์ด๋ / Binary data ID stored in BINDATASTORAGE
pub binary_data_id: UINT16,
/// ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ์ ํ์ ์ด๋ฆ (extension, "." ์ ์ธ) / Format name (extension without ".")
/// - ๊ทธ๋ฆผ์ ๊ฒฝ์ฐ: jpg, bmp, gif / For images: jpg, bmp, gif
/// - OLE์ ๊ฒฝ์ฐ: ole / For OLE: ole
pub extension: String,
}
/// STORAGE ํ์
๋ฐ์ดํฐ / Storage type data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BinDataStorage {
/// BINDATASTORAGE์ ์ ์ฅ๋ ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ์ ์์ด๋ / Binary data ID stored in BINDATASTORAGE
pub binary_data_id: UINT16,
}
/// ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ ๋ ์ฝ๋ / Binary data record
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "storage_type", rename_all = "UPPERCASE")]
pub enum BinDataRecord {
/// LINK ํ์
/ Link type
Link {
/// ์์ฑ / Attributes
attributes: BinDataAttributes,
/// LINK ๋ฐ์ดํฐ / Link data
link: BinDataLink,
},
/// EMBEDDING ํ์
/ Embedding type
Embedding {
/// ์์ฑ / Attributes
attributes: BinDataAttributes,
/// EMBEDDING ๋ฐ์ดํฐ / Embedding data
embedding: BinDataEmbedding,
},
/// STORAGE ํ์
/ Storage type
Storage {
/// ์์ฑ / Attributes
attributes: BinDataAttributes,
/// STORAGE ๋ฐ์ดํฐ / Storage data
storage: BinDataStorage,
},
}
impl BinDataRecord {
/// BinDataRecord๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse BinDataRecord from byte array.
///
/// # Arguments
/// * `data` - BinDataRecord ๋ฐ์ดํฐ / BinDataRecord data
///
/// # Returns
/// ํ์ฑ๋ BinDataRecord ๊ตฌ์กฐ์ฒด / Parsed BinDataRecord structure
///
/// # ์คํ ๋ฌธ์ ๋งคํ / Spec mapping
/// ํ 17: ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ / Table 17: Binary data
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 2 {
return Err(HwpError::insufficient_data("BinDataRecord attributes", 2, data.len()));
}
let mut offset = 0;
// ํ 17: ์์ฑ (UINT16, 2๋ฐ์ดํธ) / Table 17: Attributes (UINT16, 2 bytes)
let attr_value = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let attributes = BinDataAttributes::from_u16(attr_value);
// Type์ ๋ฐ๋ผ ๋ค๋ฅธ ํ๋ ํ์ฑ / Parse different fields based on type
match attributes.storage_type {
BinDataStorageType::Link => {
// ํ 17: Type์ด "LINK"์ผ ๋ / Table 17: When Type is "LINK"
// ์ฐ๊ฒฐ ํ์ผ์ ์ ๋ ๊ฒฝ๋ก ๊ธธ์ด (len1) / Absolute path length (len1)
if data.len() < offset + 2 {
return Err(HwpError::insufficient_data(
"BinDataRecord LINK absolute path length",
2,
data.len() - offset,
));
}
let len1 = WORD::from_le_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
// ์ฐ๊ฒฐ ํ์ผ์ ์ ๋ ๊ฒฝ๋ก / Absolute path
if data.len() < offset + (len1 * 2) {
return Err(HwpError::InsufficientData {
field: format!("BinDataRecord LINK absolute path at offset {}", offset),
expected: offset + (len1 * 2),
actual: data.len(),
});
}
let absolute_path_bytes = &data[offset..offset + (len1 * 2)];
let absolute_path = decode_utf16le(absolute_path_bytes)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode absolute path: {}", e),
})?;
offset += len1 * 2;
// ์ฐ๊ฒฐ ํ์ผ์ ์๋ ๊ฒฝ๋ก ๊ธธ์ด (len2) / Relative path length (len2)
if data.len() < offset + 2 {
return Err(HwpError::insufficient_data(
"BinDataRecord LINK relative path length",
2,
data.len() - offset,
));
}
let len2 = WORD::from_le_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
// ์ฐ๊ฒฐ ํ์ผ์ ์๋ ๊ฒฝ๋ก / Relative path
if data.len() < offset + (len2 * 2) {
return Err(HwpError::InsufficientData {
field: format!("BinDataRecord LINK relative path at offset {}", offset),
expected: offset + (len2 * 2),
actual: data.len(),
});
}
let relative_path_bytes = &data[offset..offset + (len2 * 2)];
let relative_path = decode_utf16le(relative_path_bytes)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode relative path: {}", e),
})?;
Ok(BinDataRecord::Link {
attributes,
link: BinDataLink {
absolute_path,
relative_path,
},
})
}
BinDataStorageType::Embedding => {
// ํ 17: Type์ด "EMBEDDING"์ผ ๋ / Table 17: When Type is "EMBEDDING"
// BINDATASTORAGE์ ์ ์ฅ๋ ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ์ ์์ด๋ / Binary data ID
if data.len() < offset + 2 {
return Err(HwpError::insufficient_data(
"BinDataRecord EMBEDDING binary_data_id",
2,
data.len() - offset,
));
}
let binary_data_id = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ์ ํ์ ์ด๋ฆ์ ๊ธธ์ด (len3) / Format name length (len3)
if data.len() < offset + 2 {
return Err(HwpError::insufficient_data(
"BinDataRecord EMBEDDING extension length",
2,
data.len() - offset,
));
}
let len3 = WORD::from_le_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
// ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ์ ํ์ ์ด๋ฆ (extension) / Format name (extension)
if data.len() < offset + (len3 * 2) {
return Err(HwpError::InsufficientData {
field: format!("BinDataRecord EMBEDDING extension at offset {}", offset),
expected: offset + (len3 * 2),
actual: data.len(),
});
}
let extension_bytes = &data[offset..offset + (len3 * 2)];
let extension = decode_utf16le(extension_bytes)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode extension: {}", e),
})?;
Ok(BinDataRecord::Embedding {
attributes,
embedding: BinDataEmbedding {
binary_data_id,
extension,
},
})
}
BinDataStorageType::Storage => {
// ํ 17: Type์ด "STORAGE"์ผ ๋ / Table 17: When Type is "STORAGE"
// BINDATASTORAGE์ ์ ์ฅ๋ ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ์ ์์ด๋ / Binary data ID
if data.len() < offset + 2 {
return Err(HwpError::insufficient_data(
"BinDataRecord STORAGE binary_data_id",
2,
data.len() - offset,
));
}
let binary_data_id = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
Ok(BinDataRecord::Storage {
attributes,
storage: BinDataStorage { binary_data_id },
})
}
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/compatible_document.rs | crates/hwp-core/src/document/docinfo/compatible_document.rs | /// CompatibleDocument ๊ตฌ์กฐ์ฒด / CompatibleDocument structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 54 - ํธํ ๋ฌธ์ / Spec mapping: Table 54 - Compatible document
use crate::error::HwpError;
use crate::types::UINT32;
use serde::{Deserialize, Serialize};
/// ํธํ ๋ฌธ์ (ํ 54) / Compatible document (Table 54)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompatibleDocument {
/// ๋์ ํ๋ก๊ทธ๋จ (ํ 55 ์ฐธ์กฐ) / Target program (see Table 55)
pub target_program: TargetProgram,
}
/// ๋์ ํ๋ก๊ทธ๋จ (ํ 55) / Target program (Table 55)
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TargetProgram {
/// ํ๊ธ ๋ฌธ์(ํ์ฌ ๋ฒ์ ) / HWP document (current version)
HwpCurrent,
/// ํ๊ธ 2007 ํธํ ๋ฌธ์ / HWP 2007 compatible document
Hwp2007,
/// MS ์๋ ํธํ ๋ฌธ์ / MS Word compatible document
MsWord,
}
impl CompatibleDocument {
/// CompatibleDocument๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse CompatibleDocument from byte array.
///
/// # Arguments
/// * `data` - CompatibleDocument ๋ฐ์ดํฐ (4๋ฐ์ดํธ) / CompatibleDocument data (4 bytes)
///
/// # Returns
/// ํ์ฑ๋ CompatibleDocument ๊ตฌ์กฐ์ฒด / Parsed CompatibleDocument structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 4 {
return Err(HwpError::insufficient_data("CompatibleDocument", 4, data.len()));
}
let target_program_value = UINT32::from_le_bytes([data[0], data[1], data[2], data[3]]);
let target_program = match target_program_value {
0 => TargetProgram::HwpCurrent,
1 => TargetProgram::Hwp2007,
2 => TargetProgram::MsWord,
_ => {
return Err(HwpError::UnexpectedValue {
field: "CompatibleDocument target_program".to_string(),
expected: "0, 1, or 2".to_string(),
found: target_program_value.to_string(),
});
}
};
Ok(CompatibleDocument { target_program })
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/mod.rs | crates/hwp-core/src/document/docinfo/mod.rs | /// DocInfo parsing module
///
/// This module handles parsing of HWP DocInfo stream.
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 2 - ๋ฌธ์ ์ ๋ณด (DocInfo ์คํธ๋ฆผ) / Spec mapping: Table 2 - Document information (DocInfo stream)
pub mod bin_data;
pub mod border_fill;
pub mod bullet;
pub mod char_shape;
pub mod compatible_document;
pub mod constants;
pub mod distribute_doc_data;
pub mod doc_data;
pub mod document_properties;
pub mod face_name;
pub mod forbidden_char;
pub mod id_mappings;
pub mod layout_compatibility;
pub mod memo_shape;
pub mod numbering;
pub mod para_shape;
pub mod style;
pub mod tab_def;
pub mod track_change;
pub mod track_change_author;
pub mod track_change_content;
pub use crate::decompress::decompress_deflate;
pub use crate::document::fileheader::FileHeader;
pub use crate::error::HwpError;
pub use crate::types::RecordHeader;
pub use bin_data::BinDataRecord;
pub use border_fill::{BorderFill, FillInfo};
pub use bullet::Bullet;
pub use char_shape::CharShape;
pub use compatible_document::CompatibleDocument;
pub use constants::HwpTag;
pub use distribute_doc_data::DistributeDocData;
pub use doc_data::{DocData, ParameterSet};
pub use document_properties::DocumentProperties;
pub use face_name::FaceName;
pub use forbidden_char::ForbiddenChar;
pub use id_mappings::IdMappings;
pub use layout_compatibility::LayoutCompatibility;
pub use memo_shape::MemoShape;
pub use numbering::Numbering;
pub use para_shape::{HeaderShapeType, ParaShape};
use serde::{Deserialize, Serialize};
pub use style::Style;
pub use tab_def::TabDef;
pub use track_change::TrackChange;
pub use track_change_author::TrackChangeAuthor;
pub use track_change_content::TrackChangeContent;
/// Document information structure
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DocInfo {
/// Document properties (parsed)
pub document_properties: Option<DocumentProperties>,
/// ID mappings (parsed)
pub id_mappings: Option<IdMappings>,
/// Binary data records (parsed) / ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ ๋ ์ฝ๋ (ํ์ฑ๋จ)
pub bin_data: Vec<BinDataRecord>,
/// Face names (fonts) (parsed) / ๊ธ๊ผด ๋ชฉ๋ก (ํ์ฑ๋จ)
pub face_names: Vec<FaceName>,
/// Border/fill information (parsed) / ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์ ๋ณด (ํ์ฑ๋จ)
pub border_fill: Vec<BorderFill>,
/// Character shapes (parsed) / ๊ธ์ ๋ชจ์ (ํ์ฑ๋จ)
pub char_shapes: Vec<CharShape>,
/// Tab definitions (parsed) / ํญ ์ ์ (ํ์ฑ๋จ)
pub tab_defs: Vec<TabDef>,
/// Numbering information (parsed) / ๋ฌธ๋จ ๋ฒํธ ์ ๋ณด (ํ์ฑ๋จ)
pub numbering: Vec<Numbering>,
/// Bullet information (parsed) / ๊ธ๋จธ๋ฆฌํ ์ ๋ณด (ํ์ฑ๋จ)
pub bullets: Vec<Bullet>,
/// Paragraph shapes (parsed) / ๋ฌธ๋จ ๋ชจ์ (ํ์ฑ๋จ)
pub para_shapes: Vec<ParaShape>,
/// Styles (parsed) / ์คํ์ผ (ํ์ฑ๋จ)
pub styles: Vec<Style>,
/// Document arbitrary data (parsed) / ๋ฌธ์ ์์์ ๋ฐ์ดํฐ (ํ์ฑ๋จ)
pub doc_data: Vec<DocData>,
/// Distribution document data (parsed) / ๋ฐฐํฌ์ฉ ๋ฌธ์ ๋ฐ์ดํฐ (ํ์ฑ๋จ)
pub distribute_doc_data: Option<DistributeDocData>,
/// Compatible document (parsed) / ํธํ ๋ฌธ์ (ํ์ฑ๋จ)
pub compatible_document: Option<CompatibleDocument>,
/// Layout compatibility (parsed) / ๋ ์ด์์ ํธํ์ฑ (ํ์ฑ๋จ)
pub layout_compatibility: Option<LayoutCompatibility>,
/// Track change information (parsed) / ๋ณ๊ฒฝ ์ถ์ ์ ๋ณด (ํ์ฑ๋จ)
pub track_change: Option<TrackChange>,
/// Memo shapes (parsed) / ๋ฉ๋ชจ ๋ชจ์ (ํ์ฑ๋จ)
pub memo_shapes: Vec<MemoShape>,
/// Forbidden characters (parsed) / ๊ธ์น์ฒ๋ฆฌ ๋ฌธ์ (ํ์ฑ๋จ)
pub forbidden_chars: Vec<ForbiddenChar>,
/// Track change contents (parsed) / ๋ณ๊ฒฝ ์ถ์ ๋ด์ฉ ๋ฐ ๋ชจ์ (ํ์ฑ๋จ)
pub track_change_contents: Vec<TrackChangeContent>,
/// Track change authors (parsed) / ๋ณ๊ฒฝ ์ถ์ ์์ฑ์ (ํ์ฑ๋จ)
pub track_change_authors: Vec<TrackChangeAuthor>,
}
impl DocInfo {
/// DocInfo ์คํธ๋ฆผ์ ํ์ฑํฉ๋๋ค. / Parse DocInfo stream.
///
/// # Arguments
/// * `stream_data` - DocInfo ์คํธ๋ฆผ์ ์์ ๋ฐ์ดํธ ๋ฐ์ดํฐ / Raw byte data of DocInfo stream
/// * `file_header` - FileHeader (์์ถ ์ฌ๋ถ ํ์ธ์ฉ) / FileHeader (to check compression)
///
/// # Returns
/// ํ์ฑ๋ DocInfo ๊ตฌ์กฐ์ฒด / Parsed DocInfo structure
pub fn parse(stream_data: &[u8], file_header: &FileHeader) -> Result<Self, HwpError> {
// ์์ถ ํด์ (ํ์ํ ๊ฒฝ์ฐ) / Decompress if needed
// HWP DocInfo uses raw deflate format (windowBits: -15), not zlib
let decompressed_data = if file_header.is_compressed() {
decompress_deflate(stream_data)?
} else {
stream_data.to_vec()
};
let mut doc_info = DocInfo::default();
let mut offset = 0;
// ๋ ์ฝ๋ ๋จ์๋ก ํ์ฑ / Parse record by record
while offset < decompressed_data.len() {
// ๋ ์ฝ๋ ํค๋ ํ์ฑ / Parse record header
let remaining_data = &decompressed_data[offset..];
let (header, header_size) =
RecordHeader::parse(remaining_data).map_err(|e| HwpError::from(e))?;
offset += header_size;
// ๋ฐ์ดํฐ ์์ญ ์ฝ๊ธฐ / Read data area
let data_size = header.size as usize;
if offset + data_size > decompressed_data.len() {
return Err(HwpError::InsufficientData {
field: format!("DocInfo record at offset {}", offset),
expected: offset + data_size,
actual: decompressed_data.len(),
});
}
let record_data = &decompressed_data[offset..offset + data_size];
offset += data_size;
// ํ๊ทธ๋ณ๋ก ๋ถ๋ฅํ์ฌ ์ ์ฅ / Classify and store by tag
match header.tag_id {
HwpTag::DOCUMENT_PROPERTIES => {
if header.level == 0 {
// DocumentProperties๋ ์์ ํ ํ์ฑ / Fully parse DocumentProperties
let props = DocumentProperties::parse(record_data)
.map_err(|e| HwpError::from(e))?;
doc_info.document_properties = Some(props);
}
}
HwpTag::ID_MAPPINGS => {
if header.level == 0 {
// IdMappings๋ ์์ ํ ํ์ฑ / Fully parse IdMappings
let id_mappings = IdMappings::parse(record_data, file_header.version)
.map_err(|e| HwpError::from(e))?;
doc_info.id_mappings = Some(id_mappings);
}
}
HwpTag::BIN_DATA => {
if header.level == 1 {
// BinDataRecord๋ ์์ ํ ํ์ฑ / Fully parse BinDataRecord
let bin_data_record =
BinDataRecord::parse(record_data).map_err(|e| HwpError::from(e))?;
doc_info.bin_data.push(bin_data_record);
}
}
HwpTag::FACE_NAME => {
if header.level == 1 {
// FaceName์ ์์ ํ ํ์ฑ / Fully parse FaceName
let face_name =
FaceName::parse(record_data).map_err(|e| HwpError::from(e))?;
doc_info.face_names.push(face_name);
}
}
HwpTag::BORDER_FILL => {
if header.level == 1 {
// BorderFill์ ์์ ํ ํ์ฑ / Fully parse BorderFill
let border_fill =
BorderFill::parse(record_data).map_err(|e| HwpError::from(e))?;
doc_info.border_fill.push(border_fill);
}
}
HwpTag::CHAR_SHAPE => {
if header.level == 1 {
// CharShape๋ ์์ ํ ํ์ฑ / Fully parse CharShape
let char_shape = CharShape::parse(record_data, file_header.version)
.map_err(|e| HwpError::from(e))?;
doc_info.char_shapes.push(char_shape);
}
}
HwpTag::TAB_DEF => {
if header.level == 1 {
// TabDef๋ ์์ ํ ํ์ฑ / Fully parse TabDef
let tab_def = TabDef::parse(record_data).map_err(|e| HwpError::from(e))?;
doc_info.tab_defs.push(tab_def);
}
}
HwpTag::NUMBERING => {
if header.level == 1 {
// Numbering์ ์์ ํ ํ์ฑ / Fully parse Numbering
let numbering = Numbering::parse(record_data, file_header.version)
.map_err(|e| HwpError::from(e))?;
doc_info.numbering.push(numbering);
}
}
HwpTag::BULLET => {
if header.level == 1 {
// Bullet์ ์์ ํ ํ์ฑ / Fully parse Bullet
let bullet = Bullet::parse(record_data).map_err(|e| HwpError::from(e))?;
doc_info.bullets.push(bullet);
}
}
HwpTag::PARA_SHAPE => {
if header.level == 1 {
// ParaShape์ ์์ ํ ํ์ฑ / Fully parse ParaShape
let para_shape = ParaShape::parse(record_data, file_header.version)
.map_err(|e| HwpError::from(e))?;
doc_info.para_shapes.push(para_shape);
}
}
HwpTag::STYLE => {
if header.level == 1 {
let style = Style::parse(record_data).map_err(|e| HwpError::from(e))?;
doc_info.styles.push(style);
}
}
HwpTag::DOC_DATA => {
if header.level == 0 {
// ๋ฌธ์ ์์์ ๋ฐ์ดํฐ ํ์ฑ / Parse document arbitrary data
let doc_data =
DocData::parse(record_data).map_err(|e| HwpError::from(e))?;
doc_info.doc_data.push(doc_data);
}
}
HwpTag::DISTRIBUTE_DOC_DATA => {
if header.level == 0 {
// ๋ฐฐํฌ์ฉ ๋ฌธ์ ๋ฐ์ดํฐ ํ์ฑ / Parse distribution document data
let distribute_doc_data =
DistributeDocData::parse(record_data).map_err(|e| HwpError::from(e))?;
doc_info.distribute_doc_data = Some(distribute_doc_data);
}
}
HwpTag::COMPATIBLE_DOCUMENT => {
if header.level == 0 {
// ํธํ ๋ฌธ์ ํ์ฑ / Parse compatible document
let compatible_document = CompatibleDocument::parse(record_data)
.map_err(|e| HwpError::from(e))?;
doc_info.compatible_document = Some(compatible_document);
}
}
HwpTag::LAYOUT_COMPATIBILITY => {
if header.level == 1 {
// ๋ ์ด์์ ํธํ์ฑ ํ์ฑ / Parse layout compatibility
let layout_compatibility = LayoutCompatibility::parse(record_data)
.map_err(|e| HwpError::from(e))?;
doc_info.layout_compatibility = Some(layout_compatibility);
}
}
HwpTag::TRACKCHANGE => {
if header.level == 1 {
// ๋ณ๊ฒฝ ์ถ์ ์ ๋ณด ํ์ฑ / Parse track change information
let track_change =
TrackChange::parse(record_data).map_err(|e| HwpError::from(e))?;
doc_info.track_change = Some(track_change);
}
}
HwpTag::MEMO_SHAPE => {
if header.level == 1 {
// ๋ฉ๋ชจ ๋ชจ์ ํ์ฑ / Parse memo shape
let memo_shape =
MemoShape::parse(record_data).map_err(|e| HwpError::from(e))?;
doc_info.memo_shapes.push(memo_shape);
}
}
HwpTag::FORBIDDEN_CHAR => {
if header.level == 0 {
// ๊ธ์น์ฒ๋ฆฌ ๋ฌธ์ ํ์ฑ / Parse forbidden character
let forbidden_char =
ForbiddenChar::parse(record_data).map_err(|e| HwpError::from(e))?;
doc_info.forbidden_chars.push(forbidden_char);
}
}
HwpTag::TRACK_CHANGE => {
if header.level == 1 {
// ๋ณ๊ฒฝ ์ถ์ ๋ด์ฉ ๋ฐ ๋ชจ์ ํ์ฑ / Parse track change content and shape
let track_change_content = TrackChangeContent::parse(record_data)
.map_err(|e| HwpError::from(e))?;
doc_info.track_change_contents.push(track_change_content);
}
}
HwpTag::TRACK_CHANGE_AUTHOR => {
if header.level == 1 {
// ๋ณ๊ฒฝ ์ถ์ ์์ฑ์ ํ์ฑ / Parse track change author
let track_change_author =
TrackChangeAuthor::parse(record_data).map_err(|e| HwpError::from(e))?;
doc_info.track_change_authors.push(track_change_author);
}
}
// ๊ธฐํ ํ๊ทธ๋ ๋ฌด์ (๋์ค์ ๊ตฌํ ๊ฐ๋ฅ) / Other tags are ignored (can be implemented later)
_ => {
// ์ ์ ์๋ ํ๊ทธ๋ ๋ฌด์ํ๊ณ ๊ณ์ ์งํ / Unknown tags are ignored and continue
}
}
}
Ok(doc_info)
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/style.rs | crates/hwp-core/src/document/docinfo/style.rs | /// Style ๊ตฌ์กฐ์ฒด / Style structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 47 - ์คํ์ผ / Spec mapping: Table 47 - Style
/// Tag ID: HWPTAG_STYLE
/// ์ ์ฒด ๊ธธ์ด: ๊ฐ๋ณ (12 + 2รlen1 + 2รlen2 ๋ฐ์ดํธ) / Total length: variable (12 + 2รlen1 + 2รlen2 bytes)
use crate::error::HwpError;
use crate::types::{decode_utf16le, BYTE, INT16, UINT16, WORD};
use serde::{Deserialize, Serialize};
/// ์คํ์ผ ์ข
๋ฅ / Style type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum StyleType {
/// ๋ฌธ๋จ ์คํ์ผ / Paragraph style
Paragraph = 0,
/// ๊ธ์ ์คํ์ผ / Character style
Character = 1,
}
impl StyleType {
fn from_bits(bits: u8) -> Self {
match bits & 0x07 {
1 => StyleType::Character,
_ => StyleType::Paragraph,
}
}
}
/// Style ๊ตฌ์กฐ์ฒด / Style structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Style {
/// ๋ก์ปฌ/ํ๊ธ ์คํ์ผ ์ด๋ฆ / Local/Korean style name
pub local_name: String,
/// ์๋ฌธ ์คํ์ผ ์ด๋ฆ / English style name
pub english_name: String,
/// ์์ฑ (ํ 48 ์ฐธ์กฐ, bit 0-2: ์คํ์ผ ์ข
๋ฅ) / Attributes (See Table 48, bit 0-2: style type)
pub style_type: StyleType,
/// ๋ค์ ์คํ์ผ ID ์ฐธ์กฐ ๊ฐ / Next style ID reference value
pub next_style_id: BYTE,
/// ์ธ์ด ID (ํ 48 ์ฐธ์กฐ) / Language ID (See Table 48)
pub lang_id: INT16,
/// ๋ฌธ๋จ ๋ชจ์ ID ์ฐธ์กฐ ๊ฐ (์คํ์ผ ์ข
๋ฅ๊ฐ ๋ฌธ๋จ์ธ ๊ฒฝ์ฐ ํ์) / Paragraph shape ID reference (required if style type is paragraph)
pub para_shape_id: Option<UINT16>,
/// ๊ธ์ ๋ชจ์ ID (์คํ์ผ ์ข
๋ฅ๊ฐ ๊ธ์์ธ ๊ฒฝ์ฐ ํ์) / Character shape ID (required if style type is character)
pub char_shape_id: Option<UINT16>,
}
impl Style {
/// Style์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse Style from byte array.
///
/// # Arguments
/// * `data` - Style ๋ ์ฝ๋ ๋ฐ์ดํฐ / Style record data
///
/// # Returns
/// ํ์ฑ๋ Style ๊ตฌ์กฐ์ฒด / Parsed Style structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ์ต์ 12๋ฐ์ดํธ ํ์ (๊ณ ์ ํ๋๋ค) / Need at least 12 bytes for fixed fields
if data.len() < 12 {
return Err(HwpError::insufficient_data("Style", 12, data.len()));
}
let mut offset = 0;
// WORD ๊ธธ์ด(len1) / WORD length (len1)
let len1 = WORD::from_le_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
// WCHAR array[len1] ๋ก์ปฌ/ํ๊ธ ์คํ์ผ ์ด๋ฆ / WCHAR array[len1] local/Korean style name
if offset + (len1 * 2) > data.len() {
return Err(HwpError::InsufficientData {
field: format!("Style local name at offset {}", offset),
expected: offset + (len1 * 2),
actual: data.len(),
});
}
let local_name_bytes = &data[offset..offset + (len1 * 2)];
let local_name = decode_utf16le(local_name_bytes)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode local name: {}", e),
})?;
offset += len1 * 2;
// WORD ๊ธธ์ด(len2) / WORD length (len2)
if offset + 2 > data.len() {
return Err(HwpError::insufficient_data(
"Style English name length",
2,
data.len() - offset,
));
}
let len2 = WORD::from_le_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
// WCHAR array[len2] ์๋ฌธ ์คํ์ผ ์ด๋ฆ / WCHAR array[len2] English style name
if offset + (len2 * 2) > data.len() {
return Err(HwpError::InsufficientData {
field: format!("Style English name at offset {}", offset),
expected: offset + (len2 * 2),
actual: data.len(),
});
}
let english_name_bytes = &data[offset..offset + (len2 * 2)];
let english_name = decode_utf16le(english_name_bytes)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode English name: {}", e),
})?;
offset += len2 * 2;
// BYTE ์์ฑ (ํ 48 ์ฐธ์กฐ, bit 0-2: ์คํ์ผ ์ข
๋ฅ) / BYTE attributes (See Table 48, bit 0-2: style type)
if offset + 1 > data.len() {
return Err(HwpError::insufficient_data(
"Style attributes",
1,
data.len() - offset,
));
}
let attributes = data[offset];
offset += 1;
let style_type = StyleType::from_bits(attributes);
// BYTE ๋ค์ ์คํ์ผ ID ์ฐธ์กฐ ๊ฐ / BYTE next style ID reference value
if offset + 1 > data.len() {
return Err(HwpError::insufficient_data(
"Style next style ID",
1,
data.len() - offset,
));
}
let next_style_id = data[offset];
offset += 1;
// INT16 ์ธ์ด ID (ํ 48 ์ฐธ์กฐ) / INT16 language ID (See Table 48)
if offset + 2 > data.len() {
return Err(HwpError::insufficient_data(
"Style language ID",
2,
data.len() - offset,
));
}
let lang_id = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT16 ๋ฌธ๋จ ๋ชจ์ ID ์ฐธ์กฐ ๊ฐ (์คํ์ผ ์ข
๋ฅ๊ฐ ๋ฌธ๋จ์ธ ๊ฒฝ์ฐ ํ์) / UINT16 paragraph shape ID reference (required if style type is paragraph)
if offset + 2 > data.len() {
return Err(HwpError::insufficient_data(
"Style paragraph shape ID",
2,
data.len() - offset,
));
}
let para_shape_id_value = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let para_shape_id = if style_type == StyleType::Paragraph {
Some(para_shape_id_value)
} else {
None
};
// UINT16 ๊ธ์ ๋ชจ์ ID (์คํ์ผ ์ข
๋ฅ๊ฐ ๊ธ์์ธ ๊ฒฝ์ฐ ํ์) / UINT16 character shape ID (required if style type is character)
if offset + 2 > data.len() {
return Err(HwpError::insufficient_data(
"Style character shape ID",
2,
data.len() - offset,
));
}
let char_shape_id_value = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let char_shape_id = if style_type == StyleType::Character {
Some(char_shape_id_value)
} else {
None
};
Ok(Style {
local_name,
english_name,
style_type,
next_style_id,
lang_id,
para_shape_id,
char_shape_id,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/numbering.rs | crates/hwp-core/src/document/docinfo/numbering.rs | /// Numbering ๊ตฌ์กฐ์ฒด / Numbering structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 38 - ๋ฌธ๋จ ๋ฒํธ / Spec mapping: Table 38 - Paragraph numbering
/// Tag ID: HWPTAG_NUMBERING
/// ์ ์ฒด ๊ธธ์ด: ๊ฐ๋ณ / Total length: variable
use crate::error::HwpError;
use crate::types::{decode_utf16le, HWPUNIT16, UINT16, UINT32, WORD};
use serde::{Deserialize, Serialize};
/// ๋ฌธ๋จ ๋จธ๋ฆฌ ์ ๋ณด ์์ฑ / Paragraph header information attributes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NumberingHeaderAttributes {
/// ๋ฌธ๋จ์ ์ ๋ ฌ ์ข
๋ฅ / Paragraph alignment type
pub align_type: ParagraphAlignType,
/// ์ธ์คํด์ค ์ ์ฌ ์ฌ๋ถ (bit 2) / Instance-like flag (bit 2)
pub instance_like: bool,
/// ์๋ ๋ด์ด ์ฐ๊ธฐ ์ฌ๋ถ / Auto outdent flag
pub auto_outdent: bool,
/// ์์ค๋ณ ๋ณธ๋ฌธ๊ณผ์ ๊ฑฐ๋ฆฌ ์ข
๋ฅ / Distance type from body text by level
pub distance_type: DistanceType,
}
/// ๋ฌธ๋จ ์ ๋ ฌ ์ข
๋ฅ / Paragraph alignment type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ParagraphAlignType {
/// ์ผ์ชฝ / Left
Left = 0,
/// ๊ฐ์ด๋ฐ / Center
Center = 1,
/// ์ค๋ฅธ์ชฝ / Right
Right = 2,
}
impl ParagraphAlignType {
fn from_bits(bits: u32) -> Self {
match bits & 0x00000003 {
1 => ParagraphAlignType::Center,
2 => ParagraphAlignType::Right,
_ => ParagraphAlignType::Left,
}
}
}
/// ์์ค๋ณ ๋ณธ๋ฌธ๊ณผ์ ๊ฑฐ๋ฆฌ ์ข
๋ฅ / Distance type from body text by level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DistanceType {
/// ๊ธ์ ํฌ๊ธฐ์ ๋ํ ์๋ ๋น์จ / Relative ratio to font size
Ratio = 0,
/// ๊ฐ / Value
Value = 1,
}
impl DistanceType {
fn from_bit(bit: bool) -> Self {
if bit {
DistanceType::Value
} else {
DistanceType::Ratio
}
}
}
/// ๋ฌธ๋จ ๋จธ๋ฆฌ ์ ๋ณด (์์ค๋ณ) / Paragraph header information (per level)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NumberingLevelInfo {
/// ์์ฑ (ํ 40) / Attributes (Table 40)
pub attributes: NumberingHeaderAttributes,
/// ๋๋น ๋ณด์ ๊ฐ / Width correction value
pub width: HWPUNIT16,
/// ๋ณธ๋ฌธ๊ณผ์ ๊ฑฐ๋ฆฌ / Distance from body text
pub distance: HWPUNIT16,
/// ๊ธ์ ๋ชจ์ ์์ด๋ ์ฐธ์กฐ / Character shape ID reference
pub char_shape_id: UINT32,
/// ๋ฒํธ ํ์ ๊ธธ์ด / Number format length
pub format_length: WORD,
/// ๋ฒํธ ํ์ ๋ฌธ์์ด / Number format string
pub format_string: String,
/// ์์ ๋ฒํธ / Start number
pub start_number: UINT16,
/// ์์ค๋ณ ์์๋ฒํธ (5.0.2.5 ์ด์, ์ต์
) / Level-specific start number (5.0.2.5+, optional)
pub level_start_number: Option<UINT32>,
}
/// Numbering ๊ตฌ์กฐ์ฒด / Numbering structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Numbering {
/// ์์ค๋ณ ๋ฌธ๋จ ๋จธ๋ฆฌ ์ ๋ณด (7๊ฐ ์์ค, 1~7) / Level-specific paragraph header information (7 levels, 1~7)
pub levels: Vec<NumberingLevelInfo>,
/// ํ์ฅ ๋ฒํธ ํ์ (3๊ฐ ์์ค, 8~10, ์ต์
) / Extended number format (3 levels, 8~10, optional)
pub extended_levels: Vec<ExtendedNumberingLevel>,
}
/// ํ์ฅ ๋ฒํธ ํ์ (์์ค 8~10) / Extended number format (levels 8~10)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtendedNumberingLevel {
/// ๋ฒํธ ํ์ ๊ธธ์ด / Number format length
pub format_length: WORD,
/// ๋ฒํธ ํ์ ๋ฌธ์์ด / Number format string
pub format_string: String,
}
impl Numbering {
/// Numbering์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse Numbering from byte array.
///
/// # Arguments
/// * `data` - Numbering ๋ ์ฝ๋ ๋ฐ์ดํฐ / Numbering record data
/// * `version` - HWP ํ์ผ ๋ฒ์ (5.0.2.5 ์ด์์์ ์์ค๋ณ ์์๋ฒํธ ์ง์) / HWP file version (level-specific start numbers supported in 5.0.2.5+)
///
/// # Returns
/// ํ์ฑ๋ Numbering ๊ตฌ์กฐ์ฒด / Parsed Numbering structure
pub fn parse(data: &[u8], version: u32) -> Result<Self, HwpError> {
let mut offset = 0;
let mut levels = Vec::new();
// 7๊ฐ ์์ค ํ์ฑ (1~7) / Parse 7 levels (1~7)
for _ in 0..7 {
// ๋ฐ์ดํฐ๊ฐ ๋ถ์กฑํ๋ฉด ๊ธฐ๋ณธ๊ฐ์ผ๋ก ์ฑ์ฐ๊ณ ์ข
๋ฃ / Fill with defaults and exit if insufficient data
if offset + 12 > data.len() {
// ์ต์ 12๋ฐ์ดํธ (์์ฑ 4 + ๋๋น 2 + ๊ฑฐ๋ฆฌ 2 + ๊ธ์๋ชจ์ID 4) ํ์ / Need at least 12 bytes
break;
}
// UINT ์์ฑ (ํ 40) / UINT attributes (Table 40)
let attr_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let attributes = NumberingHeaderAttributes {
align_type: ParagraphAlignType::from_bits(attr_value),
instance_like: (attr_value & 0x00000004) != 0,
auto_outdent: (attr_value & 0x00000008) != 0,
distance_type: DistanceType::from_bit((attr_value & 0x00000010) != 0),
};
// HWPUNIT16 ๋๋น ๋ณด์ ๊ฐ / HWPUNIT16 width correction value
let width = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// HWPUNIT16 ๋ณธ๋ฌธ๊ณผ์ ๊ฑฐ๋ฆฌ / HWPUNIT16 distance from body text
let distance = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT ๊ธ์ ๋ชจ์ ์์ด๋ ์ฐธ์กฐ / UINT character shape ID reference
let char_shape_id = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// WORD ๋ฒํธ ํ์ ๊ธธ์ด / WORD number format length
let (format_length, format_string) = if offset + 2 <= data.len() {
let len = WORD::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// WCHAR array[format_length] ๋ฒํธ ํ์ ๋ฌธ์์ด / WCHAR array[format_length] number format string
let format_bytes = len as usize * 2;
if offset + format_bytes <= data.len() {
let str = decode_utf16le(&data[offset..offset + format_bytes])
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode numbering format: {}", e),
})?;
offset += format_bytes;
(len, str)
} else {
// ๋ฐ์ดํฐ๊ฐ ๋ถ์กฑํ๋ฉด ๋น ๋ฌธ์์ด / Empty string if insufficient data
(0, String::new())
}
} else {
// ๋ฐ์ดํฐ๊ฐ ๋ถ์กฑํ๋ฉด ๊ธฐ๋ณธ๊ฐ ์ฌ์ฉ / Use default if insufficient data
(0, String::new())
};
// UINT16 ์์ ๋ฒํธ / UINT16 start number
let start_number = if offset + 2 <= data.len() {
let value = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
value
} else {
0
};
// UINT ์์ค๋ณ ์์๋ฒํธ (5.0.2.5 ์ด์, ์ต์
) / UINT level-specific start number (5.0.2.5+, optional)
let level_start_number = if version >= 0x00020500 && offset + 4 <= data.len() {
let value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
Some(value)
} else {
None
};
levels.push(NumberingLevelInfo {
attributes,
width,
distance,
char_shape_id,
format_length,
format_string,
start_number,
level_start_number,
});
}
// ํ์ฅ ๋ฒํธ ํ์ ํ์ฑ (3๊ฐ ์์ค, 8~10) / Parse extended number format (3 levels, 8~10)
let mut extended_levels = Vec::new();
for _ in 0..3 {
if offset + 2 > data.len() {
// ํ์ฅ ๋ ๋ฒจ์ด ์์ ์ ์์ / Extended levels may not exist
break;
}
// WORD ํ์ฅ ๋ฒํธ ํ์ ๊ธธ์ด / WORD extended number format length
let format_length = WORD::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// WCHAR array[format_length] ํ์ฅ ๋ฒํธ ํ์ ๋ฌธ์์ด / WCHAR array[format_length] extended number format string
let format_bytes = format_length as usize * 2;
if offset + format_bytes > data.len() {
// ํ์ฅ ๋ ๋ฒจ ๋ฐ์ดํฐ๊ฐ ๋ถ์์ ํ ์ ์์ / Extended level data may be incomplete
break;
}
let format_string = decode_utf16le(&data[offset..offset + format_bytes])
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode extended numbering format: {}", e),
})?;
offset += format_bytes;
extended_levels.push(ExtendedNumberingLevel {
format_length,
format_string,
});
}
Ok(Numbering {
levels,
extended_levels,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/constants.rs | crates/hwp-core/src/document/docinfo/constants.rs | /// DocInfo ํ๊ทธ ์์ ์ ์ / DocInfo tag constants definition
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 13 - ๋ฌธ์ ์ ๋ณด์ ๋ฐ์ดํฐ ๋ ์ฝ๋ / Spec mapping: Table 13 - Document information data records
use crate::document::constants::HWPTAG_BEGIN;
/// DocInfo ํ๊ทธ ์์ / DocInfo tag constants
pub struct HwpTag;
impl HwpTag {
/// ๋ฌธ์ ์์ฑ / Document properties
pub const DOCUMENT_PROPERTIES: u16 = HWPTAG_BEGIN;
/// ์์ด๋ ๋งคํ ํค๋ / ID mappings header
pub const ID_MAPPINGS: u16 = HWPTAG_BEGIN + 1;
/// ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ / Binary data
pub const BIN_DATA: u16 = HWPTAG_BEGIN + 2;
/// ๊ธ๊ผด (Typeface Name) / Face name (Typeface Name)
pub const FACE_NAME: u16 = HWPTAG_BEGIN + 3;
/// ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ / Border/fill
pub const BORDER_FILL: u16 = HWPTAG_BEGIN + 4;
/// ๊ธ์ ๋ชจ์ / Character shape
pub const CHAR_SHAPE: u16 = HWPTAG_BEGIN + 5;
/// ํญ ์ ์ / Tab definition
pub const TAB_DEF: u16 = HWPTAG_BEGIN + 6;
/// ๋ฒํธ ์ ์ / Numbering definition
pub const NUMBERING: u16 = HWPTAG_BEGIN + 7;
/// ๋ถ๋ฆฟ ์ ์ / Bullet definition
pub const BULLET: u16 = HWPTAG_BEGIN + 8;
/// ๋ฌธ๋จ ๋ชจ์ / Paragraph shape
pub const PARA_SHAPE: u16 = HWPTAG_BEGIN + 9;
/// ์คํ์ผ / Style
pub const STYLE: u16 = HWPTAG_BEGIN + 10;
/// ๋ฌธ์์ ์์์ ๋ฐ์ดํฐ / Document arbitrary data
pub const DOC_DATA: u16 = HWPTAG_BEGIN + 11;
/// ๋ฐฐํฌ์ฉ ๋ฌธ์ ๋ฐ์ดํฐ / Distribution document data
pub const DISTRIBUTE_DOC_DATA: u16 = HWPTAG_BEGIN + 12;
/// ์์ฝ / Reserved
pub const RESERVED: u16 = HWPTAG_BEGIN + 13;
/// ํธํ ๋ฌธ์ / Compatible document
pub const COMPATIBLE_DOCUMENT: u16 = HWPTAG_BEGIN + 14;
/// ๋ ์ด์์ ํธํ์ฑ / Layout compatibility
pub const LAYOUT_COMPATIBILITY: u16 = HWPTAG_BEGIN + 15;
/// ๋ณ๊ฒฝ ์ถ์ ์ ๋ณด / Track change information
pub const TRACKCHANGE: u16 = HWPTAG_BEGIN + 16;
/// ๋ฉ๋ชจ ๋ชจ์ / Memo shape
pub const MEMO_SHAPE: u16 = HWPTAG_BEGIN + 76;
/// ๊ธ์น์ฒ๋ฆฌ ๋ฌธ์ / Forbidden character
pub const FORBIDDEN_CHAR: u16 = HWPTAG_BEGIN + 78;
/// ๋ณ๊ฒฝ ์ถ์ ๋ด์ฉ ๋ฐ ๋ชจ์ / Track change content and shape
pub const TRACK_CHANGE: u16 = HWPTAG_BEGIN + 80;
/// ๋ณ๊ฒฝ ์ถ์ ์์ฑ์ / Track change author
pub const TRACK_CHANGE_AUTHOR: u16 = HWPTAG_BEGIN + 81;
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/doc_data.rs | crates/hwp-core/src/document/docinfo/doc_data.rs | /// DocData ๊ตฌ์กฐ์ฒด / DocData structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 49 - ๋ฌธ์ ์์์ ๋ฐ์ดํฐ / Spec mapping: Table 49 - Document arbitrary data
use crate::error::HwpError;
use crate::types::{decode_utf16le, INT16, INT32, INT8, UINT16, UINT32, UINT8, WORD};
use serde::{Deserialize, Serialize};
/// ๋ฌธ์ ์์์ ๋ฐ์ดํฐ (ํ 49) / Document arbitrary data (Table 49)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocData {
/// ํ๋ผ๋ฏธํฐ ์
(ํ 50 ์ฐธ์กฐ) / Parameter set (see Table 50)
pub parameter_set: ParameterSet,
}
/// ํ๋ผ๋ฏธํฐ ์
(ํ 50) / Parameter set (Table 50)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParameterSet {
/// ํ๋ผ๋ฏธํฐ ์
ID / Parameter set ID
pub set_id: WORD,
/// ํ๋ผ๋ฏธํฐ ์
์ ์กด์ฌํ๋ ์์ดํ
๊ฐ์ / Number of items in parameter set
pub item_count: INT16,
/// ํ๋ผ๋ฏธํฐ ์์ดํ
๋ฆฌ์คํธ / Parameter item list
pub items: Vec<ParameterItem>,
}
/// ํ๋ผ๋ฏธํฐ ์์ดํ
(ํ 51) / Parameter item (Table 51)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParameterItem {
/// ํ๋ผ๋ฏธํฐ ์์ดํ
ID / Parameter item ID
pub id: WORD,
/// ํ๋ผ๋ฏธํฐ ์์ดํ
์ข
๋ฅ (ํ 52 ์ฐธ์กฐ) / Parameter item type (see Table 52)
pub item_type: ParameterItemType,
/// ํ๋ผ๋ฏธํฐ ์์ดํ
๋ฐ์ดํฐ / Parameter item data
pub data: ParameterItemData,
}
/// ํ๋ผ๋ฏธํฐ ์์ดํ
์ข
๋ฅ (ํ 52) / Parameter item type (Table 52)
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ParameterItemType {
/// NULL / NULL
Null,
/// ๋ฌธ์์ด / String
Bstr,
/// INT8 / INT8
I1,
/// INT16 / INT16
I2,
/// INT32 / INT32
I4,
/// INT / INT
I,
/// UINT8 / UINT8
Ui1,
/// UINT16 / UINT16
Ui2,
/// UINT32 / UINT32
Ui4,
/// UINT / UINT
Ui,
/// ํ๋ผ๋ฏธํฐ ์
/ Parameter set
Set,
/// ํ๋ผ๋ฏธํฐ ์
๋ฐฐ์ด / Parameter set array
Array,
/// ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ ID / Binary data ID
Bindata,
}
/// ํ๋ผ๋ฏธํฐ ์์ดํ
๋ฐ์ดํฐ / Parameter item data
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ParameterItemData {
/// NULL / NULL
Null,
/// ๋ฌธ์์ด / String
Bstr(String),
/// INT8 / INT8
I1(INT8),
/// INT16 / INT16
I2(INT16),
/// INT32 / INT32
I4(INT32),
/// INT / INT
I(INT8),
/// UINT8 / UINT8
Ui1(UINT8),
/// UINT16 / UINT16
Ui2(UINT16),
/// UINT32 / UINT32
Ui4(UINT32),
/// UINT / UINT
Ui(UINT8),
/// ํ๋ผ๋ฏธํฐ ์
/ Parameter set
Set(ParameterSet),
/// ํ๋ผ๋ฏธํฐ ์
๋ฐฐ์ด / Parameter set array
Array(Vec<ParameterSet>),
/// ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ ID / Binary data ID
Bindata(UINT16),
}
impl DocData {
/// DocData๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse DocData from byte array.
///
/// # Arguments
/// * `data` - DocData ๋ฐ์ดํฐ / DocData data
///
/// # Returns
/// ํ์ฑ๋ DocData ๊ตฌ์กฐ์ฒด / Parsed DocData structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.is_empty() {
return Err(HwpError::InsufficientData {
field: "DocData data".to_string(),
expected: 1,
actual: 0,
});
}
// ํ๋ผ๋ฏธํฐ ์
ํ์ฑ (ํ 50) / Parse parameter set (Table 50)
let parameter_set = ParameterSet::parse(data)?;
Ok(DocData { parameter_set })
}
}
impl ParameterSet {
/// ParameterSet์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ParameterSet from byte array.
///
/// # Arguments
/// * `data` - ParameterSet ๋ฐ์ดํฐ / ParameterSet data
///
/// # Returns
/// ํ์ฑ๋ ParameterSet ๊ตฌ์กฐ์ฒด / Parsed ParameterSet structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 4 {
return Err(HwpError::insufficient_data("ParameterSet", 4, data.len()));
}
let mut offset = 0;
// WORD ํ๋ผ๋ฏธํฐ ์
ID / WORD parameter set ID
let set_id = WORD::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// INT16 ํ๋ผ๋ฏธํฐ ์
์ ์กด์ฌํ๋ ์์ดํ
๊ฐ์ / INT16 number of items in parameter set
let item_count = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// ํ๋ผ๋ฏธํฐ ์์ดํ
ํ์ฑ / Parse parameter items
let mut items = Vec::new();
let mut current_offset = offset;
for _ in 0..item_count {
if current_offset >= data.len() {
break; // ๋ฐ์ดํฐ๊ฐ ๋ถ์กฑํ ์ ์์ / Data may be insufficient
}
match ParameterItem::parse(&data[current_offset..]) {
Ok((item, item_size)) => {
items.push(item);
current_offset += item_size;
}
Err(e) => {
// ํ์ฑ ์คํจ ์ ๊ฒฝ๊ณ ํ๊ณ ๊ณ์ ์งํ / Warn and continue on parse failure
// ์ ์ ์๋ ํ์
์ ๊ฒฝ์ฐ ParameterItem::parse์์ ์ด๋ฏธ ์ฒ๋ฆฌํ๋ฏ๋ก ์ฌ๊ธฐ ๋๋ฌํ์ง ์์์ผ ํจ
// Continue on parse error with warning
// Unknown types should be handled in ParameterItem::parse, so this shouldn't be reached
#[cfg(debug_assertions)]
eprintln!("Failed to parse parameter item: {}", e);
// ์๋ฌ๊ฐ ๋ฐ์ํ ๊ฒฝ์ฐ ์ต์ํ id์ item_type(4๋ฐ์ดํธ)๋ ๊ฑด๋๋ฐ๊ณ ๊ณ์ ์งํ
// On error, skip at least id and item_type (4 bytes) and continue
if current_offset + 4 <= data.len() {
current_offset += 4;
} else {
break;
}
}
}
}
Ok(ParameterSet {
set_id,
item_count,
items,
})
}
}
impl ParameterItem {
/// ParameterItem์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ParameterItem from byte array.
///
/// # Arguments
/// * `data` - ParameterItem ๋ฐ์ดํฐ / ParameterItem data
///
/// # Returns
/// ํ์ฑ๋ ParameterItem๊ณผ ์ฌ์ฉ๋ ๋ฐ์ดํธ ์ / Parsed ParameterItem and bytes consumed
pub fn parse(data: &[u8]) -> Result<(Self, usize), HwpError> {
if data.len() < 4 {
return Err(HwpError::insufficient_data("ParameterItem", 4, data.len()));
}
let mut offset = 0;
// WORD ํ๋ผ๋ฏธํฐ ์์ดํ
ID / WORD parameter item ID
let id = WORD::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// WORD ํ๋ผ๋ฏธํฐ ์์ดํ
์ข
๋ฅ (ํ 52 ์ฐธ์กฐ) / WORD parameter item type (see Table 52)
let item_type_value = WORD::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let item_type = match item_type_value {
0 => ParameterItemType::Null,
1 => ParameterItemType::Bstr,
2 => ParameterItemType::I1,
3 => ParameterItemType::I2,
4 => ParameterItemType::I4,
5 => ParameterItemType::I,
6 => ParameterItemType::Ui1,
7 => ParameterItemType::Ui2,
8 => ParameterItemType::Ui4,
9 => ParameterItemType::Ui,
0x8000 => ParameterItemType::Set,
0x8001 => ParameterItemType::Array,
0x8002 => ParameterItemType::Bindata,
_ => {
// ์คํ ๋ฌธ์(ํ 52)์ ๋ช
์๋์ง ์์ ์ ์ ์๋ ํ์
// Unknown type not specified in spec (Table 52)
//
// ์ด์ : ์คํ ๋ฌธ์ ํ 52์๋ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0x8000, 0x8001, 0x8002๋ง ์ ์๋์ด ์์
// Reason: Spec document Table 52 only defines 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0x8000, 0x8001, 0x8002
//
// ์ค์ ํ์ผ์์ ๋ฐ๊ฒฌ๋ ํ์
(์: 519 = 0x0207)์ ์คํ ๋ฌธ์์ ์์ผ๋ฏ๋ก
// ๋ฐ์ดํฐ ํฌ๊ธฐ๋ฅผ ์ ์ ์์ด ํ์ฑํ ์ ์์
// Types found in actual files (e.g., 519 = 0x0207) are not in spec,
// so we cannot determine data size and cannot parse
//
// ๋ณ๋ ์ฒ๋ฆฌ: ์ ์ ์๋ ํ์
์ ๊ฒฝ์ฐ id์ item_type๋ง ์ ์ฅํ๊ณ ๋ฐ์ดํฐ๋ ๊ฑด๋๋
// Special handling: For unknown types, only save id and item_type, skip data
#[cfg(debug_assertions)]
eprintln!(
"Warning: Unknown parameter item type: {} (0x{:04x}) - not in spec Table 52, skipping data",
item_type_value, item_type_value
);
// ์ ์ ์๋ ํ์
์ ๊ฒฝ์ฐ ๋ฐ์ดํฐ ํฌ๊ธฐ๋ฅผ ์ ์ ์์ผ๋ฏ๋ก, id์ item_type๋ง ๋ฐํ
// For unknown types, we can't determine data size, so return only id and item_type
return Ok((
ParameterItem {
id,
item_type: ParameterItemType::Null, // ์ ์ ์๋ ํ์
์ด๋ฏ๋ก Null๋ก ํ์ / Mark as Null for unknown type
data: ParameterItemData::Null,
},
4, // id(2) + item_type(2)๋ง ์ฌ์ฉ / Only id(2) + item_type(2) consumed
));
}
};
// ํ๋ผ๋ฏธํฐ ์์ดํ
๋ฐ์ดํฐ ํ์ฑ / Parse parameter item data
let (data_value, data_size) = parse_parameter_item_data(&data[offset..], item_type)
.map_err(|e| HwpError::from(e))?;
offset += data_size;
Ok((
ParameterItem {
id,
item_type,
data: data_value,
},
offset,
))
}
}
/// ํ๋ผ๋ฏธํฐ ์์ดํ
๋ฐ์ดํฐ ํ์ฑ / Parse parameter item data
fn parse_parameter_item_data(
data: &[u8],
item_type: ParameterItemType,
) -> Result<(ParameterItemData, usize), HwpError> {
match item_type {
ParameterItemType::Null => {
// PIT_NULL: UINT | NULL
// ์คํ ๋ฌธ์: "UINT | NULL" - NULL์ด๋ฏ๋ก ๋ฐ์ดํฐ ์์
// Spec: "UINT | NULL" - no data for NULL
Ok((ParameterItemData::Null, 0))
}
ParameterItemType::Bstr => {
// PIT_BSTR: WORD ๋ฌธ์์ด ๊ธธ์ด(slen) + WCHAR array[len]
// ์คํ ๋ฌธ์: "WORD | ๋ฌธ์์ด ๊ธธ์ด(slen)" + "WCHAR array[len]"
// Spec: "WORD | string length(slen)" + "WCHAR array[len]"
if data.len() < 2 {
return Err(HwpError::insufficient_data("BSTR length", 2, data.len()));
}
let string_len = WORD::from_le_bytes([data[0], data[1]]) as usize;
let total_size = 2 + (string_len * 2); // WORD(2) + WCHAR array
if data.len() < total_size {
return Err(HwpError::InsufficientData {
field: "BSTR data".to_string(),
expected: total_size,
actual: data.len(),
});
}
let string_bytes = &data[2..total_size];
let string = decode_utf16le(string_bytes)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode BSTR: {}", e),
})?;
Ok((ParameterItemData::Bstr(string), total_size))
}
ParameterItemType::I1 => {
// PIT_I1: INT8 / PIT_I1: INT8
if data.len() < 1 {
return Err(HwpError::insufficient_data("I1", 1, data.len()));
}
Ok((ParameterItemData::I1(INT8::from_le_bytes([data[0]])), 1))
}
ParameterItemType::I2 => {
// PIT_I2: INT16 / PIT_I2: INT16
if data.len() < 2 {
return Err(HwpError::insufficient_data("I2", 2, data.len()));
}
Ok((
ParameterItemData::I2(INT16::from_le_bytes([data[0], data[1]])),
2,
))
}
ParameterItemType::I4 => {
// PIT_I4: INT32 / PIT_I4: INT32
if data.len() < 4 {
return Err(HwpError::insufficient_data("I4", 4, data.len()));
}
Ok((
ParameterItemData::I4(INT32::from_le_bytes([data[0], data[1], data[2], data[3]])),
4,
))
}
ParameterItemType::I => {
// PIT_I: INT8 / PIT_I: INT8
if data.len() < 1 {
return Err(HwpError::insufficient_data("I", 1, data.len()));
}
Ok((ParameterItemData::I(INT8::from_le_bytes([data[0]])), 1))
}
ParameterItemType::Ui1 => {
// PIT_UI1: UINT8 / PIT_UI1: UINT8
if data.len() < 1 {
return Err(HwpError::insufficient_data("UI1", 1, data.len()));
}
Ok((ParameterItemData::Ui1(UINT8::from_le_bytes([data[0]])), 1))
}
ParameterItemType::Ui2 => {
// PIT_UI2: UINT16 / PIT_UI2: UINT16
if data.len() < 2 {
return Err(HwpError::insufficient_data("UI2", 2, data.len()));
}
Ok((
ParameterItemData::Ui2(UINT16::from_le_bytes([data[0], data[1]])),
2,
))
}
ParameterItemType::Ui4 => {
// PIT_UI4: UINT32 / PIT_UI4: UINT32
if data.len() < 4 {
return Err(HwpError::insufficient_data("UI4", 4, data.len()));
}
Ok((
ParameterItemData::Ui4(UINT32::from_le_bytes([data[0], data[1], data[2], data[3]])),
4,
))
}
ParameterItemType::Ui => {
// PIT_UI: UINT8 / PIT_UI: UINT8
if data.len() < 1 {
return Err(HwpError::insufficient_data("UI", 1, data.len()));
}
Ok((ParameterItemData::Ui(UINT8::from_le_bytes([data[0]])), 1))
}
ParameterItemType::Set => {
// PIT_SET: Parameter Set / PIT_SET: Parameter Set
// ์ฌ๊ท์ ์ผ๋ก ํ์ฑ / Parse recursively
let parameter_set = ParameterSet::parse(data)
.map_err(|e| HwpError::from(e))?;
// ์ฌ์ฉ๋ ๋ฐ์ดํธ ์ ๊ณ์ฐ (๋๋ต์ ์ผ๋ก) / Calculate bytes consumed (approximately)
let size = 4 + parameter_set.items.iter().map(|_| 4).sum::<usize>(); // ์ต์ ํฌ๊ธฐ / Minimum size
Ok((ParameterItemData::Set(parameter_set), size))
}
ParameterItemType::Array => {
// PIT_ARRAY: ParameterArray / PIT_ARRAY: ParameterArray
// INT16 ํ๋ผ๋ฏธํฐ ์
๊ฐ์ + Parameter Set ๋ฐฐ์ด / INT16 parameter set count + Parameter Set array
if data.len() < 2 {
return Err(HwpError::insufficient_data("Array count", 2, data.len()));
}
let array_count = INT16::from_le_bytes([data[0], data[1]]) as usize;
let mut offset = 2;
let mut parameter_sets = Vec::new();
for _ in 0..array_count {
if offset >= data.len() {
break;
}
match ParameterSet::parse(&data[offset..]) {
Ok(set) => {
// ๋๋ต์ ์ธ ํฌ๊ธฐ ๊ณ์ฐ / Approximate size calculation
let set_size = 4 + set.items.len() * 4;
offset += set_size;
parameter_sets.push(set);
}
Err(e) => {
#[cfg(debug_assertions)]
eprintln!("Failed to parse parameter set in array: {}", e);
break;
}
}
}
Ok((ParameterItemData::Array(parameter_sets), offset))
}
ParameterItemType::Bindata => {
// PIT_BINDATA: UINT16 ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ ID / PIT_BINDATA: UINT16 binary data ID
if data.len() < 2 {
return Err(HwpError::insufficient_data("Bindata", 2, data.len()));
}
Ok((
ParameterItemData::Bindata(UINT16::from_le_bytes([data[0], data[1]])),
2,
))
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/para_shape.rs | crates/hwp-core/src/document/docinfo/para_shape.rs | /// ParaShape ๊ตฌ์กฐ์ฒด / ParaShape structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 43 - ๋ฌธ๋จ ๋ชจ์ / Spec mapping: Table 43 - Paragraph shape
/// Tag ID: HWPTAG_PARA_SHAPE
/// ์ ์ฒด ๊ธธ์ด: 54๋ฐ์ดํธ / Total length: 54 bytes
use crate::error::HwpError;
use crate::types::{INT16, INT32, UINT16, UINT32, UINT8};
use serde::{Deserialize, Serialize};
/// ๋ฌธ๋จ ๋ชจ์ ์์ฑ1 / Paragraph shape attributes 1
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParaShapeAttributes1 {
/// ์ค ๊ฐ๊ฒฉ ์ข
๋ฅ(ํ๊ธ 2007 ์ดํ ๋ฒ์ ) / Line spacing type (HWP 2007 and below)
pub line_spacing_type_old: LineSpacingTypeOld,
/// ์ ๋ ฌ ๋ฐฉ๋ฒ / Alignment method
pub align: ParagraphAlignment,
/// ์ค ๋๋ ๊ธฐ์ค ์๋ฌธ ๋จ์ / Line break unit for English
pub line_divide_en: LineDivideUnit,
/// ์ค ๋๋ ๊ธฐ์ค ํ๊ธ ๋จ์ / Line break unit for Korean
pub line_divide_ko: LineDivideUnit,
/// ํธ์ง ์ฉ์ง์ ์ค ๊ฒฉ์ ์ฌ์ฉ ์ฌ๋ถ / Use line grid of editing paper
pub use_line_grid: bool,
/// ์ต์ ๊ณต๋ฐฑ ๊ฐ(0%~75%) / Minimum blank value (0%~75%)
pub blank_min_value: UINT8,
/// ์ธํจ์ด ์ค ๋ณดํธ / Protect orphan line
pub protect_orphan_line: bool,
/// ๋ค์ ๋ฌธ๋จ๊ณผ ํจ๊ป / With next paragraph
pub with_next_paragraph: bool,
/// ๋ฌธ๋จ ๋ณดํธ / Protect paragraph
pub protect_paragraph: bool,
/// ๋ฌธ๋จ ์์์ ํญ์ ์ชฝ ๋๋ / Always page break before paragraph
pub always_page_break_before: bool,
/// ์ธ๋ก ์ ๋ ฌ / Vertical alignment
pub vertical_align: VerticalAlignment,
/// ๊ธ๊ผด์ ๋ง๋ ์ค ๋์ด / Line height matches font
pub line_height_matches_font: bool,
/// ๋ฌธ๋จ ๋จธ๋ฆฌ ๋ชจ์ ์ข
๋ฅ / Paragraph header shape type
pub header_shape_type: HeaderShapeType,
/// ๋ฌธ๋จ ์์ค(1~7) / Paragraph level (1~7)
pub paragraph_level: UINT8,
/// ๋ฌธ๋จ ํ
๋๋ฆฌ ์ฐ๊ฒฐ / Connect paragraph border
pub connect_border: bool,
/// ๋ฌธ๋จ ์ฌ๋ฐฑ ๋ฌด์ / Ignore paragraph margin
pub ignore_margin: bool,
/// ๋ฌธ๋จ ๊ผฌ๋ฆฌ ๋ชจ์ / Paragraph tail shape
pub tail_shape: bool,
}
/// ์ค ๊ฐ๊ฒฉ ์ข
๋ฅ(ํ๊ธ 2007 ์ดํ ๋ฒ์ ) / Line spacing type (HWP 2007 and below)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LineSpacingTypeOld {
/// ๊ธ์์ ๋ฐ๋ผ(%) / By character (%)
ByCharacter = 0,
/// ๊ณ ์ ๊ฐ / Fixed value
Fixed = 1,
/// ์ฌ๋ฐฑ๋ง ์ง์ / Margin only
MarginOnly = 2,
}
impl LineSpacingTypeOld {
fn from_bits(bits: u32) -> Self {
match bits & 0x00000003 {
1 => LineSpacingTypeOld::Fixed,
2 => LineSpacingTypeOld::MarginOnly,
_ => LineSpacingTypeOld::ByCharacter,
}
}
}
/// ์ ๋ ฌ ๋ฐฉ๋ฒ / Alignment method
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ParagraphAlignment {
/// ์์ชฝ ์ ๋ ฌ / Justify
Justify = 0,
/// ์ผ์ชฝ / Left
Left = 1,
/// ์ค๋ฅธ์ชฝ / Right
Right = 2,
/// ๊ฐ์ด๋ฐ / Center
Center = 3,
/// ๋ฐฐ๋ถ / Distribute
Distribute = 4,
/// ๋๋ / Divide
Divide = 5,
}
impl ParagraphAlignment {
fn from_bits(bits: u32) -> Self {
match (bits >> 2) & 0x00000007 {
1 => ParagraphAlignment::Left,
2 => ParagraphAlignment::Right,
3 => ParagraphAlignment::Center,
4 => ParagraphAlignment::Distribute,
5 => ParagraphAlignment::Divide,
_ => ParagraphAlignment::Justify,
}
}
}
/// ์ค ๋๋ ๊ธฐ์ค ๋จ์ / Line break unit
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LineDivideUnit {
/// ๋จ์ด / Word
Word = 0,
/// ํ์ดํ / Hyphen
Hyphen = 1,
/// ๊ธ์ / Character
Character = 2,
}
impl LineDivideUnit {
fn from_bits_en(bits: u32) -> Self {
match (bits >> 5) & 0x00000003 {
1 => LineDivideUnit::Hyphen,
2 => LineDivideUnit::Character,
_ => LineDivideUnit::Word,
}
}
fn from_bit_ko(bit: bool) -> Self {
if bit {
LineDivideUnit::Character
} else {
LineDivideUnit::Word
}
}
}
/// ์ธ๋ก ์ ๋ ฌ / Vertical alignment
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum VerticalAlignment {
/// ๊ธ๊ผด ๊ธฐ์ค์ / Font baseline
Baseline = 0,
/// ์ / Top
Top = 1,
/// ๊ฐ์ด๋ฐ / Center
Center = 2,
/// ์๋ / Bottom
Bottom = 3,
}
impl VerticalAlignment {
fn from_bits(bits: u32) -> Self {
match (bits >> 20) & 0x00000003 {
1 => VerticalAlignment::Top,
2 => VerticalAlignment::Center,
3 => VerticalAlignment::Bottom,
_ => VerticalAlignment::Baseline,
}
}
}
/// ๋ฌธ๋จ ๋จธ๋ฆฌ ๋ชจ์ ์ข
๋ฅ / Paragraph header shape type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HeaderShapeType {
/// ์์ / None
None = 0,
/// ๊ฐ์ / Outline
Outline = 1,
/// ๋ฒํธ / Number
Number = 2,
/// ๊ธ๋จธ๋ฆฌํ / Bullet
Bullet = 3,
}
impl HeaderShapeType {
fn from_bits(bits: u32) -> Self {
match (bits >> 23) & 0x00000003 {
1 => HeaderShapeType::Outline,
2 => HeaderShapeType::Number,
3 => HeaderShapeType::Bullet,
_ => HeaderShapeType::None,
}
}
}
/// ๋ฌธ๋จ ๋ชจ์ ์์ฑ2 / Paragraph shape attributes 2
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParaShapeAttributes2 {
/// ํ ์ค ์
๋ ฅ / Single line input
pub single_line_input: UINT8,
/// ํ๊ธ๊ณผ ์๋ฌธ ์ฌ์ด ์๋ ๊ฐ๊ฒฉ ์กฐ์ / Auto spacing adjustment between Korean and English
pub auto_spacing_ko_en: bool,
/// ํ๊ธ๊ณผ ์ซ์ ์ฌ์ด ์๋ ๊ฐ๊ฒฉ ์กฐ์ / Auto spacing adjustment between Korean and number
pub auto_spacing_ko_num: bool,
}
/// ์ค ๊ฐ๊ฒฉ ์ข
๋ฅ (5.0.2.5 ์ด์) / Line spacing type (5.0.2.5+)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LineSpacingType {
/// ๊ธ์์ ๋ฐ๋ผ / By character
ByCharacter = 0,
/// ๊ณ ์ ๊ฐ / Fixed value
Fixed = 1,
/// ์ฌ๋ฐฑ๋ง ์ง์ / Margin only
MarginOnly = 2,
/// ์ต์๊ฐ / Minimum value
Minimum = 3,
}
impl LineSpacingType {
fn from_bits(bits: u32) -> Self {
match bits & 0x0000001F {
1 => LineSpacingType::Fixed,
2 => LineSpacingType::MarginOnly,
3 => LineSpacingType::Minimum,
_ => LineSpacingType::ByCharacter,
}
}
}
/// ๋ฌธ๋จ ๋ชจ์ ์์ฑ3 / Paragraph shape attributes 3
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParaShapeAttributes3 {
/// ์ค ๊ฐ๊ฒฉ ์ข
๋ฅ (bit 0-4, ํ 46 ์ฐธ์กฐ) / Line spacing type (bit 0-4, See Table 46)
pub line_spacing_type: LineSpacingType,
}
/// ParaShape ๊ตฌ์กฐ์ฒด / ParaShape structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParaShape {
/// ์์ฑ1 (ํ 44) / Attributes 1 (Table 44)
pub attributes1: ParaShapeAttributes1,
/// ์ผ์ชฝ ์ฌ๋ฐฑ / Left margin
pub left_margin: INT32,
/// ์ค๋ฅธ์ชฝ ์ฌ๋ฐฑ / Right margin
pub right_margin: INT32,
/// ๋ค์ฌ์ฐ๊ธฐ / Indent
pub indent: INT32,
/// ๋ด์ด์ฐ๊ธฐ / Outdent
pub outdent: INT32,
/// ๋ฌธ๋จ ์ ๊ฐ๊ฒฉ / Paragraph top spacing
pub top_spacing: INT32,
/// ๋ฌธ๋จ ์๋ ๊ฐ๊ฒฉ / Paragraph bottom spacing
pub bottom_spacing: INT32,
/// ์ค ๊ฐ๊ฒฉ(ํ๊ธ 2007 ์ดํ ๋ฒ์ ) / Line spacing (HWP 2007 and below)
pub line_spacing_old: INT32,
/// ํญ ์ ์ ID ์ฐธ์กฐ ๊ฐ / Tab definition ID reference
pub tab_def_id: UINT16,
/// ๋ฒํธ/๊ธ๋จธ๋ฆฌํ ID ์ฐธ์กฐ ๊ฐ / Number/bullet ID reference
pub number_bullet_id: UINT16,
/// ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ID ์ฐธ์กฐ ๊ฐ / Border/fill ID reference
pub border_fill_id: UINT16,
/// ๋ฌธ๋จ ํ
๋๋ฆฌ ๊ฐ๊ฒฉ(์ผ์ชฝ) / Paragraph border spacing (left)
pub border_spacing_left: INT16,
/// ๋ฌธ๋จ ํ
๋๋ฆฌ ๊ฐ๊ฒฉ(์ค๋ฅธ์ชฝ) / Paragraph border spacing (right)
pub border_spacing_right: INT16,
/// ๋ฌธ๋จ ํ
๋๋ฆฌ ๊ฐ๊ฒฉ(์) / Paragraph border spacing (top)
pub border_spacing_top: INT16,
/// ๋ฌธ๋จ ํ
๋๋ฆฌ ๊ฐ๊ฒฉ(์๋) / Paragraph border spacing (bottom)
pub border_spacing_bottom: INT16,
/// ์์ฑ2 (ํ 45, 5.0.1.7 ์ด์, ์ต์
) / Attributes 2 (Table 45, 5.0.1.7+, optional)
pub attributes2: Option<ParaShapeAttributes2>,
/// ์์ฑ3 (ํ 46, 5.0.2.5 ์ด์, ์ต์
) / Attributes 3 (Table 46, 5.0.2.5+, optional)
pub attributes3: Option<ParaShapeAttributes3>,
/// ์ค ๊ฐ๊ฒฉ(5.0.2.5 ์ด์, ์ต์
) / Line spacing (5.0.2.5+, optional)
pub line_spacing: Option<INT32>,
}
impl ParaShape {
/// ParaShape์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ParaShape from byte array.
///
/// # Arguments
/// * `data` - ParaShape ๋ ์ฝ๋ ๋ฐ์ดํฐ / ParaShape record data
/// * `version` - HWP ํ์ผ ๋ฒ์ (5.0.1.7 ์ด์์์ ์์ฑ2 ์ง์, 5.0.2.5 ์ด์์์ ์์ฑ3 ๋ฐ ์ค ๊ฐ๊ฒฉ ์ง์) / HWP file version (attributes2 supported in 5.0.1.7+, attributes3 and line spacing in 5.0.2.5+)
///
/// # Returns
/// ํ์ฑ๋ ParaShape ๊ตฌ์กฐ์ฒด / Parsed ParaShape structure
pub fn parse(data: &[u8], version: u32) -> Result<Self, HwpError> {
// ์ต์ 46๋ฐ์ดํธ ํ์ (์์ฑ1 4 + ์ฌ๋ฐฑ/๊ฐ๊ฒฉ 28 + ID 6 + ํ
๋๋ฆฌ ๊ฐ๊ฒฉ 8) / Need at least 46 bytes
if data.len() < 46 {
return Err(HwpError::insufficient_data("ParaShape", 46, data.len()));
}
let mut offset = 0;
// UINT32 ์์ฑ1 (ํ 44) / UINT32 attributes1 (Table 44)
let attr1_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let attributes1 = ParaShapeAttributes1 {
line_spacing_type_old: LineSpacingTypeOld::from_bits(attr1_value),
align: ParagraphAlignment::from_bits(attr1_value),
line_divide_en: LineDivideUnit::from_bits_en(attr1_value),
line_divide_ko: LineDivideUnit::from_bit_ko((attr1_value & 0x00000080) != 0),
use_line_grid: (attr1_value & 0x00000100) != 0,
blank_min_value: ((attr1_value >> 9) & 0x0000007F) as UINT8,
protect_orphan_line: (attr1_value & 0x00010000) != 0,
with_next_paragraph: (attr1_value & 0x00020000) != 0,
protect_paragraph: (attr1_value & 0x00040000) != 0,
always_page_break_before: (attr1_value & 0x00080000) != 0,
vertical_align: VerticalAlignment::from_bits(attr1_value),
line_height_matches_font: (attr1_value & 0x00400000) != 0,
header_shape_type: HeaderShapeType::from_bits(attr1_value),
paragraph_level: ((attr1_value >> 25) & 0x00000007) as UINT8,
connect_border: (attr1_value & 0x10000000) != 0,
ignore_margin: (attr1_value & 0x20000000) != 0,
tail_shape: (attr1_value & 0x40000000) != 0,
};
// INT32 ์ผ์ชฝ ์ฌ๋ฐฑ / INT32 left margin
let left_margin = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32 ์ค๋ฅธ์ชฝ ์ฌ๋ฐฑ / INT32 right margin
let right_margin = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32 ๋ค์ฌ์ฐ๊ธฐ / INT32 indent
let indent = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32 ๋ด์ด์ฐ๊ธฐ / INT32 outdent
let outdent = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32 ๋ฌธ๋จ ์ ๊ฐ๊ฒฉ / INT32 paragraph top spacing
let top_spacing = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32 ๋ฌธ๋จ ์๋ ๊ฐ๊ฒฉ / INT32 paragraph bottom spacing
let bottom_spacing = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32 ์ค ๊ฐ๊ฒฉ(ํ๊ธ 2007 ์ดํ ๋ฒ์ ) / INT32 line spacing (HWP 2007 and below)
let line_spacing_old = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// UINT16 ํญ ์ ์ ID ์ฐธ์กฐ ๊ฐ / UINT16 tab definition ID reference
let tab_def_id = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT16 ๋ฒํธ/๊ธ๋จธ๋ฆฌํ ID ์ฐธ์กฐ ๊ฐ / UINT16 number/bullet ID reference
let number_bullet_id = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT16 ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ID ์ฐธ์กฐ ๊ฐ / UINT16 border/fill ID reference
let border_fill_id = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// INT16 ๋ฌธ๋จ ํ
๋๋ฆฌ ๊ฐ๊ฒฉ(์ผ์ชฝ) / INT16 paragraph border spacing (left)
let border_spacing_left = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// INT16 ๋ฌธ๋จ ํ
๋๋ฆฌ ๊ฐ๊ฒฉ(์ค๋ฅธ์ชฝ) / INT16 paragraph border spacing (right)
let border_spacing_right = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// INT16 ๋ฌธ๋จ ํ
๋๋ฆฌ ๊ฐ๊ฒฉ(์) / INT16 paragraph border spacing (top)
let border_spacing_top = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// INT16 ๋ฌธ๋จ ํ
๋๋ฆฌ ๊ฐ๊ฒฉ(์๋) / INT16 paragraph border spacing (bottom)
let border_spacing_bottom = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT32 ์์ฑ2 (ํ 45, 5.0.1.7 ์ด์) / UINT32 attributes2 (Table 45, 5.0.1.7+)
let attributes2 = if version >= 0x00010107 && offset + 4 <= data.len() {
let attr2_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
Some(ParaShapeAttributes2 {
single_line_input: (attr2_value & 0x00000003) as UINT8,
auto_spacing_ko_en: (attr2_value & 0x00000010) != 0,
auto_spacing_ko_num: (attr2_value & 0x00000020) != 0,
})
} else {
None
};
// UINT32 ์์ฑ3 (ํ 46, 5.0.2.5 ์ด์) / UINT32 attributes3 (Table 46, 5.0.2.5+)
let attributes3 = if version >= 0x00020500 && offset + 4 <= data.len() {
let attr3_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
Some(ParaShapeAttributes3 {
line_spacing_type: LineSpacingType::from_bits(attr3_value),
})
} else {
None
};
// INT32 ์ค ๊ฐ๊ฒฉ(5.0.2.5 ์ด์) / INT32 line spacing (5.0.2.5+)
let line_spacing = if version >= 0x00020500 && offset + 4 <= data.len() {
let value = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
Some(value)
} else {
None
};
Ok(ParaShape {
attributes1,
left_margin,
right_margin,
indent,
outdent,
top_spacing,
bottom_spacing,
line_spacing_old,
tab_def_id,
number_bullet_id,
border_fill_id,
border_spacing_left,
border_spacing_right,
border_spacing_top,
border_spacing_bottom,
attributes2,
attributes3,
line_spacing,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/layout_compatibility.rs | crates/hwp-core/src/document/docinfo/layout_compatibility.rs | /// LayoutCompatibility ๊ตฌ์กฐ์ฒด / LayoutCompatibility structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 56 - ๋ ์ด์์ ํธํ์ฑ / Spec mapping: Table 56 - Layout compatibility
use crate::error::HwpError;
use crate::types::UINT32;
use serde::{Deserialize, Serialize};
/// ๋ ์ด์์ ํธํ์ฑ (ํ 56) / Layout compatibility (Table 56)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LayoutCompatibility {
/// ๊ธ์ ๋จ์ ์์ / Character unit format
pub character_format: UINT32,
/// ๋ฌธ๋จ ๋จ์ ์์ / Paragraph unit format
pub paragraph_format: UINT32,
/// ๊ตฌ์ญ ๋จ์ ์์ / Section unit format
pub section_format: UINT32,
/// ๊ฐ์ฒด ๋จ์ ์์ / Object unit format
pub object_format: UINT32,
/// ํ๋ ๋จ์ ์์ / Field unit format
pub field_format: UINT32,
}
impl LayoutCompatibility {
/// LayoutCompatibility๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse LayoutCompatibility from byte array.
///
/// # Arguments
/// * `data` - LayoutCompatibility ๋ฐ์ดํฐ (20๋ฐ์ดํธ) / LayoutCompatibility data (20 bytes)
///
/// # Returns
/// ํ์ฑ๋ LayoutCompatibility ๊ตฌ์กฐ์ฒด / Parsed LayoutCompatibility structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 20 {
return Err(HwpError::insufficient_data("LayoutCompatibility", 20, data.len()));
}
Ok(LayoutCompatibility {
character_format: UINT32::from_le_bytes([data[0], data[1], data[2], data[3]]),
paragraph_format: UINT32::from_le_bytes([data[4], data[5], data[6], data[7]]),
section_format: UINT32::from_le_bytes([data[8], data[9], data[10], data[11]]),
object_format: UINT32::from_le_bytes([data[12], data[13], data[14], data[15]]),
field_format: UINT32::from_le_bytes([data[16], data[17], data[18], data[19]]),
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/docinfo/forbidden_char.rs | crates/hwp-core/src/document/docinfo/forbidden_char.rs | /// ForbiddenChar ๊ตฌ์กฐ์ฒด / ForbiddenChar structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 4 - ๊ธ์น์ฒ๋ฆฌ ๋ฌธ์ / Spec mapping: Table 4 - Forbidden character
/// ์์ธ ๊ตฌ์กฐ๋ ์คํ ๋ฌธ์์ ๋ช
์๋์ง ์์ / Detailed structure not specified in spec
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// ๊ธ์น์ฒ๋ฆฌ ๋ฌธ์ / Forbidden character
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForbiddenChar {
/// Raw data (๊ฐ๋ณ) / Raw data (variable)
#[serde(skip)]
pub raw_data: Vec<u8>,
}
impl ForbiddenChar {
/// ForbiddenChar๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ForbiddenChar from byte array.
///
/// # Arguments
/// * `data` - ForbiddenChar ๋ฐ์ดํฐ (๊ฐ๋ณ) / ForbiddenChar data (variable)
///
/// # Returns
/// ํ์ฑ๋ ForbiddenChar ๊ตฌ์กฐ์ฒด / Parsed ForbiddenChar structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
Ok(ForbiddenChar {
raw_data: data.to_vec(),
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/memo_list.rs | crates/hwp-core/src/document/bodytext/memo_list.rs | /// MemoList ๊ตฌ์กฐ์ฒด / MemoList structure
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ์คํ ๋ฌธ์์ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ / Spec document does not specify detailed structure
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ MEMO_LIST ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain MEMO_LIST records
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// ๋ฉ๋ชจ ๋ฆฌ์คํธ ํค๋ / Memo list header
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoList {
/// Raw ๋ฐ์ดํฐ / Raw data
/// ์คํ ๋ฌธ์์ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ผ๋ฏ๋ก raw ๋ฐ์ดํฐ๋ก ์ ์ฅํฉ๋๋ค.
/// Raw data is stored because the spec document does not specify detailed structure.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub raw_data: Vec<u8>,
}
impl MemoList {
/// MemoList์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse MemoList from byte array.
///
/// # Arguments
/// * `data` - MemoList ๋ฐ์ดํฐ / MemoList data
///
/// # Returns
/// ํ์ฑ๋ MemoList ๊ตฌ์กฐ์ฒด / Parsed MemoList structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 57์๋ "๋ฉ๋ชจ ๋ฆฌ์คํธ ํค๋"๋ก๋ง ์ธ๊ธ๋์ด ์๊ณ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ต๋๋ค.
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ raw ๋ฐ์ดํฐ๋ก๋ง ์ ์ฅํ๊ณ ์์ต๋๋ค.
/// Spec document Table 57 only mentions "Memo list header" and does not specify detailed structure.
/// Legacy code (hwp.js) also stores only raw data.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ MEMO_LIST ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ MEMO_LIST ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain MEMO_LIST records, so it has not been verified with actual files.
/// If an actual HWP file contains MEMO_LIST records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
Ok(MemoList {
raw_data: data.to_vec(),
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/eqedit.rs | crates/hwp-core/src/document/bodytext/eqedit.rs | /// EqEdit ๊ตฌ์กฐ์ฒด / EqEdit structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 105 - ์์ ๊ฐ์ฒด ์์ฑ / Spec mapping: Table 105 - Equation editor object attributes
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ EQEDIT ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain EQEDIT records
use crate::error::HwpError;
use crate::types::{decode_utf16le, COLORREF, HWPUNIT, INT16, UINT16, UINT32};
use serde::{Deserialize, Serialize};
/// ์์ ๊ฐ์ฒด / Equation editor object
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EqEdit {
/// ์์ฑ. ์คํฌ๋ฆฝํธ๊ฐ ์ฐจ์งํ๋ ๋ฒ์. ์ฒซ ๋นํธ๊ฐ ์ผ์ ธ ์์ผ๋ฉด ์ค ๋จ์, ๊บผ์ ธ ์์ผ๋ฉด ๊ธ์ ๋จ์.
/// Attribute. Range occupied by script. If first bit is set, line unit; otherwise, character unit.
pub attribute: UINT32,
/// ์คํฌ๋ฆฝํธ ๊ธธ์ด / Script length
pub script_length: UINT16,
/// ํ๊ธ ์์ ์คํฌ๋ฆฝํธ / HWP equation script (EQN script compatible)
pub script: String,
/// ์์ ๊ธ์ ํฌ๊ธฐ / Equation character size
pub character_size: HWPUNIT,
/// ๊ธ์ ์์ / Character color
pub character_color: COLORREF,
/// base line / Base line
pub base_line: INT16,
/// ์์ ๋ฒ์ ์ ๋ณด / Equation version information
pub version_info: String,
/// ์์ ํฐํธ ์ด๋ฆ / Equation font name
pub font_name: String,
}
impl EqEdit {
/// EqEdit์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse EqEdit from byte array.
///
/// # Arguments
/// * `data` - EqEdit ๋ฐ์ดํฐ (์์ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง) / EqEdit data (equation editor object attributes only)
///
/// # Returns
/// ํ์ฑ๋ EqEdit ๊ตฌ์กฐ์ฒด / Parsed EqEdit structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 104์ ๋ฐ๋ฅด๋ฉด EQEDIT๋ ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋๋ค:
/// - ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 68 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ์์ ๊ฐ์ฒด ์์ฑ(ํ 105 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด (16 + 6รlen ๋ฐ์ดํธ)
///
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ ์์ ๊ฐ์ฒด ์์ฑ์ ์ผ๋ถ๋ง ํ์ฑํ๊ณ ์์ต๋๋ค.
/// According to spec Table 104, EQEDIT has the following structure:
/// - Object common properties (Table 68) - variable length
/// - Equation editor object attributes (Table 105) - variable length (16 + 6รlen bytes)
///
/// Legacy code (hwp.js) only parses part of equation editor object attributes.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ EQEDIT ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ EQEDIT ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain EQEDIT records, so it has not been verified with actual files.
/// If an actual HWP file contains EQEDIT records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ์ต์ 16๋ฐ์ดํธ ํ์ (len=0์ผ ๋) / Need at least 16 bytes (when len=0)
if data.len() < 16 {
return Err(HwpError::insufficient_data("EqEdit", 16, data.len()));
}
let mut offset = 0;
// ํ 105: ์์ฑ (UINT32, 4๋ฐ์ดํธ) / Table 105: Attribute (UINT32, 4 bytes)
let attribute = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 105: ์คํฌ๋ฆฝํธ ๊ธธ์ด (WORD, 2๋ฐ์ดํธ) / Table 105: Script length (WORD, 2 bytes)
let script_length = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let script_length_usize = script_length as usize;
// ํ์ํ ๋ฐ์ดํธ ์ ๊ณ์ฐ / Calculate required bytes
// UINT32(4) + WORD(2) + WCHAR array[len](2รlen) + HWPUNIT(4) + COLORREF(4) + INT16(2) + WCHAR array[len](2รlen) + WCHAR array[len](2รlen)
// = 16 + 6รlen
let required_bytes = 16 + 6 * script_length_usize;
if data.len() < required_bytes {
return Err(HwpError::InsufficientData {
field: format!("EqEdit (script_length={})", script_length_usize),
expected: required_bytes,
actual: data.len(),
});
}
// ํ 105: ํ๊ธ ์์ ์คํฌ๋ฆฝํธ (WCHAR array[len], 2รlen ๋ฐ์ดํธ) / Table 105: HWP equation script (WCHAR array[len], 2รlen bytes)
let script_bytes = &data[offset..offset + 2 * script_length_usize];
let script = decode_utf16le(script_bytes)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode EqEdit script: {}", e),
})?;
offset += 2 * script_length_usize;
// ํ 105: ์์ ๊ธ์ ํฌ๊ธฐ (HWPUNIT, 4๋ฐ์ดํธ) / Table 105: Equation character size (HWPUNIT, 4 bytes)
let character_size_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
let character_size = HWPUNIT::from(character_size_value);
offset += 4;
// ํ 105: ๊ธ์ ์์ (COLORREF, 4๋ฐ์ดํธ) / Table 105: Character color (COLORREF, 4 bytes)
let color_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
let character_color = COLORREF(color_value);
offset += 4;
// ํ 105: base line (INT16, 2๋ฐ์ดํธ) / Table 105: Base line (INT16, 2 bytes)
let base_line = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// ํ 105: ์์ ๋ฒ์ ์ ๋ณด (WCHAR array[len], 2รlen ๋ฐ์ดํธ) / Table 105: Equation version information (WCHAR array[len], 2รlen bytes)
let version_bytes = &data[offset..offset + 2 * script_length_usize];
let version_info = decode_utf16le(version_bytes)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode EqEdit version_info: {}", e),
})?;
offset += 2 * script_length_usize;
// ํ 105: ์์ ํฐํธ ์ด๋ฆ (WCHAR array[len], 2รlen ๋ฐ์ดํธ) / Table 105: Equation font name (WCHAR array[len], 2รlen bytes)
let font_bytes = &data[offset..offset + 2 * script_length_usize];
let font_name = decode_utf16le(font_bytes)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode EqEdit font_name: {}", e),
})?;
offset += 2 * script_length_usize;
Ok(EqEdit {
attribute,
script_length,
script,
character_size,
character_color,
base_line,
version_info,
font_name,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/record_tree.rs | crates/hwp-core/src/document/bodytext/record_tree.rs | /// ๋ ์ฝ๋ ํธ๋ฆฌ ๊ตฌ์กฐ / Record tree structure
///
/// HWP ๋ ์ฝ๋๋ ๊ณ์ธต ๊ตฌ์กฐ๋ก ์ ์ฅ๋๋ฉฐ, ๋ ๋ฒจ ์ ๋ณด๋ฅผ ํตํด ํธ๋ฆฌ ๊ตฌ์กฐ๋ฅผ ์ฌ๊ตฌ์ฑํ ์ ์์ต๋๋ค.
/// HWP records are stored in a hierarchical structure, and the tree structure can be reconstructed using level information.
use crate::error::HwpError;
use crate::types::RecordHeader;
/// ๋ ์ฝ๋ ํธ๋ฆฌ ๋
ธ๋ / Record tree node
#[derive(Debug, Clone)]
pub struct RecordTreeNode {
/// ๋ ์ฝ๋ ํค๋ / Record header
pub header: RecordHeader,
/// ๋ ์ฝ๋ ๋ฐ์ดํฐ / Record data
pub data: Vec<u8>,
/// ์์ ๋
ธ๋๋ค / Child nodes
pub children: Vec<RecordTreeNode>,
}
impl RecordTreeNode {
/// ๋ ์ฝ๋ ํธ๋ฆฌ๋ฅผ ํ์ฑํฉ๋๋ค. / Parse record tree.
///
/// hwp.js์ parseRecordTree ๋ก์ง์ ์ ํํ ๋ฐ๋ผ๊ฐ๋๋ค:
/// Follows hwp.js's parseRecordTree logic exactly:
/// ```typescript
/// let parent: HWPRecord = root
/// for (let i = 0; i < level; i += 1) {
/// parent = parent.children.slice(-1).pop()!
/// }
/// parent.children.push(new HWPRecord(...))
/// ```
///
/// # Arguments
/// * `data` - Section์ ์์ ๋ฐ์ดํธ ๋ฐ์ดํฐ / Raw byte data of section
///
/// # Returns
/// ๋ฃจํธ ๋
ธ๋ (๋ ๋ฒจ 0 ๋ ์ฝ๋๋ค์ด ์์์ผ๋ก ํฌํจ๋จ) / Root node (level 0 records are included as children)
pub fn parse_tree(data: &[u8]) -> Result<RecordTreeNode, HwpError> {
let root = RecordTreeNode {
header: RecordHeader {
tag_id: 0,
level: 0,
size: 0,
has_extended_size: false,
},
data: Vec::new(),
children: Vec::new(),
};
let mut offset = 0;
// ์คํ: ๊ฐ ๋ ๋ฒจ์ ๋ง์ง๋ง ๋
ธ๋ ์ฐธ์กฐ๋ฅผ ์ ์ฅ / Stack: stores reference to last node at each level
// hwp.js ๋ฐฉ์: for (let i = 0; i < level; i += 1) { parent = parent.children.slice(-1).pop()! }
// hwp.js way: for (let i = 0; i < level; i += 1) { parent = parent.children.slice(-1).pop()! }
// ์คํ[i]๋ ๋ ๋ฒจ i์ ๋ง์ง๋ง ๋
ธ๋ ์ธ๋ฑ์ค / stack[i] is the last node index at level i
// ๋ ๋ฒจ i์ ๋ถ๋ชจ๋ ์คํ[i-1] (๋ ๋ฒจ 0์ ๋ถ๋ชจ๋ ๋ฃจํธ) / Parent of level i is stack[i-1] (parent of level 0 is root)
let mut stack: Vec<usize> = Vec::new(); // ๊ฐ ๋ ๋ฒจ์ ๋ง์ง๋ง ๋
ธ๋ ์ธ๋ฑ์ค / Last node index at each level
let mut nodes: Vec<(RecordTreeNode, Vec<usize>)> = Vec::new(); // (๋
ธ๋, ์์ ์ธ๋ฑ์ค ๋ฆฌ์คํธ) / (node, child indices)
nodes.push((root, Vec::new()));
while offset < data.len() {
// ๋ ์ฝ๋ ํค๋ ํ์ฑ / Parse record header
let remaining_data = &data[offset..];
let (header, header_size) = RecordHeader::parse(remaining_data)
.map_err(|e| HwpError::from(e))?;
offset += header_size;
// ๋ฐ์ดํฐ ์์ญ ์ฝ๊ธฐ / Read data area
let data_size = header.size as usize;
if offset + data_size > data.len() {
return Err(HwpError::InsufficientData {
field: format!("Record at offset {}", offset),
expected: offset + data_size,
actual: data.len(),
});
}
let record_data = &data[offset..offset + data_size];
offset += data_size;
// ์ ๋
ธ๋ ์์ฑ / Create new node
let new_node = RecordTreeNode {
header,
data: record_data.to_vec(),
children: Vec::new(),
};
let new_node_index = nodes.len();
nodes.push((new_node, Vec::new()));
// ๋ถ๋ชจ ๋
ธ๋ ์ฐพ๊ธฐ: hwp.js ๋ก์ง ์ ํํ ๋ฐ๋ผ๊ฐ๊ธฐ
// Find parent node: follow hwp.js logic exactly
// hwp.js: for (let i = 0; i < level; i += 1) { parent = parent.children.slice(-1).pop()! }
// ์ฆ, ๋ ๋ฒจ๋งํผ ๊น์ด ๋ค์ด๊ฐ์ ๋ง์ง๋ง ์์์ ๋ถ๋ชจ๋ก ์ ํ
// That is, go level deep and select the last child as parent
// ์คํ์ ๋ ๋ฒจ์ ๋ง๊ฒ ์กฐ์ : ๋ ๋ฒจ์ด ๊ฐ์ํ๋ฉด ์์ ๋ ๋ฒจ๋ก ๋์๊ฐ
// Adjust stack to match level: if level decreases, return to higher level
while stack.len() > header.level as usize {
stack.pop();
}
// ๋ถ๋ชจ ๋
ธ๋ ์ฐพ๊ธฐ / Find parent node
let parent_index = if header.level == 0 {
0 // ๋ฃจํธ / Root
} else {
// ์คํ์ ๋ ๋ฒจ์ ๋ง๊ฒ ํ์ฅ / Expand stack to match level
while stack.len() < header.level as usize {
// ์คํ์ด ๋ถ์กฑํ๋ฉด ์ด์ ๋ ๋ฒจ์ ๋ง์ง๋ง ๋
ธ๋๋ฅผ ์ฌ์ฉ / Use last node of previous level if stack is insufficient
if let Some(&last) = stack.last() {
stack.push(last);
} else {
stack.push(0); // ๋ฃจํธ / Root
}
}
// ๋ ๋ฒจ i์ ๋ถ๋ชจ๋ ๋ ๋ฒจ i-1์ ๋ง์ง๋ง ๋
ธ๋ (์คํ[i-1])
// Parent of level i is last node at level i-1 (stack[i-1])
stack[header.level as usize - 1]
};
// ๋ถ๋ชจ์ ์์ ์ถ๊ฐ / Add child to parent
nodes[parent_index].1.push(new_node_index);
// ์ ๋
ธ๋๋ฅผ ์คํ์ ์ถ๊ฐ (๋ค์ ๋ ์ฝ๋์ ๋ถ๋ชจ๊ฐ ๋ ์ ์์)
// Add new node to stack (can be parent of next record)
// ์คํ์ ๋ ๋ฒจ ํฌ๊ธฐ๋ก ํ์ฅ / Expand stack to level size
while stack.len() <= header.level as usize {
stack.push(0); // ํ๋ ์ด์คํ๋ / Placeholder
}
stack[header.level as usize] = new_node_index;
}
// ์ธ๋ฑ์ค ๊ธฐ๋ฐ ํธ๋ฆฌ๋ฅผ ์ค์ ํธ๋ฆฌ๋ก ๋ณํ / Convert index-based tree to actual tree
fn build_tree(nodes: &[(RecordTreeNode, Vec<usize>)], index: usize) -> RecordTreeNode {
let (node, children_indices) = &nodes[index];
let mut result = RecordTreeNode {
header: node.header,
data: node.data.clone(),
children: Vec::new(),
};
for &child_index in children_indices {
result.children.push(build_tree(nodes, child_index));
}
result
}
Ok(build_tree(&nodes, 0))
}
/// ํ๊ทธ ID ๋ฐํ / Get tag ID
pub fn tag_id(&self) -> u16 {
self.header.tag_id
}
/// ๋ ๋ฒจ ๋ฐํ / Get level
pub fn level(&self) -> u16 {
self.header.level
}
/// ๋ฐ์ดํฐ ๋ฐํ / Get data
pub fn data(&self) -> &[u8] {
&self.data
}
/// ์์ ๋
ธ๋๋ค ๋ฐํ / Get children
pub fn children(&self) -> &[RecordTreeNode] {
&self.children
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/line_seg.rs | crates/hwp-core/src/document/bodytext/line_seg.rs | /// LineSegmentInfo ๊ตฌ์กฐ์ฒด / LineSegmentInfo structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 62 - ๋ฌธ๋จ์ ๋ ์ด์์ / Spec mapping: Table 62 - Paragraph line segment
/// ๊ฐ ํญ๋ชฉ: 36๋ฐ์ดํธ
use crate::error::HwpError;
use crate::types::{INT32, UINT32};
use serde::{Deserialize, Serialize};
/// ์ค ์ธ๊ทธ๋จผํธ ํ๊ทธ ํ๋๊ทธ / Line segment tag flags
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineSegmentTag {
/// ํ์ด์ง์ ์ฒซ ์ค์ธ์ง ์ฌ๋ถ / Is first line of page
pub is_first_line_of_page: bool,
/// ์ปฌ๋ผ์ ์ฒซ ์ค์ธ์ง ์ฌ๋ถ / Is first line of column
pub is_first_line_of_column: bool,
/// ํ
์คํธ๊ฐ ๋ฐฐ์ด๋์ง ์์ ๋น ์ธ๊ทธ๋จผํธ์ธ์ง ์ฌ๋ถ / Is empty segment without text
pub is_empty_segment: bool,
/// ์ค์ ์ฒซ ์ธ๊ทธ๋จผํธ์ธ์ง ์ฌ๋ถ / Is first segment of line
pub is_first_segment_of_line: bool,
/// ์ค์ ๋ง์ง๋ง ์ธ๊ทธ๋จผํธ์ธ์ง ์ฌ๋ถ / Is last segment of line
pub is_last_segment_of_line: bool,
/// ์ค์ ๋ง์ง๋ง์ auto-hyphenation์ด ์ํ๋์๋์ง ์ฌ๋ถ / Auto-hyphenation performed at end of line
pub has_auto_hyphenation: bool,
/// indentation ์ ์ฉ / Indentation applied
pub has_indentation: bool,
/// ๋ฌธ๋จ ๋จธ๋ฆฌ ๋ชจ์ ์ ์ฉ / Paragraph header shape applied
pub has_paragraph_header_shape: bool,
}
impl LineSegmentTag {
/// UINT32 ํ๊ทธ ๊ฐ์์ LineSegmentTag๋ฅผ ํ์ฑํฉ๋๋ค. / Parse LineSegmentTag from UINT32 tag value.
fn from_bits(tag: UINT32) -> Self {
LineSegmentTag {
is_first_line_of_page: (tag & 0x00000001) != 0,
is_first_line_of_column: (tag & 0x00000002) != 0,
is_empty_segment: (tag & 0x00010000) != 0,
is_first_segment_of_line: (tag & 0x00020000) != 0,
is_last_segment_of_line: (tag & 0x00040000) != 0,
has_auto_hyphenation: (tag & 0x00080000) != 0,
has_indentation: (tag & 0x00100000) != 0,
has_paragraph_header_shape: (tag & 0x00200000) != 0,
}
}
}
/// ์ค ์ธ๊ทธ๋จผํธ ์ ๋ณด / Line segment information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LineSegmentInfo {
/// ํ
์คํธ ์์ ์์น / Text start position
pub text_start_position: UINT32,
/// ์ค์ ์ธ๋ก ์์น / Vertical position of line
pub vertical_position: INT32,
/// ์ค์ ๋์ด / Height of line
pub line_height: INT32,
/// ํ
์คํธ ๋ถ๋ถ์ ๋์ด / Height of text portion
pub text_height: INT32,
/// ์ค์ ์ธ๋ก ์์น์์ ๋ฒ ์ด์ค๋ผ์ธ๊น์ง ๊ฑฐ๋ฆฌ / Distance from vertical position to baseline
pub baseline_distance: INT32,
/// ์ค๊ฐ๊ฒฉ / Line spacing
pub line_spacing: INT32,
/// ์ปฌ๋ผ์์์ ์์ ์์น / Start position in column
pub column_start_position: INT32,
/// ์ธ๊ทธ๋จผํธ์ ํญ / Width of segment
pub segment_width: INT32,
/// ํ๊ทธ (ํ๋๊ทธ๋ค) / Tag (flags)
pub tag: LineSegmentTag,
}
impl LineSegmentInfo {
/// LineSegmentInfo๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse LineSegmentInfo from byte array.
///
/// # Arguments
/// * `data` - ์ต์ 36๋ฐ์ดํธ์ ๋ฐ์ดํฐ / At least 36 bytes of data
///
/// # Returns
/// ํ์ฑ๋ LineSegmentInfo ๊ตฌ์กฐ์ฒด / Parsed LineSegmentInfo structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 36 {
return Err(HwpError::insufficient_data("LineSegmentInfo", 36, data.len()));
}
let mut offset = 0;
// UINT32 ํ
์คํธ ์์ ์์น / UINT32 text start position
let text_start_position = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32 ์ค์ ์ธ๋ก ์์น / INT32 vertical position of line
let vertical_position = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32 ์ค์ ๋์ด / INT32 height of line
let line_height = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32 ํ
์คํธ ๋ถ๋ถ์ ๋์ด / INT32 height of text portion
let text_height = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32 ์ค์ ์ธ๋ก ์์น์์ ๋ฒ ์ด์ค๋ผ์ธ๊น์ง ๊ฑฐ๋ฆฌ / INT32 distance from vertical position to baseline
let baseline_distance = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32 ์ค๊ฐ๊ฒฉ / INT32 line spacing
let line_spacing = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32 ์ปฌ๋ผ์์์ ์์ ์์น / INT32 start position in column
let column_start_position = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32 ์ธ๊ทธ๋จผํธ์ ํญ / INT32 width of segment
let segment_width = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// UINT32 ํ๊ทธ / UINT32 tag
let tag_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
let tag = LineSegmentTag::from_bits(tag_value);
Ok(LineSegmentInfo {
text_start_position,
vertical_position,
line_height,
text_height,
baseline_distance,
line_spacing,
column_start_position,
segment_width,
tag,
})
}
}
/// ๋ฌธ๋จ์ ๋ ์ด์์ ๋ฆฌ์คํธ / Paragraph line segment list
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ParaLineSeg {
/// ์ค ์ธ๊ทธ๋จผํธ ์ ๋ณด ๋ฆฌ์คํธ / Line segment information list
pub segments: Vec<LineSegmentInfo>,
}
impl ParaLineSeg {
/// ParaLineSeg๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ParaLineSeg from byte array.
///
/// # Arguments
/// * `data` - ๋ ์ด์์ ๋ฐ์ดํฐ (36รn ๋ฐ์ดํธ) / Line segment data (36รn bytes)
///
/// # Returns
/// ํ์ฑ๋ ParaLineSeg ๊ตฌ์กฐ์ฒด / Parsed ParaLineSeg structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() % 36 != 0 {
return Err(HwpError::UnexpectedValue {
field: "ParaLineSeg data length".to_string(),
expected: "multiple of 36".to_string(),
found: format!("{} bytes", data.len()),
});
}
let count = data.len() / 36;
let mut segments = Vec::with_capacity(count);
for i in 0..count {
let offset = i * 36;
let segment_data = &data[offset..offset + 36];
let segment_info = LineSegmentInfo::parse(segment_data)
.map_err(|e| HwpError::from(e))?;
segments.push(segment_info);
}
Ok(ParaLineSeg { segments })
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/char_shape.rs | crates/hwp-core/src/document/bodytext/char_shape.rs | /// CharShapeInfo ๊ตฌ์กฐ์ฒด / CharShapeInfo structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 61 - ๋ฌธ๋จ์ ๊ธ์ ๋ชจ์ / Spec mapping: Table 61 - Paragraph character shape
/// ๊ฐ ํญ๋ชฉ: 8๋ฐ์ดํธ
use crate::error::HwpError;
use crate::types::UINT32;
use serde::{Deserialize, Serialize};
/// ๊ธ์ ๋ชจ์ ์ ๋ณด / Character shape information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CharShapeInfo {
/// ๊ธ์ ๋ชจ์์ด ๋ฐ๋๋ ์์ ์์น / Position where character shape changes
pub position: UINT32,
/// ๊ธ์ ๋ชจ์ ID / Character shape ID
pub shape_id: UINT32,
}
impl CharShapeInfo {
/// CharShapeInfo๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse CharShapeInfo from byte array.
///
/// # Arguments
/// * `data` - ์ต์ 8๋ฐ์ดํธ์ ๋ฐ์ดํฐ / At least 8 bytes of data
///
/// # Returns
/// ํ์ฑ๋ CharShapeInfo ๊ตฌ์กฐ์ฒด / Parsed CharShapeInfo structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 8 {
return Err(HwpError::insufficient_data("CharShapeInfo", 8, data.len()));
}
// UINT32 ๊ธ์ ๋ชจ์์ด ๋ฐ๋๋ ์์ ์์น / UINT32 position where character shape changes
let position = UINT32::from_le_bytes([data[0], data[1], data[2], data[3]]);
// UINT32 ๊ธ์ ๋ชจ์ ID / UINT32 character shape ID
let shape_id = UINT32::from_le_bytes([data[4], data[5], data[6], data[7]]);
Ok(CharShapeInfo { position, shape_id })
}
}
/// ๋ฌธ๋จ์ ๊ธ์ ๋ชจ์ ๋ฆฌ์คํธ / Paragraph character shape list
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ParaCharShape {
/// ๊ธ์ ๋ชจ์ ์ ๋ณด ๋ฆฌ์คํธ / Character shape information list
pub shapes: Vec<CharShapeInfo>,
}
impl ParaCharShape {
/// ParaCharShape๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ParaCharShape from byte array.
///
/// # Arguments
/// * `data` - ๊ธ์ ๋ชจ์ ๋ฐ์ดํฐ (8รn ๋ฐ์ดํธ) / Character shape data (8รn bytes)
///
/// # Returns
/// ํ์ฑ๋ ParaCharShape ๊ตฌ์กฐ์ฒด / Parsed ParaCharShape structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() % 8 != 0 {
return Err(HwpError::UnexpectedValue {
field: "ParaCharShape data length".to_string(),
expected: "multiple of 8".to_string(),
found: format!("{} bytes", data.len()),
});
}
let count = data.len() / 8;
let mut shapes = Vec::with_capacity(count);
for i in 0..count {
let offset = i * 8;
let shape_data = &data[offset..offset + 8];
let shape_info = CharShapeInfo::parse(shape_data)
.map_err(|e| HwpError::from(e))?;
shapes.push(shape_info);
}
Ok(ParaCharShape { shapes })
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/page_def.rs | crates/hwp-core/src/document/bodytext/page_def.rs | /// PageDef ๊ตฌ์กฐ์ฒด / PageDef structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 131 - ์ฉ์ง ์ค์ / Spec mapping: Table 131 - Page definition
use crate::error::HwpError;
use crate::types::{HWPUNIT, UINT32};
use serde::{Deserialize, Serialize};
/// ์ฉ์ง ์ค์ / Page definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PageDef {
/// ์ฉ์ง ๊ฐ๋ก ํฌ๊ธฐ / Paper width
pub paper_width: HWPUNIT,
/// ์ฉ์ง ์ธ๋ก ํฌ๊ธฐ / Paper height
pub paper_height: HWPUNIT,
/// ์ฉ์ง ์ผ์ชฝ ์ฌ๋ฐฑ / Left margin
pub left_margin: HWPUNIT,
/// ์ค๋ฅธ์ชฝ ์ฌ๋ฐฑ / Right margin
pub right_margin: HWPUNIT,
/// ์ ์ฌ๋ฐฑ / Top margin
pub top_margin: HWPUNIT,
/// ์๋ ์ฌ๋ฐฑ / Bottom margin
pub bottom_margin: HWPUNIT,
/// ๋จธ๋ฆฌ๋ง ์ฌ๋ฐฑ / Header margin
pub header_margin: HWPUNIT,
/// ๊ผฌ๋ฆฌ๋ง ์ฌ๋ฐฑ / Footer margin
pub footer_margin: HWPUNIT,
/// ์ ๋ณธ ์ฌ๋ฐฑ / Binding margin
pub binding_margin: HWPUNIT,
/// ์์ฑ / Attributes
pub attributes: PageDefAttributes,
}
/// ์ฉ์ง ์ค์ ์์ฑ / Page definition attributes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PageDefAttributes {
/// ์ฉ์ง ๋ฐฉํฅ / Paper direction
pub paper_direction: PaperDirection,
/// ์ ์ฑ
๋ฐฉ๋ฒ / Binding method
pub binding_method: BindingMethod,
}
/// ์ฉ์ง ๋ฐฉํฅ / Paper direction
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PaperDirection {
/// ์ข๊ฒ (์ธ๋ก) / Vertical (narrow)
Vertical,
/// ๋๊ฒ (๊ฐ๋ก) / Horizontal (wide)
Horizontal,
}
/// ์ ์ฑ
๋ฐฉ๋ฒ / Binding method
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BindingMethod {
/// ํ์ชฝ ํธ์ง / Single page editing
SinglePage,
/// ๋ง์ชฝ ํธ์ง / Facing pages editing
FacingPages,
/// ์๋ก ๋๊ธฐ๊ธฐ / Flip up
FlipUp,
}
impl PageDef {
/// PageDef๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse PageDef from byte array.
///
/// # Arguments
/// * `data` - ์ต์ 40๋ฐ์ดํธ์ ๋ฐ์ดํฐ / At least 40 bytes of data
///
/// # Returns
/// ํ์ฑ๋ PageDef ๊ตฌ์กฐ์ฒด / Parsed PageDef structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 40 {
return Err(HwpError::insufficient_data("PageDef", 40, data.len()));
}
let mut offset = 0;
// HWPUNIT ์ฉ์ง ๊ฐ๋ก ํฌ๊ธฐ / HWPUNIT paper width
let paper_width = HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// HWPUNIT ์ฉ์ง ์ธ๋ก ํฌ๊ธฐ / HWPUNIT paper height
let paper_height = HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// HWPUNIT ์ฉ์ง ์ผ์ชฝ ์ฌ๋ฐฑ / HWPUNIT left margin
let left_margin = HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// HWPUNIT ์ค๋ฅธ์ชฝ ์ฌ๋ฐฑ / HWPUNIT right margin
let right_margin = HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// HWPUNIT ์ ์ฌ๋ฐฑ / HWPUNIT top margin
let top_margin = HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// HWPUNIT ์๋ ์ฌ๋ฐฑ / HWPUNIT bottom margin
let bottom_margin = HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// HWPUNIT ๋จธ๋ฆฌ๋ง ์ฌ๋ฐฑ / HWPUNIT header margin
let header_margin = HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// HWPUNIT ๊ผฌ๋ฆฌ๋ง ์ฌ๋ฐฑ / HWPUNIT footer margin
let footer_margin = HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// HWPUNIT ์ ๋ณธ ์ฌ๋ฐฑ / HWPUNIT binding margin
let binding_margin = HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
// UINT32 ์์ฑ (ํ 132 ์ฐธ์กฐ) / UINT32 attributes (see Table 132)
let attribute_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
// ์์ฑ ํ์ฑ (ํ 132) / Parse attributes (Table 132)
let attributes = parse_page_def_attributes(attribute_value);
Ok(PageDef {
paper_width,
paper_height,
left_margin,
right_margin,
top_margin,
bottom_margin,
header_margin,
footer_margin,
binding_margin,
attributes,
})
}
}
/// ์ฉ์ง ์ค์ ์์ฑ ํ์ฑ (ํ 132) / Parse page definition attributes (Table 132)
fn parse_page_def_attributes(value: UINT32) -> PageDefAttributes {
// bit 0: ์ฉ์ง ๋ฐฉํฅ / bit 0: paper direction
// 0: ์ข๊ฒ (์ธ๋ก) / 0: vertical (narrow)
// 1: ๋๊ฒ (๊ฐ๋ก) / 1: horizontal (wide)
let paper_direction = if (value & 0x01) == 0 {
PaperDirection::Vertical
} else {
PaperDirection::Horizontal
};
// bit 1-2: ์ ์ฑ
๋ฐฉ๋ฒ / bit 1-2: binding method
// 0: ํ์ชฝ ํธ์ง / 0: single page editing
// 1: ๋ง์ชฝ ํธ์ง / 1: facing pages editing
// 2: ์๋ก ๋๊ธฐ๊ธฐ / 2: flip up
let binding_method = match (value >> 1) & 0x03 {
0 => BindingMethod::SinglePage,
1 => BindingMethod::FacingPages,
2 => BindingMethod::FlipUp,
_ => BindingMethod::SinglePage, // ๊ธฐ๋ณธ๊ฐ / default
};
PageDefAttributes {
paper_direction,
binding_method,
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/footnote_shape.rs | crates/hwp-core/src/document/bodytext/footnote_shape.rs | /// FootnoteShape ๊ตฌ์กฐ์ฒด / FootnoteShape structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 133 - ๊ฐ์ฃผ/๋ฏธ์ฃผ ๋ชจ์ / Spec mapping: Table 133 - Footnote/endnote shape
use crate::error::HwpError;
use crate::types::{COLORREF, HWPUNIT16, UINT16, UINT32, UINT8, WCHAR};
use serde::{Deserialize, Serialize};
/// ๊ฐ์ฃผ/๋ฏธ์ฃผ ๋ชจ์ / Footnote/endnote shape
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FootnoteShape {
/// ์์ฑ / Attributes
pub attributes: FootnoteShapeAttributes,
/// ์ฌ์ฉ์ ๊ธฐํธ / Custom symbol
pub custom_symbol: WCHAR,
/// ์ ์ฅ์ ๋ฌธ์ / Front decoration character
pub front_decoration: WCHAR,
/// ๋ค ์ฅ์ ๋ฌธ์ / Back decoration character
pub back_decoration: WCHAR,
/// ์์ ๋ฒํธ / Start number
pub start_number: UINT16,
/// ๊ตฌ๋ถ์ ๊ธธ์ด / Breakline length
pub breakline_length: HWPUNIT16,
/// ๊ตฌ๋ถ์ ์ ์ฌ๋ฐฑ / Breakline top margin
pub breakline_top_margin: HWPUNIT16,
/// ๊ตฌ๋ถ์ ์๋ ์ฌ๋ฐฑ / Breakline bottom margin
pub breakline_bottom_margin: HWPUNIT16,
/// ์ฃผ์ ์ฌ์ด ์ฌ๋ฐฑ / Remark between margin
pub remark_between_margin: HWPUNIT16,
/// ๊ตฌ๋ถ์ ์ข
๋ฅ / Breakline type
pub breakline_type: UINT8,
/// ๊ตฌ๋ถ์ ๊ตต๊ธฐ / Breakline thickness
pub breakline_thickness: UINT8,
/// ๊ตฌ๋ถ์ ์์ / Breakline color
pub breakline_color: COLORREF,
}
/// ๊ฐ์ฃผ/๋ฏธ์ฃผ ๋ชจ์ ์์ฑ / Footnote/endnote shape attributes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FootnoteShapeAttributes {
/// ๋ฒํธ ๋ชจ์ / Number shape
pub number_shape: NumberShape,
/// ํ ํ์ด์ง ๋ด์์ ๊ฐ์ฃผ๋ฅผ ๋ค๋จ์ ์์น์ํฌ ๋ฐฉ๋ฒ / Page position method for footnotes in multi-column
pub page_position: PagePosition,
/// ๋ฒํธ ๋งค๊ธฐ๊ธฐ ๋ฐฉ๋ฒ / Numbering method
pub numbering: NumberingMethod,
/// ๊ฐ์ฃผ ๋ด์ฉ ์ค ๋ฒํธ ์ฝ๋์ ๋ชจ์์ ์ ์ฒจ์ ํ์์ผ๋ก ํ ์ง ์ฌ๋ถ / Superscript format for number code in footnote content
pub superscript: bool,
/// ํ
์คํธ์ ์ด์ด ๋ฐ๋ก ์ถ๋ ฅํ ์ง ์ฌ๋ถ / Output immediately after text
pub prefix: bool,
}
/// ๋ฒํธ ๋ชจ์ / Number shape
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NumberShape {
/// 1, 2, 3
Arabic,
/// ๋๊ทธ๋ผ๋ฏธ ์ณ์ง 1, 2, 3
CircledArabic,
/// I, II, III
RomanUpper,
/// i, ii, iii
RomanLower,
/// A, B, C
AlphaUpper,
/// a, b, c
AlphaLower,
/// ๋๊ทธ๋ผ๋ฏธ ์ณ์ง A, B, C
CircledAlphaUpper,
/// ๋๊ทธ๋ผ๋ฏธ ์ณ์ง a, b, c
CircledAlphaLower,
/// ๊ฐ, ๋, ๋ค
Hangul,
/// ๋๊ทธ๋ผ๋ฏธ ์ณ์ง ๊ฐ, ๋, ๋ค
CircledHangul,
/// ใฑ, ใด, ใท
HangulJamo,
/// ๋๊ทธ๋ผ๋ฏธ ์ณ์ง ใฑ, ใด, ใท
CircledHangulJamo,
/// ์ผ, ์ด, ์ผ
HangulNumber,
/// ไธ, ไบ, ไธ
ChineseNumber,
/// ๋๊ทธ๋ผ๋ฏธ ์ณ์ง ไธ, ไบ, ไธ
CircledChineseNumber,
/// ๊ฐ, ์, ๋ณ, ์ , ๋ฌด, ๊ธฐ, ๊ฒฝ, ์ , ์, ๊ณ
HeavenlyStem,
/// ็ฒ, ไน, ไธ, ไธ, ๆ, ๅทฑ, ๅบ, ่พ, ๅฃฌ, ็ธ
HeavenlyStemChinese,
/// 4๊ฐ์ง ๋ฌธ์๊ฐ ์ฐจ๋ก๋ก ๋ฐ๋ณต
FourCharRepeat,
/// ์ฌ์ฉ์ ์ง์ ๋ฌธ์ ๋ฐ๋ณต
CustomCharRepeat,
}
/// ํ ํ์ด์ง ๋ด์์ ๊ฐ์ฃผ๋ฅผ ๋ค๋จ์ ์์น์ํฌ ๋ฐฉ๋ฒ / Page position method for footnotes in multi-column
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PagePosition {
/// (๊ฐ์ฃผ์ธ ๊ฒฝ์ฐ) ๊ฐ ๋จ๋ง๋ค ๋ฐ๋ก ๋ฐฐ์ด / (For footnote) Arrange separately for each column
/// (๋ฏธ์ฃผ์ธ ๊ฒฝ์ฐ) ๋ฌธ์์ ๋ง์ง๋ง / (For endnote) End of document
Separate,
/// (๊ฐ์ฃผ์ธ ๊ฒฝ์ฐ) ํต๋จ์ผ๋ก ๋ฐฐ์ด / (For footnote) Arrange across columns
/// (๋ฏธ์ฃผ์ธ ๊ฒฝ์ฐ) ๊ตฌ์ญ์ ๋ง์ง๋ง / (For endnote) End of section
Across,
/// (๊ฐ์ฃผ์ธ ๊ฒฝ์ฐ) ๊ฐ์ฅ ์ค๋ฅธ์ชฝ ๋จ์ ๋ฐฐ์ด / (For footnote) Arrange in rightmost column
Rightmost,
}
/// ๋ฒํธ ๋งค๊ธฐ๊ธฐ ๋ฐฉ๋ฒ / Numbering method
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NumberingMethod {
/// ์ ๊ตฌ์ญ์ ์ด์ด์ / Continue from previous section
Continue,
/// ํ์ฌ ๊ตฌ์ญ๋ถํฐ ์๋ก ์์ / Start from current section
Restart,
/// ์ชฝ๋ง๋ค ์๋ก ์์(๊ฐ์ฃผ ์ ์ฉ) / Restart per page (footnote only)
PerPage,
}
impl FootnoteShape {
/// FootnoteShape๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse FootnoteShape from byte array.
///
/// # Arguments
/// * `data` - ์ต์ 26๋ฐ์ดํธ์ ๋ฐ์ดํฐ / At least 26 bytes of data
///
/// # Returns
/// ํ์ฑ๋ FootnoteShape ๊ตฌ์กฐ์ฒด / Parsed FootnoteShape structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 26 {
return Err(HwpError::insufficient_data("FootnoteShape", 26, data.len()));
}
let mut offset = 0;
// UINT32 ์์ฑ (ํ 134 ์ฐธ์กฐ) / UINT32 attributes (see Table 134)
let attribute_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ์์ฑ ํ์ฑ (ํ 134) / Parse attributes (Table 134)
let attributes = parse_footnote_shape_attributes(attribute_value);
// WCHAR ์ฌ์ฉ์ ๊ธฐํธ / WCHAR custom symbol
let custom_symbol = WCHAR::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// WCHAR ์ ์ฅ์ ๋ฌธ์ / WCHAR front decoration character
let front_decoration = WCHAR::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// WCHAR ๋ค ์ฅ์ ๋ฌธ์ / WCHAR back decoration character
let back_decoration = WCHAR::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT16 ์์ ๋ฒํธ / UINT16 start number
let start_number = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// HWPUNIT16 ๊ตฌ๋ถ์ ๊ธธ์ด / HWPUNIT16 breakline length
let breakline_length = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// HWPUNIT16 ๊ตฌ๋ถ์ ์ ์ฌ๋ฐฑ / HWPUNIT16 breakline top margin
let breakline_top_margin = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// HWPUNIT16 ๊ตฌ๋ถ์ ์๋ ์ฌ๋ฐฑ / HWPUNIT16 breakline bottom margin
let breakline_bottom_margin = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// HWPUNIT16 ์ฃผ์ ์ฌ์ด ์ฌ๋ฐฑ / HWPUNIT16 remark between margin
let remark_between_margin = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT8 ๊ตฌ๋ถ์ ์ข
๋ฅ / UINT8 breakline type
let breakline_type = data[offset];
offset += 1;
// UINT8 ๊ตฌ๋ถ์ ๊ตต๊ธฐ / UINT8 breakline thickness
let breakline_thickness = data[offset];
offset += 1;
// COLORREF ๊ตฌ๋ถ์ ์์ / COLORREF breakline color
let breakline_color = COLORREF(u32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
Ok(FootnoteShape {
attributes,
custom_symbol,
front_decoration,
back_decoration,
start_number,
breakline_length,
breakline_top_margin,
breakline_bottom_margin,
remark_between_margin,
breakline_type,
breakline_thickness,
breakline_color,
})
}
}
/// ๊ฐ์ฃผ/๋ฏธ์ฃผ ๋ชจ์ ์์ฑ ํ์ฑ (ํ 134) / Parse footnote/endnote shape attributes (Table 134)
fn parse_footnote_shape_attributes(value: UINT32) -> FootnoteShapeAttributes {
// bit 0-7: ๋ฒํธ ๋ชจ์ / bit 0-7: number shape
let number_shape_value = (value & 0xFF) as u8;
let number_shape = match number_shape_value {
0 => NumberShape::Arabic,
1 => NumberShape::CircledArabic,
2 => NumberShape::RomanUpper,
3 => NumberShape::RomanLower,
4 => NumberShape::AlphaUpper,
5 => NumberShape::AlphaLower,
6 => NumberShape::CircledAlphaUpper,
7 => NumberShape::CircledAlphaLower,
8 => NumberShape::Hangul,
9 => NumberShape::CircledHangul,
10 => NumberShape::HangulJamo,
11 => NumberShape::CircledHangulJamo,
12 => NumberShape::HangulNumber,
13 => NumberShape::ChineseNumber,
14 => NumberShape::CircledChineseNumber,
15 => NumberShape::HeavenlyStem,
16 => NumberShape::HeavenlyStemChinese,
0x80 => NumberShape::FourCharRepeat,
0x81 => NumberShape::CustomCharRepeat,
_ => NumberShape::Arabic, // ๊ธฐ๋ณธ๊ฐ / default
};
// bit 8-9: ํ ํ์ด์ง ๋ด์์ ๊ฐ์ฃผ๋ฅผ ๋ค๋จ์ ์์น์ํฌ ๋ฐฉ๋ฒ / bit 8-9: page position method
let page_position = match (value >> 8) & 0x03 {
0 => PagePosition::Separate,
1 => PagePosition::Across,
2 => PagePosition::Rightmost,
_ => PagePosition::Separate, // ๊ธฐ๋ณธ๊ฐ / default
};
// bit 10-11: numbering / bit 10-11: numbering method
let numbering = match (value >> 10) & 0x03 {
0 => NumberingMethod::Continue,
1 => NumberingMethod::Restart,
2 => NumberingMethod::PerPage,
_ => NumberingMethod::Continue, // ๊ธฐ๋ณธ๊ฐ / default
};
// bit 12: ๊ฐ์ฃผ ๋ด์ฉ ์ค ๋ฒํธ ์ฝ๋์ ๋ชจ์์ ์ ์ฒจ์ ํ์์ผ๋ก ํ ์ง ์ฌ๋ถ / bit 12: superscript format
let superscript = (value & 0x1000) != 0;
// bit 13: ํ
์คํธ์ ์ด์ด ๋ฐ๋ก ์ถ๋ ฅํ ์ง ์ฌ๋ถ / bit 13: output immediately after text
let prefix = (value & 0x2000) != 0;
FootnoteShapeAttributes {
number_shape,
page_position,
numbering,
superscript,
prefix,
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/memo_shape.rs | crates/hwp-core/src/document/bodytext/memo_shape.rs | /// MemoShape ๊ตฌ์กฐ์ฒด / MemoShape structure
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ์คํ ๋ฌธ์์ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ / Spec document does not specify detailed structure
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ MEMO_SHAPE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain MEMO_SHAPE records
///
/// **์ฐธ๊ณ / Note**
/// DocInfo์ MEMO_SHAPE๋ 22๋ฐ์ดํธ๋ก ์ ์๋์ด ์์ง๋ง, BodyText์ MEMO_SHAPE๋ ๊ฐ๋ณ ๊ธธ์ด์
๋๋ค.
/// DocInfo's MEMO_SHAPE is defined as 22 bytes, but BodyText's MEMO_SHAPE is variable length.
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// ๋ฉ๋ชจ ๋ชจ์ / Memo shape
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoShape {
/// Raw ๋ฐ์ดํฐ / Raw data
/// ์คํ ๋ฌธ์์ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ผ๋ฏ๋ก raw ๋ฐ์ดํฐ๋ก ์ ์ฅํฉ๋๋ค.
/// Raw data is stored because the spec document does not specify detailed structure.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub raw_data: Vec<u8>,
}
impl MemoShape {
/// MemoShape์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse MemoShape from byte array.
///
/// # Arguments
/// * `data` - MemoShape ๋ฐ์ดํฐ / MemoShape data
///
/// # Returns
/// ํ์ฑ๋ MemoShape ๊ตฌ์กฐ์ฒด / Parsed MemoShape structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 57์๋ "๋ฉ๋ชจ ๋ชจ์"์ผ๋ก๋ง ์ธ๊ธ๋์ด ์๊ณ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ต๋๋ค.
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ raw ๋ฐ์ดํฐ๋ก๋ง ์ ์ฅํ๊ณ ์์ต๋๋ค.
/// Spec document Table 57 only mentions "Memo shape" and does not specify detailed structure.
/// Legacy code (hwp.js) also stores only raw data.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ MEMO_SHAPE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ MEMO_SHAPE ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain MEMO_SHAPE records, so it has not been verified with actual files.
/// If an actual HWP file contains MEMO_SHAPE records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
Ok(MemoShape {
raw_data: data.to_vec(),
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/table.rs | crates/hwp-core/src/document/bodytext/table.rs | /// Table ๊ตฌ์กฐ์ฒด / Table structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 74 - ํ ๊ฐ์ฒด / Spec mapping: Table 74 - Table object
use crate::error::HwpError;
use crate::types::{HWPUNIT, HWPUNIT16, UINT16, UINT32};
use serde::{Deserialize, Serialize};
use super::list_header::ListHeader;
/// ํ ๊ฐ์ฒด / Table object
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Table {
/// ํ ๊ฐ์ฒด ์์ฑ (ํ 75 ์ฐธ์กฐ) / Table object attributes (see Table 75)
pub attributes: TableAttributes,
/// ์
๋ฆฌ์คํธ (ํ 79 ์ฐธ์กฐ) / Cell list (see Table 79)
pub cells: Vec<TableCell>,
}
/// ํ ๊ฐ์ฒด ์์ฑ (ํ 75) / Table object attributes (Table 75)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableAttributes {
/// ์์ฑ (ํ 76 ์ฐธ์กฐ) / Attribute (see Table 76)
pub attribute: TableAttribute,
/// ํ ๊ฐ์ / Row count
pub row_count: UINT16,
/// ์ด ๊ฐ์ / Column count
pub col_count: UINT16,
/// ์
๊ฐ๊ฒฉ / Cell spacing
pub cell_spacing: HWPUNIT16,
/// ์์ชฝ ์ฌ๋ฐฑ ์ ๋ณด (ํ 77 ์ฐธ์กฐ) / Padding information (see Table 77)
pub padding: TablePadding,
/// ํ ํฌ๊ธฐ ๋ฆฌ์คํธ / Row size list
pub row_sizes: Vec<HWPUNIT16>,
/// ํ
๋๋ฆฌ ์ฑ์ฐ๊ธฐ ID / Border fill ID
pub border_fill_id: UINT16,
/// ์์ญ ์์ฑ ๋ฆฌ์คํธ (5.0.1.0 ์ด์) / Zone attributes list (5.0.1.0 and above)
pub zones: Vec<TableZone>,
}
/// ํ ์์ฑ์ ์์ฑ (ํ 76) / Table attribute properties (Table 76)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableAttribute {
/// ์ชฝ ๊ฒฝ๊ณ์์ ๋๋ / Page break behavior
pub page_break: PageBreakBehavior,
/// ์ ๋ชฉ ์ค ์๋ ๋ฐ๋ณต ์ฌ๋ถ / Header row auto repeat
pub header_row_repeat: bool,
}
/// ์ชฝ ๊ฒฝ๊ณ์์ ๋๋ / Page break behavior
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PageBreakBehavior {
/// ๋๋์ง ์์ / No break
NoBreak,
/// ์
๋จ์๋ก ๋๋ / Break by cell
BreakByCell,
/// ๋๋์ง ์์ (๋ค๋ฅธ ๊ฐ) / No break (other value)
NoBreakOther,
}
/// ์์ชฝ ์ฌ๋ฐฑ ์ ๋ณด (ํ 77) / Padding information (Table 77)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TablePadding {
/// ์ผ์ชฝ ์ฌ๋ฐฑ / Left padding
pub left: HWPUNIT16,
/// ์ค๋ฅธ์ชฝ ์ฌ๋ฐฑ / Right padding
pub right: HWPUNIT16,
/// ์์ชฝ ์ฌ๋ฐฑ / Top padding
pub top: HWPUNIT16,
/// ์๋์ชฝ ์ฌ๋ฐฑ / Bottom padding
pub bottom: HWPUNIT16,
}
/// ์์ญ ์์ฑ (ํ 78) / Zone attributes (Table 78)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableZone {
/// ์์ ์ด ์ฃผ์ / Start column address
pub start_col: UINT16,
/// ์์ ํ ์ฃผ์ / Start row address
pub start_row: UINT16,
/// ๋ ์ด ์ฃผ์ / End column address
pub end_col: UINT16,
/// ๋ ํ ์ฃผ์ / End row address
pub end_row: UINT16,
/// ํ
๋๋ฆฌ ์ฑ์ฐ๊ธฐ ID / Border fill ID
pub border_fill_id: UINT16,
}
/// ์
๋ฆฌ์คํธ (ํ 79) / Cell list (Table 79)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TableCell {
/// ๋ฌธ๋จ ๋ฆฌ์คํธ ํค๋ (ํ 65 ์ฐธ์กฐ) / Paragraph list header (see Table 65)
pub list_header: ListHeader,
/// ์
์์ฑ (ํ 80 ์ฐธ์กฐ) / Cell attributes (see Table 80)
pub cell_attributes: CellAttributes,
/// ์
๋ด๋ถ์ ๋ฌธ๋จ๋ค (๋ ๋ฒจ 3) / Paragraphs inside cell (level 3)
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub paragraphs: Vec<super::Paragraph>,
}
/// ์
์์ฑ (ํ 80) / Cell attributes (Table 80)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CellAttributes {
/// ์ด ์ฃผ์ / Column address
pub col_address: UINT16,
/// ํ ์ฃผ์ / Row address
pub row_address: UINT16,
/// ์ด ๋ณํฉ ๊ฐ์ / Column merge count
pub col_span: UINT16,
/// ํ ๋ณํฉ ๊ฐ์ / Row merge count
pub row_span: UINT16,
/// ํญ / Width
pub width: HWPUNIT,
/// ๋์ด / Height
pub height: HWPUNIT,
/// ์ผ์ชฝ ์ฌ๋ฐฑ / Left margin
pub left_margin: HWPUNIT16,
/// ์ค๋ฅธ์ชฝ ์ฌ๋ฐฑ / Right margin
pub right_margin: HWPUNIT16,
/// ์์ชฝ ์ฌ๋ฐฑ / Top margin
pub top_margin: HWPUNIT16,
/// ์๋์ชฝ ์ฌ๋ฐฑ / Bottom margin
pub bottom_margin: HWPUNIT16,
/// ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์ด๋ / Border fill ID
pub border_fill_id: UINT16,
}
impl Table {
/// Table์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse Table from byte array.
///
/// # Arguments
/// * `data` - Table ๋ฐ์ดํฐ (๊ฐ์ฒด ๊ณตํต ์์ฑ ํฌํจ) / Table data (including object common properties)
/// * `version` - ํ์ผ ๋ฒ์ / File version
///
/// # Returns
/// ํ์ฑ๋ Table ๊ตฌ์กฐ์ฒด / Parsed Table structure
pub fn parse(data: &[u8], version: u32) -> Result<Self, HwpError> {
if data.is_empty() {
return Err(HwpError::InsufficientData {
field: "Table data".to_string(),
expected: 1,
actual: 0,
});
}
let mut offset = 0;
// ๋ ๊ฑฐ์ ์ฝ๋๋ฅผ ๋ณด๋ฉด HWPTAG_TABLE์ ๊ฐ์ฒด ๊ณตํต ์์ฑ์ ๊ฑด๋๋ฐ๊ณ ํ ๊ฐ์ฒด ์์ฑ๋ถํฐ ์์
// According to legacy code, HWPTAG_TABLE skips object common properties and starts from table attributes
// ํ ๊ฐ์ฒด ์์ฑ ํ์ฑ (ํ 75) / Parse table object attributes (Table 75)
let attributes = parse_table_attributes(data, &mut offset, version)?;
// IMPORTANT:
// HWP 5.x ์ค๋ฐ์ดํฐ์์๋ "ํ ์
"์ ์ค์ ๋ฉํ(ํ/์ด, ํญ/๋์ด, ๋ง์ง, borderFill ๋ฑ)์
// ์
๋ด๋ถ ๋ฌธ๋จ์ ๋๋ถ๋ถ HWPTAG_LIST_HEADER(ํ
์ด๋ธ ์
๋ฆฌ์คํธ) ํธ๋ฆฌ๋ก ์ ๊ณต๋ฉ๋๋ค.
//
// legacy hwpjs / pyhwp ๊ตฌํ๋ ์ด LIST_HEADER ๊ธฐ๋ฐ์ ๋จ์ผ ์์ค๋ก ์ทจ๊ธํ๋ ๋ฐฉ์์ด๋ฉฐ,
// HWPTAG_TABLE payload(ํ 79/80)๋ฅผ ์ถ์ ํ์ฑํ๋ฉด ์คํ์
๋ถ์ผ์น๋ก "๊ฐ์ง ์
"์ด ํ๋ ๋ ์๊ธฐ๋
// ์ผ์ด์ค(table-caption ๋ฑ)๊ฐ ์์ต๋๋ค.
//
// ๋ฐ๋ผ์ ์ฌ๊ธฐ์๋ HWPTAG_TABLE payload์์ ์
๋ฆฌ์คํธ๋ฅผ ๋ง๋ค์ง ์๊ณ ,
// ํธ๋ฆฌ ๊ฒฐํฉ ๋จ๊ณ(document/bodytext/mod.rs)์์ LIST_HEADER ๊ธฐ๋ฐ์ผ๋ก table.cells๋ฅผ ๊ตฌ์ฑํฉ๋๋ค.
let cells = Vec::new();
Ok(Table { attributes, cells })
}
}
/// ํ ๊ฐ์ฒด ์์ฑ ํ์ฑ (ํ 75) / Parse table object attributes (Table 75)
fn parse_table_attributes(
data: &[u8],
offset: &mut usize,
version: u32,
) -> Result<TableAttributes, HwpError> {
// ์ต์ 22๋ฐ์ดํธ ํ์ (๊ธฐ๋ณธ ํ๋) / Need at least 22 bytes (basic fields)
if data.len() < *offset + 22 {
return Err(HwpError::insufficient_data(
"Table attributes",
22,
data.len() - *offset,
));
}
// UINT32 ์์ฑ (ํ 76 ์ฐธ์กฐ) / UINT32 attribute (see Table 76)
let attribute_value = UINT32::from_le_bytes([
data[*offset],
data[*offset + 1],
data[*offset + 2],
data[*offset + 3],
]);
*offset += 4;
// UINT16 RowCount / UINT16 RowCount
let row_count_raw = UINT16::from_le_bytes([data[*offset], data[*offset + 1]]);
*offset += 2;
// UINT16 nCols / UINT16 nCols
let col_count_raw = UINT16::from_le_bytes([data[*offset], data[*offset + 1]]);
*offset += 2;
// row_count์ col_count๋ UINT16์ด๋ฏ๋ก ์ต๋ 65535๊น์ง ๊ฐ๋ฅ / row_count and col_count are UINT16, so max 65535
// JSON์์๋ ์ ์์ ์ผ๋ก ํ์ฑ๋๋ฏ๋ก ํ์ฑ ์์ฒด๋ ๋ฌธ์ ์์ / Parsing is fine since JSON shows normal values
// ์ค์ ๋ฌธ์ ๋ row_sizes ๋ฉ๋ชจ๋ฆฌ ์์์ด๋ฏ๋ก, row_count/col_count๋ ๊ทธ๋๋ก ์ฌ์ฉ / Actual issue is row_sizes memory corruption, so use row_count/col_count as is
let row_count = row_count_raw;
let col_count = col_count_raw;
// HWPUNIT16 CellSpacing / HWPUNIT16 CellSpacing
let cell_spacing = HWPUNIT16::from_le_bytes([data[*offset], data[*offset + 1]]);
*offset += 2;
// BYTE stream 8 ์์ชฝ ์ฌ๋ฐฑ ์ ๋ณด (ํ 77 ์ฐธ์กฐ) / BYTE stream 8 padding information (see Table 77)
let padding = TablePadding {
left: HWPUNIT16::from_le_bytes([data[*offset], data[*offset + 1]]),
right: HWPUNIT16::from_le_bytes([data[*offset + 2], data[*offset + 3]]),
top: HWPUNIT16::from_le_bytes([data[*offset + 4], data[*offset + 5]]),
bottom: HWPUNIT16::from_le_bytes([data[*offset + 6], data[*offset + 7]]),
};
*offset += 8;
// BYTE stream 2รrow Row Size / BYTE stream 2รrow Row Size
// row_count๊ฐ ์ด๋ฏธ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ๊ฑฐ์ณค์ผ๋ฏ๋ก ์์ ํ๊ฒ ํ์ฑ / row_count is already validated, so safe to parse
let mut row_sizes = Vec::new();
for _ in 0..row_count {
if *offset + 2 > data.len() {
// ๋ฐ์ดํฐ๊ฐ ๋ถ์กฑํ๋ฉด ์ค๋จํ๊ณ ์ง๊ธ๊น์ง ํ์ฑํ ๊ฒ๋ง ์ฌ์ฉ / Stop if insufficient data and use what we've parsed so far
break;
}
row_sizes.push(HWPUNIT16::from_le_bytes([data[*offset], data[*offset + 1]]));
*offset += 2;
}
// row_sizes๊ฐ row_count์ ์ผ์นํ์ง ์์ผ๋ฉด ๋น Vec๋ก ์ด๊ธฐํ / Initialize as empty Vec if row_sizes doesn't match row_count
// ๋ฉ๋ชจ๋ฆฌ ์์ ๋ฐฉ์ง๋ฅผ ์ํด ์ ํจ์ฑ ๊ฒ์ฌ / Validate to prevent memory corruption
if row_sizes.len() != row_count as usize {
row_sizes = Vec::new();
}
// UINT16 Border Fill ID / UINT16 Border Fill ID
let border_fill_id = UINT16::from_le_bytes([data[*offset], data[*offset + 1]]);
*offset += 2;
// UINT16 Valid Zone Info Size (5.0.1.0 ์ด์) / UINT16 Valid Zone Info Size (5.0.1.0 and above)
let mut zones = Vec::new();
if version >= 5010 {
if *offset + 2 > data.len() {
return Err(HwpError::insufficient_data(
"valid zone info size",
2,
data.len() - *offset,
));
}
let valid_zone_info_size = UINT16::from_le_bytes([data[*offset], data[*offset + 1]]);
*offset += 2;
// BYTE stream 10รzone ์์ญ ์์ฑ (ํ 78 ์ฐธ์กฐ) / BYTE stream 10รzone zone attributes (see Table 78)
let zone_count = valid_zone_info_size as usize / 10;
for _ in 0..zone_count {
if *offset + 10 > data.len() {
return Err(HwpError::insufficient_data(
"zone attributes",
10,
data.len() - *offset,
));
}
zones.push(TableZone {
start_col: UINT16::from_le_bytes([data[*offset], data[*offset + 1]]),
start_row: UINT16::from_le_bytes([data[*offset + 2], data[*offset + 3]]),
end_col: UINT16::from_le_bytes([data[*offset + 4], data[*offset + 5]]),
end_row: UINT16::from_le_bytes([data[*offset + 6], data[*offset + 7]]),
border_fill_id: UINT16::from_le_bytes([data[*offset + 8], data[*offset + 9]]),
});
*offset += 10;
}
}
// ์์ฑ ํ์ฑ (ํ 76) / Parse attribute (Table 76)
let attribute = parse_table_attribute(attribute_value);
// row_count=0์ด๊ฑฐ๋ row_sizes๊ฐ row_count์ ์ผ์นํ์ง ์์ผ๋ฉด ๋น Vec๋ก ์ด๊ธฐํ / Initialize as empty Vec if row_count=0 or row_sizes doesn't match row_count
// Vec์ ๋ฉํ๋ฐ์ดํฐ ์์ ๋ฐฉ์ง๋ฅผ ์ํด ๋ช
์์ ์ผ๋ก ๋น Vec ์ฌ์ฉ / Use explicit empty Vec to prevent Vec metadata corruption
let final_row_sizes = if row_count == 0 || row_sizes.len() != row_count as usize {
Vec::new()
} else {
row_sizes
};
let result = TableAttributes {
attribute,
row_count,
col_count,
cell_spacing,
padding,
row_sizes: final_row_sizes, // row_count=0์ด๊ฑฐ๋ row_sizes๊ฐ ๋น์ด์๊ฑฐ๋ ๋น์ ์์ ์ผ๋ก ํฌ๋ฉด ๋น Vec ์ฌ์ฉ / Use empty Vec when row_count=0 or row_sizes is empty/abnormal
border_fill_id,
zones,
};
Ok(result)
}
/// ํ ์์ฑ์ ์์ฑ ํ์ฑ (ํ 76) / Parse table attribute properties (Table 76)
fn parse_table_attribute(value: UINT32) -> TableAttribute {
// bit 0-1: ์ชฝ ๊ฒฝ๊ณ์์ ๋๋ / bit 0-1: page break behavior
let page_break = match value & 0x03 {
0 => PageBreakBehavior::NoBreak,
1 => PageBreakBehavior::BreakByCell,
2 => PageBreakBehavior::NoBreakOther,
_ => PageBreakBehavior::NoBreak,
};
// bit 2: ์ ๋ชฉ ์ค ์๋ ๋ฐ๋ณต ์ฌ๋ถ / bit 2: header row auto repeat
let header_row_repeat = (value & 0x04) != 0;
TableAttribute {
page_break,
header_row_repeat,
}
}
/// ์
๋ฆฌ์คํธ ํ์ฑ (ํ 79) / Parse cell list (Table 79)
#[allow(dead_code)]
fn parse_cell_list(
data: &[u8],
row_count: UINT16,
col_count: UINT16,
row_sizes: &[HWPUNIT16], // ๊ฐ ํ์ ์ค์ ์
๊ฐ์
) -> Result<Vec<TableCell>, HwpError> {
let mut cells = Vec::new();
let mut offset = 0;
// ์
๊ฐ์ ์ฐ์ :
// - ์คํ/์ค๋ฐ์ดํฐ์์ row_sizes๋ "๊ฐ ํ์ ์ค์ ์
๊ฐ์"๋ก ์ฌ์ฉ๋ฉ๋๋ค.
// - row_sizes๊ฐ ์ ํจํ๋ฉด(ํฉ>0) ๊ทธ๋๋ก ์ฌ์ฉํ๊ณ , ์์ผ๋ฉด row_count*col_count๋ก ํด๋ฐฑํฉ๋๋ค.
let total_cells_from_row_sizes: usize = row_sizes.iter().map(|&size| size as usize).sum();
let total_cells = if total_cells_from_row_sizes > 0 {
total_cells_from_row_sizes
} else {
row_count as usize * col_count as usize
};
// ListHeader(ํ 65)๋ ๋ฌธ์์ 6๋ฐ์ดํธ๋ก ๋์ด ์์ผ๋, ์ค์ ํ์ผ์์๋
// [paragraph_count:2][unknown1:2][attribute:4]์ 8๋ฐ์ดํธ ํํ๊ฐ ์กด์ฌํฉ๋๋ค.
//
// TableCell์์๋ ListHeader ๋ฐ๋ก ๋ค์ CellAttributes(ํ 80, 26๋ฐ์ดํธ)๊ฐ ์ด์ด์ง๋ฏ๋ก,
// "6๋ฐ์ดํธ/8๋ฐ์ดํธ" ์ค ์ด๋ค ๋ ์ด์์์ธ์ง ์ค์ ๋ฐ์ดํธ๋ฅผ ๋ณด๊ณ ํ๋ณํด์ผ ์คํ์
์ด ํ์ด์ง์ง ์์ต๋๋ค.
fn parse_cell_attributes_at(data: &[u8], offset: usize) -> Option<CellAttributes> {
if offset + 26 > data.len() {
return None;
}
Some(CellAttributes {
col_address: UINT16::from_le_bytes([data[offset], data[offset + 1]]),
row_address: UINT16::from_le_bytes([data[offset + 2], data[offset + 3]]),
col_span: UINT16::from_le_bytes([data[offset + 4], data[offset + 5]]),
row_span: UINT16::from_le_bytes([data[offset + 6], data[offset + 7]]),
width: HWPUNIT::from(UINT32::from_le_bytes([
data[offset + 8],
data[offset + 9],
data[offset + 10],
data[offset + 11],
])),
height: HWPUNIT::from(UINT32::from_le_bytes([
data[offset + 12],
data[offset + 13],
data[offset + 14],
data[offset + 15],
])),
left_margin: HWPUNIT16::from_le_bytes([data[offset + 16], data[offset + 17]]),
right_margin: HWPUNIT16::from_le_bytes([data[offset + 18], data[offset + 19]]),
top_margin: HWPUNIT16::from_le_bytes([data[offset + 20], data[offset + 21]]),
bottom_margin: HWPUNIT16::from_le_bytes([data[offset + 22], data[offset + 23]]),
border_fill_id: UINT16::from_le_bytes([data[offset + 24], data[offset + 25]]),
})
}
fn is_plausible_cell_attrs(
attrs: &CellAttributes,
row_count: UINT16,
col_count: UINT16,
) -> bool {
// row/col์ ํ
์ด๋ธ ๋ฒ์ ๋ด์ฌ์ผ ํจ
if attrs.row_address >= row_count || attrs.col_address >= col_count {
return false;
}
// ํญ/๋์ด๋ 0์ด ์๋ ๊ฒ์ด ์ผ๋ฐ์ (0์ด๋ฉด ์คํ์
์คํ ๊ฐ๋ฅ์ฑ์ด ํผ)
if attrs.width.0 == 0 || attrs.height.0 == 0 {
return false;
}
true
}
for _ in 0..total_cells {
if offset >= data.len() {
break; // ์
๋ฐ์ดํฐ๊ฐ ๋ถ์กฑํ ์ ์์ / Cell data may be insufficient
}
// 1) ListHeader ํฌ๊ธฐ(6/8) ํ๋ณ
// - ์ฐ์ 8๋ฐ์ดํธ๋ก ๊ฐ์ ํ ๋ค, ๊ทธ ๋ค์ 26๋ฐ์ดํธ๋ฅผ CellAttributes๋ก ํด์ํ์ ๋ ๊ฐ์ด ๊ทธ๋ด๋ฏํ๋ฉด 8
// - ์๋๋ฉด 6๋ฐ์ดํธ๋ก ์๋
// - ๋ ๋ค ๊ทธ๋ด๋ฏํ์ง ์์ผ๋ฉด(๋ฐ์ดํฐ ์์ ๋ฑ) 8์ ๊ธฐ๋ณธ์ผ๋ก ๋ (๊ธฐ์กด ๋ก์ง๊ณผ ํธํ)
let header_len = {
let mut chosen = 8usize;
let try8 = parse_cell_attributes_at(data, offset + 8)
.filter(|a| is_plausible_cell_attrs(a, row_count, col_count));
let try6 = parse_cell_attributes_at(data, offset + 6)
.filter(|a| is_plausible_cell_attrs(a, row_count, col_count));
if try8.is_some() {
chosen = 8;
} else if try6.is_some() {
chosen = 6;
}
chosen
};
// 2) ListHeader ํ์ฑ (ํ์ ๋ ๊ธธ์ด๋งํผ)
if offset + header_len > data.len() {
break;
}
let list_header =
ListHeader::parse(&data[offset..offset + header_len]).map_err(|e| HwpError::from(e))?;
offset += header_len;
// ์
์์ฑ ํ์ฑ (ํ 80 ์ฐธ์กฐ) / Parse cell attributes (see Table 80)
// ํ 80: ์ ์ฒด ๊ธธ์ด 26๋ฐ์ดํธ
// UINT16(2) + UINT16(2) + UINT16(2) + UINT16(2) + HWPUNIT(4) + HWPUNIT(4) + HWPUNIT16[4](8) + UINT16(2) = 26
if offset + 26 > data.len() {
return Err(HwpError::insufficient_data(
"cell attributes",
26,
data.len() - offset,
));
}
let cell_attributes = parse_cell_attributes_at(data, offset).ok_or_else(|| {
HwpError::insufficient_data("cell attributes", 26, data.len().saturating_sub(offset))
})?;
offset += 26;
cells.push(TableCell {
list_header,
cell_attributes,
paragraphs: Vec::new(), // ํธ๋ฆฌ ๊ตฌ์กฐ์์ ๋์ค์ ์ฑ์์ง / Will be filled from tree structure later
});
}
Ok(cells)
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/range_tag.rs | crates/hwp-core/src/document/bodytext/range_tag.rs | /// RangeTagInfo ๊ตฌ์กฐ์ฒด / RangeTagInfo structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 63 - ๋ฌธ๋จ์ ์์ญ ํ๊ทธ / Spec mapping: Table 63 - Paragraph range tag
/// ๊ฐ ํญ๋ชฉ: 12๋ฐ์ดํธ
use crate::error::HwpError;
use crate::types::{UINT32, UINT8};
use serde::{Deserialize, Serialize};
/// ์์ญ ํ๊ทธ ์ ๋ณด / Range tag information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RangeTagInfo {
/// ์์ญ ์์ ์์น / Range start position
pub start: UINT32,
/// ์์ญ ๋ ์์น / Range end position
pub end: UINT32,
/// ํ๊ทธ ์ข
๋ฅ (์์ 8๋นํธ) / Tag type (upper 8 bits)
pub tag_type: UINT8,
/// ํ๊ทธ ๋ฐ์ดํฐ (ํ์ 24๋นํธ) / Tag data (lower 24 bits)
pub tag_data: UINT32,
}
impl RangeTagInfo {
/// RangeTagInfo๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse RangeTagInfo from byte array.
///
/// # Arguments
/// * `data` - ์ต์ 12๋ฐ์ดํธ์ ๋ฐ์ดํฐ / At least 12 bytes of data
///
/// # Returns
/// ํ์ฑ๋ RangeTagInfo ๊ตฌ์กฐ์ฒด / Parsed RangeTagInfo structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 12 {
return Err(HwpError::insufficient_data("RangeTagInfo", 12, data.len()));
}
// UINT32 ์์ญ ์์ / UINT32 range start
let start = UINT32::from_le_bytes([data[0], data[1], data[2], data[3]]);
// UINT32 ์์ญ ๋ / UINT32 range end
let end = UINT32::from_le_bytes([data[4], data[5], data[6], data[7]]);
// UINT32 ํ๊ทธ(์ข
๋ฅ + ๋ฐ์ดํฐ) / UINT32 tag (type + data)
// ์์ 8๋นํธ๊ฐ ์ข
๋ฅ, ํ์ 24๋นํธ๊ฐ ๋ฐ์ดํฐ / Upper 8 bits are type, lower 24 bits are data
let tag_value = UINT32::from_le_bytes([data[8], data[9], data[10], data[11]]);
let tag_type = ((tag_value >> 24) & 0xFF) as UINT8;
let tag_data = tag_value & 0x00FFFFFF;
Ok(RangeTagInfo {
start,
end,
tag_type,
tag_data,
})
}
}
/// ๋ฌธ๋จ์ ์์ญ ํ๊ทธ ๋ฆฌ์คํธ / Paragraph range tag list
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ParaRangeTag {
/// ์์ญ ํ๊ทธ ์ ๋ณด ๋ฆฌ์คํธ / Range tag information list
pub tags: Vec<RangeTagInfo>,
}
impl ParaRangeTag {
/// ParaRangeTag๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ParaRangeTag from byte array.
///
/// # Arguments
/// * `data` - ์์ญ ํ๊ทธ ๋ฐ์ดํฐ (12รn ๋ฐ์ดํธ) / Range tag data (12รn bytes)
///
/// # Returns
/// ํ์ฑ๋ ParaRangeTag ๊ตฌ์กฐ์ฒด / Parsed ParaRangeTag structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() % 12 != 0 {
return Err(HwpError::UnexpectedValue {
field: "ParaRangeTag data length".to_string(),
expected: "multiple of 12".to_string(),
found: format!("{} bytes", data.len()),
});
}
let count = data.len() / 12;
let mut tags = Vec::with_capacity(count);
for i in 0..count {
let offset = i * 12;
let tag_data = &data[offset..offset + 12];
let tag_info = RangeTagInfo::parse(tag_data)
.map_err(|e| HwpError::from(e))?;
tags.push(tag_info);
}
Ok(ParaRangeTag { tags })
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/page_border_fill.rs | crates/hwp-core/src/document/bodytext/page_border_fill.rs | /// PageBorderFill ๊ตฌ์กฐ์ฒด / PageBorderFill structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 135 - ์ชฝ ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ / Spec mapping: Table 135 - Page border/fill
use crate::error::HwpError;
use crate::types::{HWPUNIT16, UINT16, UINT32};
use serde::{Deserialize, Serialize};
/// ์ชฝ ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ / Page border/fill
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PageBorderFill {
/// ์์ฑ / Attributes
pub attributes: PageBorderFillAttributes,
/// ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์น ์ผ์ชฝ ๊ฐ๊ฒฉ / Left spacing
pub left_spacing: HWPUNIT16,
/// ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์น ์ค๋ฅธ์ชฝ ๊ฐ๊ฒฉ / Right spacing
pub right_spacing: HWPUNIT16,
/// ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์น ์์ชฝ ๊ฐ๊ฒฉ / Top spacing
pub top_spacing: HWPUNIT16,
/// ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์น ์๋์ชฝ ๊ฐ๊ฒฉ / Bottom spacing
pub bottom_spacing: HWPUNIT16,
/// ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ID / Border/fill ID
pub border_fill_id: UINT16,
}
/// ์ชฝ ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์ฑ / Page border/fill attributes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PageBorderFillAttributes {
/// ์์น ๊ธฐ์ค / Position reference
pub position_reference: PositionReference,
/// ๋จธ๋ฆฌ๋ง ํฌํจ ์ฌ๋ถ / Include header
pub include_header: bool,
/// ๊ผฌ๋ฆฌ๋ง ํฌํจ ์ฌ๋ถ / Include footer
pub include_footer: bool,
/// ์ฑ์ธ ์์ญ / Fill area
pub fill_area: FillArea,
}
/// ์์น ๊ธฐ์ค / Position reference
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PositionReference {
/// ๋ณธ๋ฌธ ๊ธฐ์ค / Body text reference
BodyText,
/// ์ข
์ด ๊ธฐ์ค / Paper reference
Paper,
}
/// ์ฑ์ธ ์์ญ / Fill area
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FillArea {
/// ์ข
์ด / Paper
Paper,
/// ์ชฝ / Page
Page,
/// ํ
๋๋ฆฌ / Border
Border,
}
impl PageBorderFill {
/// PageBorderFill๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse PageBorderFill from byte array.
///
/// # Arguments
/// * `data` - ์ต์ 12๋ฐ์ดํธ์ ๋ฐ์ดํฐ / At least 12 bytes of data
///
/// # Returns
/// ํ์ฑ๋ PageBorderFill ๊ตฌ์กฐ์ฒด / Parsed PageBorderFill structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 12 {
return Err(HwpError::insufficient_data("PageBorderFill", 12, data.len()));
}
let mut offset = 0;
// UINT ์์ฑ (ํ 136 ์ฐธ์กฐ) / UINT attributes (see Table 136)
let attribute_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ์์ฑ ํ์ฑ (ํ 136) / Parse attributes (Table 136)
let attributes = parse_page_border_fill_attributes(attribute_value);
// HWPUNIT16 ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์น ์ผ์ชฝ ๊ฐ๊ฒฉ / HWPUNIT16 left spacing
let left_spacing = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// HWPUNIT16 ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์น ์ค๋ฅธ์ชฝ ๊ฐ๊ฒฉ / HWPUNIT16 right spacing
let right_spacing = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// HWPUNIT16 ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์น ์์ชฝ ๊ฐ๊ฒฉ / HWPUNIT16 top spacing
let top_spacing = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// HWPUNIT16 ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์น ์๋์ชฝ ๊ฐ๊ฒฉ / HWPUNIT16 bottom spacing
let bottom_spacing = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT16 ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ID / UINT16 border/fill ID
let border_fill_id = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
Ok(PageBorderFill {
attributes,
left_spacing,
right_spacing,
top_spacing,
bottom_spacing,
border_fill_id,
})
}
}
/// ์ชฝ ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์์ฑ ํ์ฑ (ํ 136) / Parse page border/fill attributes (Table 136)
fn parse_page_border_fill_attributes(value: UINT32) -> PageBorderFillAttributes {
// bit 0: ์์น ๊ธฐ์ค / bit 0: position reference
// 0: ๋ณธ๋ฌธ ๊ธฐ์ค / 0: body text reference
// 1: ์ข
์ด ๊ธฐ์ค / 1: paper reference
let position_reference = if (value & 0x01) == 0 {
PositionReference::BodyText
} else {
PositionReference::Paper
};
// bit 1: ๋จธ๋ฆฌ๋ง ํฌํจ ์ฌ๋ถ / bit 1: include header
let include_header = (value & 0x02) != 0;
// bit 2: ๊ผฌ๋ฆฌ๋ง ํฌํจ ์ฌ๋ถ / bit 2: include footer
let include_footer = (value & 0x04) != 0;
// bit 3-4: ์ฑ์ธ ์์ญ / bit 3-4: fill area
// 0: ์ข
์ด / 0: paper
// 1: ์ชฝ / 1: page
// 2: ํ
๋๋ฆฌ / 2: border
let fill_area = match (value >> 3) & 0x03 {
0 => FillArea::Paper,
1 => FillArea::Page,
2 => FillArea::Border,
_ => FillArea::Paper, // ๊ธฐ๋ณธ๊ฐ / default
};
PageBorderFillAttributes {
position_reference,
include_header,
include_footer,
fill_area,
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/video_data.rs | crates/hwp-core/src/document/bodytext/video_data.rs | /// VideoData ๊ตฌ์กฐ์ฒด / VideoData structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 123 - ๋์์ ๊ฐ์ฒด ์์ฑ / Spec mapping: Table 123 - Video object attributes
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ VIDEO_DATA ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain VIDEO_DATA records
use crate::error::HwpError;
use crate::types::{decode_utf16le, INT32, UINT16};
use serde::{Deserialize, Serialize};
/// ๋์์ ๊ฐ์ฒด / Video object
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoData {
/// ๋์์ ํ์
(ํ 124 ์ฐธ์กฐ) / Video type (see Table 124)
/// - 0: ๋ก์ปฌ ๋์์ / Local video
/// - 1: ์น ๋์์ / Web video
pub video_type: INT32,
/// ๋์์ ํ์
์ ๋ฐ๋ฅธ ์์ฑ / Attributes based on video type
pub video_attributes: VideoAttributes,
}
/// ๋์์ ์์ฑ / Video attributes
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum VideoAttributes {
/// ๋ก์ปฌ ๋์์ ์์ฑ (ํ 125 ์ฐธ์กฐ) / Local video attributes (see Table 125)
Local {
/// ๋น๋์ค ํ์ผ์ด ์ฌ์ฉํ๋ ์คํ ๋ฆฌ์ง์ BinData ID / BinData ID of storage used by video file
video_bindata_id: UINT16,
/// ์ธ๋ค์ผ ํ์ผ์ด ์ฌ์ฉํ๋ ์คํ ๋ฆฌ์ง์ BinData ID / BinData ID of storage used by thumbnail file
thumbnail_bindata_id: UINT16,
},
/// ์น ๋์์ ์์ฑ (ํ 126 ์ฐธ์กฐ) / Web video attributes (see Table 126)
Web {
/// ์น ํ๊ทธ / Web tag
web_tag: String,
/// ์ธ๋ค์ผ ํ์ผ์ด ์ฌ์ฉํ๋ ์คํ ๋ฆฌ์ง์ BinData ID / BinData ID of storage used by thumbnail file
thumbnail_bindata_id: UINT16,
},
}
impl VideoData {
/// VideoData๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse VideoData from byte array.
///
/// # Arguments
/// * `data` - VideoData ๋ฐ์ดํฐ (๋์์ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง) / VideoData data (video object attributes only)
///
/// # Returns
/// ํ์ฑ๋ VideoData ๊ตฌ์กฐ์ฒด / Parsed VideoData structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 122์ ๋ฐ๋ฅด๋ฉด VIDEO_DATA๋ ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋๋ค:
/// - ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 68 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ๋์์ ๊ฐ์ฒด ์์ฑ(ํ 123 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด (4 + n ๋ฐ์ดํธ)
///
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ ๋์์ ๊ฐ์ฒด ์์ฑ์ ํ์ฑํ์ง ์๊ณ ์์ต๋๋ค.
/// According to spec Table 122, VIDEO_DATA has the following structure:
/// - Object common properties (Table 68) - variable length
/// - Video object attributes (Table 123) - variable length (4 + n bytes)
///
/// Legacy code (hwp.js) does not parse video object attributes.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ VIDEO_DATA ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ VIDEO_DATA ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain VIDEO_DATA records, so it has not been verified with actual files.
/// If an actual HWP file contains VIDEO_DATA records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ์ต์ 4๋ฐ์ดํธ ํ์ (๋์์ ํ์
) / Need at least 4 bytes (video type)
if data.len() < 4 {
return Err(HwpError::insufficient_data("VideoData", 4, data.len()));
}
let mut offset = 0;
// ํ 123: ๋์์ ํ์
(INT32, 4๋ฐ์ดํธ) / Table 123: Video type (INT32, 4 bytes)
let video_type = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 123: ๋์์ ํ์
์ ๋ฐ๋ฅธ ์์ฑ ํ์ฑ / Table 123: Parse attributes based on video type
let video_attributes = match video_type {
0 => {
// ๋ก์ปฌ ๋์์ ์์ฑ (ํ 125) / Local video attributes (Table 125)
if data.len() < offset + 4 {
return Err(HwpError::insufficient_data(
"VideoData local video attributes",
4,
data.len() - offset,
));
}
let video_bindata_id = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let thumbnail_bindata_id = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
VideoAttributes::Local {
video_bindata_id,
thumbnail_bindata_id,
}
}
1 => {
// ์น ๋์์ ์์ฑ (ํ 126) / Web video attributes (Table 126)
// ์น ํ๊ทธ๋ ๊ฐ๋ณ ๊ธธ์ด์ด๋ฏ๋ก, ๋๋จธ์ง ๋ฐ์ดํฐ์์ ์ธ๋ค์ผ BinData ID(2๋ฐ์ดํธ)๋ฅผ ์ ์ธํ ๋ถ๋ถ์ด ์น ํ๊ทธ
// Web tag is variable length, so remaining data minus thumbnail BinData ID (2 bytes) is web tag
if data.len() < offset + 2 {
return Err(HwpError::insufficient_data(
"VideoData web video attributes",
2,
data.len() - offset,
));
}
// ์น ํ๊ทธ ๊ธธ์ด ๊ณ์ฐ: ์ ์ฒด ๊ธธ์ด - offset - ์ธ๋ค์ผ BinData ID(2๋ฐ์ดํธ)
// Calculate web tag length: total length - offset - thumbnail BinData ID (2 bytes)
let web_tag_length = data.len().saturating_sub(offset + 2);
if web_tag_length == 0 {
return Err(HwpError::UnexpectedValue {
field: "VideoData web tag length".to_string(),
expected: "positive number".to_string(),
found: "0".to_string(),
});
}
let web_tag_bytes = &data[offset..offset + web_tag_length];
let web_tag = decode_utf16le(web_tag_bytes)
.map_err(|e| HwpError::EncodingError {
reason: format!("Failed to decode web tag: {}", e),
})?;
offset += web_tag_length;
let thumbnail_bindata_id = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
VideoAttributes::Web {
web_tag,
thumbnail_bindata_id,
}
}
_ => {
return Err(HwpError::UnexpectedValue {
field: "VideoData video_type".to_string(),
expected: "0 or 1".to_string(),
found: video_type.to_string(),
});
}
};
Ok(VideoData {
video_type,
video_attributes,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/mod.rs | crates/hwp-core/src/document/bodytext/mod.rs | mod char_shape;
/// BodyText parsing module
///
/// This module handles parsing of HWP BodyText storage.
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 2 - ๋ณธ๋ฌธ (BodyText ์คํ ๋ฆฌ์ง)
pub mod constants;
pub use constants::HwpTag;
pub mod control_char;
pub use control_char::{ControlChar, ControlCharPosition};
pub mod chart_data;
pub mod ctrl_data;
pub mod ctrl_header;
pub mod eqedit;
pub mod footnote_shape;
pub mod form_object;
pub mod line_seg;
pub mod list_header;
pub mod memo_list;
pub mod memo_shape;
pub mod page_border_fill;
pub mod page_def;
pub mod para_header;
pub mod range_tag;
pub mod record_tree;
pub mod shape_component;
pub mod table;
pub mod video_data;
pub use char_shape::{CharShapeInfo, ParaCharShape};
pub use chart_data::ChartData;
pub use ctrl_data::CtrlData;
pub use ctrl_header::{CtrlHeader, CtrlHeaderData, CtrlId, Margin, PageNumberPosition};
pub use eqedit::EqEdit;
pub use footnote_shape::{FootnoteShape, NumberShape};
pub use form_object::FormObject;
pub use line_seg::{LineSegmentInfo, ParaLineSeg};
pub use list_header::ListHeader;
pub use memo_list::MemoList;
pub use memo_shape::MemoShape;
pub use page_border_fill::PageBorderFill;
pub use page_def::{PageDef, PaperDirection};
pub use para_header::{ColumnDivideType, ControlMask, ParaHeader};
pub use range_tag::{ParaRangeTag, RangeTagInfo};
pub use shape_component::ShapeComponent;
pub use shape_component::ShapeComponentArc;
pub use shape_component::ShapeComponentContainer;
pub use shape_component::ShapeComponentCurve;
pub use shape_component::ShapeComponentEllipse;
pub use shape_component::ShapeComponentLine;
pub use shape_component::ShapeComponentOle;
pub use shape_component::ShapeComponentPicture;
pub use shape_component::ShapeComponentPolygon;
pub use shape_component::ShapeComponentRectangle;
pub use shape_component::ShapeComponentTextArt;
pub use shape_component::ShapeComponentUnknown;
pub use table::{Table, TableCell};
pub use video_data::VideoData;
use crate::cfb::CfbParser;
use crate::decompress::decompress_deflate;
use crate::document::bodytext::ctrl_header::Caption;
use crate::document::fileheader::FileHeader;
use crate::error::HwpError;
use crate::types::{decode_utf16le, RecordHeader, WORD};
use cfb::CompoundFile;
use record_tree::RecordTreeNode;
use serde::{Deserialize, Serialize};
use std::io::Cursor;
/// Body text structure
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BodyText {
/// Sections (Section0, Section1, etc.)
pub sections: Vec<Section>,
}
/// Section structure
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Section {
/// Section index
pub index: WORD,
/// Paragraphs in this section
pub paragraphs: Vec<Paragraph>,
}
/// Paragraph structure
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Paragraph {
/// Paragraph header (level 0 record)
pub para_header: ParaHeader,
/// Paragraph records (level 1 records)
pub records: Vec<ParagraphRecord>,
}
/// Paragraph record (level 1 records)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ParagraphRecord {
/// ๋ฌธ๋จ์ ํ
์คํธ / Paragraph text
ParaText {
/// ํ
์คํธ ๋ด์ฉ (UTF-16LE) / Text content (UTF-16LE)
text: String,
/// ํ
์คํธ/์ปจํธ๋กค ํ ํฐ ์ํ์ค (ํ/๊ฐ์ฒด ๋ฑ ์์น๋ฅผ ๋ณด์กดํ๊ธฐ ์ํ ๊ตฌ์กฐ) / Text/control token sequence
#[serde(skip_serializing_if = "Vec::is_empty", default)]
runs: Vec<ParaTextRun>,
/// ์ ์ด ๋ฌธ์ ์์น ์ ๋ณด / Control character positions
/// ์ ์ด ๋ฌธ์๊ฐ ์์ด๋ ๋น ๋ฐฐ์ด๋ก ํ์๋์ด JSON์ ํฌํจ๋ฉ๋๋ค / Empty array is included in JSON even if no control characters
#[serde(default)]
control_char_positions: Vec<crate::document::bodytext::control_char::ControlCharPosition>,
/// INLINE ์ ์ด ๋ฌธ์ ํ๋ผ๋ฏธํฐ ์ ๋ณด (๋ฌธ์ ์ธ๋ฑ์ค, ํ๋ผ๋ฏธํฐ) / INLINE control character parameter information (char index, parameter)
/// INLINE ํ์
์ ์ด ๋ฌธ์(FIELD_END, TITLE_MARK, TAB ๋ฑ)์ ํ๋ผ๋ฏธํฐ๋ฅผ ์ ์ฅํฉ๋๋ค.
/// Stores parameters for INLINE type control characters (FIELD_END, TITLE_MARK, TAB, etc.).
/// ์คํ ๋ฌธ์์ ํ๋ผ๋ฏธํฐ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ง ์์์ผ๋ฏ๋ก ๋ฐ์ดํธ ๋ฐฐ์ด๋ก ์ ์ฅ๋ฉ๋๋ค.
/// Parameter structure is not specified in spec document, so stored as byte array.
#[serde(skip_serializing_if = "Vec::is_empty", default)]
inline_control_params: Vec<(
usize,
crate::document::bodytext::control_char::InlineControlParam,
)>,
},
/// ๋ฌธ๋จ์ ๊ธ์ ๋ชจ์ / Paragraph character shape
ParaCharShape {
/// ๊ธ์ ๋ชจ์ ์ ๋ณด ๋ฆฌ์คํธ / Character shape information list
shapes: Vec<CharShapeInfo>,
},
/// ๋ฌธ๋จ์ ๋ ์ด์์ / Paragraph line segment
ParaLineSeg {
/// ์ค ์ธ๊ทธ๋จผํธ ์ ๋ณด ๋ฆฌ์คํธ / Line segment information list
segments: Vec<LineSegmentInfo>,
},
/// ๋ฌธ๋จ์ ์์ญ ํ๊ทธ / Paragraph range tag
ParaRangeTag {
/// ์์ญ ํ๊ทธ ์ ๋ณด ๋ฆฌ์คํธ / Range tag information list
tags: Vec<RangeTagInfo>,
},
/// ์ปจํธ๋กค ํค๋ / Control header
CtrlHeader {
/// ์ปจํธ๋กค ํค๋ ์ ๋ณด / Control header information
#[serde(flatten)]
header: CtrlHeader,
/// ์ปจํธ๋กค ํค๋์ ์์ ๋ ์ฝ๋ (๋ ๋ฒจ 2) / Child records of control header (level 2)
/// ๊ฐ์ฃผ/๋ฏธ์ฃผ, ๋จธ๋ฆฌ๋ง/๊ผฌ๋ฆฌ๋ง ๋ฑ์ ์ปจํธ๋กค ํค๋ ๋ด๋ถ์ PARA_HEADER๊ฐ ์ง์ ์ฌ ์ ์์
/// PARA_HEADER๋ Paragraph๋ก ๋ณํ๋์ด paragraphs์ ์ ์ฅ๋จ
/// PARA_HEADER can appear directly inside control headers like footnotes/endnotes, headers/footers, etc.
/// PARA_HEADER is converted to Paragraph and stored in paragraphs
#[serde(skip_serializing_if = "Vec::is_empty", default)]
children: Vec<ParagraphRecord>,
/// ์ปจํธ๋กค ํค๋ ๋ด๋ถ์ ๋ฌธ๋จ๋ค (๋ ๋ฒจ 2 ์ด์์ PARA_HEADER) / Paragraphs inside control header (PARA_HEADER at level 2 or higher)
/// ๊ฐ์ฃผ/๋ฏธ์ฃผ, ๋จธ๋ฆฌ๋ง/๊ผฌ๋ฆฌ๋ง ๋ฑ์ ์ปจํธ๋กค ํค๋ ๋ด๋ถ์ ์ง์ ๋ํ๋๋ ๋ฌธ๋จ๋ค
/// Paragraphs that appear directly inside control headers like footnotes/endnotes, headers/footers, etc.
#[serde(skip_serializing_if = "Vec::is_empty", default)]
paragraphs: Vec<Paragraph>,
},
/// ๋ฌธ๋จ ๋ฆฌ์คํธ ํค๋ / Paragraph list header
ListHeader {
/// ๋ฌธ๋จ ๋ฆฌ์คํธ ํค๋ ์ ๋ณด / Paragraph list header information
header: ListHeader,
/// ๋ฆฌ์คํธ ํค๋์ ์์ ๋ฌธ๋จ๋ค (๋ ๋ฒจ 3, ์: ํ
์ด๋ธ ์
๋ด๋ถ ๋ฌธ๋จ) / Child paragraphs of list header (level 3, e.g., paragraphs inside table cell)
#[serde(skip_serializing_if = "Vec::is_empty", default)]
paragraphs: Vec<Paragraph>,
},
/// ํ ๊ฐ์ฒด / Table object
Table {
/// ํ ๊ฐ์ฒด ์ ๋ณด / Table object information
table: Table,
},
/// ์ฉ์ง ์ค์ / Page definition
PageDef {
/// ์ฉ์ง ์ค์ ์ ๋ณด / Page definition information
page_def: PageDef,
},
/// ๊ฐ์ฃผ/๋ฏธ์ฃผ ๋ชจ์ / Footnote/endnote shape
FootnoteShape {
/// ๊ฐ์ฃผ/๋ฏธ์ฃผ ๋ชจ์ ์ ๋ณด / Footnote/endnote shape information
footnote_shape: FootnoteShape,
},
/// ์ชฝ ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ / Page border/fill
PageBorderFill {
/// ์ชฝ ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ ์ ๋ณด / Page border/fill information
page_border_fill: PageBorderFill,
},
/// ๊ฐ์ฒด ์์ / Shape component
ShapeComponent {
/// ๊ฐ์ฒด ์์ ์ ๋ณด / Shape component information
shape_component: ShapeComponent,
/// ๊ฐ์ฒด ์์์ ์์ ๋ ์ฝ๋ (๋ ๋ฒจ 3, ์: SHAPE_COMPONENT_PICTURE) / Child records of shape component (level 3, e.g., SHAPE_COMPONENT_PICTURE)
#[serde(skip_serializing_if = "Vec::is_empty", default)]
children: Vec<ParagraphRecord>,
},
/// ์ง์ ๊ฐ์ฒด / Line shape component
ShapeComponentLine {
/// ์ง์ ๊ฐ์ฒด ์ ๋ณด / Line shape component information
shape_component_line: ShapeComponentLine,
},
/// ์ฌ๊ฐํ ๊ฐ์ฒด / Rectangle shape component
ShapeComponentRectangle {
/// ์ฌ๊ฐํ ๊ฐ์ฒด ์ ๋ณด / Rectangle shape component information
shape_component_rectangle: ShapeComponentRectangle,
},
/// ํ์ ๊ฐ์ฒด / Ellipse shape component
ShapeComponentEllipse {
/// ํ์ ๊ฐ์ฒด ์ ๋ณด / Ellipse shape component information
shape_component_ellipse: ShapeComponentEllipse,
},
/// ํธ ๊ฐ์ฒด / Arc shape component
ShapeComponentArc {
/// ํธ ๊ฐ์ฒด ์ ๋ณด / Arc shape component information
shape_component_arc: ShapeComponentArc,
},
/// ๋ค๊ฐํ ๊ฐ์ฒด / Polygon shape component
ShapeComponentPolygon {
/// ๋ค๊ฐํ ๊ฐ์ฒด ์ ๋ณด / Polygon shape component information
shape_component_polygon: ShapeComponentPolygon,
},
/// ๊ณก์ ๊ฐ์ฒด / Curve shape component
ShapeComponentCurve {
/// ๊ณก์ ๊ฐ์ฒด ์ ๋ณด / Curve shape component information
shape_component_curve: ShapeComponentCurve,
},
/// OLE ๊ฐ์ฒด / OLE shape component
ShapeComponentOle {
/// OLE ๊ฐ์ฒด ์ ๋ณด / OLE shape component information
shape_component_ole: ShapeComponentOle,
},
/// ๊ทธ๋ฆผ ๊ฐ์ฒด / Picture shape component
ShapeComponentPicture {
/// ๊ทธ๋ฆผ ๊ฐ์ฒด ์ ๋ณด / Picture shape component information
shape_component_picture: ShapeComponentPicture,
},
/// ๋ฌถ์ ๊ฐ์ฒด / Container shape component
ShapeComponentContainer {
/// ๋ฌถ์ ๊ฐ์ฒด ์ ๋ณด / Container shape component information
shape_component_container: ShapeComponentContainer,
},
/// ์ปจํธ๋กค ์์์ ๋ฐ์ดํฐ / Control arbitrary data
CtrlData {
/// ์ปจํธ๋กค ์์์ ๋ฐ์ดํฐ ์ ๋ณด / Control arbitrary data information
ctrl_data: CtrlData,
},
/// ์์ ๊ฐ์ฒด / Equation editor object
EqEdit {
/// ์์ ๊ฐ์ฒด ์ ๋ณด / Equation editor object information
eqedit: EqEdit,
},
/// ๊ธ๋งต์ ๊ฐ์ฒด / Text art shape component
ShapeComponentTextArt {
/// ๊ธ๋งต์ ๊ฐ์ฒด ์ ๋ณด / Text art shape component information
shape_component_textart: ShapeComponentTextArt,
},
/// ์์ ๊ฐ์ฒด / Form object
FormObject {
/// ์์ ๊ฐ์ฒด ์ ๋ณด / Form object information
form_object: FormObject,
},
/// ๋ฉ๋ชจ ๋ชจ์ / Memo shape
MemoShape {
/// ๋ฉ๋ชจ ๋ชจ์ ์ ๋ณด / Memo shape information
memo_shape: MemoShape,
},
/// ๋ฉ๋ชจ ๋ฆฌ์คํธ ํค๋ / Memo list header
MemoList {
/// ๋ฉ๋ชจ ๋ฆฌ์คํธ ํค๋ ์ ๋ณด / Memo list header information
memo_list: MemoList,
},
/// ์ฐจํธ ๋ฐ์ดํฐ / Chart data
ChartData {
/// ์ฐจํธ ๋ฐ์ดํฐ ์ ๋ณด / Chart data information
chart_data: ChartData,
},
/// ๋น๋์ค ๋ฐ์ดํฐ / Video data
VideoData {
/// ๋น๋์ค ๋ฐ์ดํฐ ์ ๋ณด / Video data information
video_data: VideoData,
},
/// Unknown ๊ฐ์ฒด / Unknown shape component
ShapeComponentUnknown {
/// Unknown ๊ฐ์ฒด ์ ๋ณด / Unknown shape component information
shape_component_unknown: ShapeComponentUnknown,
},
/// ๊ธฐํ ๋ ์ฝ๋ / Other records
Other {
/// Tag ID
tag_id: WORD,
/// Raw data
data: Vec<u8>,
},
}
/// ParaText์ ํ
์คํธ/์ปจํธ๋กค ํ ํฐ / ParaText token (text or control)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ParaTextRun {
/// ์ผ๋ฐ ํ
์คํธ ์กฐ๊ฐ / Plain text chunk
Text { text: String },
/// ์ปจํธ๋กค ํ ํฐ(ํ/๊ฐ์ฒด ๋ฑ) / Control token (table/shape object etc.)
Control {
/// ์๋ณธ WCHAR ์ธ๋ฑ์ค ์์น / Original WCHAR index position
position: usize,
/// ์ ์ด ๋ฌธ์ ์ฝ๋ (0-31) / Control character code (0-31)
code: u8,
/// ์ ์ด ๋ฌธ์ ์ด๋ฆ / Control character name
name: String,
/// ์๋ณธ์์ ์ฐจ์งํ๋ WCHAR ๊ธธ์ด / Size in WCHAR units in original stream
size_wchars: usize,
/// ํ์ ํ
์คํธ(ํ์๊ฐ) / Display text (derived value)
///
/// - **Source of truth๊ฐ ์๋**: ์๋ณธ ๋ณต์/Writer์์๋ `runs`์ ์ปจํธ๋กค ์ ๋ณด์ ๋ฌธ์ ์ค์ ์ผ๋ก ์ฌ๊ณ์ฐํด์ผ ํฉ๋๋ค.
/// - ๋ทฐ์ด/ํ๋ฆฌ๋ทฐ ์ฉ๋๋ก๋ง ์ฌ์ฉํ๋ฉฐ, ๋ถ์ผ์น ์ ๋ฌด์๋ ์ ์์ต๋๋ค.
#[serde(skip_serializing_if = "Option::is_none")]
display_text: Option<String>,
},
}
impl Section {
/// Section ๋ฐ์ดํฐ๋ฅผ ํ์ฑํ์ฌ Paragraph ๋ฆฌ์คํธ๋ก ๋ณํํฉ๋๋ค. / Parse section data into paragraph list.
///
/// ํธ๋ฆฌ ๊ตฌ์กฐ๋ฅผ ๋จผ์ ํ์ฑํ ํ ์ฌ๊ท์ ์ผ๋ก ๋ฐฉ๋ฌธํ์ฌ ๊ตฌ์กฐํ๋ ๋ฐ์ดํฐ๋ก ๋ณํํฉ๋๋ค.
/// First parses the tree structure, then recursively visits it to convert to structured data.
///
/// # Arguments
/// * `data` - Section์ ์์ ๋ฐ์ดํธ ๋ฐ์ดํฐ / Raw byte data of section
/// * `version` - ํ์ผ ๋ฒ์ / File version
///
/// # Returns
/// ํ์ฑ๋ Paragraph ๋ฆฌ์คํธ / Parsed paragraph list
pub fn parse_data(data: &[u8], version: u32) -> Result<Vec<Paragraph>, HwpError> {
// ๋จผ์ ๋ ์ฝ๋๋ฅผ ํธ๋ฆฌ ๊ตฌ์กฐ๋ก ํ์ฑ / First parse records into tree structure
let tree = RecordTreeNode::parse_tree(data).map_err(|e| HwpError::from(e))?;
// ํธ๋ฆฌ๋ฅผ ์ฌ๊ท์ ์ผ๋ก ๋ฐฉ๋ฌธํ์ฌ Paragraph ๋ฆฌ์คํธ๋ก ๋ณํ / Recursively visit tree to convert to Paragraph list
let mut paragraphs = Vec::new();
for child in tree.children() {
if child.tag_id() == HwpTag::PARA_HEADER {
paragraphs.push(
Self::parse_paragraph_from_tree(child, version, data)
.map_err(|e| HwpError::from(e))?,
);
}
}
Ok(paragraphs)
}
/// ํธ๋ฆฌ ๋
ธ๋์์ Paragraph๋ฅผ ํ์ฑํฉ๋๋ค. / Parse Paragraph from tree node.
///
/// ๋ฌธ๋จ ํค๋ ๋
ธ๋์ ๊ทธ ์์๋ค์ ์ฌ๊ท์ ์ผ๋ก ์ฒ๋ฆฌํฉ๋๋ค.
/// Recursively processes paragraph header node and its children.
fn parse_paragraph_from_tree(
node: &RecordTreeNode,
version: u32,
original_data: &[u8],
) -> Result<Paragraph, HwpError> {
Self::parse_paragraph_from_tree_internal(node, version, original_data, false)
}
/// ๋ฌธ๋จ ํค๋ ๋
ธ๋์ ๊ทธ ์์๋ค์ ์ฌ๊ท์ ์ผ๋ก ์ฒ๋ฆฌํฉ๋๋ค (๋ด๋ถ ํจ์).
/// Recursively processes paragraph header node and its children (internal function).
/// `is_inside_control_header`: ์ปจํธ๋กค ํค๋ ๋ด๋ถ์ Paragraph์ธ์ง ์ฌ๋ถ
/// `is_inside_control_header`: Whether this paragraph is inside a control header
fn parse_paragraph_from_tree_internal(
node: &RecordTreeNode,
version: u32,
original_data: &[u8],
is_inside_control_header: bool,
) -> Result<Paragraph, HwpError> {
if node.tag_id() != HwpTag::PARA_HEADER {
return Err(HwpError::UnexpectedValue {
field: "Paragraph tag".to_string(),
expected: format!("{}", HwpTag::PARA_HEADER),
found: format!("{}", node.tag_id()),
});
}
let para_header = ParaHeader::parse(node.data(), version).map_err(|e| HwpError::from(e))?;
let mut records = Vec::new();
// ์์๋ค์ ์ฒ๋ฆฌ / Process children
for child in node.children() {
records.push(
Self::parse_record_from_tree(child, version, original_data)
.map_err(|e| HwpError::from(e))?,
);
}
// ์ปจํธ๋กค ํค๋ ๋ด๋ถ์ ๋จธ๋ฆฌ๋ง/๊ผฌ๋ฆฌ๋ง/๊ฐ์ฃผ/๋ฏธ์ฃผ ๋ฌธ๋จ์ธ ๊ฒฝ์ฐ์๋ง ParaText ๋ ์ฝ๋ ์ ๊ฑฐ (์ค๋ณต ๋ฐฉ์ง, hwplib ๋ฐฉ์)
// Remove ParaText records only from header/footer/footnote/endnote paragraphs inside control headers (avoid duplication, hwplib approach)
// hwplib: ์ปจํธ๋กค ํค๋ ๋ด๋ถ์ Paragraph์ ParaText์๋ ExtendChar๋ง ํฌํจ๋๊ณ , ์ค์ ํ
์คํธ๋ ControlHeader ๋ด๋ถ์ ParagraphList์๋ง ์์
// hwplib: ParaText in paragraphs inside control headers only contains ExtendChar, actual text is only in ControlHeader's ParagraphList
// ๋ณธ๋ฌธ Paragraph์ ๊ฒฝ์ฐ ParaText์ ์ฐธ์กฐ ํ
์คํธ("๊ฐ์ฃผ์ฐธ์กฐ" ๋ฑ)๊ฐ ํฌํจ๋๋ฏ๋ก ์ ๊ฑฐํ์ง ์์
// For body paragraphs, ParaText contains reference text ("๊ฐ์ฃผ์ฐธ์กฐ" etc.), so don't remove it
if is_inside_control_header {
let is_control_paragraph = records.iter().any(|record| {
if let ParagraphRecord::CtrlHeader { header, .. } = record {
use crate::document::bodytext::CtrlId;
header.ctrl_id.as_str() == CtrlId::HEADER
|| header.ctrl_id.as_str() == CtrlId::FOOTER
|| header.ctrl_id.as_str() == CtrlId::FOOTNOTE
|| header.ctrl_id.as_str() == CtrlId::ENDNOTE
} else {
false
}
});
if is_control_paragraph {
// ParaText ๋ ์ฝ๋๋ง ํํฐ๋ง (๋ค๋ฅธ ๋ ์ฝ๋๋ ์ ์ง)
// Filter out only ParaText records (keep other records)
let before_count = records.len();
records.retain(|record| !matches!(record, ParagraphRecord::ParaText { .. }));
let after_count = records.len();
if before_count != after_count {
#[cfg(debug_assertions)]
eprintln!("[DEBUG] Removed {} ParaText records from control paragraph (is_inside_control_header={})",
before_count - after_count, is_inside_control_header);
}
}
} else {
// ๋ณธ๋ฌธ Paragraph์ ๊ฒฝ์ฐ ParaText ํ์ธ (๋๋ฒ๊ทธ)
// Check ParaText in body paragraph (debug)
let para_text_count = records
.iter()
.filter(|record| matches!(record, ParagraphRecord::ParaText { .. }))
.count();
if para_text_count > 0 {
for record in &records {
if let ParagraphRecord::ParaText { text, .. } = record {
#[cfg(debug_assertions)]
eprintln!("[DEBUG] Body paragraph ParaText: {}", text);
}
}
}
}
Ok(Paragraph {
para_header,
records,
})
}
/// ํธ๋ฆฌ ๋
ธ๋์์ ParagraphRecord๋ฅผ ํ์ฑํฉ๋๋ค. / Parse ParagraphRecord from tree node.
///
/// ๋ชจ๋ ๋ ๋ฒจ์ ๋ ์ฝ๋๋ฅผ ์ฌ๊ท์ ์ผ๋ก ์ฒ๋ฆฌํฉ๋๋ค.
/// Recursively processes records at all levels.
fn parse_record_from_tree(
node: &RecordTreeNode,
version: u32,
original_data: &[u8],
) -> Result<ParagraphRecord, HwpError> {
match node.tag_id() {
HwpTag::PARA_TEXT => {
let data = node.data();
// pyhwp์ฒ๋ผ ์ ์ด ๋ฌธ์๋ฅผ ์ฐพ๊ณ ํ
์คํธ๋ง ์ถ์ถ / Find control characters and extract only text like pyhwp
let mut control_char_positions = Vec::new();
let mut inline_control_params = Vec::new();
let mut cleaned_text = String::new();
let mut runs: Vec<ParaTextRun> = Vec::new();
let mut idx = 0;
while idx < data.len() {
// ์ ์ด ๋ฌธ์ ์ฐพ๊ธฐ (UTF-16LE ๋ฐ์ดํธ ๋ฐฐ์ด์์) / Find control character (in UTF-16LE byte array)
let mut found_control = false;
let mut control_code = 0u8;
let mut control_size = 0usize;
// ํ์ฌ ์์น์์ ์ ์ด ๋ฌธ์ ํ์ธ (0-31 ๋ฒ์) / Check for control character at current position (range 0-31)
if idx + 1 < data.len() {
let code = data[idx] as u32;
// ์ ์ด ๋ฌธ์๋ UTF-16LE์์ ํ์ ๋ฐ์ดํธ๊ฐ 0-31์ด๊ณ ์์ ๋ฐ์ดํธ๊ฐ 0์ธ ๊ฒฝ์ฐ / Control character is when lower byte is 0-31 and upper byte is 0 in UTF-16LE
if code <= 31 && data[idx + 1] == 0 {
control_code = code as u8;
control_size = ControlChar::get_size_by_code(control_code) * 2; // WCHAR๋ฅผ ๋ฐ์ดํธ๋ก ๋ณํ / Convert WCHAR to bytes
found_control = true;
}
}
if found_control {
// ์ ์ด ๋ฌธ์ ์์น ์ ์ฅ (๋ฌธ์ ์ธ๋ฑ์ค ๊ธฐ์ค) / Store control character position (based on character index)
let char_idx = idx / 2; // UTF-16LE์์ ๋ฌธ์ ์ธ๋ฑ์ค๋ ๋ฐ์ดํธ ์ธ๋ฑ์ค / 2 / Character index in UTF-16LE is byte index / 2
let control_name = ControlChar::to_name(control_code);
control_char_positions.push(
crate::document::bodytext::control_char::ControlCharPosition {
position: char_idx,
code: control_code,
name: control_name.clone(),
},
);
runs.push(ParaTextRun::Control {
position: char_idx,
code: control_code,
name: control_name,
size_wchars: ControlChar::get_size_by_code(control_code),
display_text: None,
});
// INLINE ํ์
์ ์ด ๋ฌธ์์ธ ๊ฒฝ์ฐ ํ๋ผ๋ฏธํฐ ํ์ฑ / Parse parameters for INLINE type control characters
if ControlChar::get_size_by_code(control_code) == 8
&& matches!(
control_code,
ControlChar::FIELD_END
| ControlChar::RESERVED_5_7_START..=ControlChar::RESERVED_5_7_END
| ControlChar::TITLE_MARK
| ControlChar::TAB
| ControlChar::RESERVED_19_20_START..=ControlChar::RESERVED_19_20_END
)
{
// ์ ์ด ๋ฌธ์ ์ฝ๋(2 bytes) ์ดํ์ ํ๋ผ๋ฏธํฐ(12 bytes) ํ์ฑ / Parse parameter (12 bytes) after control character code (2 bytes)
if idx + 2 + 12 <= data.len() {
let param_data = &data[idx + 2..idx + 2 + 12];
if let Ok(param) =
crate::document::bodytext::control_char::InlineControlParam::parse(control_code, param_data)
{
inline_control_params.push((char_idx, param));
}
}
}
// ํ
์คํธ๋ก ํํ ๊ฐ๋ฅํ ์ ์ด ๋ฌธ์๋ ํ
์คํธ์ ๋ณํ๋ ํํ๋ก ์ถ๊ฐ / Add convertible control characters as converted text
// ๋จ, PARA_BREAK์ LINE_BREAK๋ control_char_positions์๋ง ์ ์ฅํ๊ณ ํ
์คํธ์๋ ํฌํจํ์ง ์์
// However, PARA_BREAK and LINE_BREAK are only stored in control_char_positions, not added to text
if ControlChar::is_convertible(control_code) {
// PARA_BREAK์ LINE_BREAK๋ ํ
์คํธ์ ์ถ๊ฐํ์ง ์์ (control_char_positions์๋ง ์ ์ฅ)
// Don't add PARA_BREAK and LINE_BREAK to text (only store in control_char_positions)
if control_code != ControlChar::PARA_BREAK
&& control_code != ControlChar::LINE_BREAK
{
if let Some(text_repr) = ControlChar::to_text(control_code) {
cleaned_text.push_str(text_repr);
runs.push(ParaTextRun::Text {
text: text_repr.to_string(),
});
}
}
}
// ์ ๊ฑฐํด์ผ ํ ์ ์ด ๋ฌธ์๋ ํ
์คํธ์ ์ถ๊ฐํ์ง ์์ / Don't add removable control characters to text
idx += control_size; // ์ ์ด ๋ฌธ์์ ํ๋ผ๋ฏธํฐ ๊ฑด๋๋ฐ๊ธฐ / Skip control character and parameters
} else {
// ํ
์คํธ ๋ถ๋ถ ๋์ฝ๋ฉ / Decode text portion
// ๋ค์ ์ ์ด ๋ฌธ์๊น์ง ๋๋ ๋๊น์ง / Until next control character or end
let mut text_end = idx;
while text_end < data.len() {
if text_end + 1 < data.len() {
let code = data[text_end] as u32;
if code <= 31 && data[text_end + 1] == 0 {
break; // ์ ์ด ๋ฌธ์ ๋ฐ๊ฒฌ / Control character found
}
}
text_end += 2; // UTF-16LE๋ 2๋ฐ์ดํธ ๋จ์ / UTF-16LE is 2-byte units
}
if text_end > idx {
// ํ
์คํธ ๋ถ๋ถ ๋์ฝ๋ฉ / Decode text portion
let text_bytes = &data[idx..text_end];
if let Ok(text) = decode_utf16le(text_bytes) {
cleaned_text.push_str(&text);
if !text.is_empty() {
runs.push(ParaTextRun::Text { text });
}
}
idx = text_end;
} else {
// ๋ ์ด์ ์ฒ๋ฆฌํ ๋ฐ์ดํฐ ์์ / No more data to process
break;
}
}
}
Ok(ParagraphRecord::ParaText {
text: cleaned_text,
runs,
control_char_positions,
inline_control_params,
})
}
HwpTag::PARA_CHAR_SHAPE => {
let para_char_shape =
ParaCharShape::parse(node.data()).map_err(|e| HwpError::from(e))?;
Ok(ParagraphRecord::ParaCharShape {
shapes: para_char_shape.shapes,
})
}
HwpTag::PARA_LINE_SEG => {
let para_line_seg =
ParaLineSeg::parse(node.data()).map_err(|e| HwpError::from(e))?;
Ok(ParagraphRecord::ParaLineSeg {
segments: para_line_seg.segments,
})
}
HwpTag::PARA_RANGE_TAG => {
let para_range_tag =
ParaRangeTag::parse(node.data()).map_err(|e| HwpError::from(e))?;
Ok(ParagraphRecord::ParaRangeTag {
tags: para_range_tag.tags,
})
}
HwpTag::CTRL_HEADER => {
let ctrl_header = CtrlHeader::parse(node.data()).map_err(|e| HwpError::from(e))?;
// ๋๋ฒ๊ทธ: CTRL_HEADER ํ์ฑ ์์ / Debug: Start parsing CTRL_HEADER
use crate::document::bodytext::ctrl_header::CtrlId;
#[cfg(debug_assertions)]
eprintln!(
"[DEBUG] Parsing CTRL_HEADER: ctrl_id={:?}, ctrl_id_value={}",
ctrl_header.ctrl_id, ctrl_header.ctrl_id_value
);
// ์์ ๋ ์ฝ๋๋ค์ ์ฌ๊ท์ ์ผ๋ก ์ฒ๋ฆฌ / Recursively process child records
// hwp.js: visitControlHeader์์ record.children๋ฅผ ๋ชจ๋ ์ฒ๋ฆฌ
// hwp.js: visitControlHeader processes all record.children
// hwp.js: visitListHeader์์ record.parentTagID === HWPTAG_CTRL_HEADER์ด๊ณ isTable(control)์ผ ๋ ํ
์ด๋ธ ์
๋ก ์ฒ๋ฆฌ
// hwp.js: visitListHeader processes as table cell when record.parentTagID === HWPTAG_CTRL_HEADER and isTable(control)
let mut children = Vec::new();
let mut table_opt: Option<crate::document::bodytext::Table> = None;
let mut list_headers_for_table: Vec<(
u16,
u16,
Vec<super::Paragraph>,
Option<crate::document::bodytext::table::CellAttributes>,
)> = Vec::new(); // (row_address, col_address, paragraphs, cell_attributes)
// CTRL_HEADER๊ฐ ํ
์ด๋ธ์ธ์ง ํ์ธ / Check if CTRL_HEADER is a table
// hwp.js: CommonCtrlID.Table = makeCtrlID('t', 'b', 'l', ' ') = 0x206C6274 (little-endian: 0x74626C20)
// hwp.js: CommonCtrlID.Table = makeCtrlID('t', 'b', 'l', ' ') = 0x206C6274 (little-endian: 0x74626C20)
// pyhwp: CHID.TBL = 'tbl ' (๋ฐ์ดํธ ๋ฆฌ๋ฒ์ค ํ) / pyhwp: CHID.TBL = 'tbl ' (after byte reverse)
let is_table = ctrl_header.ctrl_id == CtrlId::TABLE
|| ctrl_header.ctrl_id_value == 0x74626C20u32;
let mut paragraphs = Vec::new();
// libhwp ๋ฐฉ์: TABLE ์์น๋ฅผ ๋จผ์ ์ฐพ์์ TABLE ์ดํ์ LIST_HEADER๋ children์ ์ถ๊ฐํ์ง ์์
// libhwp approach: Find TABLE position first, then don't add LIST_HEADERs after TABLE to children
let children_slice: Vec<_> = node.children().iter().collect();
// TABLE ์ด์ ์ LIST_HEADER๋ฅผ ์ฐพ์์ ์บก์
์ผ๋ก ํ์ฑ / Find LIST_HEADER before TABLE and parse as caption
// hwplib๊ณผ hwp-rs ๋ฐฉ์: ๋ณ๋ ๋ ์ฝ๋๋ก ์บก์
์ฒ๋ฆฌ / hwplib and hwp-rs approach: process caption as separate record
let mut caption_opt: Option<Caption> = None;
// TABLE ์์น ์ฐพ๊ธฐ / Find TABLE position
let table_index = if is_table {
children_slice
.iter()
.position(|child| child.tag_id() == HwpTag::TABLE)
} else {
None
};
if is_table {
if let Some(table_idx) = table_index {
// TABLE ์ด์ ์ LIST_HEADER ์ฐพ๊ธฐ / Find LIST_HEADER before TABLE
for child in children_slice.iter().take(table_idx) {
if child.tag_id() == HwpTag::LIST_HEADER {
// ์บก์
์ผ๋ก ํ์ฑ / Parse as caption
use crate::document::bodytext::ctrl_header::parse_caption_from_list_header;
caption_opt = parse_caption_from_list_header(child.data())?;
break; // ์ฒซ ๋ฒ์งธ LIST_HEADER๋ง ์บก์
์ผ๋ก ์ฒ๋ฆฌ / Only process first LIST_HEADER as caption
}
}
}
}
// CTRL_HEADER๊ฐ LIST_HEADER๋ฅผ ๊ฐ์ง๊ณ ์๋์ง ๋จผ์ ํ์ธ (๋จธ๋ฆฌ๋ง/๊ผฌ๋ฆฌ๋ง/๊ฐ์ฃผ/๋ฏธ์ฃผ์ ๊ฒฝ์ฐ)
// Check if CTRL_HEADER has LIST_HEADER first (for headers/footers/footnotes/endnotes)
// PARA_HEADER ์ฒ๋ฆฌ ์ ์ ํ์ธํ์ฌ ์ค๋ณต ๋ฐฉ์ง
// Check before processing PARA_HEADER to avoid duplication
let has_list_header = children_slice
.iter()
.any(|child| child.tag_id() == HwpTag::LIST_HEADER && !is_table);
for (idx, child) in children_slice.iter().enumerate() {
if child.tag_id() == HwpTag::TABLE {
// TABLE์ ๋ณ๋๋ก ์ฒ๋ฆฌ / TABLE is processed separately
let table_data =
Table::parse(child.data(), version).map_err(|e| HwpError::from(e))?;
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | true |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/list_header.rs | crates/hwp-core/src/document/bodytext/list_header.rs | /// ListHeader ๊ตฌ์กฐ์ฒด / ListHeader structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 65 - ๋ฌธ๋จ ๋ฆฌ์คํธ ํค๋ / Spec mapping: Table 65 - Paragraph list header
use crate::error::HwpError;
use crate::types::{INT16, UINT32};
use serde::{Deserialize, Serialize};
/// ๋ฌธ๋จ ๋ฆฌ์คํธ ํค๋ / Paragraph list header
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListHeader {
/// ๋ฌธ๋จ ์ / Paragraph count
pub paragraph_count: INT16,
/// ์์ฑ (ํ 65-1 ์ฐธ์กฐ) / Attribute (see Table 65-1)
pub attribute: ListHeaderAttribute,
}
/// ๋ฌธ๋จ ๋ฆฌ์คํธ ํค๋ ์์ฑ (ํ 65-1) / Paragraph list header attribute (Table 65-1)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListHeaderAttribute {
/// ํ
์คํธ ๋ฐฉํฅ / Text direction
pub text_direction: TextDirection,
/// ๋ฌธ๋จ์ ์ค๋ฐ๊ฟ / Paragraph line break
pub line_break: LineBreak,
/// ์ธ๋ก ์ ๋ ฌ / Vertical alignment
pub vertical_align: VerticalAlign,
}
/// ํ
์คํธ ๋ฐฉํฅ / Text direction
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TextDirection {
/// ๊ฐ๋ก / Horizontal
Horizontal,
/// ์ธ๋ก / Vertical
Vertical,
}
/// ๋ฌธ๋จ์ ์ค๋ฐ๊ฟ / Paragraph line break
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LineBreak {
/// ์ผ๋ฐ์ ์ธ ์ค๋ฐ๊ฟ / Normal line break
Normal,
/// ์๊ฐ์ ์กฐ์ข
ํ์ฌ ํ ์ค์ ์ ์ง / Maintain one line by adjusting character spacing
MaintainOneLine,
/// ๋ด์ฉ์ ๋ฐ๋ผ ํญ์ด ๋์ด๋จ / Width increases according to content
ExpandByContent,
}
/// ์ธ๋ก ์ ๋ ฌ / Vertical alignment
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum VerticalAlign {
/// ์์ชฝ / Top
Top,
/// ๊ฐ์ด๋ฐ / Center
Center,
/// ์๋์ชฝ / Bottom
Bottom,
}
impl ListHeader {
/// ListHeader๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ListHeader from byte array.
///
/// # Arguments
/// * `data` - ์ต์ 6๋ฐ์ดํธ์ ๋ฐ์ดํฐ / At least 6 bytes of data
///
/// # Returns
/// ํ์ฑ๋ ListHeader ๊ตฌ์กฐ์ฒด / Parsed ListHeader structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ํ 65์๋ 6๋ฐ์ดํธ๋ก ๋์ด์์ง๋ง ์ค์ ํ์ผ/๊ตฌํ์์๋
// - 6๋ฐ์ดํธ: [paragraph_count:2][attribute:4]
// - 8๋ฐ์ดํธ: [paragraph_count:2][unknown1:2][attribute:4]
// ๋ณํ์ด ์กด์ฌํฉ๋๋ค. pyhwp๋ 8๋ฐ์ดํธ ๊ตฌ์กฐ๋ฅผ ๊ธฐ๋ณธ์ผ๋ก ์ฌ์ฉํฉ๋๋ค.
// ๋ฐ๋ผ์ ์ต์ 6๋ฐ์ดํธ๋ฅผ ํ์ฉํ๋, 8๋ฐ์ดํธ ์ด์์ด๋ฉด 8๋ฐ์ดํธ ๊ตฌ์กฐ๋ฅผ ์ฐ์ ํฉ๋๋ค.
if data.len() < 6 {
return Err(HwpError::insufficient_data("ListHeader", 6, data.len()));
}
// INT16 ๋ฌธ๋จ ์ / INT16 paragraph count
let paragraph_count = INT16::from_le_bytes([data[0], data[1]]);
// UINT32 ์์ฑ (ํ 65-1 ์ฐธ์กฐ) / UINT32 attribute (see Table 65-1)
// 6๋ฐ์ดํธ ๊ตฌ์กฐ: [paragraph_count:2][attribute:4]
// 8๋ฐ์ดํธ ๊ตฌ์กฐ: [paragraph_count:2][unknown1:2][attribute:4]
let attribute_value = if data.len() >= 8 {
UINT32::from_le_bytes([data[4], data[5], data[6], data[7]])
} else {
UINT32::from_le_bytes([data[2], data[3], data[4], data[5]])
};
// ์์ฑ ํ์ฑ (ํ 65-1) / Parse attribute (Table 65-1)
let attribute = parse_list_header_attribute(attribute_value);
Ok(ListHeader {
paragraph_count,
attribute,
})
}
}
/// ๋ฌธ๋จ ๋ฆฌ์คํธ ํค๋ ์์ฑ ํ์ฑ (ํ 65-1) / Parse list header attribute (Table 65-1)
fn parse_list_header_attribute(value: UINT32) -> ListHeaderAttribute {
// bit 0-2: ํ
์คํธ ๋ฐฉํฅ / bit 0-2: text direction
let text_direction = match value & 0x07 {
0 => TextDirection::Horizontal,
1 => TextDirection::Vertical,
_ => TextDirection::Horizontal,
};
// bit 3-4: ๋ฌธ๋จ์ ์ค๋ฐ๊ฟ / bit 3-4: paragraph line break
let line_break = match (value >> 3) & 0x03 {
0 => LineBreak::Normal,
1 => LineBreak::MaintainOneLine,
2 => LineBreak::ExpandByContent,
_ => LineBreak::Normal,
};
// bit 5-6: ์ธ๋ก ์ ๋ ฌ / bit 5-6: vertical alignment
let vertical_align = match (value >> 5) & 0x03 {
// ์คํ(ํ 65-1): 0=top, 1=center, 2=bottom
0 => VerticalAlign::Top,
1 => VerticalAlign::Center,
2 => VerticalAlign::Bottom,
_ => VerticalAlign::Top,
};
ListHeaderAttribute {
text_direction,
line_break,
vertical_align,
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/constants.rs | crates/hwp-core/src/document/bodytext/constants.rs | /// BodyText ๋ ์ฝ๋ ํ๊ทธ ์์ ์ ์ / BodyText record tag constants definition
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 57 - ๋ณธ๋ฌธ์ ๋ฐ์ดํฐ ๋ ์ฝ๋ / Spec mapping: Table 57 - BodyText data records
use crate::document::constants::HWPTAG_BEGIN;
/// BodyText ํ๊ทธ ์์ / BodyText tag constants
pub struct HwpTag;
impl HwpTag {
/// ๋ฌธ๋จ ํค๋ / Paragraph header
pub const PARA_HEADER: u16 = HWPTAG_BEGIN + 50;
/// ๋ฌธ๋จ์ ํ
์คํธ / Paragraph text
pub const PARA_TEXT: u16 = HWPTAG_BEGIN + 51;
/// ๋ฌธ๋จ์ ๊ธ์ ๋ชจ์ / Paragraph character shape
pub const PARA_CHAR_SHAPE: u16 = HWPTAG_BEGIN + 52;
/// ๋ฌธ๋จ์ ๋ ์ด์์ / Paragraph line segment
pub const PARA_LINE_SEG: u16 = HWPTAG_BEGIN + 53;
/// ๋ฌธ๋จ์ ์์ญ ํ๊ทธ / Paragraph range tag
pub const PARA_RANGE_TAG: u16 = HWPTAG_BEGIN + 54;
/// ์ปจํธ๋กค ํค๋ / Control header
pub const CTRL_HEADER: u16 = HWPTAG_BEGIN + 55;
/// ๋ฌธ๋จ ๋ฆฌ์คํธ ํค๋ / Paragraph list header
pub const LIST_HEADER: u16 = HWPTAG_BEGIN + 56;
/// ์ฉ์ง ์ค์ / Page definition
pub const PAGE_DEF: u16 = HWPTAG_BEGIN + 57;
/// ๊ฐ์ฃผ/๋ฏธ์ฃผ ๋ชจ์ / Footnote/endnote shape
pub const FOOTNOTE_SHAPE: u16 = HWPTAG_BEGIN + 58;
/// ์ชฝ ํ
๋๋ฆฌ/๋ฐฐ๊ฒฝ / Page border/fill
pub const PAGE_BORDER_FILL: u16 = HWPTAG_BEGIN + 59;
/// ๊ฐ์ฒด / Shape component
pub const SHAPE_COMPONENT: u16 = HWPTAG_BEGIN + 60;
/// ํ ๊ฐ์ฒด / Table object
pub const TABLE: u16 = HWPTAG_BEGIN + 61;
/// ์ง์ ๊ฐ์ฒด / Line shape component
pub const SHAPE_COMPONENT_LINE: u16 = HWPTAG_BEGIN + 62;
/// ์ฌ๊ฐํ ๊ฐ์ฒด / Rectangle shape component
pub const SHAPE_COMPONENT_RECTANGLE: u16 = HWPTAG_BEGIN + 63;
/// ํ์ ๊ฐ์ฒด / Ellipse shape component
pub const SHAPE_COMPONENT_ELLIPSE: u16 = HWPTAG_BEGIN + 64;
/// ํธ ๊ฐ์ฒด / Arc shape component
pub const SHAPE_COMPONENT_ARC: u16 = HWPTAG_BEGIN + 65;
/// ๋ค๊ฐํ ๊ฐ์ฒด / Polygon shape component
pub const SHAPE_COMPONENT_POLYGON: u16 = HWPTAG_BEGIN + 66;
/// ๊ณก์ ๊ฐ์ฒด / Curve shape component
pub const SHAPE_COMPONENT_CURVE: u16 = HWPTAG_BEGIN + 67;
/// OLE ๊ฐ์ฒด / OLE shape component
pub const SHAPE_COMPONENT_OLE: u16 = HWPTAG_BEGIN + 68;
/// ๊ทธ๋ฆผ ๊ฐ์ฒด / Picture shape component
pub const SHAPE_COMPONENT_PICTURE: u16 = HWPTAG_BEGIN + 69;
/// ์ปจํ
์ด๋ ๊ฐ์ฒด / Container shape component
pub const SHAPE_COMPONENT_CONTAINER: u16 = HWPTAG_BEGIN + 70;
/// ์ปจํธ๋กค ์์์ ๋ฐ์ดํฐ / Control arbitrary data
pub const CTRL_DATA: u16 = HWPTAG_BEGIN + 71;
/// ์์ ๊ฐ์ฒด / Equation editor
pub const EQEDIT: u16 = HWPTAG_BEGIN + 72;
/// ์์ฝ / Reserved
pub const RESERVED: u16 = HWPTAG_BEGIN + 73;
/// ๊ธ๋งต์ / Text art shape component
pub const SHAPE_COMPONENT_TEXTART: u16 = HWPTAG_BEGIN + 74;
/// ์์ ๊ฐ์ฒด / Form object
pub const FORM_OBJECT: u16 = HWPTAG_BEGIN + 75;
/// ๋ฉ๋ชจ ๋ชจ์ / Memo shape
pub const MEMO_SHAPE: u16 = HWPTAG_BEGIN + 76;
/// ๋ฉ๋ชจ ๋ฆฌ์คํธ ํค๋ / Memo list header
pub const MEMO_LIST: u16 = HWPTAG_BEGIN + 77;
/// ์ฐจํธ ๋ฐ์ดํฐ / Chart data
pub const CHART_DATA: u16 = HWPTAG_BEGIN + 79;
/// ๋น๋์ค ๋ฐ์ดํฐ / Video data
pub const VIDEO_DATA: u16 = HWPTAG_BEGIN + 82;
/// Unknown ๊ฐ์ฒด / Unknown shape component
pub const SHAPE_COMPONENT_UNKNOWN: u16 = HWPTAG_BEGIN + 99;
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_data.rs | crates/hwp-core/src/document/bodytext/ctrl_data.rs | /// CtrlData ๊ตฌ์กฐ์ฒด / CtrlData structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 66 - ์ปจํธ๋กค ์์์ ๋ฐ์ดํฐ / Spec mapping: Table 66 - Control arbitrary data
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ CTRL_DATA ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain CTRL_DATA records
use crate::document::docinfo::ParameterSet;
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// ์ปจํธ๋กค ์์์ ๋ฐ์ดํฐ / Control arbitrary data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CtrlData {
/// ํ๋ผ๋ฏธํฐ ์
(ํ 50 ์ฐธ์กฐ) / Parameter set (see Table 50)
pub parameter_set: ParameterSet,
}
impl CtrlData {
/// CtrlData๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse CtrlData from byte array.
///
/// # Arguments
/// * `data` - CtrlData ๋ฐ์ดํฐ / CtrlData data
///
/// # Returns
/// ํ์ฑ๋ CtrlData ๊ตฌ์กฐ์ฒด / Parsed CtrlData structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 66์ ๋ฐ๋ฅด๋ฉด CTRL_DATA๋ ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋๋ค:
/// - Parameter Set (ํ 50 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
///
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ CTRL_DATA๋ฅผ ํ์ฑํ์ง ์๊ณ ์์ต๋๋ค.
/// According to spec Table 66, CTRL_DATA has the following structure:
/// - Parameter Set (Table 50) - variable length
///
/// Legacy code (hwp.js) does not parse CTRL_DATA.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ CTRL_DATA ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ CTRL_DATA ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain CTRL_DATA records, so it has not been verified with actual files.
/// If an actual HWP file contains CTRL_DATA records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.is_empty() {
return Err(HwpError::InsufficientData {
field: "CtrlData data".to_string(),
expected: 1,
actual: 0,
});
}
// ํ๋ผ๋ฏธํฐ ์
ํ์ฑ (ํ 50) / Parse parameter set (Table 50)
let parameter_set = ParameterSet::parse(data)
.map_err(|e| HwpError::from(e))?;
Ok(CtrlData { parameter_set })
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/para_header.rs | crates/hwp-core/src/document/bodytext/para_header.rs | /// ParaHeader ๊ตฌ์กฐ์ฒด / ParaHeader structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 58 - ๋ฌธ๋จ ํค๋ / Spec mapping: Table 58 - Paragraph header
/// Tag ID: HWPTAG_PARA_HEADER
/// ์ ์ฒด ๊ธธ์ด: 24๋ฐ์ดํธ (5.0.3.2 ์ด์) / Total length: 24 bytes (5.0.3.2 and above)
///
/// **๋ ๋ฒจ๋ณ ์ฌ์ฉ / Usage by Level**
///
/// - **Level 0**: ๋ณธ๋ฌธ์ ๋ฌธ๋จ ํค๋ (์ผ๋ฐ์ ์ธ ์ฌ์ฉ) / Paragraph header in body text (normal usage)
/// - `Section::parse_data`์์ ์ฒ๋ฆฌ๋์ด `Paragraph` ๊ตฌ์กฐ์ฒด์ `para_header` ํ๋๋ก ์ ์ฅ๋จ
/// - Processed in `Section::parse_data` and stored in `Paragraph` struct's `para_header` field
///
/// - **Level 1 ์ด์**: ์ปจํธ๋กค ํค๋ ๋ด๋ถ์ ๋ฌธ๋จ ํค๋ / Paragraph header inside control header
/// - ๊ฐ์ฃผ/๋ฏธ์ฃผ(`fn `, `en `), ๋จธ๋ฆฌ๋ง/๊ผฌ๋ฆฌ๋ง(`head`, `foot`) ๋ฑ์ ์ปจํธ๋กค ํค๋ ๋ด๋ถ์ ์ง์ ๋ํ๋ ์ ์์
/// - Can appear directly inside control headers like footnotes/endnotes (`fn `, `en `), headers/footers (`head`, `foot`), etc.
/// - `CtrlHeader`์ children์์ ์ฒ๋ฆฌ๋์ด `ParagraphRecord::CtrlHeader`์ `paragraphs` ํ๋์ ์ ์ฅ๋จ
/// - Processed in `CtrlHeader`'s children and stored in `ParagraphRecord::CtrlHeader`'s `paragraphs` field
/// - ๋ ๊ฑฐ์ ์ฝ๋ ์ฐธ๊ณ : `legacy/ruby-hwp/lib/hwp/model.rb`์ `Footnote`, `Header`, `Footer` ๋ฑ์์
/// `@ctrl_header.para_headers << para_header`๋ก ์ฒ๋ฆฌ๋จ
/// - Reference: `legacy/ruby-hwp/lib/hwp/model.rb`'s `Footnote`, `Header`, `Footer`, etc.
/// where `@ctrl_header.para_headers << para_header`
use crate::error::HwpError;
use crate::types::{UINT16, UINT32, UINT8};
use serde::{Deserialize, Serialize};
/// Control Mask ๊ตฌ์กฐ์ฒด / Control Mask structure
///
/// libhwp์ HWPControlMask๋ฅผ ์ฐธ๊ณ ํ์ฌ ๊ตฌํ
/// ๊ฐ ๋นํธ๋ `(UINT32)(1<<ctrich) ์กฐํฉ`์ผ๋ก, ํน์ ์ ์ด ๋ฌธ์์ ์กด์ฌ ์ฌ๋ถ๋ฅผ ๋ํ๋
๋๋ค.
/// Control mask structure
///
/// Implemented based on libhwp's HWPControlMask
/// Each bit represents `(UINT32)(1<<ctrich) combination`, indicating the presence of specific control characters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ControlMask {
/// ์๋ณธ ๊ฐ / Raw value
pub value: UINT32,
}
impl Serialize for ControlMask {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeMap;
let active_flags = self.active_flags();
let mut map = serializer.serialize_map(Some(2))?;
map.serialize_entry("value", &self.value)?;
map.serialize_entry("flags", &active_flags)?;
map.end()
}
}
impl<'de> Deserialize<'de> for ControlMask {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
// ๊ธฐ์กด ํธํ์ฑ: ์ซ์๋ก ์ง๋ ฌํ๋ ๊ฒฝ์ฐ๋ ์ฒ๋ฆฌ / Backward compatibility: handle numeric serialization
// ์๋ก์ด ํ์: ๊ฐ์ฒด๋ก ์ง๋ ฌํ๋ ๊ฒฝ์ฐ๋ ์ฒ๋ฆฌ / New format: handle object serialization
struct ControlMaskVisitor;
impl<'de> serde::de::Visitor<'de> for ControlMaskVisitor {
type Value = ControlMask;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("control mask as u32 or object with value and flags")
}
// ์ซ์๋ก ์ง๋ ฌํ๋ ๊ฒฝ์ฐ (๊ธฐ์กด ํ์) / Numeric serialization (old format)
fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(ControlMask::new(value))
}
fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(ControlMask::new(value as u32))
}
// ๊ฐ์ฒด๋ก ์ง๋ ฌํ๋ ๊ฒฝ์ฐ (์ ํ์) / Object serialization (new format)
fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
where
M: serde::de::MapAccess<'de>,
{
let mut value: Option<UINT32> = None;
let mut flags: Option<Vec<String>> = None;
while let Some(key) = map.next_key::<String>()? {
match key.as_str() {
"value" => {
if value.is_some() {
return Err(serde::de::Error::duplicate_field("value"));
}
value = Some(map.next_value()?);
}
"flags" => {
if flags.is_some() {
return Err(serde::de::Error::duplicate_field("flags"));
}
flags = Some(map.next_value()?);
}
_ => {
let _ = map.next_value::<serde::de::IgnoredAny>()?;
}
}
}
let value = value.ok_or_else(|| serde::de::Error::missing_field("value"))?;
// flags๋ ๋ฌด์ํ๊ณ value๋ง ์ฌ์ฉ (flags๋ value์์ ๊ณ์ฐ ๊ฐ๋ฅ) / Ignore flags and use only value (flags can be calculated from value)
Ok(ControlMask::new(value))
}
}
deserializer.deserialize_any(ControlMaskVisitor)
}
}
impl ControlMask {
/// ControlMask๋ฅผ ์์ฑํฉ๋๋ค. / Create a ControlMask.
pub fn new(value: UINT32) -> Self {
Self { value }
}
/// ์๋ณธ ๊ฐ์ ๋ฐํํฉ๋๋ค. / Returns the raw value.
pub fn value(&self) -> UINT32 {
self.value
}
/// ๋นํธ๊ฐ ์ค์ ๋์ด ์๋์ง ํ์ธํฉ๋๋ค. / Check if a bit is set.
fn has_bit(&self, bit: u32) -> bool {
(self.value & (1u32 << bit)) != 0
}
/// ๊ตฌ์ญ/๋จ ์ ์ ์ปจํธ๋กค์ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has section/column definition control
/// bit 2 (Ch 2)
pub fn has_sect_col_def(&self) -> bool {
self.has_bit(2)
}
/// ํ๋ ์์ ์ปจํธ๋กค์ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has field start control
/// bit 3 (Ch 3)
pub fn has_field_start(&self) -> bool {
self.has_bit(3)
}
/// ํ๋ ๋ ์ปจํธ๋กค์ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has field end control
/// bit 4 (Ch 4)
pub fn has_field_end(&self) -> bool {
self.has_bit(4)
}
/// Title Mark๋ฅผ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has title mark
/// bit 8 (Ch 8)
pub fn has_title_mark(&self) -> bool {
self.has_bit(8)
}
/// ํญ์ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has tab
/// bit 9 (Ch 9)
pub fn has_tab(&self) -> bool {
self.has_bit(9)
}
/// ๊ฐ์ ์ค ๋๋์ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has line break
/// bit 10 (Ch 10)
pub fn has_line_break(&self) -> bool {
self.has_bit(10)
}
/// ๊ทธ๋ฆฌ๊ธฐ ๊ฐ์ฒด ๋๋ ํ ๊ฐ์ฒด๋ฅผ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has drawing object or table
/// bit 11 (Ch 11)
pub fn has_gso_table(&self) -> bool {
self.has_bit(11)
}
/// ๋ฌธ๋จ ๋๋๊ธฐ๋ฅผ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has paragraph break
/// bit 13 (Ch 13)
pub fn has_para_break(&self) -> bool {
self.has_bit(13)
}
/// ์จ์ ์ค๋ช
์ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has hidden comment
/// bit 15 (Ch 15)
pub fn has_hidden_comment(&self) -> bool {
self.has_bit(15)
}
/// ๋จธ๋ฆฌ๋ง ๋๋ ๊ผฌ๋ฆฌ๋ง์ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has header/footer
/// bit 16 (Ch 16)
pub fn has_header_footer(&self) -> bool {
self.has_bit(16)
}
/// ๊ฐ์ฃผ ๋๋ ๋ฏธ์ฃผ๋ฅผ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has footnote/endnote
/// bit 17 (Ch 17)
pub fn has_footnote_endnote(&self) -> bool {
self.has_bit(17)
}
/// ์๋ ๋ฒํธ๋ฅผ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has auto number
/// bit 18 (Ch 18)
pub fn has_auto_number(&self) -> bool {
self.has_bit(18)
}
/// ํ์ด์ง ์ปจํธ๋กค์ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has page control
/// bit 21 (Ch 21)
pub fn has_page_control(&self) -> bool {
self.has_bit(21)
}
/// ์ฑ
๊ฐํผ/์ฐพ์๋ณด๊ธฐ ํ์๋ฅผ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has bookmark/index mark
/// bit 22 (Ch 22)
pub fn has_bookmark(&self) -> bool {
self.has_bit(22)
}
/// ๋ง๋ง/๊ธ์ ๊ฒน์นจ์ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has additional text overlapping letter
/// bit 23 (Ch 23)
pub fn has_additional_text_overlapping_letter(&self) -> bool {
self.has_bit(23)
}
/// ํ์ดํ์ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has hyphen
/// bit 24 (Ch 24)
pub fn has_hyphen(&self) -> bool {
self.has_bit(24)
}
/// ๋ฌถ์ ๋น์นธ์ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has bundle blank
/// bit 30 (Ch 30)
pub fn has_bundle_blank(&self) -> bool {
self.has_bit(30)
}
/// ๊ณ ์ ํญ ๋น์นธ์ ๊ฐ์ก๋์ง ์ฌ๋ถ / Whether the paragraph has fixed width blank
/// bit 31 (Ch 31)
pub fn has_fix_width_blank(&self) -> bool {
self.has_bit(31)
}
/// ํ์ฑํ๋ ๋ชจ๋ ํ๋๊ทธ๋ฅผ ๋ฌธ์์ด ๋ฐฐ์ด๋ก ๋ฐํํฉ๋๋ค. / Returns all active flags as a string array.
pub fn active_flags(&self) -> Vec<&'static str> {
let mut flags = Vec::new();
if self.has_sect_col_def() {
flags.push("section_column_definition");
}
if self.has_field_start() {
flags.push("field_start");
}
if self.has_field_end() {
flags.push("field_end");
}
if self.has_title_mark() {
flags.push("title_mark");
}
if self.has_tab() {
flags.push("tab");
}
if self.has_line_break() {
flags.push("line_break");
}
if self.has_gso_table() {
flags.push("gso_table");
}
if self.has_para_break() {
flags.push("paragraph_break");
}
if self.has_hidden_comment() {
flags.push("hidden_comment");
}
if self.has_header_footer() {
flags.push("header_footer");
}
if self.has_footnote_endnote() {
flags.push("footnote_endnote");
}
if self.has_auto_number() {
flags.push("auto_number");
}
if self.has_page_control() {
flags.push("page_control");
}
if self.has_bookmark() {
flags.push("bookmark");
}
if self.has_additional_text_overlapping_letter() {
flags.push("additional_text_overlapping_letter");
}
if self.has_hyphen() {
flags.push("hyphen");
}
if self.has_bundle_blank() {
flags.push("bundle_blank");
}
if self.has_fix_width_blank() {
flags.push("fix_width_blank");
}
flags
}
}
impl From<UINT32> for ControlMask {
fn from(value: UINT32) -> Self {
Self::new(value)
}
}
impl From<ControlMask> for UINT32 {
fn from(mask: ControlMask) -> Self {
mask.value
}
}
/// ๋จ ๋๋๊ธฐ ์ข
๋ฅ / Column divide type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ColumnDivideType {
/// ๊ตฌ์ญ ๋๋๊ธฐ / Section divide
Section = 0x01,
/// ๋ค๋จ ๋๋๊ธฐ / Multi-column divide
MultiColumn = 0x02,
/// ์ชฝ ๋๋๊ธฐ / Page divide
Page = 0x04,
/// ๋จ ๋๋๊ธฐ / Column divide
Column = 0x08,
}
impl ColumnDivideType {
fn from_bits(bits: u8) -> Vec<Self> {
let mut types = Vec::new();
if bits & 0x01 != 0 {
types.push(ColumnDivideType::Section);
}
if bits & 0x02 != 0 {
types.push(ColumnDivideType::MultiColumn);
}
if bits & 0x04 != 0 {
types.push(ColumnDivideType::Page);
}
if bits & 0x08 != 0 {
types.push(ColumnDivideType::Column);
}
types
}
}
/// ๋ฌธ๋จ ํค๋ ๊ตฌ์กฐ์ฒด / Paragraph header structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParaHeader {
/// ํ
์คํธ ๋ฌธ์ ์ / Text character count
/// `if (nchars & 0x80000000) { nchars &= 0x7fffffff; }`
pub text_char_count: UINT32,
/// ์ปจํธ๋กค ๋ง์คํฌ / Control mask
/// `(UINT32)(1<<ctrich) ์กฐํฉ`
/// JSON ์ง๋ ฌํ ์ value๋ง ์ง๋ ฌํํ์ฌ ๊ธฐ์กด ํธํ์ฑ ์ ์ง / Only value is serialized in JSON to maintain backward compatibility
pub control_mask: ControlMask,
/// ๋ฌธ๋จ ๋ชจ์ ์์ด๋ ์ฐธ์กฐ๊ฐ / Paragraph shape ID reference
pub para_shape_id: UINT16,
/// ๋ฌธ๋จ ์คํ์ผ ์์ด๋ ์ฐธ์กฐ๊ฐ / Paragraph style ID reference
pub para_style_id: UINT8,
/// ๋จ ๋๋๊ธฐ ์ข
๋ฅ / Column divide type
pub column_divide_type: Vec<ColumnDivideType>,
/// ๊ธ์ ๋ชจ์ ์ ๋ณด ์ / Character shape info count
pub char_shape_count: UINT16,
/// range tag ์ ๋ณด ์ / Range tag info count
pub range_tag_count: UINT16,
/// ๊ฐ ์ค์ ๋ํ align์ ๋ํ ์ ๋ณด ์ / Line align info count
pub line_align_count: UINT16,
/// ๋ฌธ๋จ Instance ID (unique ID) / Paragraph instance ID
pub instance_id: UINT32,
/// ๋ณ๊ฒฝ์ถ์ ๋ณํฉ ๋ฌธ๋จ์ฌ๋ถ (5.0.3.2 ๋ฒ์ ์ด์) / Track change merge paragraph flag (5.0.3.2 and above)
pub section_merge: Option<UINT16>,
}
impl Default for ParaHeader {
fn default() -> Self {
Self {
text_char_count: 0,
control_mask: ControlMask::new(0),
para_shape_id: 0,
para_style_id: 0,
column_divide_type: Vec::new(),
char_shape_count: 0,
range_tag_count: 0,
line_align_count: 0,
instance_id: 0,
section_merge: None,
}
}
}
impl ParaHeader {
/// ParaHeader๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ParaHeader from byte array.
///
/// # Arguments
/// * `data` - ์ต์ 22๋ฐ์ดํธ์ ๋ฐ์ดํฐ (5.0.3.2 ์ด์์ 24๋ฐ์ดํธ) / At least 22 bytes of data (24 bytes for 5.0.3.2 and above)
/// * `version` - ํ์ผ ๋ฒ์ (5.0.3.2 ์ด์์ธ์ง ํ์ธ์ฉ) / File version (to check if 5.0.3.2 and above)
///
/// # Returns
/// ํ์ฑ๋ ParaHeader ๊ตฌ์กฐ์ฒด / Parsed ParaHeader structure
pub fn parse(data: &[u8], version: u32) -> Result<Self, HwpError> {
// ์ต์ 22๋ฐ์ดํธ ํ์ (5.0.3.2 ์ด์์ 24๋ฐ์ดํธ) / Need at least 22 bytes (24 bytes for 5.0.3.2 and above)
let min_size = if version >= 0x05000302 { 24 } else { 22 };
if data.len() < min_size {
return Err(HwpError::insufficient_data("ParaHeader", min_size, data.len()));
}
let mut offset = 0;
// UINT32 text(=chars) / UINT32 text character count
let mut text_char_count = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
// `if (nchars & 0x80000000) { nchars &= 0x7fffffff; }`
if text_char_count & 0x80000000 != 0 {
text_char_count &= 0x7fffffff;
}
offset += 4;
// UINT32 control mask / UINT32 control mask
let control_mask_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
let control_mask = ControlMask::new(control_mask_value);
offset += 4;
// UINT16 ๋ฌธ๋จ ๋ชจ์ ์์ด๋ ์ฐธ์กฐ๊ฐ / UINT16 paragraph shape ID reference
let para_shape_id = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT8 ๋ฌธ๋จ ์คํ์ผ ์์ด๋ ์ฐธ์กฐ๊ฐ / UINT8 paragraph style ID reference
let para_style_id = data[offset];
offset += 1;
// UINT8 ๋จ ๋๋๊ธฐ ์ข
๋ฅ / UINT8 column divide type
let column_divide_bits = data[offset];
let column_divide_type = ColumnDivideType::from_bits(column_divide_bits);
offset += 1;
// UINT16 ๊ธ์ ๋ชจ์ ์ ๋ณด ์ / UINT16 character shape info count
let char_shape_count = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT16 range tag ์ ๋ณด ์ / UINT16 range tag info count
let range_tag_count = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT16 ๊ฐ ์ค์ ๋ํ align์ ๋ํ ์ ๋ณด ์ / UINT16 line align info count
let line_align_count = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT32 ๋ฌธ๋จ Instance ID / UINT32 paragraph instance ID
let instance_id = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// UINT16 ๋ณ๊ฒฝ์ถ์ ๋ณํฉ ๋ฌธ๋จ์ฌ๋ถ (5.0.3.2 ๋ฒ์ ์ด์) / UINT16 track change merge paragraph flag (5.0.3.2 and above)
let section_merge = if version >= 0x05000302 && data.len() >= 24 {
Some(UINT16::from_le_bytes([data[offset], data[offset + 1]]))
} else {
None
};
Ok(ParaHeader {
text_char_count,
control_mask,
para_shape_id,
para_style_id,
column_divide_type,
char_shape_count,
range_tag_count,
line_align_count,
instance_id,
section_merge,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/control_char.rs | crates/hwp-core/src/document/bodytext/control_char.rs | /// Control character constants based on HWP 5.0 Specification Table 6
/// HWP 5.0 ์คํ ํ 6 ๊ธฐ๋ฐ ์ ์ด ๋ฌธ์ ์์
///
/// ํ 6: ์ ์ด ๋ฌธ์ / Table 6: Control characters
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
pub struct ControlChar;
/// ์ ์ด ๋ฌธ์ ์์น ์ ๋ณด / Control character position information
///
/// ๋ฌธ๋จ ํ
์คํธ ๋ด์์ ์ ์ด ๋ฌธ์์ ์์น์ ์ข
๋ฅ๋ฅผ ๋ํ๋
๋๋ค.
/// Represents the position and type of control characters within paragraph text.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ControlCharPosition {
/// ๋ฌธ์ ์ธ๋ฑ์ค (ํ
์คํธ ๋ด ์์น) / Character index (position in text)
pub position: usize,
/// ์ ์ด ๋ฌธ์ ์ฝ๋ (0-31) / Control character code (0-31)
pub code: u8,
/// ์ ์ด ๋ฌธ์ ์ด๋ฆ (์์ ์ด๋ฆ) / Control character name (constant name)
pub name: String,
}
/// INLINE ์ ์ด ๋ฌธ์ ํ๋ผ๋ฏธํฐ / INLINE control character parameter
///
/// JSON์ผ๋ก ํํ ๊ฐ๋ฅํ ์๋ฏธ ์๋ ๊ฐ๋ง ์ ์ฅํฉ๋๋ค.
/// Only stores meaningful values that can be expressed in JSON.
///
/// INLINE ํ์
์ ์ด ๋ฌธ์๋ ์ ์ด ๋ฌธ์ 1 WCHAR (2 bytes) + ํ๋ผ๋ฏธํฐ 6 WCHAR (12 bytes) = ์ด 8 WCHAR (16 bytes)
/// INLINE type control characters: control char 1 WCHAR (2 bytes) + parameter 6 WCHAR (12 bytes) = total 8 WCHAR (16 bytes)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InlineControlParam {
/// TAB ์ ์ด ๋ฌธ์์ ๋๋น (HWPUNIT, 1/7200์ธ์น) / Width for TAB control character (HWPUNIT, 1/7200 inch)
/// TAB (0x09)์ ๊ฒฝ์ฐ ์ฒซ 4๋ฐ์ดํธ๋ฅผ UINT32๋ก ์ฝ์ด์ ์ ์ฅ / For TAB (0x09), first 4 bytes read as UINT32
#[serde(skip_serializing_if = "Option::is_none")]
pub width: Option<crate::types::HWPUNIT>,
/// ์ปจํธ๋กค ID (4๋ฐ์ดํธ ASCII ๋ฌธ์์ด) / Control ID (4-byte ASCII string)
/// ๋ค๋ฅธ INLINE ํ์
์ ๊ฒฝ์ฐ ์ฒซ 4๋ฐ์ดํธ๋ฅผ ASCII๋ก ์ฝ๊ธฐ ์๋ / For other INLINE types, attempt to read first 4 bytes as ASCII
/// ์คํ ๋ฌธ์์ ๋ช
์๋์ง ์์ ์๋ณ์๋ก, ์ ํํ ์๋ฏธ๋ ์ ์ ์์ / Unspecified identifier in spec document, exact meaning is unknown
#[serde(skip_serializing_if = "Option::is_none")]
pub chid: Option<String>,
}
impl InlineControlParam {
/// INLINE ์ ์ด ๋ฌธ์ ํ๋ผ๋ฏธํฐ๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse INLINE control character parameter from byte array.
///
/// # Arguments
/// * `control_code` - ์ ์ด ๋ฌธ์ ์ฝ๋ / Control character code
/// * `data` - ์ต์ 12๋ฐ์ดํธ์ ๋ฐ์ดํฐ (์ ์ด ๋ฌธ์ ์ฝ๋ ์ดํ์ ๋ฐ์ดํฐ) / At least 12 bytes of data (data after control character code)
///
/// # Returns
/// ํ์ฑ๋ InlineControlParam ๊ตฌ์กฐ์ฒด / Parsed InlineControlParam structure
pub fn parse(control_code: u8, data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 12 {
return Err(HwpError::insufficient_data("InlineControlParam", 12, data.len()));
}
let mut param = InlineControlParam {
width: None,
chid: None,
};
if control_code == ControlChar::TAB {
// TAB์ ๊ฒฝ์ฐ: ์ฒซ 4๋ฐ์ดํธ๋ฅผ UINT32๋ก ์ฝ์ด์ width๋ก ์ ์ฅ
// For TAB: read first 4 bytes as UINT32 and store as width
use crate::types::UINT32;
let width_value = UINT32::from_le_bytes([data[0], data[1], data[2], data[3]]);
param.width = Some(crate::types::HWPUNIT::from(width_value));
} else {
// ๋ค๋ฅธ INLINE ํ์
์ ๊ฒฝ์ฐ: ์ฒซ 4๋ฐ์ดํธ๋ฅผ ASCII ๋ฌธ์์ด๋ก ์ฝ๊ธฐ ์๋
// For other INLINE types: attempt to read first 4 bytes as ASCII string
// ์คํ ๋ฌธ์์ ํ๋ผ๋ฏธํฐ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ง ์์ ์ ํํ ์๋ฏธ๋ฅผ ์ ์ ์๋ ์๋ณ์
// Parameter structure not specified in spec document, exact meaning of identifier is unknown
let chid_bytes = &data[0..4];
// ASCII๋ก ์ฝ์ ์ ์๋์ง ํ์ธ (๋ชจ๋ ๋ฐ์ดํธ๊ฐ 0x20-0x7E ๋ฒ์์ด๊ฑฐ๋ 0x00)
// Check if can be read as ASCII (all bytes in range 0x20-0x7E or 0x00)
if chid_bytes
.iter()
.all(|&b| b == 0 || (b >= 0x20 && b <= 0x7E))
{
let chid_str = String::from_utf8_lossy(chid_bytes)
.trim_end_matches('\0')
.to_string();
if !chid_str.is_empty() {
param.chid = Some(chid_str);
}
}
}
Ok(param)
}
}
impl ControlChar {
// Char control characters / ๋ฌธ์ ์ ์ด ๋ฌธ์
/// NULL ๋ฌธ์ / NULL character
/// ํ 6์๋ ๋ช
์๋์ง ์์์ง๋ง CHAR ํ์
์ผ๋ก ์ฒ๋ฆฌ๋จ / Not specified in Table 6 but handled as CHAR type
pub const NULL: u8 = 0;
// Extended control characters / ํ์ฅ ์ ์ด ๋ฌธ์
/// ์์ฝ (1-3) / Reserved (1-3)
/// ํ 6์๋ ๋ช
์๋์ง ์์์ง๋ง EXTENDED ํ์
์ผ๋ก ์ฒ๋ฆฌ๋จ / Not specified in Table 6 but handled as EXTENDED type
pub const RESERVED_1_3_START: u8 = 1;
pub const RESERVED_1_3_END: u8 = 3;
// Inline control characters / ์ธ๋ผ์ธ ์ ์ด ๋ฌธ์
/// ํ๋ ๋ / Field end
pub const FIELD_END: u8 = 4;
/// ์์ฝ (5-7) / Reserved (5-7)
pub const RESERVED_5_7_START: u8 = 5;
pub const RESERVED_5_7_END: u8 = 7;
/// title mark
pub const TITLE_MARK: u8 = 8;
/// ํญ / Tab
pub const TAB: u8 = 9;
/// ์์ฝ (19-20) / Reserved (19-20)
pub const RESERVED_19_20_START: u8 = 19;
pub const RESERVED_19_20_END: u8 = 20;
// Char control characters (continued) / ๋ฌธ์ ์ ์ด ๋ฌธ์ (๊ณ์)
/// ํ ์ค ๋(line break) / Line break
pub const LINE_BREAK: u8 = 10;
/// ๋ฌธ๋จ ๋(para break) / Paragraph break
pub const PARA_BREAK: u8 = 13;
/// ํ์ดํ / Hyphen
pub const HYPHEN: u8 = 24;
/// ์์ฝ (25-29) / Reserved (25-29)
pub const RESERVED_25_29_START: u8 = 25;
pub const RESERVED_25_29_END: u8 = 29;
/// ๋ฌถ์ ๋น์นธ / Bound space
pub const BOUND_SPACE: u8 = 30;
/// ๊ณ ์ ํญ ๋น์นธ / Fixed-width space
pub const FIXED_SPACE: u8 = 31;
// Extended control characters / ํ์ฅ ์ ์ด ๋ฌธ์
/// ๊ทธ๋ฆฌ๊ธฐ ๊ฐ์ฒด/ํ / Drawing object/table
pub const SHAPE_OBJECT: u8 = 11;
/// ์์ฝ (12) / Reserved (12)
pub const RESERVED_12: u8 = 12;
/// ์์ฝ (14) / Reserved (14)
pub const RESERVED_14: u8 = 14;
/// ์จ์ ์ค๋ช
/ Hidden description
pub const HIDDEN_DESC: u8 = 15;
/// ๋จธ๋ฆฌ๋ง/๊ผฌ๋ฆฌ๋ง / Header/footer
/// ์ ์ด ๋ฌธ์ ์ฝ๋๋ 16์ผ๋ก ๋์ผํ๋ฉฐ, ์ค์ ๊ตฌ๋ถ์ ์ปจํธ๋กค ํค๋์ ์ปจํธ๋กค ID๋ก ์ด๋ฃจ์ด์ง ("head" = ๋จธ๋ฆฌ๋ง, "foot" = ๊ผฌ๋ฆฌ๋ง)
/// Control character code is 16 for both, actual distinction is made by control ID in control header ("head" = header, "foot" = footer)
pub const HEADER_FOOTER: u8 = 16;
/// ๊ฐ์ฃผ/๋ฏธ์ฃผ / Footnote/endnote
/// ์ ์ด ๋ฌธ์ ์ฝ๋๋ 17๋ก ๋์ผํ์ง๋ง, ์ค์ ์ปจํธ๋กค ID๋ก ๊ตฌ๋ถ๋จ ("fn " = ๊ฐ์ฃผ, "en " = ๋ฏธ์ฃผ)
/// Control character code is 17 for both, but distinguished by control ID ("fn " = footnote, "en " = endnote)
pub const FOOTNOTE: u8 = 17;
/// ์๋๋ฒํธ(๊ฐ์ฃผ, ํ ๋ฑ) / Auto number (footnote, table, etc.)
pub const AUTO_NUMBER: u8 = 18;
/// ํ์ด์ง ์ปจํธ๋กค(๊ฐ์ถ๊ธฐ, ์ ๋ฒํธ๋ก ์์ ๋ฑ) / Page control (hide, start new number, etc.)
pub const PAGE_CONTROL: u8 = 21;
/// ์ฑ
๊ฐํผ/์ฐพ์๋ณด๊ธฐ ํ์ / Bookmark/find mark
pub const BOOKMARK: u8 = 22;
/// ๋ง๋ง/๊ธ์ ๊ฒน์นจ / Comment overlap
pub const COMMENT_OVERLAP: u8 = 23;
/// ๋ณํ ๊ฐ๋ฅํ ์ ์ด ๋ฌธ์์ธ์ง ํ์ธ / Check if control character can be converted
///
/// ํ
์คํธ๋ก ํํ ๊ฐ๋ฅํ ์ ์ด ๋ฌธ์ (ํ
์คํธ์ ์ ์ง๋จ) / Control characters that can be expressed as text (kept in text)
pub fn is_convertible(code: u8) -> bool {
matches!(
code,
Self::TAB
| Self::LINE_BREAK
| Self::PARA_BREAK
| Self::HYPHEN
| Self::BOUND_SPACE
| Self::FIXED_SPACE
)
}
/// ์ ์ด ๋ฌธ์๋ฅผ ํ
์คํธ ํํ์ผ๋ก ๋ณํ / Convert control character to text representation
///
/// ๋ณํ ๋ถ๊ฐ๋ฅํ ๊ฒฝ์ฐ None ๋ฐํ / Returns None if conversion is not possible
pub fn to_text(code: u8) -> Option<&'static str> {
match code {
Self::TAB => Some("\t"), // ํญ ๋ฌธ์ ๊ทธ๋๋ก ์ ์ง / Keep tab character as-is
Self::LINE_BREAK => Some("\n"), // ํ ์ค ๋(line break) / Line break
Self::PARA_BREAK => Some("\n"), // ๋ฌธ๋จ ๋(para break) - ์ค๋ฐ๊ฟ์ผ๋ก ํํ / Paragraph break - expressed as line break
Self::HYPHEN => Some("-"), // ํ์ดํ / Hyphen
Self::BOUND_SPACE => Some(" "), // ๋ฌถ์ ๋น์นธ์ ๊ณต๋ฐฑ์ผ๋ก ๋ณํ / Convert bound space to space
Self::FIXED_SPACE => Some(" "), // ๊ณ ์ ํญ ๋น์นธ์ ๊ณต๋ฐฑ์ผ๋ก ๋ณํ / Convert fixed-width space to space
_ => None,
}
}
/// ์ ์ด ๋ฌธ์ ์ฝ๋๋ฅผ ์ด๋ฆ์ผ๋ก ๋ณํ / Convert control character code to name
///
/// # Arguments
/// * `code` - ์ ์ด ๋ฌธ์ ์ฝ๋ (0-31) / Control character code (0-31)
///
/// # Returns
/// ์ ์ด ๋ฌธ์ ์์ ์ด๋ฆ (์: "FOOTNOTE", "AUTO_NUMBER") / Control character constant name (e.g., "FOOTNOTE", "AUTO_NUMBER")
pub fn to_name(code: u8) -> String {
match code {
Self::NULL => "NULL".to_string(),
Self::RESERVED_1_3_START..=Self::RESERVED_1_3_END => {
format!("RESERVED_{}", code)
}
Self::FIELD_END => "FIELD_END".to_string(),
Self::RESERVED_5_7_START..=Self::RESERVED_5_7_END => {
format!("RESERVED_{}", code)
}
Self::TITLE_MARK => "TITLE_MARK".to_string(),
Self::TAB => "TAB".to_string(),
Self::LINE_BREAK => "LINE_BREAK".to_string(),
Self::SHAPE_OBJECT => "SHAPE_OBJECT".to_string(),
Self::RESERVED_12 => "RESERVED_12".to_string(),
Self::PARA_BREAK => "PARA_BREAK".to_string(),
Self::RESERVED_14 => "RESERVED_14".to_string(),
Self::HIDDEN_DESC => "HIDDEN_DESC".to_string(),
Self::HEADER_FOOTER => "HEADER_FOOTER".to_string(),
Self::FOOTNOTE => "FOOTNOTE".to_string(),
Self::AUTO_NUMBER => "AUTO_NUMBER".to_string(),
Self::RESERVED_19_20_START..=Self::RESERVED_19_20_END => {
format!("RESERVED_{}", code)
}
Self::PAGE_CONTROL => "PAGE_CONTROL".to_string(),
Self::BOOKMARK => "BOOKMARK".to_string(),
Self::COMMENT_OVERLAP => "COMMENT_OVERLAP".to_string(),
Self::HYPHEN => "HYPHEN".to_string(),
Self::RESERVED_25_29_START..=Self::RESERVED_25_29_END => {
format!("RESERVED_{}", code)
}
Self::BOUND_SPACE => "BOUND_SPACE".to_string(),
Self::FIXED_SPACE => "FIXED_SPACE".to_string(),
_ => format!("UNKNOWN_{}", code),
}
}
/// ์ ์ด ๋ฌธ์ ํ์
์ ๋ฐ๋ฅธ ํฌ๊ธฐ ๋ฐํ (WCHAR ๋จ์) / Get size based on control character type (in WCHAR units)
///
/// CHAR: 1 WCHAR (2 bytes)
/// INLINE: 8 WCHAR (16 bytes) - ์ ์ด ๋ฌธ์ 1 + ํ๋ผ๋ฏธํฐ 6
/// EXTENDED: 8 WCHAR (16 bytes) - ์ ์ด ๋ฌธ์ 1 + ํฌ์ธํฐ 6
#[allow(clippy::if_same_then_else)]
pub fn get_size_by_code(code: u8) -> usize {
if code <= 31 {
// CHAR ํ์
: 1 WCHAR (2 bytes)
// ํ 6 ์ฐธ์กฐ: 10 (LINE_BREAK), 13 (PARA_BREAK), 24 (HYPHEN), 30 (BOUND_SPACE), 31 (FIXED_SPACE)
// ํ 6 ๋ฏธ๋ช
์: 0 (NULL) - CHAR ํ์
์ผ๋ก ์ฒ๋ฆฌ
if matches!(
code,
Self::NULL
| Self::LINE_BREAK
| Self::PARA_BREAK
| Self::HYPHEN
| Self::BOUND_SPACE
| Self::FIXED_SPACE
) {
1
}
// INLINE ํ์
: 8 WCHAR (16 bytes)
// ํ 6 ์ฐธ์กฐ: 4 (FIELD_END), 5-7 (์์ฝ), 8 (TITLE_MARK), 9 (TAB), 19-20 (์์ฝ)
else if matches!(
code,
Self::FIELD_END
| Self::RESERVED_5_7_START..=Self::RESERVED_5_7_END
| Self::TITLE_MARK
| Self::TAB
| Self::RESERVED_19_20_START..=Self::RESERVED_19_20_END
) {
8
}
// EXTENDED ํ์
: 8 WCHAR (16 bytes)
// ํ 6 ์ฐธ์กฐ: 11-12, 14-18, 21-23
// ํ 6 ๋ฏธ๋ช
์: 1-3 - EXTENDED ํ์
์ผ๋ก ์ฒ๋ฆฌ
// INLINE๊ณผ ๋์ผํ ํฌ๊ธฐ(8)์ด์ง๋ง ์๋ฏธ์ ์ผ๋ก ๋ค๋ฅธ ํ์
์ / Same size (8) as INLINE but semantically different type
else {
8
}
} else {
1 // ์ผ๋ฐ ๋ฌธ์
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/form_object.rs | crates/hwp-core/src/document/bodytext/form_object.rs | /// FormObject ๊ตฌ์กฐ์ฒด / FormObject structure
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ์คํ ๋ฌธ์์ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ / Spec document does not specify detailed structure
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ FORM_OBJECT ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain FORM_OBJECT records
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// ์์ ๊ฐ์ฒด / Form object
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FormObject {
/// Raw ๋ฐ์ดํฐ / Raw data
/// ์คํ ๋ฌธ์์ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ผ๋ฏ๋ก raw ๋ฐ์ดํฐ๋ก ์ ์ฅํฉ๋๋ค.
/// Raw data is stored because the spec document does not specify detailed structure.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub raw_data: Vec<u8>,
}
impl FormObject {
/// FormObject์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse FormObject from byte array.
///
/// # Arguments
/// * `data` - FormObject ๋ฐ์ดํฐ / FormObject data
///
/// # Returns
/// ํ์ฑ๋ FormObject ๊ตฌ์กฐ์ฒด / Parsed FormObject structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 57์๋ "์์ ๊ฐ์ฒด"๋ก๋ง ์ธ๊ธ๋์ด ์๊ณ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ต๋๋ค.
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ raw ๋ฐ์ดํฐ๋ก๋ง ์ ์ฅํ๊ณ ์์ต๋๋ค.
/// Spec document Table 57 only mentions "Form object" and does not specify detailed structure.
/// Legacy code (hwp.js) also stores only raw data.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ FORM_OBJECT ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ FORM_OBJECT ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain FORM_OBJECT records, so it has not been verified with actual files.
/// If an actual HWP file contains FORM_OBJECT records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
Ok(FormObject {
raw_data: data.to_vec(),
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/chart_data.rs | crates/hwp-core/src/document/bodytext/chart_data.rs | /// ChartData ๊ตฌ์กฐ์ฒด / ChartData structure
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ์คํ ๋ฌธ์์ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ / Spec document does not specify detailed structure
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ CHART_DATA ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain CHART_DATA records
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// ์ฐจํธ ๋ฐ์ดํฐ / Chart data
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChartData {
/// Raw ๋ฐ์ดํฐ / Raw data
/// ์คํ ๋ฌธ์์ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ผ๋ฏ๋ก raw ๋ฐ์ดํฐ๋ก ์ ์ฅํฉ๋๋ค.
/// Raw data is stored because the spec document does not specify detailed structure.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub raw_data: Vec<u8>,
}
impl ChartData {
/// ChartData๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ChartData from byte array.
///
/// # Arguments
/// * `data` - ChartData ๋ฐ์ดํฐ / ChartData data
///
/// # Returns
/// ํ์ฑ๋ ChartData ๊ตฌ์กฐ์ฒด / Parsed ChartData structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 57์๋ "์ฐจํธ ๋ฐ์ดํฐ"๋ก๋ง ์ธ๊ธ๋์ด ์๊ณ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ต๋๋ค.
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ raw ๋ฐ์ดํฐ๋ก๋ง ์ ์ฅํ๊ณ ์์ต๋๋ค.
/// Spec document Table 57 only mentions "Chart data" and does not specify detailed structure.
/// Legacy code (hwp.js) also stores only raw data.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ CHART_DATA ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ CHART_DATA ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain CHART_DATA records, so it has not been verified with actual files.
/// If an actual HWP file contains CHART_DATA records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
Ok(ChartData {
raw_data: data.to_vec(),
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/shape_component/ole.rs | crates/hwp-core/src/document/bodytext/shape_component/ole.rs | /// ShapeComponentOle ๊ตฌ์กฐ์ฒด / ShapeComponentOle structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 118 - OLE ๊ฐ์ฒด ์์ฑ / Spec mapping: Table 118 - OLE shape component attributes
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_OLE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain SHAPE_COMPONENT_OLE records
use crate::error::HwpError;
use crate::types::{COLORREF, INT32, UINT16, UINT32};
use serde::{Deserialize, Serialize};
/// OLE ๊ฐ์ฒด / OLE shape component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShapeComponentOle {
/// ์์ฑ / Attributes (ํ 119 ์ฐธ์กฐ / See Table 119)
pub attributes: OleAttributes,
/// ์ค๋ธ์ ํธ ์์ฒด์ extent xํฌ๊ธฐ / Object extent X size
pub extent_x: INT32,
/// ์ค๋ธ์ ํธ ์์ฒด์ extent yํฌ๊ธฐ / Object extent Y size
pub extent_y: INT32,
/// ์ค๋ธ์ ํธ๊ฐ ์ฌ์ฉํ๋ ์คํ ๋ฆฌ์ง์ BinData ID / BinData ID of storage used by object
pub bindata_id: UINT16,
/// ํ
๋๋ฆฌ ์ / Border color
pub border_color: COLORREF,
/// ํ
๋๋ฆฌ ๋๊ป / Border width
pub border_width: INT32,
/// ํ
๋๋ฆฌ ์์ฑ / Border attributes (ํ 87 ์ฐธ์กฐ / See Table 87)
pub border_attributes: UINT32,
}
/// OLE ๊ฐ์ฒด ์์ฑ / OLE shape component attributes
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct OleAttributes {
/// Drawing aspect (bit 0-7)
/// - DVASPECT_CONTENT = 1
/// - DVASPECT_THUMBNAIL = 2
/// - DVASPECT_ICON = 4
/// - DVASPECT_DOCPRINT = 8
/// ์์ธํ ์ค๋ช
์ MSDN์ MFC COleClientItem::m_nDrawAspect ์ฐธ๊ณ
/// See MSDN MFC COleClientItem::m_nDrawAspect for details
pub drawing_aspect: u8,
/// TRUE if moniker is assigned (bit 8)
/// ์์ธํ ์ค๋ช
์ MSDN์ MFC COleClientItem::m_bMoniker ์ฐธ๊ณ
/// See MSDN MFC COleClientItem::m_bMoniker for details
pub has_moniker: bool,
/// ๋ฒ ์ด์ค๋ผ์ธ (bit 9-15)
/// 0์ ๊ธฐ๋ณธ๊ฐ(85%), 1-101์ 0-100%๋ฅผ ๋ํ๋. ํ์ฌ๋ ์์๋ง ๋ณ๋์ ๋ฒ ์ด์ค๋ผ์ธ์ ๊ฐ์ง
/// 0 is default (85%), 1-101 represents 0-100%. Currently only equations have separate baseline
pub baseline: u8,
/// ๊ฐ์ฒด ์ข
๋ฅ (bit 16-21) / Object type
/// - 0: Unknown
/// - 1: Embedded
/// - 2: Link
/// - 3: Static
/// - 4: Equation
pub object_type: u8,
}
impl ShapeComponentOle {
/// ShapeComponentOle์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ShapeComponentOle from byte array.
///
/// # Arguments
/// * `data` - ShapeComponentOle ๋ฐ์ดํฐ (OLE ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง) / ShapeComponentOle data (OLE shape component attributes only)
///
/// # Returns
/// ํ์ฑ๋ ShapeComponentOle ๊ตฌ์กฐ์ฒด / Parsed ShapeComponentOle structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 117์ ๋ฐ๋ฅด๋ฉด SHAPE_COMPONENT_OLE์ ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋๋ค:
/// - ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 68 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - OLE ๊ฐ์ฒด ์์ฑ(ํ 118 ์ฐธ์กฐ) - 24๋ฐ์ดํธ
///
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ OLE ๊ฐ์ฒด ์์ฑ์ ํ์ฑํ์ง ์๊ณ ์์ต๋๋ค.
/// According to spec Table 117, SHAPE_COMPONENT_OLE has the following structure:
/// - Object common properties (Table 68) - variable length
/// - OLE shape component attributes (Table 118) - 24 bytes
///
/// Legacy code (hwp.js) does not parse OLE shape component attributes.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_OLE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ SHAPE_COMPONENT_OLE ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain SHAPE_COMPONENT_OLE records, so it has not been verified with actual files.
/// If an actual HWP file contains SHAPE_COMPONENT_OLE records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ํ 118: OLE ๊ฐ์ฒด ์์ฑ์ 24๋ฐ์ดํธ / Table 118: OLE shape component attributes is 24 bytes
// UINT16(2) + INT32(4) + INT32(4) + UINT16(2) + COLORREF(4) + INT32(4) + UINT32(4) = 24 bytes
if data.len() < 24 {
return Err(HwpError::insufficient_data("ShapeComponentOle", 24, data.len()));
}
let mut offset = 0;
// ํ 118: ์์ฑ (UINT16, 2๋ฐ์ดํธ) / Table 118: Attributes (UINT16, 2 bytes)
let attr_value = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// ํ 119: ์์ฑ ๋นํธ ํ๋ ํ์ฑ / Table 119: Parse attribute bit fields
// Note: UINT16 is 16 bits, so bits 16-21 don't exist in this field
// ์ฐธ๊ณ : UINT16์ 16๋นํธ์ด๋ฏ๋ก bit 16-21์ ์ด ํ๋์ ์กด์ฌํ์ง ์์ต๋๋ค
let drawing_aspect = (attr_value & 0xFF) as u8; // bit 0-7
let has_moniker = (attr_value & 0x100) != 0; // bit 8
let baseline = ((attr_value >> 9) & 0x7F) as u8; // bit 9-15
// object_type is not in UINT16 field, will be read from later data if needed
// object_type์ UINT16 ํ๋์ ์์ผ๋ฉฐ, ํ์์ ์ดํ ๋ฐ์ดํฐ์์ ์ฝ์ต๋๋ค
let object_type = 0u8; // Placeholder - may need to read from additional data
// ํ 118: ์ค๋ธ์ ํธ ์์ฒด์ extent xํฌ๊ธฐ (INT32, 4๋ฐ์ดํธ) / Table 118: Object extent X size (INT32, 4 bytes)
let extent_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 118: ์ค๋ธ์ ํธ ์์ฒด์ extent yํฌ๊ธฐ (INT32, 4๋ฐ์ดํธ) / Table 118: Object extent Y size (INT32, 4 bytes)
let extent_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 118: ์ค๋ธ์ ํธ๊ฐ ์ฌ์ฉํ๋ ์คํ ๋ฆฌ์ง์ BinData ID (UINT16, 2๋ฐ์ดํธ) / Table 118: BinData ID (UINT16, 2 bytes)
let bindata_id = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// ํ 118: ํ
๋๋ฆฌ ์ (COLORREF, 4๋ฐ์ดํธ) / Table 118: Border color (COLORREF, 4 bytes)
let border_color_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
let border_color = COLORREF(border_color_value);
offset += 4;
// ํ 118: ํ
๋๋ฆฌ ๋๊ป (INT32, 4๋ฐ์ดํธ) / Table 118: Border width (INT32, 4 bytes)
let border_width = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 118: ํ
๋๋ฆฌ ์์ฑ (UINT32, 4๋ฐ์ดํธ) / Table 118: Border attributes (UINT32, 4 bytes)
let border_attributes = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
Ok(ShapeComponentOle {
attributes: OleAttributes {
drawing_aspect,
has_moniker,
baseline,
object_type,
},
extent_x,
extent_y,
bindata_id,
border_color,
border_width,
border_attributes,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/shape_component/picture.rs | crates/hwp-core/src/document/bodytext/shape_component/picture.rs | /// ShapeComponentPicture ๊ตฌ์กฐ์ฒด / ShapeComponentPicture structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 107 - ๊ทธ๋ฆผ ๊ฐ์ฒด ์์ฑ / Spec mapping: Table 107 - Picture shape component attributes
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_PICTURE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain SHAPE_COMPONENT_PICTURE records
use crate::error::HwpError;
use crate::types::{COLORREF, HWPUNIT16, INT32, INT8, UINT16, UINT32};
use serde::{Deserialize, Serialize};
/// ๊ทธ๋ฆผ ๊ฐ์ฒด / Picture shape component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShapeComponentPicture {
/// ํ
๋๋ฆฌ ์ / Border color
pub border_color: COLORREF,
/// ํ
๋๋ฆฌ ๋๊ป / Border width
pub border_width: INT32,
/// ํ
๋๋ฆฌ ์์ฑ / Border attributes (ํ 87 ์ฐธ์กฐ / See Table 87)
pub border_attributes: UINT32,
/// ์ด๋ฏธ์ง์ ํ
๋๋ฆฌ ์ฌ๊ฐํ์ x ์ขํ / X coordinates of image border rectangle (์ต์ด ๊ทธ๋ฆผ ์ฝ์
์ ํฌ๊ธฐ / size at initial picture insertion)
pub border_rectangle_x: RectangleCoordinates,
/// ์ด๋ฏธ์ง์ ํ
๋๋ฆฌ ์ฌ๊ฐํ์ y ์ขํ / Y coordinates of image border rectangle (์ต์ด ๊ทธ๋ฆผ ์ฝ์
์ ํฌ๊ธฐ / size at initial picture insertion)
pub border_rectangle_y: RectangleCoordinates,
/// ์๋ฅด๊ธฐ ํ ํ ์ฌ๊ฐํ / Cropped rectangle
pub crop_rectangle: CropRectangle,
/// ์์ชฝ ์ฌ๋ฐฑ ์ ๋ณด / Inner padding information (ํ 77 ์ฐธ์กฐ / See Table 77)
pub padding: Padding,
/// ๊ทธ๋ฆผ ์ ๋ณด / Picture information (ํ 32 ์ฐธ์กฐ / See Table 32)
pub picture_info: PictureInfo,
/// ํ
๋๋ฆฌ ํฌ๋ช
๋ / Border opacity
pub border_opacity: u8,
/// ๋ฌธ์ ๋ด ๊ฐ ๊ฐ์ฒด์ ๋ํ ๊ณ ์ ์์ด๋(instance ID) / Unique ID (instance ID) for each object in document
pub instance_id: UINT32,
/// ๊ทธ๋ฆผ ํจ๊ณผ ์ ๋ณด / Picture effect information (ํ 108 ์ฐธ์กฐ / See Table 108)
/// ๊ฐ๋ณ ๊ธธ์ด์ด๋ฏ๋ก raw ๋ฐ์ดํฐ๋ก ์ ์ฅ / Variable length, stored as raw data
#[serde(skip_serializing_if = "Vec::is_empty")]
pub effect_data: Vec<u8>,
}
/// ์ฌ๊ฐํ ์ขํ / Rectangle coordinates
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct RectangleCoordinates {
/// ์ผ์ชฝ / Left
pub left: INT32,
/// ์์ชฝ / Top
pub top: INT32,
/// ์ค๋ฅธ์ชฝ / Right
pub right: INT32,
/// ์๋์ชฝ / Bottom
pub bottom: INT32,
}
/// ์๋ฅด๊ธฐ ์ฌ๊ฐํ / Crop rectangle
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct CropRectangle {
/// ์ผ์ชฝ / Left
pub left: INT32,
/// ์์ชฝ / Top
pub top: INT32,
/// ์ค๋ฅธ์ชฝ / Right
pub right: INT32,
/// ์๋์ชฝ / Bottom
pub bottom: INT32,
}
/// ์์ชฝ ์ฌ๋ฐฑ ์ ๋ณด / Inner padding information
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct Padding {
/// ์ผ์ชฝ ์ฌ๋ฐฑ / Left padding
pub left: HWPUNIT16,
/// ์ค๋ฅธ์ชฝ ์ฌ๋ฐฑ / Right padding
pub right: HWPUNIT16,
/// ์์ชฝ ์ฌ๋ฐฑ / Top padding
pub top: HWPUNIT16,
/// ์๋์ชฝ ์ฌ๋ฐฑ / Bottom padding
pub bottom: HWPUNIT16,
}
/// ๊ทธ๋ฆผ ์ ๋ณด / Picture information
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct PictureInfo {
/// ๋ฐ๊ธฐ / Brightness
pub brightness: INT8,
/// ๋ช
์ / Contrast
pub contrast: INT8,
/// ๊ทธ๋ฆผ ํจ๊ณผ / Picture effect
/// - 0: REAL_PIC
/// - 1: GRAY_SCALE
/// - 2: BLACK_WHITE
/// - 4: PATTERN8x8
pub effect: u8,
/// BinItem์ ์์ด๋ ์ฐธ์กฐ๊ฐ / BinItem ID reference
pub bindata_id: UINT16,
}
impl ShapeComponentPicture {
/// ShapeComponentPicture์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ShapeComponentPicture from byte array.
///
/// # Arguments
/// * `data` - ShapeComponentPicture ๋ฐ์ดํฐ (๊ทธ๋ฆผ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง) / ShapeComponentPicture data (picture shape component attributes only)
///
/// # Returns
/// ํ์ฑ๋ ShapeComponentPicture ๊ตฌ์กฐ์ฒด / Parsed ShapeComponentPicture structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 106์ ๋ฐ๋ฅด๋ฉด SHAPE_COMPONENT_PICTURE์ ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋๋ค:
/// - ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 68 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ๊ฐ์ฒด ์์ ๊ณตํต ์์ฑ(ํ 83 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ๊ทธ๋ฆผ ๊ฐ์ฒด ์์ฑ(ํ 107 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด (78 + n ๋ฐ์ดํธ)
///
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ ๊ทธ๋ฆผ ๊ฐ์ฒด ์์ฑ์ ์ผ๋ถ๋ง ํ์ฑํ๊ณ ์์ต๋๋ค.
/// According to spec Table 106, SHAPE_COMPONENT_PICTURE has the following structure:
/// - Object common properties (Table 68) - variable length
/// - Object element common properties (Table 83) - variable length
/// - Picture shape component attributes (Table 107) - variable length (78 + n bytes)
///
/// Legacy code (hwp.js) only parses part of picture shape component attributes.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_PICTURE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ SHAPE_COMPONENT_PICTURE ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain SHAPE_COMPONENT_PICTURE records, so it has not been verified with actual files.
/// If an actual HWP file contains SHAPE_COMPONENT_PICTURE records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
let mut offset = 0;
// ๊ทธ๋ฆผ ๊ฐ์ฒด ์์ฑ(ํ 107) ํ์ฑ ์์ / Start parsing picture shape component attributes (Table 107)
// ์ต์ 78๋ฐ์ดํธ ํ์ (๊ณ ์ ๋ถ๋ถ) / Need at least 78 bytes (fixed part)
if data.len() < 78 {
return Err(HwpError::insufficient_data("ShapeComponentPicture", 78, data.len()));
}
// ํ 107: ํ
๋๋ฆฌ ์ (COLORREF, 4๋ฐ์ดํธ) / Table 107: Border color (COLORREF, 4 bytes)
let border_color_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
let border_color = COLORREF(border_color_value);
offset += 4;
// ํ 107: ํ
๋๋ฆฌ ๋๊ป (INT32, 4๋ฐ์ดํธ) / Table 107: Border width (INT32, 4 bytes)
let border_width = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 107: ํ
๋๋ฆฌ ์์ฑ (UINT32, 4๋ฐ์ดํธ) / Table 107: Border attributes (UINT32, 4 bytes)
let border_attributes = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 107: ์ด๋ฏธ์ง์ ํ
๋๋ฆฌ ์ฌ๊ฐํ์ x ์ขํ (INT32 array[4], 16๋ฐ์ดํธ) / Table 107: X coordinates of image border rectangle (INT32 array[4], 16 bytes)
let border_x_left = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let border_x_top = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let border_x_right = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let border_x_bottom = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 107: ์ด๋ฏธ์ง์ ํ
๋๋ฆฌ ์ฌ๊ฐํ์ y ์ขํ (INT32 array[4], 16๋ฐ์ดํธ) / Table 107: Y coordinates of image border rectangle (INT32 array[4], 16 bytes)
let border_y_left = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let border_y_top = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let border_y_right = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let border_y_bottom = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 107: ์๋ฅด๊ธฐ ํ ํ ์ฌ๊ฐํ์ left (INT32, 4๋ฐ์ดํธ) / Table 107: Cropped rectangle left (INT32, 4 bytes)
let crop_left = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 107: ์๋ฅด๊ธฐ ํ ํ ์ฌ๊ฐํ์ top (INT32, 4๋ฐ์ดํธ) / Table 107: Cropped rectangle top (INT32, 4 bytes)
let crop_top = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 107: ์๋ฅด๊ธฐ ํ ํ ์ฌ๊ฐํ์ right (INT32, 4๋ฐ์ดํธ) / Table 107: Cropped rectangle right (INT32, 4 bytes)
let crop_right = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 107: ์๋ฅด๊ธฐ ํ ํ ์ฌ๊ฐํ์ bottom (INT32, 4๋ฐ์ดํธ) / Table 107: Cropped rectangle bottom (INT32, 4 bytes)
let crop_bottom = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 107: ์์ชฝ ์ฌ๋ฐฑ ์ ๋ณด (ํ 77 ์ฐธ์กฐ, 8๋ฐ์ดํธ) / Table 107: Inner padding information (Table 77, 8 bytes)
let padding_left = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let padding_right = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let padding_top = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let padding_bottom = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// ํ 107: ๊ทธ๋ฆผ ์ ๋ณด (ํ 32 ์ฐธ์กฐ, 5๋ฐ์ดํธ) / Table 107: Picture information (Table 32, 5 bytes)
let brightness = data[offset] as i8;
offset += 1;
let contrast = data[offset] as i8;
offset += 1;
let effect = data[offset];
offset += 1;
let bindata_id = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// ํ 107: ํ
๋๋ฆฌ ํฌ๋ช
๋ (BYTE, 1๋ฐ์ดํธ) / Table 107: Border opacity (BYTE, 1 byte)
let border_opacity = data[offset];
offset += 1;
// ํ 107: ๋ฌธ์ ๋ด ๊ฐ ๊ฐ์ฒด์ ๋ํ ๊ณ ์ ์์ด๋(instance ID) (UINT32, 4๋ฐ์ดํธ) / Table 107: Instance ID (UINT32, 4 bytes)
let instance_id = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 107: ๊ทธ๋ฆผ ํจ๊ณผ ์ ๋ณด (ํ 108 ์ฐธ์กฐ, ๊ฐ๋ณ ๊ธธ์ด) / Table 107: Picture effect information (Table 108, variable length)
let effect_data = if offset < data.len() {
data[offset..].to_vec()
} else {
Vec::new()
};
Ok(ShapeComponentPicture {
border_color,
border_width,
border_attributes,
border_rectangle_x: RectangleCoordinates {
left: border_x_left,
top: border_x_top,
right: border_x_right,
bottom: border_x_bottom,
},
border_rectangle_y: RectangleCoordinates {
left: border_y_left,
top: border_y_top,
right: border_y_right,
bottom: border_y_bottom,
},
crop_rectangle: CropRectangle {
left: crop_left,
top: crop_top,
right: crop_right,
bottom: crop_bottom,
},
padding: Padding {
left: padding_left,
right: padding_right,
top: padding_top,
bottom: padding_bottom,
},
picture_info: PictureInfo {
brightness,
contrast,
effect,
bindata_id,
},
border_opacity,
instance_id,
effect_data,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/shape_component/unknown.rs | crates/hwp-core/src/document/bodytext/shape_component/unknown.rs | /// ShapeComponentUnknown ๊ตฌ์กฐ์ฒด / ShapeComponentUnknown structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 57 - Unknown (36๋ฐ์ดํธ) / Spec mapping: Table 57 - Unknown (36 bytes)
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ์คํ ๋ฌธ์์ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ / Spec document does not specify detailed structure
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_UNKNOWN ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain SHAPE_COMPONENT_UNKNOWN records
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// Unknown ๊ฐ์ฒด / Unknown shape component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShapeComponentUnknown {
/// Raw ๋ฐ์ดํฐ / Raw data
/// ์คํ ๋ฌธ์์ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ผ๋ฏ๋ก raw ๋ฐ์ดํฐ๋ก ์ ์ฅํฉ๋๋ค.
/// ์คํ ๋ฌธ์ ํ 57์๋ 36๋ฐ์ดํธ๋ก ์ ์๋์ด ์์ต๋๋ค.
/// Raw data is stored because the spec document does not specify detailed structure.
/// Spec document Table 57 defines it as 36 bytes.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub raw_data: Vec<u8>,
}
impl ShapeComponentUnknown {
/// ShapeComponentUnknown์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ShapeComponentUnknown from byte array.
///
/// # Arguments
/// * `data` - ShapeComponentUnknown ๋ฐ์ดํฐ / ShapeComponentUnknown data
///
/// # Returns
/// ํ์ฑ๋ ShapeComponentUnknown ๊ตฌ์กฐ์ฒด / Parsed ShapeComponentUnknown structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 57์๋ "Unknown"์ผ๋ก๋ง ์ธ๊ธ๋์ด ์๊ณ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ต๋๋ค.
/// ์คํ ๋ฌธ์์๋ 36๋ฐ์ดํธ๋ก ์ ์๋์ด ์์ง๋ง, ์ค์ ํ์ผ์์๋ ๋ค๋ฅผ ์ ์์ต๋๋ค.
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ raw ๋ฐ์ดํฐ๋ก๋ง ์ ์ฅํ๊ณ ์์ต๋๋ค.
/// Spec document Table 57 only mentions "Unknown" and does not specify detailed structure.
/// Spec document defines it as 36 bytes, but actual files may differ.
/// Legacy code (hwp.js) also stores only raw data.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_UNKNOWN ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ SHAPE_COMPONENT_UNKNOWN ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain SHAPE_COMPONENT_UNKNOWN records, so it has not been verified with actual files.
/// If an actual HWP file contains SHAPE_COMPONENT_UNKNOWN records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
Ok(ShapeComponentUnknown {
raw_data: data.to_vec(),
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/shape_component/textart.rs | crates/hwp-core/src/document/bodytext/shape_component/textart.rs | /// ShapeComponentTextArt ๊ตฌ์กฐ์ฒด / ShapeComponentTextArt structure
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ์คํ ๋ฌธ์์ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ / Spec document does not specify detailed structure
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_TEXTART ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain SHAPE_COMPONENT_TEXTART records
use crate::error::HwpError;
use serde::{Deserialize, Serialize};
/// ๊ธ๋งต์ ๊ฐ์ฒด / Text art shape component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShapeComponentTextArt {
/// Raw ๋ฐ์ดํฐ / Raw data
/// ์คํ ๋ฌธ์์ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ผ๋ฏ๋ก raw ๋ฐ์ดํฐ๋ก ์ ์ฅํฉ๋๋ค.
/// Raw data is stored because the spec document does not specify detailed structure.
#[serde(skip_serializing_if = "Vec::is_empty")]
pub raw_data: Vec<u8>,
}
impl ShapeComponentTextArt {
/// ShapeComponentTextArt์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ShapeComponentTextArt from byte array.
///
/// # Arguments
/// * `data` - ShapeComponentTextArt ๋ฐ์ดํฐ / ShapeComponentTextArt data
///
/// # Returns
/// ํ์ฑ๋ ShapeComponentTextArt ๊ตฌ์กฐ์ฒด / Parsed ShapeComponentTextArt structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 57์๋ "๊ธ๋งต์"๋ก๋ง ์ธ๊ธ๋์ด ์๊ณ ์์ธ ๊ตฌ์กฐ๊ฐ ๋ช
์๋์ด ์์ง ์์ต๋๋ค.
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ raw ๋ฐ์ดํฐ๋ก๋ง ์ ์ฅํ๊ณ ์์ต๋๋ค.
/// Spec document Table 57 only mentions "Text art" and does not specify detailed structure.
/// Legacy code (hwp.js) also stores only raw data.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_TEXTART ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ SHAPE_COMPONENT_TEXTART ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain SHAPE_COMPONENT_TEXTART records, so it has not been verified with actual files.
/// If an actual HWP file contains SHAPE_COMPONENT_TEXTART records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
Ok(ShapeComponentTextArt {
raw_data: data.to_vec(),
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/shape_component/container.rs | crates/hwp-core/src/document/bodytext/shape_component/container.rs | /// ShapeComponentContainer ๊ตฌ์กฐ์ฒด / ShapeComponentContainer structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 121 - ๋ฌถ์ ๊ฐ์ฒด ์์ฑ / Spec mapping: Table 121 - Container shape component attributes
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_CONTAINER ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain SHAPE_COMPONENT_CONTAINER records
use crate::error::HwpError;
use crate::types::{UINT16, UINT32};
use serde::{Deserialize, Serialize};
/// ๋ฌถ์ ๊ฐ์ฒด / Container shape component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShapeComponentContainer {
/// ๊ฐ์ฒด์ ๊ฐ์ / Number of objects
pub object_count: UINT16,
/// ๊ฐ์ฒด์ ์ปจํธ๋กค ID ๋ฐฐ์ด / Control ID array of objects
pub control_ids: Vec<UINT32>,
}
impl ShapeComponentContainer {
/// ShapeComponentContainer์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ShapeComponentContainer from byte array.
///
/// # Arguments
/// * `data` - ShapeComponentContainer ๋ฐ์ดํฐ (๋ฌถ์ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง) / ShapeComponentContainer data (container shape component attributes only)
///
/// # Returns
/// ํ์ฑ๋ ShapeComponentContainer ๊ตฌ์กฐ์ฒด / Parsed ShapeComponentContainer structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 120์ ๋ฐ๋ฅด๋ฉด SHAPE_COMPONENT_CONTAINER์ ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋๋ค:
/// - ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 68 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ๋ฌถ์ ๊ฐ์ฒด ์์ฑ(ํ 121 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด (2 + 4รn ๋ฐ์ดํธ)
/// - ๊ฐ์ฒด ์์ฑ x ๋ฌถ์ ๊ฐ์ฒด์ ๊ฐฏ์ - ๊ฐ๋ณ ๊ธธ์ด
///
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ ๋ฌถ์ ๊ฐ์ฒด ์์ฑ์ ํ์ฑํ์ง ์๊ณ ์์ต๋๋ค.
/// According to spec Table 120, SHAPE_COMPONENT_CONTAINER has the following structure:
/// - Object common properties (Table 68) - variable length
/// - Container shape component attributes (Table 121) - variable length (2 + 4รn bytes)
/// - Object properties ร number of container objects - variable length
///
/// Legacy code (hwp.js) does not parse container shape component attributes.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_CONTAINER ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ SHAPE_COMPONENT_CONTAINER ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain SHAPE_COMPONENT_CONTAINER records, so it has not been verified with actual files.
/// If an actual HWP file contains SHAPE_COMPONENT_CONTAINER records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ์ต์ 2๋ฐ์ดํธ ํ์ (๊ฐ์ฒด์ ๊ฐ์) / Need at least 2 bytes (object count)
if data.len() < 2 {
return Err(HwpError::insufficient_data("ShapeComponentContainer", 2, data.len()));
}
let mut offset = 0;
// ํ 121: ๊ฐ์ฒด์ ๊ฐ์ (WORD, 2๋ฐ์ดํธ) / Table 121: Number of objects (WORD, 2 bytes)
let object_count = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let object_count_usize = object_count as usize;
// ํ์ํ ๋ฐ์ดํธ ์ ๊ณ์ฐ / Calculate required bytes
// WORD(2) + UINT32 array[n](4รn) = 2 + 4รn
let required_bytes = 2 + 4 * object_count_usize;
if data.len() < required_bytes {
return Err(HwpError::InsufficientData {
field: format!("ShapeComponentContainer (object_count={})", object_count_usize),
expected: required_bytes,
actual: data.len(),
});
}
// ํ 121: ๊ฐ์ฒด์ ์ปจํธ๋กค ID ๋ฐฐ์ด (UINT32 array[n], 4รn ๋ฐ์ดํธ) / Table 121: Control ID array (UINT32 array[n], 4รn bytes)
let mut control_ids = Vec::with_capacity(object_count_usize);
for _ in 0..object_count_usize {
let control_id = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
control_ids.push(control_id);
offset += 4;
}
Ok(ShapeComponentContainer {
object_count,
control_ids,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/shape_component/rectangle.rs | crates/hwp-core/src/document/bodytext/shape_component/rectangle.rs | /// ShapeComponentRectangle ๊ตฌ์กฐ์ฒด / ShapeComponentRectangle structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 94 - ์ฌ๊ฐํ ๊ฐ์ฒด ์์ฑ / Spec mapping: Table 94 - Rectangle shape component attributes
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_RECTANGLE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain SHAPE_COMPONENT_RECTANGLE records
use crate::error::HwpError;
use crate::types::INT32;
use serde::{Deserialize, Serialize};
/// ์ฌ๊ฐํ ๊ฐ์ฒด / Rectangle shape component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShapeComponentRectangle {
/// ์ฌ๊ฐํ ๋ชจ์๋ฆฌ ๊ณก๋ฅ (%) / Rectangle corner curvature (%)
/// ์ง๊ฐ์ 0, ๋ฅ๊ทผ ๋ชจ์์ 20, ๋ฐ์์ 50, ๊ทธ ์ธ๋ ์ ๋นํ ๊ฐ์ % ๋จ์๋ก ์ฌ์ฉํ๋ค.
/// Right angle is 0, rounded shape is 20, semicircle is 50, others use appropriate values in %.
pub corner_curvature: u8,
/// ์ฌ๊ฐํ์ ์ขํ(x) / Rectangle coordinates (x)
pub x_coordinates: RectangleCoordinates,
/// ์ฌ๊ฐํ์ ์ขํ(y) / Rectangle coordinates (y)
pub y_coordinates: RectangleCoordinates,
}
/// ์ฌ๊ฐํ ์ขํ / Rectangle coordinates
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct RectangleCoordinates {
/// ์๋จ / Top
pub top: INT32,
/// ์ค๋ฅธ์ชฝ / Right
pub right: INT32,
/// ํ๋จ / Bottom
pub bottom: INT32,
/// ์ผ์ชฝ / Left
pub left: INT32,
}
impl ShapeComponentRectangle {
/// ShapeComponentRectangle์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ShapeComponentRectangle from byte array.
///
/// # Arguments
/// * `data` - ShapeComponentRectangle ๋ฐ์ดํฐ (์ฌ๊ฐํ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง) / ShapeComponentRectangle data (rectangle shape component attributes only)
///
/// # Returns
/// ํ์ฑ๋ ShapeComponentRectangle ๊ตฌ์กฐ์ฒด / Parsed ShapeComponentRectangle structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 93์ ๋ฐ๋ฅด๋ฉด SHAPE_COMPONENT_RECTANGLE์ ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋๋ค:
/// - ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 68 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ๊ทธ๋ฆฌ๊ธฐ ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 81 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ์ฌ๊ฐํ ๊ฐ์ฒด ์์ฑ(ํ 94 ์ฐธ์กฐ) - 33๋ฐ์ดํธ
///
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ ์ฌ๊ฐํ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง ํ์ฑํ๊ณ ์์ต๋๋ค.
/// According to spec Table 93, SHAPE_COMPONENT_RECTANGLE has the following structure:
/// - Object common properties (Table 68) - variable length
/// - Drawing object common properties (Table 81) - variable length
/// - Rectangle shape component attributes (Table 94) - 33 bytes
///
/// Legacy code (hwp.js) only parses the rectangle shape component attributes part.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_RECTANGLE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ SHAPE_COMPONENT_RECTANGLE ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain SHAPE_COMPONENT_RECTANGLE records, so it has not been verified with actual files.
/// If an actual HWP file contains SHAPE_COMPONENT_RECTANGLE records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ํ 94: ์ฌ๊ฐํ ๊ฐ์ฒด ์์ฑ์ 33๋ฐ์ดํธ / Table 94: Rectangle shape component attributes is 33 bytes
// BYTE(1) + INT32 array[4](16) + INT32 array[4](16) = 33 bytes
if data.len() < 33 {
return Err(HwpError::insufficient_data("ShapeComponentRectangle", 33, data.len()));
}
let mut offset = 0;
// ํ 94: ์ฌ๊ฐํ ๋ชจ์๋ฆฌ ๊ณก๋ฅ (%) (BYTE, 1๋ฐ์ดํธ) / Table 94: Rectangle corner curvature (%) (BYTE, 1 byte)
let corner_curvature = data[offset];
offset += 1;
// ํ 94: ์ฌ๊ฐํ์ ์ขํ(x) (INT32 array[4], 16๋ฐ์ดํธ) / Table 94: Rectangle coordinates (x) (INT32 array[4], 16 bytes)
let x_top = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let x_right = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let x_bottom = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let x_left = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 94: ์ฌ๊ฐํ์ ์ขํ(y) (INT32 array[4], 16๋ฐ์ดํธ) / Table 94: Rectangle coordinates (y) (INT32 array[4], 16 bytes)
let y_top = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let y_right = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let y_bottom = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let y_left = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
Ok(ShapeComponentRectangle {
corner_curvature,
x_coordinates: RectangleCoordinates {
top: x_top,
right: x_right,
bottom: x_bottom,
left: x_left,
},
y_coordinates: RectangleCoordinates {
top: y_top,
right: y_right,
bottom: y_bottom,
left: y_left,
},
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/shape_component/curve.rs | crates/hwp-core/src/document/bodytext/shape_component/curve.rs | /// ShapeComponentCurve ๊ตฌ์กฐ์ฒด / ShapeComponentCurve structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 103 - ๊ณก์ ๊ฐ์ฒด ์์ฑ / Spec mapping: Table 103 - Curve shape component attributes
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_CURVE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain SHAPE_COMPONENT_CURVE records
use crate::error::HwpError;
use crate::types::{INT16, INT32};
use serde::{Deserialize, Serialize};
/// ๊ณก์ ๊ฐ์ฒด / Curve shape component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShapeComponentCurve {
/// ์ ์ ๊ฐ์ / Count of points
pub point_count: INT16,
/// X ์ขํ ๋ฐฐ์ด / X coordinates array
pub x_coordinates: Vec<INT32>,
/// Y ์ขํ ๋ฐฐ์ด / Y coordinates array
pub y_coordinates: Vec<INT32>,
/// ์ธ๊ทธ๋จผํธ ํ์
๋ฐฐ์ด / Segment type array
/// 0: line, 1: curve
pub segment_types: Vec<u8>,
}
impl ShapeComponentCurve {
/// ShapeComponentCurve์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ShapeComponentCurve from byte array.
///
/// # Arguments
/// * `data` - ShapeComponentCurve ๋ฐ์ดํฐ (๊ณก์ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง) / ShapeComponentCurve data (curve shape component attributes only)
///
/// # Returns
/// ํ์ฑ๋ ShapeComponentCurve ๊ตฌ์กฐ์ฒด / Parsed ShapeComponentCurve structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 102์ ๋ฐ๋ฅด๋ฉด SHAPE_COMPONENT_CURVE์ ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋๋ค:
/// - ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 68 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ๊ทธ๋ฆฌ๊ธฐ ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 81 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ๊ณก์ ๊ฐ์ฒด ์์ฑ(ํ 103 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด (2 + 2(4รcnt) + cnt-1 ๋ฐ์ดํธ)
///
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ ๊ณก์ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง ํ์ฑํ๊ณ ์์ต๋๋ค.
/// According to spec Table 102, SHAPE_COMPONENT_CURVE has the following structure:
/// - Object common properties (Table 68) - variable length
/// - Drawing object common properties (Table 81) - variable length
/// - Curve shape component attributes (Table 103) - variable length (2 + 2(4รcnt) + cnt-1 bytes)
///
/// Legacy code (hwp.js) only parses the curve shape component attributes part.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_CURVE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ SHAPE_COMPONENT_CURVE ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain SHAPE_COMPONENT_CURVE records, so it has not been verified with actual files.
/// If an actual HWP file contains SHAPE_COMPONENT_CURVE records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ์ต์ 2๋ฐ์ดํธ ํ์ (์ ์ ๊ฐ์) / Need at least 2 bytes (point count)
if data.len() < 2 {
return Err(HwpError::insufficient_data("ShapeComponentCurve", 2, data.len()));
}
let mut offset = 0;
// ํ 103: ์ ์ ๊ฐ์ (INT16, 2๋ฐ์ดํธ) / Table 103: Count of points (INT16, 2 bytes)
let point_count = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// ์ ์ ๊ฐ์๊ฐ ์์์ด๊ฑฐ๋ 0์ด๋ฉด ์ค๋ฅ / If point count is negative or zero, error
if point_count <= 0 {
return Err(HwpError::UnexpectedValue {
field: "ShapeComponentCurve point_count".to_string(),
expected: "positive number".to_string(),
found: point_count.to_string(),
});
}
let point_count_usize = point_count as usize;
// ํ์ํ ๋ฐ์ดํธ ์ ๊ณ์ฐ / Calculate required bytes
// INT16(2) + INT32 array[cnt](4รcnt) + INT32 array[cnt](4รcnt) + BYTE array[cnt-1](cnt-1) = 2 + 8รcnt + cnt-1
let required_bytes = 2 + 8 * point_count_usize + point_count_usize - 1;
if data.len() < required_bytes {
return Err(HwpError::InsufficientData {
field: format!("ShapeComponentCurve (point_count={})", point_count_usize),
expected: required_bytes,
actual: data.len(),
});
}
// ํ 103: X ์ขํ ๋ฐฐ์ด (INT32 array[cnt], 4รcnt ๋ฐ์ดํธ) / Table 103: X coordinates array (INT32 array[cnt], 4รcnt bytes)
let mut x_coordinates = Vec::with_capacity(point_count_usize);
for _ in 0..point_count_usize {
let x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
x_coordinates.push(x);
offset += 4;
}
// ํ 103: Y ์ขํ ๋ฐฐ์ด (INT32 array[cnt], 4รcnt ๋ฐ์ดํธ) / Table 103: Y coordinates array (INT32 array[cnt], 4รcnt bytes)
let mut y_coordinates = Vec::with_capacity(point_count_usize);
for _ in 0..point_count_usize {
let y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
y_coordinates.push(y);
offset += 4;
}
// ํ 103: ์ธ๊ทธ๋จผํธ ํ์
๋ฐฐ์ด (BYTE array[cnt-1], cnt-1 ๋ฐ์ดํธ) / Table 103: Segment type array (BYTE array[cnt-1], cnt-1 bytes)
let mut segment_types = Vec::with_capacity(point_count_usize - 1);
for _ in 0..(point_count_usize - 1) {
segment_types.push(data[offset]);
offset += 1;
}
Ok(ShapeComponentCurve {
point_count,
x_coordinates,
y_coordinates,
segment_types,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/shape_component/polygon.rs | crates/hwp-core/src/document/bodytext/shape_component/polygon.rs | /// ShapeComponentPolygon ๊ตฌ์กฐ์ฒด / ShapeComponentPolygon structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 99 - ๋ค๊ฐํ ๊ฐ์ฒด ์์ฑ / Spec mapping: Table 99 - Polygon shape component attributes
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_POLYGON ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain SHAPE_COMPONENT_POLYGON records
use crate::error::HwpError;
use crate::types::{INT16, INT32};
use serde::{Deserialize, Serialize};
/// ๋ค๊ฐํ ๊ฐ์ฒด / Polygon shape component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShapeComponentPolygon {
/// ์ ์ ๊ฐ์ / Count of points
pub point_count: INT16,
/// X ์ขํ ๋ฐฐ์ด / X coordinates array
pub x_coordinates: Vec<INT32>,
/// Y ์ขํ ๋ฐฐ์ด / Y coordinates array
pub y_coordinates: Vec<INT32>,
}
impl ShapeComponentPolygon {
/// ShapeComponentPolygon์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ShapeComponentPolygon from byte array.
///
/// # Arguments
/// * `data` - ShapeComponentPolygon ๋ฐ์ดํฐ (๋ค๊ฐํ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง) / ShapeComponentPolygon data (polygon shape component attributes only)
///
/// # Returns
/// ํ์ฑ๋ ShapeComponentPolygon ๊ตฌ์กฐ์ฒด / Parsed ShapeComponentPolygon structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 98์ ๋ฐ๋ฅด๋ฉด SHAPE_COMPONENT_POLYGON์ ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋๋ค:
/// - ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 68 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ๊ทธ๋ฆฌ๊ธฐ ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 81 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ๋ค๊ฐํ ๊ฐ์ฒด ์์ฑ(ํ 99 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด (2 + 2(4รcnt) ๋ฐ์ดํธ)
///
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ ๋ค๊ฐํ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง ํ์ฑํ๊ณ ์์ต๋๋ค.
/// According to spec Table 98, SHAPE_COMPONENT_POLYGON has the following structure:
/// - Object common properties (Table 68) - variable length
/// - Drawing object common properties (Table 81) - variable length
/// - Polygon shape component attributes (Table 99) - variable length (2 + 2(4รcnt) bytes)
///
/// Legacy code (hwp.js) only parses the polygon shape component attributes part.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_POLYGON ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ SHAPE_COMPONENT_POLYGON ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain SHAPE_COMPONENT_POLYGON records, so it has not been verified with actual files.
/// If an actual HWP file contains SHAPE_COMPONENT_POLYGON records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ์ต์ 2๋ฐ์ดํธ ํ์ (์ ์ ๊ฐ์) / Need at least 2 bytes (point count)
if data.len() < 2 {
return Err(HwpError::insufficient_data("ShapeComponentPolygon", 2, data.len()));
}
let mut offset = 0;
// ํ 99: ์ ์ ๊ฐ์ (INT16, 2๋ฐ์ดํธ) / Table 99: Count of points (INT16, 2 bytes)
let point_count = INT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// ์ ์ ๊ฐ์๊ฐ ์์์ด๊ฑฐ๋ 0์ด๋ฉด ์ค๋ฅ / If point count is negative or zero, error
if point_count <= 0 {
return Err(HwpError::UnexpectedValue {
field: "ShapeComponentPolygon point_count".to_string(),
expected: "positive number".to_string(),
found: point_count.to_string(),
});
}
let point_count_usize = point_count as usize;
// ํ์ํ ๋ฐ์ดํธ ์ ๊ณ์ฐ / Calculate required bytes
// INT16(2) + INT32 array[cnt](4รcnt) + INT32 array[cnt](4รcnt) = 2 + 8รcnt
let required_bytes = 2 + 8 * point_count_usize;
if data.len() < required_bytes {
return Err(HwpError::InsufficientData {
field: format!("ShapeComponentPolygon (point_count={})", point_count_usize),
expected: required_bytes,
actual: data.len(),
});
}
// ํ 99: X ์ขํ ๋ฐฐ์ด (INT32 array[cnt], 4รcnt ๋ฐ์ดํธ) / Table 99: X coordinates array (INT32 array[cnt], 4รcnt bytes)
let mut x_coordinates = Vec::with_capacity(point_count_usize);
for _ in 0..point_count_usize {
let x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
x_coordinates.push(x);
offset += 4;
}
// ํ 99: Y ์ขํ ๋ฐฐ์ด (INT32 array[cnt], 4รcnt ๋ฐ์ดํธ) / Table 99: Y coordinates array (INT32 array[cnt], 4รcnt bytes)
let mut y_coordinates = Vec::with_capacity(point_count_usize);
for _ in 0..point_count_usize {
let y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
y_coordinates.push(y);
offset += 4;
}
Ok(ShapeComponentPolygon {
point_count,
x_coordinates,
y_coordinates,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/shape_component/mod.rs | crates/hwp-core/src/document/bodytext/shape_component/mod.rs | mod common;
mod arc;
mod container;
mod curve;
mod ellipse;
mod line;
mod ole;
mod picture;
mod polygon;
mod rectangle;
mod textart;
mod unknown;
pub use common::ShapeComponent;
pub use arc::ShapeComponentArc;
pub use container::ShapeComponentContainer;
pub use curve::ShapeComponentCurve;
pub use ellipse::ShapeComponentEllipse;
pub use line::ShapeComponentLine;
pub use ole::ShapeComponentOle;
pub use picture::ShapeComponentPicture;
pub use polygon::ShapeComponentPolygon;
pub use rectangle::ShapeComponentRectangle;
pub use textart::ShapeComponentTextArt;
pub use unknown::ShapeComponentUnknown;
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/shape_component/common.rs | crates/hwp-core/src/document/bodytext/shape_component/common.rs | /// ShapeComponent ๊ตฌ์กฐ์ฒด / ShapeComponent structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 82, 83 - ๊ฐ์ฒด ์์ ์์ฑ / Spec mapping: Table 82, 83 - Shape component attributes
use crate::error::HwpError;
use crate::types::{HWPUNIT16, INT32, UINT16, UINT32};
use serde::{Deserialize, Serialize};
/// ๊ฐ์ฒด ์์ / Shape component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShapeComponent {
/// ๊ฐ์ฒด ์ปจํธ๋กค ID / Object control ID
pub object_control_id: String,
/// ๊ฐ์ฒด ์ปจํธ๋กค ID 2 (GenShapeObject์ผ ๊ฒฝ์ฐ id๊ฐ ๋ ๋ฒ ๊ธฐ๋ก๋จ) / Object control ID 2 (for GenShapeObject, ID is recorded twice)
#[serde(skip_serializing_if = "Option::is_none")]
pub object_control_id2: Option<String>,
/// ๊ฐ์ฒด๊ฐ ์ํ ๊ทธ๋ฃน ๋ด์์์ offset / Offset within group
pub group_offset: GroupOffset,
/// ๋ช ๋ฒ์ด๋ ๊ทธ๋ฃน ๋์๋์ง / Number of times grouped
pub group_count: UINT16,
/// ๊ฐ์ฒด ์์์ local file version / Local file version
pub local_version: UINT16,
/// ๊ฐ์ฒด ์์ฑ ์ ์ด๊ธฐ ํญ / Initial width
pub initial_width: UINT32,
/// ๊ฐ์ฒด ์์ฑ ์ ์ด๊ธฐ ๋์ด / Initial height
pub initial_height: UINT32,
/// ๊ฐ์ฒด์ ํ์ฌ ํญ / Current width
pub width: UINT32,
/// ๊ฐ์ฒด์ ํ์ฌ ๋์ด / Current height
pub height: UINT32,
/// ์์ฑ / Attributes
pub attributes: ShapeComponentAttributes,
/// ํ์ ๊ฐ / Rotation angle
pub rotation_angle: HWPUNIT16,
/// ํ์ ์ค์ฌ ์ขํ / Rotation center coordinates
pub rotation_center: RotationCenter,
/// Rendering ์ ๋ณด / Rendering information
pub rendering: RenderingInfo,
}
/// ๊ฐ์ฒด๊ฐ ์ํ ๊ทธ๋ฃน ๋ด์์์ offset / Offset within group
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct GroupOffset {
/// X offset
pub x: INT32,
/// Y offset
pub y: INT32,
}
/// ๊ฐ์ฒด ์์ ์์ฑ / Shape component attributes
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ShapeComponentAttributes {
/// ์ํ ๋ค์ง๊ธฐ / Horizontal flip
HorizontalFlip,
/// ์์ง ๋ค์ง๊ธฐ / Vertical flip
VerticalFlip,
}
/// ํ์ ์ค์ฌ ์ขํ / Rotation center coordinates
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct RotationCenter {
/// X ์ขํ(๊ฐ์ฒด ์ขํ๊ณ) / X coordinate (object coordinate system)
pub x: INT32,
/// Y ์ขํ(๊ฐ์ฒด ์ขํ๊ณ) / Y coordinate (object coordinate system)
pub y: INT32,
}
/// Rendering ์ ๋ณด / Rendering information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RenderingInfo {
/// scale matrix์ rotation matrix์์ ๊ฐ์ / Number of scale matrix and rotation matrix pairs
pub matrix_count: UINT16,
/// translation matrix / Translation matrix
pub translation_matrix: Matrix,
/// scale matrix/rotation matrix sequence / Scale matrix/rotation matrix sequence
pub matrix_sequence: Vec<MatrixPair>,
}
/// Matrix ์ ๋ณด / Matrix information
/// 3X3 matrix์ ์์ (๋ง์ง๋ง ์ค์ ํญ์ 0, 0, 1์ด๋ฏ๋ก ์ ์ฅ๋์ง ์์)
/// Elements of 3X3 matrix (last row is always 0, 0, 1 so not stored)
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct Matrix {
/// 3X2 matrix์ ์์ (6๊ฐ double ๊ฐ, 48๋ฐ์ดํธ) / Elements of 3X2 matrix (6 double values, 48 bytes)
pub elements: [f64; 6],
}
/// Matrix ์ / Matrix pair
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct MatrixPair {
/// Scale matrix
pub scale: Matrix,
/// Rotation matrix
pub rotation: Matrix,
}
impl ShapeComponent {
/// ShapeComponent๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ShapeComponent from byte array.
///
/// # Arguments
/// * `data` - ShapeComponent ๋ฐ์ดํฐ / ShapeComponent data
///
/// # Returns
/// ํ์ฑ๋ ShapeComponent ๊ตฌ์กฐ์ฒด / Parsed ShapeComponent structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 4 {
return Err(HwpError::insufficient_data("ShapeComponent", 4, data.len()));
}
let mut offset = 0;
// ํ 82: ๊ฐ์ฒด ์ปจํธ๋กค ID (UINT32, 4๋ฐ์ดํธ) / Table 82: Object control ID (UINT32, 4 bytes)
let ctrl_id_value1 = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ctrl_id๋ฅผ ๋ฌธ์์ด๋ก ๋ณํ (4๋ฐ์ดํธ ASCII) / Convert ctrl_id to string (4-byte ASCII)
let object_control_id = String::from_utf8_lossy(&data[offset - 4..offset])
.trim_end_matches('\0')
.trim_end_matches(' ')
.to_string();
// ์คํ ๋ฌธ์ ํ 82 ์ฃผ์: "GenShapeObject์ผ ๊ฒฝ์ฐ id๊ฐ ๋ ๋ฒ ๊ธฐ๋ก๋จ"
// ํ์ง๋ง ์ค์ ํ์ผ์์๋ ๋ชจ๋ SHAPE_COMPONENT์์ ๋ ๋ฒ์งธ ID๊ฐ ์กด์ฌํจ
// ๋ ๊ฑฐ์ ์ฝ๋๋ ํญ์ ๋ ๋ฒ์งธ ID๋ฅผ ์ฝ๊ณ ์์
// Spec Table 82 comment: "For GenShapeObject, ID is recorded twice"
// However, in actual files, second ID exists in all SHAPE_COMPONENT records
// Legacy code also always reads the second ID
let object_control_id2 = if data.len() >= offset + 4 {
// ๋ ๋ฒ์งธ ID ์ฝ๊ธฐ / Read second ID
let ctrl_id_value2 = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
Some(
String::from_utf8_lossy(&data[offset - 4..offset])
.trim_end_matches('\0')
.trim_end_matches(' ')
.to_string(),
)
} else {
None
};
// ํ 83: ๊ฐ์ฒด ์์ ์์ฑ / Table 83: Shape component attributes
if data.len() < offset + 42 {
return Err(HwpError::InsufficientData {
field: format!("ShapeComponent attributes at offset {}", offset),
expected: offset + 42,
actual: data.len(),
});
}
// INT32: ๊ฐ์ฒด๊ฐ ์ํ ๊ทธ๋ฃน ๋ด์์์ X offset / INT32: X offset within group
let group_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32: ๊ฐ์ฒด๊ฐ ์ํ ๊ทธ๋ฃน ๋ด์์์ Y offset / INT32: Y offset within group
let group_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// WORD: ๋ช ๋ฒ์ด๋ ๊ทธ๋ฃน ๋์๋์ง / WORD: Number of times grouped
let group_count = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// WORD: ๊ฐ์ฒด ์์์ local file version / WORD: Local file version
let local_version = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// UINT32: ๊ฐ์ฒด ์์ฑ ์ ์ด๊ธฐ ํญ / UINT32: Initial width
let initial_width = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// UINT32: ๊ฐ์ฒด ์์ฑ ์ ์ด๊ธฐ ๋์ด / UINT32: Initial height
let initial_height = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// UINT32: ๊ฐ์ฒด์ ํ์ฌ ํญ / UINT32: Current width
let width = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// UINT32: ๊ฐ์ฒด์ ํ์ฌ ๋์ด / UINT32: Current height
let height = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// UINT32: ์์ฑ / UINT32: Attributes
// 0: horz flip, 1: vert flip
let attribute_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let attributes = if attribute_value == 0 {
ShapeComponentAttributes::HorizontalFlip
} else {
ShapeComponentAttributes::VerticalFlip
};
// HWPUNIT16: ํ์ ๊ฐ / HWPUNIT16: Rotation angle
let rotation_angle = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// INT32: ํ์ ์ค์ฌ์ x ์ขํ(๊ฐ์ฒด ์ขํ๊ณ) / INT32: Rotation center x coordinate (object coordinate system)
let rotation_center_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// INT32: ํ์ ์ค์ฌ์ y ์ขํ(๊ฐ์ฒด ์ขํ๊ณ) / INT32: Rotation center y coordinate (object coordinate system)
let rotation_center_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 84: Rendering ์ ๋ณด / Table 84: Rendering information
if data.len() < offset + 2 {
return Err(HwpError::insufficient_data(
"ShapeComponent rendering info",
2,
data.len() - offset,
));
}
// WORD: scale matrix์ rotation matrix์์ ๊ฐ์ / WORD: Number of scale matrix and rotation matrix pairs
let matrix_count = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
// BYTE stream (48๋ฐ์ดํธ): translation matrix / BYTE stream (48 bytes): Translation matrix
if data.len() < offset + 48 {
return Err(HwpError::InsufficientData {
field: format!("ShapeComponent translation matrix at offset {}", offset),
expected: offset + 48,
actual: data.len(),
});
}
let translation_matrix =
parse_matrix(&data[offset..offset + 48]).map_err(|e| HwpError::from(e))?;
offset += 48;
// BYTE stream (cntร48ร2): scale matrix/rotation matrix sequence
let matrix_sequence_size = matrix_count as usize * 48 * 2;
if data.len() < offset + matrix_sequence_size {
return Err(HwpError::InsufficientData {
field: format!("ShapeComponent matrix sequence at offset {}", offset),
expected: offset + matrix_sequence_size,
actual: data.len(),
});
}
let mut matrix_sequence = Vec::new();
for i in 0..matrix_count as usize {
let seq_offset = offset + (i * 48 * 2);
let scale_matrix =
parse_matrix(&data[seq_offset..seq_offset + 48]).map_err(|e| HwpError::from(e))?;
let rotation_matrix = parse_matrix(&data[seq_offset + 48..seq_offset + 96])
.map_err(|e| HwpError::from(e))?;
matrix_sequence.push(MatrixPair {
scale: scale_matrix,
rotation: rotation_matrix,
});
}
let _ = offset + matrix_sequence_size; // offset์ ๋ ์ด์ ์ฌ์ฉ๋์ง ์์ / offset is no longer used
Ok(ShapeComponent {
object_control_id,
object_control_id2,
group_offset: GroupOffset {
x: group_x,
y: group_y,
},
group_count,
local_version,
initial_width,
initial_height,
width,
height,
attributes,
rotation_angle,
rotation_center: RotationCenter {
x: rotation_center_x,
y: rotation_center_y,
},
rendering: RenderingInfo {
matrix_count,
translation_matrix,
matrix_sequence,
},
})
}
}
/// Matrix ํ์ฑ (ํ 85) / Parse matrix (Table 85)
/// double array[6] (48๋ฐ์ดํธ) - 3X2 matrix์ ์์ / double array[6] (48 bytes) - Elements of 3X2 matrix
fn parse_matrix(data: &[u8]) -> Result<Matrix, HwpError> {
if data.len() < 48 {
return Err(HwpError::insufficient_data("Matrix", 48, data.len()));
}
let mut elements = [0.0; 6];
for (i, element) in elements.iter_mut().enumerate() {
let offset = i * 8;
*element = f64::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
data[offset + 4],
data[offset + 5],
data[offset + 6],
data[offset + 7],
]);
}
Ok(Matrix { elements })
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/shape_component/line.rs | crates/hwp-core/src/document/bodytext/shape_component/line.rs | /// ShapeComponentLine ๊ตฌ์กฐ์ฒด / ShapeComponentLine structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 92 - ์ ๊ฐ์ฒด ์์ฑ / Spec mapping: Table 92 - Line shape component attributes
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_LINE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain SHAPE_COMPONENT_LINE records
use crate::error::HwpError;
use crate::types::{INT32, UINT16};
use serde::{Deserialize, Serialize};
/// ์ ๊ฐ์ฒด / Line shape component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShapeComponentLine {
/// ์์์ / Start point
pub start_point: Point,
/// ๋์ / End point
pub end_point: Point,
/// ์์ฑ / Attributes
/// ์ฒ์ ์์ฑ ์ ์์ง ๋๋ ์ํ์ ์ผ ๋, ์ ์ ๋ฐฉํฅ์ด ์ธ์ ๋ ์ค๋ฅธ์ชฝ(์์ชฝ)์ผ๋ก ์กํ์ผ๋ก ์ธํ ํ์ ๋๋ฌธ์, ๋ฐฉํฅ์ ๋ฐ๋ก ์ก์์ฃผ๊ธฐ ์ํ ํ๋๊ทธ
/// Flag to correct direction when initially created as vertical or horizontal line,
/// as the direction is always set to right (up) due to a phenomenon
pub flag: UINT16,
}
/// ์ ์ขํ / Point coordinates
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct Point {
/// X ์ขํ / X coordinate
pub x: INT32,
/// Y ์ขํ / Y coordinate
pub y: INT32,
}
impl ShapeComponentLine {
/// ShapeComponentLine์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ShapeComponentLine from byte array.
///
/// # Arguments
/// * `data` - ShapeComponentLine ๋ฐ์ดํฐ (์ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง) / ShapeComponentLine data (line shape component attributes only)
///
/// # Returns
/// ํ์ฑ๋ ShapeComponentLine ๊ตฌ์กฐ์ฒด / Parsed ShapeComponentLine structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 91์ ๋ฐ๋ฅด๋ฉด SHAPE_COMPONENT_LINE์ ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋๋ค:
/// - ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 68 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ๊ทธ๋ฆฌ๊ธฐ ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 81 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ์ ๊ฐ์ฒด ์์ฑ(ํ 92 ์ฐธ์กฐ) - 18๋ฐ์ดํธ
///
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ ์ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง ํ์ฑํ๊ณ ์์ต๋๋ค.
/// According to spec Table 91, SHAPE_COMPONENT_LINE has the following structure:
/// - Object common properties (Table 68) - variable length
/// - Drawing object common properties (Table 81) - variable length
/// - Line shape component attributes (Table 92) - 18 bytes
///
/// Legacy code (hwp.js) only parses the line shape component attributes part.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_LINE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ SHAPE_COMPONENT_LINE ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain SHAPE_COMPONENT_LINE records, so it has not been verified with actual files.
/// If an actual HWP file contains SHAPE_COMPONENT_LINE records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ํ 92: ์ ๊ฐ์ฒด ์์ฑ์ 18๋ฐ์ดํธ / Table 92: Line shape component attributes is 18 bytes
// INT32(4) + INT32(4) + INT32(4) + INT32(4) + UINT16(2) = 18 bytes
if data.len() < 18 {
return Err(HwpError::insufficient_data("ShapeComponentLine", 18, data.len()));
}
let mut offset = 0;
// ํ 92: ์์์ X ์ขํ (INT32, 4๋ฐ์ดํธ) / Table 92: Start point X coordinate (INT32, 4 bytes)
let start_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 92: ์์์ Y ์ขํ (INT32, 4๋ฐ์ดํธ) / Table 92: Start point Y coordinate (INT32, 4 bytes)
let start_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 92: ๋์ X ์ขํ (INT32, 4๋ฐ์ดํธ) / Table 92: End point X coordinate (INT32, 4 bytes)
let end_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 92: ๋์ Y ์ขํ (INT32, 4๋ฐ์ดํธ) / Table 92: End point Y coordinate (INT32, 4 bytes)
let end_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 92: ์์ฑ (UINT16, 2๋ฐ์ดํธ) / Table 92: Attributes (UINT16, 2 bytes)
let flag = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
Ok(ShapeComponentLine {
start_point: Point {
x: start_x,
y: start_y,
},
end_point: Point { x: end_x, y: end_y },
flag,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/shape_component/ellipse.rs | crates/hwp-core/src/document/bodytext/shape_component/ellipse.rs | /// ShapeComponentEllipse ๊ตฌ์กฐ์ฒด / ShapeComponentEllipse structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 96 - ํ์ ๊ฐ์ฒด ์์ฑ / Spec mapping: Table 96 - Ellipse shape component attributes
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_ELLIPSE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain SHAPE_COMPONENT_ELLIPSE records
use crate::error::HwpError;
use crate::types::{INT32, UINT32};
use serde::{Deserialize, Serialize};
/// ํ์ ๊ฐ์ฒด / Ellipse shape component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShapeComponentEllipse {
/// ์์ฑ / Attributes (ํ 97 ์ฐธ์กฐ / See Table 97)
pub attributes: EllipseArcAttributes,
/// ์ค์ฌ ์ขํ / Center coordinates
pub center: Point,
/// ์ 1์ถ ์ขํ / First axis coordinates
pub axis1: Point,
/// ์ 2์ถ ์ขํ / Second axis coordinates
pub axis2: Point,
/// ์์ ์์น / Start position
pub start_pos: Point,
/// ๋ ์์น / End position
pub end_pos: Point,
/// ์์ ์์น 2 / Start position 2
pub start_pos2: Point,
/// ๊ณก์ ๊ฐ๊ฒฉ (ํธ์ผ ๋๋ง ์ ํจ) / Interval of curve (effective only when it is an arc)
pub interval: INT32,
/// ๋ ์์น 2 / End position 2
pub end_pos2: Point,
}
/// ํ์/ํธ ๊ฐ์ฒด ์์ฑ / Ellipse/Arc shape component attributes
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct EllipseArcAttributes {
/// ํธ(ARC)๋ก ๋ฐ๋์์ ๋, interval์ ๋ค์ ๊ณ์ฐํด์ผ ํ ํ์๊ฐ ์๋์ง ์ฌ๋ถ / Whether interval needs to be recalculated when changed to ARC
/// (interval - ์ ์์ ์กด์ฌํ๋ ๋ ์ ์ฌ์ด์ ๊ฑฐ๋ฆฌ) / (interval - distance between two points on the circle)
pub needs_interval_recalculation: bool,
/// ํธ(ARC)๋ก ๋ฐ๋์๋์ง ์ฌ๋ถ / Whether it has been changed to ARC
pub is_arc: bool,
/// ํธ(ARC)์ ์ข
๋ฅ / ARC type
pub arc_type: u8,
}
/// ์ ์ขํ / Point coordinates
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct Point {
/// X ์ขํ / X coordinate
pub x: INT32,
/// Y ์ขํ / Y coordinate
pub y: INT32,
}
impl ShapeComponentEllipse {
/// ShapeComponentEllipse์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ShapeComponentEllipse from byte array.
///
/// # Arguments
/// * `data` - ShapeComponentEllipse ๋ฐ์ดํฐ (ํ์ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง) / ShapeComponentEllipse data (ellipse shape component attributes only)
///
/// # Returns
/// ํ์ฑ๋ ShapeComponentEllipse ๊ตฌ์กฐ์ฒด / Parsed ShapeComponentEllipse structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 95์ ๋ฐ๋ฅด๋ฉด SHAPE_COMPONENT_ELLIPSE์ ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋๋ค:
/// - ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 68 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ๊ทธ๋ฆฌ๊ธฐ ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 81 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ํ์ ๊ฐ์ฒด ์์ฑ(ํ 96 ์ฐธ์กฐ) - 60๋ฐ์ดํธ
///
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ ํ์ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง ํ์ฑํ๊ณ ์์ต๋๋ค.
/// According to spec Table 95, SHAPE_COMPONENT_ELLIPSE has the following structure:
/// - Object common properties (Table 68) - variable length
/// - Drawing object common properties (Table 81) - variable length
/// - Ellipse shape component attributes (Table 96) - 60 bytes
///
/// Legacy code (hwp.js) only parses the ellipse shape component attributes part.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_ELLIPSE ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ SHAPE_COMPONENT_ELLIPSE ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain SHAPE_COMPONENT_ELLIPSE records, so it has not been verified with actual files.
/// If an actual HWP file contains SHAPE_COMPONENT_ELLIPSE records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ํ 96: ํ์ ๊ฐ์ฒด ์์ฑ์ 60๋ฐ์ดํธ / Table 96: Ellipse shape component attributes is 60 bytes
// UINT32(4) + INT32(4) * 14 = 60 bytes
if data.len() < 60 {
return Err(HwpError::insufficient_data("ShapeComponentEllipse", 60, data.len()));
}
let mut offset = 0;
// ํ 96: ์์ฑ (UINT32, 4๋ฐ์ดํธ) / Table 96: Attributes (UINT32, 4 bytes)
let attr_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 97: ์์ฑ ๋นํธ ํ๋ ํ์ฑ / Table 97: Parse attribute bit fields
let needs_interval_recalculation = (attr_value & 0x01) != 0; // bit 0
let is_arc = (attr_value & 0x02) != 0; // bit 1
let arc_type = ((attr_value >> 2) & 0xFF) as u8; // bit 2-9
// ํ 96: ์ค์ฌ ์ขํ์ X ๊ฐ (INT32, 4๋ฐ์ดํธ) / Table 96: Center X coordinate (INT32, 4 bytes)
let center_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: ์ค์ฌ ์ขํ์ Y ๊ฐ (INT32, 4๋ฐ์ดํธ) / Table 96: Center Y coordinate (INT32, 4 bytes)
let center_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: ์ 1์ถ X ์ขํ ๊ฐ (INT32, 4๋ฐ์ดํธ) / Table 96: First axis X coordinate (INT32, 4 bytes)
let axis1_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: ์ 1์ถ Y ์ขํ ๊ฐ (INT32, 4๋ฐ์ดํธ) / Table 96: First axis Y coordinate (INT32, 4 bytes)
let axis1_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: ์ 2์ถ X ์ขํ ๊ฐ (INT32, 4๋ฐ์ดํธ) / Table 96: Second axis X coordinate (INT32, 4 bytes)
let axis2_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: ์ 2์ถ Y ์ขํ ๊ฐ (INT32, 4๋ฐ์ดํธ) / Table 96: Second axis Y coordinate (INT32, 4 bytes)
let axis2_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: start pos x (INT32, 4๋ฐ์ดํธ) / Table 96: Start position X (INT32, 4 bytes)
let start_pos_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: start pos y (INT32, 4๋ฐ์ดํธ) / Table 96: Start position Y (INT32, 4 bytes)
let start_pos_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: end pos x (INT32, 4๋ฐ์ดํธ) / Table 96: End position X (INT32, 4 bytes)
let end_pos_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: end pos y (INT32, 4๋ฐ์ดํธ) / Table 96: End position Y (INT32, 4 bytes)
let end_pos_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: start pos x2 (INT32, 4๋ฐ์ดํธ) / Table 96: Start position X2 (INT32, 4 bytes)
let start_pos2_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: interval of curve (INT32, 4๋ฐ์ดํธ) / Table 96: Interval of curve (INT32, 4 bytes)
let interval = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: start pos y2 (INT32, 4๋ฐ์ดํธ) / Table 96: Start position Y2 (INT32, 4 bytes)
let start_pos2_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: end pos x2 (INT32, 4๋ฐ์ดํธ) / Table 96: End position X2 (INT32, 4 bytes)
let end_pos_x2 = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 96: end pos y2 (INT32, 4๋ฐ์ดํธ) / Table 96: End position Y2 (INT32, 4 bytes)
let end_pos_y2 = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
Ok(ShapeComponentEllipse {
attributes: EllipseArcAttributes {
needs_interval_recalculation,
is_arc,
arc_type,
},
center: Point {
x: center_x,
y: center_y,
},
axis1: Point {
x: axis1_x,
y: axis1_y,
},
axis2: Point {
x: axis2_x,
y: axis2_y,
},
start_pos: Point {
x: start_pos_x,
y: start_pos_y,
},
end_pos: Point {
x: end_pos_x,
y: end_pos_y,
},
start_pos2: Point {
x: start_pos2_x,
y: start_pos2_y,
},
interval,
end_pos2: Point {
x: end_pos_x2,
y: end_pos_y2,
},
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/shape_component/arc.rs | crates/hwp-core/src/document/bodytext/shape_component/arc.rs | /// ShapeComponentArc ๊ตฌ์กฐ์ฒด / ShapeComponentArc structure
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 101 - ํธ ๊ฐ์ฒด ์์ฑ / Spec mapping: Table 101 - Arc shape component attributes
///
/// **๊ตฌํ ์ํ / Implementation Status**
/// - ๊ตฌํ ์๋ฃ / Implementation complete
/// - ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_ARC ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ํ
์คํธ๋์ง ์์
/// - Implementation complete, but not tested with actual file as test file (`noori.hwp`) does not contain SHAPE_COMPONENT_ARC records
use crate::error::HwpError;
use crate::types::{INT32, UINT32};
use serde::{Deserialize, Serialize};
/// ํธ ๊ฐ์ฒด / Arc shape component
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShapeComponentArc {
/// ์์ฑ / Attributes (ํ 97 ์ฐธ์กฐ / See Table 97)
pub attributes: EllipseArcAttributes,
/// ํ์์ ์ค์ฌ ์ขํ / Ellipse center coordinates
pub ellipse_center: Point,
/// ์ 1์ถ ์ขํ / First axis coordinates
pub axis1: Point,
/// ์ 2์ถ ์ขํ / Second axis coordinates
pub axis2: Point,
}
/// ํ์/ํธ ๊ฐ์ฒด ์์ฑ / Ellipse/Arc shape component attributes
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct EllipseArcAttributes {
/// ํธ(ARC)๋ก ๋ฐ๋์์ ๋, interval์ ๋ค์ ๊ณ์ฐํด์ผ ํ ํ์๊ฐ ์๋์ง ์ฌ๋ถ / Whether interval needs to be recalculated when changed to ARC
/// (interval - ์ ์์ ์กด์ฌํ๋ ๋ ์ ์ฌ์ด์ ๊ฑฐ๋ฆฌ) / (interval - distance between two points on the circle)
pub needs_interval_recalculation: bool,
/// ํธ(ARC)๋ก ๋ฐ๋์๋์ง ์ฌ๋ถ / Whether it has been changed to ARC
pub is_arc: bool,
/// ํธ(ARC)์ ์ข
๋ฅ / ARC type
pub arc_type: u8,
}
/// ์ ์ขํ / Point coordinates
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct Point {
/// X ์ขํ / X coordinate
pub x: INT32,
/// Y ์ขํ / Y coordinate
pub y: INT32,
}
impl ShapeComponentArc {
/// ShapeComponentArc์ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse ShapeComponentArc from byte array.
///
/// # Arguments
/// * `data` - ShapeComponentArc ๋ฐ์ดํฐ (ํธ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง) / ShapeComponentArc data (arc shape component attributes only)
///
/// # Returns
/// ํ์ฑ๋ ShapeComponentArc ๊ตฌ์กฐ์ฒด / Parsed ShapeComponentArc structure
///
/// # Note
/// ์คํ ๋ฌธ์ ํ 100์ ๋ฐ๋ฅด๋ฉด SHAPE_COMPONENT_ARC์ ๋ค์ ๊ตฌ์กฐ๋ฅผ ๊ฐ์ง๋๋ค:
/// - ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 68 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ๊ทธ๋ฆฌ๊ธฐ ๊ฐ์ฒด ๊ณตํต ์์ฑ(ํ 81 ์ฐธ์กฐ) - ๊ฐ๋ณ ๊ธธ์ด
/// - ํธ ๊ฐ์ฒด ์์ฑ(ํ 101 ์ฐธ์กฐ) - 28๋ฐ์ดํธ
///
/// ๋ ๊ฑฐ์ ์ฝ๋(hwp.js)๋ ํธ ๊ฐ์ฒด ์์ฑ ๋ถ๋ถ๋ง ํ์ฑํ๊ณ ์์ต๋๋ค.
/// According to spec Table 100, SHAPE_COMPONENT_ARC has the following structure:
/// - Object common properties (Table 68) - variable length
/// - Drawing object common properties (Table 81) - variable length
/// - Arc shape component attributes (Table 101) - 28 bytes
///
/// Legacy code (hwp.js) only parses the arc shape component attributes part.
///
/// **ํ
์คํธ ์ํ / Testing Status**
/// ํ์ฌ ํ
์คํธ ํ์ผ(`noori.hwp`)์ SHAPE_COMPONENT_ARC ๋ ์ฝ๋๊ฐ ์์ด ์ค์ ํ์ผ๋ก ๊ฒ์ฆ๋์ง ์์์ต๋๋ค.
/// ์ค์ HWP ํ์ผ์ SHAPE_COMPONENT_ARC ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด ์๋์ผ๋ก ํ์ฑ๋ฉ๋๋ค.
/// Current test file (`noori.hwp`) does not contain SHAPE_COMPONENT_ARC records, so it has not been verified with actual files.
/// If an actual HWP file contains SHAPE_COMPONENT_ARC records, they will be automatically parsed.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
// ํ 101: ํธ ๊ฐ์ฒด ์์ฑ์ 28๋ฐ์ดํธ / Table 101: Arc shape component attributes is 28 bytes
// UINT32(4) + INT32(4) * 6 = 28 bytes
if data.len() < 28 {
return Err(HwpError::insufficient_data("ShapeComponentArc", 28, data.len()));
}
let mut offset = 0;
// ํ 101: ์์ฑ (UINT32, 4๋ฐ์ดํธ) / Table 101: Attributes (UINT32, 4 bytes)
let attr_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 97: ์์ฑ ๋นํธ ํ๋ ํ์ฑ / Table 97: Parse attribute bit fields
let needs_interval_recalculation = (attr_value & 0x01) != 0; // bit 0
let is_arc = (attr_value & 0x02) != 0; // bit 1
let arc_type = ((attr_value >> 2) & 0xFF) as u8; // bit 2-9
// ํ 101: ํ์์ ์ค์ฌ ์ขํ X ๊ฐ (INT32, 4๋ฐ์ดํธ) / Table 101: Ellipse center X coordinate (INT32, 4 bytes)
let center_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 101: ํ์์ ์ค์ฌ ์ขํ Y ๊ฐ (INT32, 4๋ฐ์ดํธ) / Table 101: Ellipse center Y coordinate (INT32, 4 bytes)
let center_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 101: ์ 1์ถ X ์ขํ ๊ฐ (INT32, 4๋ฐ์ดํธ) / Table 101: First axis X coordinate (INT32, 4 bytes)
let axis1_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 101: ์ 1์ถ Y ์ขํ ๊ฐ (INT32, 4๋ฐ์ดํธ) / Table 101: First axis Y coordinate (INT32, 4 bytes)
let axis1_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 101: ์ 2์ถ X ์ขํ ๊ฐ (INT32, 4๋ฐ์ดํธ) / Table 101: Second axis X coordinate (INT32, 4 bytes)
let axis2_x = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
// ํ 101: ์ 2์ถ Y ์ขํ ๊ฐ (INT32, 4๋ฐ์ดํธ) / Table 101: Second axis Y coordinate (INT32, 4 bytes)
let axis2_y = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
Ok(ShapeComponentArc {
attributes: EllipseArcAttributes {
needs_interval_recalculation,
is_arc,
arc_type,
},
ellipse_center: Point {
x: center_x,
y: center_y,
},
axis1: Point {
x: axis1_x,
y: axis1_y,
},
axis2: Point {
x: axis2_x,
y: axis2_y,
},
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/field.rs | crates/hwp-core/src/document/bodytext/ctrl_header/field.rs | use crate::error::HwpError;
use crate::types::decode_utf16le;
use crate::types::{UINT16, UINT32, UINT8};
use super::types::CtrlHeaderData;
/// ํ๋ ํ์ฑ (ํ 152) / Parse field (Table 152)
pub(crate) fn parse_field(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 15 {
return Err(HwpError::insufficient_data("Field data", 15, data.len()));
}
let mut offset = 0usize;
let field_type_bytes = [
data[offset + 3],
data[offset + 2],
data[offset + 1],
data[offset],
];
let field_type = String::from_utf8_lossy(&field_type_bytes)
.trim_end_matches('\0')
.to_string();
offset += 4;
let attribute = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let other_attr = UINT8::from_le_bytes([data[offset]]);
offset += 1;
let command_len = UINT16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
let command = if command_len > 0 && offset + (command_len * 2) <= data.len() {
let command_bytes = &data[offset..offset + (command_len * 2)];
decode_utf16le(command_bytes).unwrap_or_default()
} else {
String::new()
};
offset += command_len * 2;
let id = if offset + 4 <= data.len() {
UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
])
} else {
0
};
Ok(CtrlHeaderData::Field {
field_type,
attribute,
other_attr,
command_len: command_len as UINT16,
command,
id,
})
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/object_common.rs | crates/hwp-core/src/document/bodytext/ctrl_header/object_common.rs | use crate::error::HwpError;
use crate::types::decode_utf16le;
use crate::types::{HWPUNIT, HWPUNIT16, INT32, SHWPUNIT, UINT16, UINT32};
use super::types::{
CtrlHeaderData, HorzRelTo, Margin, ObjectAttribute, ObjectCategory, ObjectHeightStandard,
ObjectTextOption, ObjectTextPositionOption, ObjectWidthStandard, VertRelTo,
};
/// ๊ฐ์ฒด ๊ณตํต ์์ฑ ํ์ฑ (ํ 69) / Parse object common properties (Table 69)
pub(crate) fn parse_object_common(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 40 {
return Err(HwpError::insufficient_data(
"Object common properties",
40,
data.len(),
));
}
let mut offset = 0usize;
let attribute_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let offset_y = SHWPUNIT::from(INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
let offset_x = SHWPUNIT::from(INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
let width = HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
let height = HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]));
offset += 4;
let z_order = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let margin_bottom = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let margin_left = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let margin_right = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let margin_top = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let instance_id = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let page_divide = INT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let description = if offset + 2 <= data.len() {
let description_len = UINT16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
if description_len > 0 && offset + (description_len * 2) <= data.len() {
let description_bytes = &data[offset..offset + (description_len * 2)];
match decode_utf16le(description_bytes) {
Ok(text) if !text.is_empty() => Some(text),
_ => None,
}
} else {
None
}
} else {
None
};
let attribute = parse_object_attribute(attribute_value);
Ok(CtrlHeaderData::ObjectCommon {
attribute,
offset_y,
offset_x,
width,
height,
z_order,
margin: Margin {
top: margin_top,
right: margin_right,
bottom: margin_bottom,
left: margin_left,
},
instance_id,
page_divide,
description,
caption: None,
})
}
/// ๊ฐ์ฒด ์์ฑ ํ์ฑ (ํ 70) / Parse object attribute (Table 70)
fn parse_object_attribute(value: UINT32) -> ObjectAttribute {
let like_letters = (value & 0x01) != 0;
let affect_line_spacing = (value & 0x04) != 0;
let vert_rel_to = match (value >> 3) & 0x03 {
0 => VertRelTo::Paper,
1 => VertRelTo::Page,
2 => VertRelTo::Para,
_ => VertRelTo::Para,
};
let vert_relative = ((value >> 5) & 0x07) as u8;
// NOTE (HWP spec Table 70):
// vert_rel_to has Paper/Page/Para; horz_rel_to also has Paper/Page/Column/Para.
// Previously we collapsed (0|1) into Page which loses "paper" anchors and breaks fixtures
// (e.g. table-position 'ํ 5' should be paper-left 35mm, but became page-left 65mm).
let horz_rel_to = match (value >> 8) & 0x03 {
0 => HorzRelTo::Paper,
1 => HorzRelTo::Page,
2 => HorzRelTo::Column,
3 => HorzRelTo::Para,
_ => HorzRelTo::Page,
};
let horz_relative = ((value >> 10) & 0x07) as u8;
let vert_rel_to_para_limit = (value & 0x2000) != 0;
let overlap = (value & 0x4000) != 0;
let object_width_standard = match (value >> 15) & 0x07 {
0 => ObjectWidthStandard::Paper,
1 => ObjectWidthStandard::Page,
2 => ObjectWidthStandard::Column,
3 => ObjectWidthStandard::Para,
4 => ObjectWidthStandard::Absolute,
_ => ObjectWidthStandard::Absolute,
};
let object_height_standard = match (value >> 18) & 0x03 {
0 => ObjectHeightStandard::Paper,
1 => ObjectHeightStandard::Page,
2 => ObjectHeightStandard::Absolute,
_ => ObjectHeightStandard::Absolute,
};
let object_text_option = match (value >> 21) & 0x07 {
0 => ObjectTextOption::Square,
1 => ObjectTextOption::Tight,
2 => ObjectTextOption::Through,
3 => ObjectTextOption::TopAndBottom,
4 => ObjectTextOption::BehindText,
5 => ObjectTextOption::InFrontOfText,
_ => ObjectTextOption::Square,
};
let object_text_position_option = match (value >> 24) & 0x03 {
0 => ObjectTextPositionOption::BothSides,
1 => ObjectTextPositionOption::LeftOnly,
2 => ObjectTextPositionOption::RightOnly,
3 => ObjectTextPositionOption::LargestOnly,
_ => ObjectTextPositionOption::BothSides,
};
let object_category = match (value >> 26) & 0x07 {
0 => ObjectCategory::None,
1 => ObjectCategory::Figure,
2 => ObjectCategory::Table,
3 => ObjectCategory::Equation,
_ => ObjectCategory::None,
};
let size_protect = (value & 0x100000) != 0;
ObjectAttribute {
like_letters,
affect_line_spacing,
vert_rel_to,
vert_relative,
horz_rel_to,
horz_relative,
vert_rel_to_para_limit,
overlap,
object_width_standard,
object_height_standard,
object_text_option,
object_text_position_option,
object_category,
size_protect,
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/bookmark_marker.rs | crates/hwp-core/src/document/bodytext/ctrl_header/bookmark_marker.rs | use crate::error::HwpError;
use crate::types::decode_utf16le;
use crate::types::UINT16;
use super::types::CtrlHeaderData;
/// ์ฐพ์๋ณด๊ธฐ ํ์ ํ์ฑ (ํ 149) / Parse bookmark marker (Table 149)
pub(crate) fn parse_bookmark_marker(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 6 {
return Err(HwpError::insufficient_data("Bookmark marker", 6, data.len()));
}
let mut offset = 0usize;
let keyword1_len = UINT16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
let keyword1 = if keyword1_len > 0 && offset + (keyword1_len * 2) <= data.len() {
let keyword1_bytes = &data[offset..offset + (keyword1_len * 2)];
decode_utf16le(keyword1_bytes).unwrap_or_default()
} else {
String::new()
};
offset += keyword1_len * 2;
let keyword2_len = if offset + 2 <= data.len() {
UINT16::from_le_bytes([data[offset], data[offset + 1]]) as usize
} else {
0
};
offset += 2;
let keyword2 = if keyword2_len > 0 && offset + (keyword2_len * 2) <= data.len() {
let keyword2_bytes = &data[offset..offset + (keyword2_len * 2)];
decode_utf16le(keyword2_bytes).unwrap_or_default()
} else {
String::new()
};
Ok(CtrlHeaderData::BookmarkMarker { keyword1, keyword2 })
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/page_number_position.rs | crates/hwp-core/src/document/bodytext/ctrl_header/page_number_position.rs | use crate::error::HwpError;
use crate::types::decode_utf16le;
use crate::types::UINT32;
use super::types::{CtrlHeaderData, PageNumberPosition, PageNumberPositionFlags};
/// ์ชฝ ๋ฒํธ ์์น ํ์ฑ (ํ 147) / Parse page number position (Table 147)
pub(crate) fn parse_page_number_position(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 12 {
return Err(HwpError::insufficient_data(
"PageNumberPosition",
12,
data.len(),
));
}
let mut offset = 0usize;
let flags_value = UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]);
offset += 4;
let shape = (flags_value & 0xFF) as u8;
let position = match (flags_value >> 8) & 0x0F {
0 => PageNumberPosition::None,
1 => PageNumberPosition::TopLeft,
2 => PageNumberPosition::TopCenter,
3 => PageNumberPosition::TopRight,
4 => PageNumberPosition::BottomLeft,
5 => PageNumberPosition::BottomCenter,
6 => PageNumberPosition::BottomRight,
7 => PageNumberPosition::OutsideTop,
8 => PageNumberPosition::OutsideBottom,
9 => PageNumberPosition::InsideTop,
10 => PageNumberPosition::InsideBottom,
_ => PageNumberPosition::None,
};
let flags = PageNumberPositionFlags { shape, position };
let user_symbol = decode_utf16le(&data[offset..offset + 2])?;
offset += 2;
let prefix = decode_utf16le(&data[offset..offset + 2])?;
offset += 2;
let suffix = decode_utf16le(&data[offset..offset + 2])?;
Ok(CtrlHeaderData::PageNumberPosition {
flags,
user_symbol,
prefix,
suffix,
})
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/footnote_endnote.rs | crates/hwp-core/src/document/bodytext/ctrl_header/footnote_endnote.rs | use crate::error::HwpError;
use super::types::CtrlHeaderData;
/// ๊ฐ์ฃผ/๋ฏธ์ฃผ ํ์ฑ (ํ 4.3.10.4) / Parse footnote/endnote (Table 4.3.10.4)
pub(crate) fn parse_footnote_endnote(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 8 {
return Err(HwpError::insufficient_data(
"Footnote/endnote",
8,
data.len(),
));
}
let number = data[0];
let mut reserved = [0u8; 5];
reserved.copy_from_slice(&data[1..6]);
let attribute = data[6];
let reserved2 = data[7];
Ok(CtrlHeaderData::FootnoteEndnote {
number,
reserved,
attribute,
reserved2,
})
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/hide.rs | crates/hwp-core/src/document/bodytext/ctrl_header/hide.rs | use crate::error::HwpError;
use crate::types::UINT16;
use super::types::CtrlHeaderData;
/// ๊ฐ์ถ๊ธฐ ํ์ฑ (ํ 145) / Parse hide (Table 145)
pub(crate) fn parse_hide(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 2 {
return Err(HwpError::insufficient_data("Hide", 2, data.len()));
}
let attribute = UINT16::from_le_bytes([data[0], data[1]]);
Ok(CtrlHeaderData::Hide { attribute })
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/header_footer.rs | crates/hwp-core/src/document/bodytext/ctrl_header/header_footer.rs | use crate::error::HwpError;
use crate::types::{HWPUNIT, UINT32};
use super::types::{ApplyPage, CtrlHeaderData, HeaderFooterAttribute};
/// ๋จธ๋ฆฌ๋ง/๊ผฌ๋ฆฌ๋ง ํ์ฑ (ํ 140) / Parse header/footer (Table 140)
pub(crate) fn parse_header_footer(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 4 {
return Err(HwpError::insufficient_data("Header/Footer", 4, data.len()));
}
let mut offset = 0usize;
let attribute_value =
UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);
offset += 4;
let apply_page = match attribute_value & 0x03 {
0 => ApplyPage::Both,
1 => ApplyPage::EvenOnly,
2 => ApplyPage::OddOnly,
_ => ApplyPage::Both,
};
let attribute = HeaderFooterAttribute { apply_page };
let text_width = if offset + 4 <= data.len() {
HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]))
} else {
HWPUNIT::from(0)
};
offset += 4;
let text_height = if offset + 4 <= data.len() {
HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]))
} else {
HWPUNIT::from(0)
};
offset += 4;
let text_ref = if offset < data.len() { data[offset] } else { 0 };
offset += 1;
let number_ref = if offset < data.len() { data[offset] } else { 0 };
Ok(CtrlHeaderData::HeaderFooter {
attribute,
text_width,
text_height,
text_ref,
number_ref,
})
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/ids.rs | crates/hwp-core/src/document/bodytext/ctrl_header/ids.rs | /// ์ปจํธ๋กค ID ์์ ์ ์ / Control ID constants definition
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 127 - ๊ฐ์ฒด ์ด์ธ์ ์ปจํธ๋กค๊ณผ ์ปจํธ๋กค ID, ํ 128 - ํ๋ ์ปจํธ๋กค ID
/// Spec mapping: Table 127 - Controls other than objects and Control IDs, Table 128 - Field Control IDs
pub struct CtrlId;
impl CtrlId {
// ๊ฐ์ฒด ์ปจํธ๋กค ID / Object Control IDs
/// ํ
์ด๋ธ ์ปจํธ๋กค / Table control
/// ๊ฐ์ฒด ๊ณตํต ์์ฑ์ ๊ฐ์ง๋ ์ปจํธ๋กค ID / Control ID with object common properties
pub const TABLE: &str = "tbl ";
/// ์ผ๋ฐ ๊ทธ๋ฆฌ๊ธฐ ๊ฐ์ฒด / General shape object
/// ๊ฐ์ฒด ๊ณตํต ์์ฑ์ ๊ฐ์ง๋ ์ปจํธ๋กค ID / Control ID with object common properties
pub const SHAPE_OBJECT: &str = "gso ";
// ํ 127: ๊ฐ์ฒด ์ด์ธ์ ์ปจํธ๋กค๊ณผ ์ปจํธ๋กค ID / Table 127: Controls other than objects and Control IDs
/// ๊ตฌ์ญ ์ ์ / Section definition
/// ์คํ ๋ฌธ์: ํ 127, ํ 129 ์ฐธ์กฐ / Spec: See Table 127, Table 129
pub const SECTION_DEF: &str = "secd";
/// ๋จ ์ ์ / Column definition
pub const COLUMN_DEF: &str = "cold";
/// ๋จธ๋ฆฌ๋ง / Header
pub const HEADER: &str = "head";
/// ๊ผฌ๋ฆฌ๋ง / Footer
pub const FOOTER: &str = "foot";
/// ๊ฐ์ฃผ / Footnote (๊ณต๋ฐฑ ํฌํจ)
pub const FOOTNOTE: &str = "fn ";
/// ๋ฏธ์ฃผ / Endnote (๊ณต๋ฐฑ ํฌํจ)
pub const ENDNOTE: &str = "en ";
/// ๋จธ๋ฆฌ๋ง/๊ผฌ๋ฆฌ๋ง (๋ ๊ฑฐ์ ํธํ์ฉ) / Header/Footer (legacy compatibility)
#[deprecated(note = "Use HEADER or FOOTER instead")]
pub const HEADER_FOOTER: &str = "head";
/// ์๋๋ฒํธ / Auto numbering
///
/// NOTE:
/// - ์ค์ ํ์ผ/๋ ๊ฑฐ์ ๊ตฌํ์์ `"atno"`๋ก ๋ํ๋๋ ๊ฒฝ์ฐ๊ฐ ์์ต๋๋ค.
/// - ๋ฐ๋ผ์ ํ์๋ `"autn"`๊ณผ `"atno"` ๋ชจ๋๋ฅผ ์๋๋ฒํธ ์ปจํธ๋กค๋ก ์ฒ๋ฆฌํฉ๋๋ค.
pub const AUTO_NUMBER: &str = "autn";
/// ์๋๋ฒํธ(๋์ฒด CHID) / Auto numbering (alternate CHID)
pub const AUTO_NUMBER_ALT: &str = "atno";
/// ์ ๋ฒํธ ์ง์ / New number specification
pub const NEW_NUMBER: &str = "newn";
/// ๊ฐ์ถ๊ธฐ / Hide
pub const HIDE: &str = "pghd";
/// ํ/์ง์ ์กฐ์ / Odd/Even page adjustment
pub const PAGE_ADJUST: &str = "pgad";
/// ์ชฝ ๋ฒํธ ์์น / Page number position
pub const PAGE_NUMBER: &str = "pgno";
/// ์ชฝ ๋ฒํธ ์์น (pgnp) / Page number position (pgnp)
pub const PAGE_NUMBER_POS: &str = "pgnp";
/// ์ฐพ์๋ณด๊ธฐ ํ์ / Bookmark marker
pub const BOOKMARK_MARKER: &str = "bkmk";
/// ๊ธ์ ๊ฒน์นจ / Character overlap
pub const OVERLAP: &str = "over";
/// ๋ง๋ง / Comment
pub const COMMENT: &str = "cmtt";
/// ์จ์ ์ค๋ช
/ Hidden description
pub const HIDDEN_DESC: &str = "hide";
/// ํ๋ ์์ / Field start
pub const FIELD_START: &str = "%%%%";
// ํ 128: ํ๋ ์ปจํธ๋กค ID / Table 128: Field Control IDs
pub const FIELD_UNKNOWN: &str = "%unk";
pub const FIELD_DATE: &str = "%dte";
pub const FIELD_DOC_DATE: &str = "%ddt";
pub const FIELD_PATH: &str = "%pat";
pub const FIELD_BOOKMARK: &str = "%bmk";
pub const FIELD_CROSS_REF: &str = "%xrf";
pub const FIELD_FORMULA: &str = "%eqr";
pub const FIELD_DOCSUMMARY: &str = "%dsm";
pub const FIELD_USER: &str = "%usr";
pub const FIELD_MAIL_MERGE: &str = "%mmg";
pub const FIELD_HYPERLINK: &str = "%hlk";
pub const FIELD_REVISION: &str = "%rvs";
pub const FIELD_OUTLINE: &str = "%out";
pub const FIELD_TABLE_OF_CONTENTS: &str = "%toc";
pub const FIELD_INDEXMARK: &str = "%idx";
pub const FIELD_PAGECTRL: &str = "%pgc";
pub const FIELD_HWP_SUMMARY: &str = "%hsm";
pub const FIELD_KOGL: &str = "%kgl";
pub const FIELD_GLOSSARY: &str = "%gls";
pub const FIELD_INPUT: &str = "%inp";
pub const FIELD_CHANGE: &str = "%chg";
pub const FIELD_FILE: &str = "%fil";
pub const FIELD_PAGE_NUM: &str = "%pgn";
pub const FIELD_DOC_TITLE: &str = "%ttl";
pub const FIELD_DOC_AUTHOR: &str = "%aut";
pub const FIELD_DOC_KEYWORD: &str = "%key";
pub const FIELD_DOC_SUBJECT: &str = "%sub";
pub const FIELD_DOC_COMMENT: &str = "%cmt";
pub const FIELD_DOC_LASTSAVEDBY: &str = "%lsb";
pub const FIELD_DOC_REVISION: &str = "%rev";
pub const FIELD_DOC_LASTPRINTED: &str = "%lpt";
pub const FIELD_DOC_CREATED: &str = "%crt";
pub const FIELD_DOC_LASTSAVED: &str = "%sav";
pub const FIELD_DOC_PAGECOUNT: &str = "%pgc";
pub const FIELD_DOC_WORDCOUNT: &str = "%wct";
pub const FIELD_DOC_CHARCOUNT: &str = "%cct";
pub const FIELD_PRIVATE_INFO_SECURITY: &str = "%cpr";
pub const FIELD_TABLE_OF_CONTENTS_ALT: &str = "%oc";
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/types.rs | crates/hwp-core/src/document/bodytext/ctrl_header/types.rs | use crate::types::{HWPUNIT, HWPUNIT16, INT32, INT8, SHWPUNIT, UINT16, UINT32, UINT8};
use serde::{Deserialize, Serialize};
/// ์ปจํธ๋กค ํค๋ / Control header
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CtrlHeader {
/// ์ปจํธ๋กค ID (4๋ฐ์ดํธ, ASCII ๋ฌธ์์ด๋ก ํด์ ๊ฐ๋ฅ) / Control ID (4 bytes, can be interpreted as ASCII string)
pub ctrl_id: String,
/// ์ปจํธ๋กค ID ๊ฐ (UINT32) / Control ID value (UINT32)
pub ctrl_id_value: UINT32,
/// ์ปจํธ๋กค ID ์ดํ์ ๋ฐ์ดํฐ (CtrlID์ ๋ฐ๋ผ ๋ค๋ฆ) / Data after control ID (varies by CtrlID)
#[serde(flatten)]
pub data: CtrlHeaderData,
}
/// ์บก์
์ ๋ ฌ (ํ 73) / Caption alignment (Table 73)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CaptionAlign {
Left = 0,
Right = 1,
Top = 2,
Bottom = 3,
}
/// ์บก์
์์ง ์ ๋ ฌ (ListHeaderProperty bit 5-6) / Caption vertical alignment (ListHeaderProperty bit 5-6)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CaptionVAlign {
Top = 0,
Middle = 1,
Bottom = 2,
}
/// ์บก์
์ ๋ณด (ํ 72) / Caption information (Table 72)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Caption {
pub align: CaptionAlign,
pub include_margin: bool,
pub width: HWPUNIT,
pub gap: HWPUNIT16,
pub last_width: HWPUNIT,
#[serde(skip_serializing_if = "Option::is_none")]
pub vertical_align: Option<CaptionVAlign>,
}
/// ์ปจํธ๋กค ํค๋ ๋ฐ์ดํฐ (์ปจํธ๋กค ID๋ณ ๊ตฌ์กฐ) / Control header data (structure varies by CtrlID)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "data_type", rename_all = "snake_case")]
pub enum CtrlHeaderData {
ObjectCommon {
attribute: ObjectAttribute,
offset_y: SHWPUNIT,
offset_x: SHWPUNIT,
width: HWPUNIT,
height: HWPUNIT,
z_order: INT32,
margin: Margin,
instance_id: UINT32,
page_divide: INT32,
description: Option<String>,
caption: Option<Caption>,
},
ColumnDefinition {
attribute: ColumnDefinitionAttribute,
column_spacing: HWPUNIT16,
column_widths: Vec<HWPUNIT16>,
attribute_high: UINT16,
divider_line_type: UINT8,
divider_line_thickness: UINT8,
divider_line_color: UINT32,
},
FootnoteEndnote {
number: UINT8,
reserved: [UINT8; 5],
attribute: UINT8,
reserved2: UINT8,
},
HeaderFooter {
attribute: HeaderFooterAttribute,
text_width: HWPUNIT,
text_height: HWPUNIT,
text_ref: UINT8,
number_ref: UINT8,
},
PageNumberPosition {
flags: PageNumberPositionFlags,
user_symbol: String,
prefix: String,
suffix: String,
},
Field {
field_type: String,
attribute: UINT32,
other_attr: UINT8,
command_len: UINT16,
command: String,
id: UINT32,
},
SectionDefinition {
attribute: UINT32,
column_spacing: HWPUNIT16,
vertical_alignment: HWPUNIT16,
horizontal_alignment: HWPUNIT16,
default_tip_spacing: HWPUNIT,
number_para_shape_id: UINT16,
page_number: UINT16,
figure_number: UINT16,
table_number: UINT16,
equation_number: UINT16,
language: UINT16,
},
AutoNumber {
attribute: UINT32,
number: UINT16,
user_symbol: String,
prefix: String,
suffix: String,
},
NewNumber {
attribute: UINT32,
number: UINT16,
},
Hide {
attribute: UINT16,
},
PageAdjust {
attribute: UINT32,
},
BookmarkMarker {
keyword1: String,
keyword2: String,
},
Overlap {
ctrl_id: String,
text: String,
border_type: UINT8,
internal_text_size: INT8,
border_internal_text_spread: UINT8,
char_shape_ids: Vec<UINT32>,
},
Comment {
main_text: String,
sub_text: String,
position: UINT32,
fsize_ratio: UINT32,
option: UINT32,
style_number: UINT32,
alignment: UINT32,
},
HiddenDescription,
Other,
}
/// ๊ฐ์ฒด ์์ฑ / Object attribute
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObjectAttribute {
pub like_letters: bool,
pub affect_line_spacing: bool,
pub vert_rel_to: VertRelTo,
pub vert_relative: UINT8,
pub horz_rel_to: HorzRelTo,
pub horz_relative: UINT8,
pub vert_rel_to_para_limit: bool,
pub overlap: bool,
pub object_width_standard: ObjectWidthStandard,
pub object_height_standard: ObjectHeightStandard,
pub object_text_option: ObjectTextOption,
pub object_text_position_option: ObjectTextPositionOption,
pub object_category: ObjectCategory,
pub size_protect: bool,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum VertRelTo {
Paper,
Page,
Para,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HorzRelTo {
Paper,
Page,
Column,
Para,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ObjectWidthStandard {
Paper,
Page,
Column,
Para,
Absolute,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ObjectHeightStandard {
Paper,
Page,
Absolute,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ObjectTextOption {
Square,
Tight,
Through,
TopAndBottom,
BehindText,
InFrontOfText,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ObjectTextPositionOption {
BothSides,
LeftOnly,
RightOnly,
LargestOnly,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ObjectCategory {
None,
Figure,
Table,
Equation,
}
/// ๋จ ์ ์ ์์ฑ (ํ 139) / Column definition attribute (Table 139)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ColumnDefinitionAttribute {
pub column_type: ColumnType,
pub column_count: UINT8,
pub column_direction: ColumnDirection,
pub equal_width: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ColumnType {
Normal,
Distributed,
Parallel,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ColumnDirection {
Left,
Right,
Both,
}
/// ์ค๋ธ์ ํธ์ ๋ฐ๊นฅ 4๋ฐฉํฅ ์ฌ๋ฐฑ / Object outer margins (4 directions)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Margin {
pub top: HWPUNIT16,
pub right: HWPUNIT16,
pub bottom: HWPUNIT16,
pub left: HWPUNIT16,
}
/// ์ชฝ ๋ฒํธ ์์น ์์ฑ (ํ 148) / Page number position attributes (Table 148)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PageNumberPositionFlags {
pub shape: u8,
pub position: PageNumberPosition,
}
/// ์ชฝ ๋ฒํธ์ ํ์ ์์น / Page number display position
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PageNumberPosition {
None,
TopLeft,
TopCenter,
TopRight,
BottomLeft,
BottomCenter,
BottomRight,
OutsideTop,
OutsideBottom,
InsideTop,
InsideBottom,
}
/// ๋จธ๋ฆฌ๋ง/๊ผฌ๋ฆฌ๋ง ์์ฑ (ํ 141) / Header/Footer attribute (Table 141)
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct HeaderFooterAttribute {
pub apply_page: ApplyPage,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApplyPage {
Both,
EvenOnly,
OddOnly,
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/overlap.rs | crates/hwp-core/src/document/bodytext/ctrl_header/overlap.rs | use crate::error::HwpError;
use crate::types::decode_utf16le;
use crate::types::{INT8, UINT16, UINT32, UINT8};
use super::types::CtrlHeaderData;
/// ๊ธ์ ๊ฒน์นจ ํ์ฑ (ํ 150) / Parse character overlap (Table 150)
pub(crate) fn parse_overlap(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 10 {
return Err(HwpError::insufficient_data("Overlap", 10, data.len()));
}
let mut offset = 0usize;
let ctrl_id_bytes = [data[offset + 3], data[offset + 2], data[offset + 1], data[offset]];
let ctrl_id = String::from_utf8_lossy(&ctrl_id_bytes)
.trim_end_matches('\0')
.to_string();
offset += 4;
let text_len = UINT16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
let text = if text_len > 0 && offset + (text_len * 2) <= data.len() {
let text_bytes = &data[offset..offset + (text_len * 2)];
decode_utf16le(text_bytes).unwrap_or_default()
} else {
String::new()
};
offset += text_len * 2;
let border_type = if offset < data.len() { UINT8::from_le_bytes([data[offset]]) } else { 0 };
offset += 1;
let internal_text_size = if offset < data.len() { INT8::from_le_bytes([data[offset]]) } else { 0 };
offset += 1;
let border_internal_text_spread =
if offset < data.len() { UINT8::from_le_bytes([data[offset]]) } else { 0 };
offset += 1;
let cnt = if offset < data.len() {
UINT8::from_le_bytes([data[offset]]) as usize
} else {
0
};
offset += 1;
let mut char_shape_ids = Vec::new();
if cnt > 0 && offset + (cnt * 4) <= data.len() {
for _ in 0..cnt {
let id = UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);
char_shape_ids.push(id);
offset += 4;
}
}
Ok(CtrlHeaderData::Overlap {
ctrl_id,
text,
border_type,
internal_text_size,
border_internal_text_spread,
char_shape_ids,
})
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/mod.rs | crates/hwp-core/src/document/bodytext/ctrl_header/mod.rs | // CtrlHeader parsing/types split into modules.
mod ids;
mod types;
mod auto_number;
mod bookmark_marker;
mod caption;
mod column_definition;
mod comment;
mod field;
mod footnote_endnote;
mod header_footer;
mod hide;
mod object_common;
mod overlap;
mod page_adjust;
mod page_number_position;
mod section_definition;
pub use ids::CtrlId;
pub use types::*;
pub use caption::parse_caption_from_list_header;
use crate::error::HwpError;
use crate::types::UINT32;
impl CtrlHeader {
/// CtrlHeader๋ฅผ ๋ฐ์ดํธ ๋ฐฐ์ด์์ ํ์ฑํฉ๋๋ค. / Parse CtrlHeader from byte array.
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 4 {
return Err(HwpError::insufficient_data("CtrlHeader", 4, data.len()));
}
let ctrl_id_value = UINT32::from_le_bytes([data[0], data[1], data[2], data[3]]);
// pyhwp์ฒ๋ผ ๋ฐ์ดํธ๋ฅผ ๋ฆฌ๋ฒ์คํด์ ์ฝ์ / Read bytes in reverse order like pyhwp
let ctrl_id_bytes = [data[3], data[2], data[1], data[0]];
// ๊ณต๋ฐฑ๊น์ง ํฌํจํด์ ํ์ฑ (trim_end ์ ๊ฑฐ) / Parse including spaces (remove trim_end)
let ctrl_id = String::from_utf8_lossy(&ctrl_id_bytes)
.trim_end_matches('\0')
.to_string();
let remaining_data = if data.len() > 4 { &data[4..] } else { &[] };
let parsed_data = match ctrl_id.as_str() {
CtrlId::TABLE | CtrlId::SHAPE_OBJECT => object_common::parse_object_common(remaining_data)?,
CtrlId::COLUMN_DEF => column_definition::parse_column_definition(remaining_data)?,
CtrlId::FOOTNOTE | CtrlId::ENDNOTE => footnote_endnote::parse_footnote_endnote(remaining_data)?,
CtrlId::HEADER | CtrlId::FOOTER => header_footer::parse_header_footer(remaining_data)?,
CtrlId::PAGE_NUMBER | CtrlId::PAGE_NUMBER_POS => {
page_number_position::parse_page_number_position(remaining_data)?
}
CtrlId::FIELD_START => field::parse_field(remaining_data)?,
CtrlId::SECTION_DEF => section_definition::parse_section_definition(remaining_data)?,
CtrlId::AUTO_NUMBER | CtrlId::AUTO_NUMBER_ALT => auto_number::parse_auto_number(remaining_data)?,
CtrlId::NEW_NUMBER => auto_number::parse_new_number(remaining_data)?,
CtrlId::HIDE => hide::parse_hide(remaining_data)?,
CtrlId::PAGE_ADJUST => page_adjust::parse_page_adjust(remaining_data)?,
CtrlId::BOOKMARK_MARKER => bookmark_marker::parse_bookmark_marker(remaining_data)?,
CtrlId::OVERLAP => overlap::parse_overlap(remaining_data)?,
CtrlId::COMMENT => comment::parse_comment(remaining_data)?,
CtrlId::HIDDEN_DESC => CtrlHeaderData::HiddenDescription,
_ => CtrlHeaderData::Other,
};
Ok(CtrlHeader {
ctrl_id,
ctrl_id_value,
data: parsed_data,
})
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/column_definition.rs | crates/hwp-core/src/document/bodytext/ctrl_header/column_definition.rs | use crate::error::HwpError;
use crate::types::{HWPUNIT16, UINT16, UINT32, UINT8};
use super::types::{ColumnDefinitionAttribute, ColumnDirection, ColumnType, CtrlHeaderData};
/// ๋จ ์ ์ ํ์ฑ (ํ 138) / Parse column definition (Table 138)
pub(crate) fn parse_column_definition(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 12 {
return Err(HwpError::insufficient_data(
"Column definition",
12,
data.len(),
));
}
let mut offset = 0usize;
let attribute_low = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let column_type = match attribute_low & 0x03 {
0 => ColumnType::Normal,
1 => ColumnType::Distributed,
2 => ColumnType::Parallel,
_ => ColumnType::Normal,
};
let column_count = ((attribute_low >> 2) & 0xFF) as UINT8;
let column_count_u8 = if column_count == 0 { 1 } else { column_count };
let column_direction = match (attribute_low >> 10) & 0x03 {
0 => ColumnDirection::Left,
1 => ColumnDirection::Right,
2 => ColumnDirection::Both,
_ => ColumnDirection::Left,
};
let equal_width = (attribute_low & 0x1000) != 0;
let attribute = ColumnDefinitionAttribute {
column_type,
column_count: column_count_u8,
column_direction,
equal_width,
};
let column_spacing = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let mut column_widths = Vec::new();
if !equal_width {
for _ in 0..column_count_u8 {
if offset + 2 <= data.len() {
column_widths.push(HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]));
offset += 2;
} else {
break;
}
}
}
let attribute_high = if offset + 2 <= data.len() {
UINT16::from_le_bytes([data[offset], data[offset + 1]])
} else {
0
};
offset += 2;
let divider_line_type = if offset < data.len() { data[offset] } else { 0 };
offset += 1;
let divider_line_thickness = if offset < data.len() { data[offset] } else { 0 };
offset += 1;
let divider_line_color = if offset + 4 <= data.len() {
UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]])
} else {
0
};
Ok(CtrlHeaderData::ColumnDefinition {
attribute,
column_spacing,
column_widths,
attribute_high,
divider_line_type,
divider_line_thickness,
divider_line_color,
})
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/page_adjust.rs | crates/hwp-core/src/document/bodytext/ctrl_header/page_adjust.rs | use crate::error::HwpError;
use crate::types::UINT32;
use super::types::CtrlHeaderData;
/// ํ/์ง์ ์กฐ์ ํ์ฑ (ํ 146) / Parse page adjustment (Table 146)
pub(crate) fn parse_page_adjust(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 4 {
return Err(HwpError::insufficient_data("Page adjust", 4, data.len()));
}
let attribute = UINT32::from_le_bytes([data[0], data[1], data[2], data[3]]);
Ok(CtrlHeaderData::PageAdjust { attribute })
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/auto_number.rs | crates/hwp-core/src/document/bodytext/ctrl_header/auto_number.rs | use crate::error::HwpError;
use crate::types::decode_utf16le;
use crate::types::{UINT16, UINT32};
use super::types::CtrlHeaderData;
/// ์๋๋ฒํธ ํ์ฑ (ํ 142) / Parse auto number (Table 142)
pub(crate) fn parse_auto_number(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 12 {
return Err(HwpError::insufficient_data("Auto number", 12, data.len()));
}
let mut offset = 0usize;
let attribute = UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);
offset += 4;
let number = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let user_symbol = decode_utf16le(&data[offset..offset + 2]).unwrap_or_default();
offset += 2;
let prefix = decode_utf16le(&data[offset..offset + 2]).unwrap_or_default();
offset += 2;
let suffix = decode_utf16le(&data[offset..offset + 2]).unwrap_or_default();
Ok(CtrlHeaderData::AutoNumber {
attribute,
number,
user_symbol,
prefix,
suffix,
})
}
/// ์ ๋ฒํธ ์ง์ ํ์ฑ (ํ 144) / Parse new number specification (Table 144)
pub(crate) fn parse_new_number(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 8 {
return Err(HwpError::insufficient_data("New number", 8, data.len()));
}
let mut offset = 0usize;
let attribute = UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);
offset += 4;
let number = UINT16::from_le_bytes([data[offset], data[offset + 1]]);
Ok(CtrlHeaderData::NewNumber { attribute, number })
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/section_definition.rs | crates/hwp-core/src/document/bodytext/ctrl_header/section_definition.rs | use crate::error::HwpError;
use crate::types::{HWPUNIT, HWPUNIT16, UINT16, UINT32};
use super::types::CtrlHeaderData;
/// ๊ตฌ์ญ ์ ์ ํ์ฑ (ํ 129) / Parse section definition (Table 129)
pub(crate) fn parse_section_definition(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 24 {
return Err(HwpError::insufficient_data(
"Section definition",
24,
data.len(),
));
}
let mut offset = 0usize;
let attribute = UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);
offset += 4;
let column_spacing = if offset + 2 <= data.len() {
HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]])
} else {
0
};
offset += 2;
let vertical_alignment = if offset + 2 <= data.len() {
HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]])
} else {
0
};
offset += 2;
let horizontal_alignment = if offset + 2 <= data.len() {
HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]])
} else {
0
};
offset += 2;
let default_tip_spacing = if offset + 4 <= data.len() {
HWPUNIT::from(UINT32::from_le_bytes([
data[offset],
data[offset + 1],
data[offset + 2],
data[offset + 3],
]))
} else {
HWPUNIT::from(0)
};
offset += 4;
let number_para_shape_id = if offset + 2 <= data.len() {
UINT16::from_le_bytes([data[offset], data[offset + 1]])
} else {
0
};
offset += 2;
let page_number = if offset + 2 <= data.len() {
UINT16::from_le_bytes([data[offset], data[offset + 1]])
} else {
0
};
offset += 2;
let figure_number = if offset + 2 <= data.len() {
UINT16::from_le_bytes([data[offset], data[offset + 1]])
} else {
0
};
offset += 2;
let table_number = if offset + 2 <= data.len() {
UINT16::from_le_bytes([data[offset], data[offset + 1]])
} else {
0
};
offset += 2;
let equation_number = if offset + 2 <= data.len() {
UINT16::from_le_bytes([data[offset], data[offset + 1]])
} else {
0
};
offset += 2;
let language = if offset + 2 <= data.len() {
UINT16::from_le_bytes([data[offset], data[offset + 1]])
} else {
0
};
Ok(CtrlHeaderData::SectionDefinition {
attribute,
column_spacing,
vertical_alignment,
horizontal_alignment,
default_tip_spacing,
number_para_shape_id,
page_number,
figure_number,
table_number,
equation_number,
language,
})
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/caption.rs | crates/hwp-core/src/document/bodytext/ctrl_header/caption.rs | use crate::error::HwpError;
use crate::types::{HWPUNIT, HWPUNIT16, UINT32}; // keep
use super::types::{Caption, CaptionAlign, CaptionVAlign};
/// LIST_HEADER ๋ ์ฝ๋์์ ์บก์
ํ์ฑ (hwplib ๋ฐฉ์) / Parse caption from LIST_HEADER record (hwplib approach)
pub fn parse_caption_from_list_header(data: &[u8]) -> Result<Option<Caption>, HwpError> {
if data.len() < 22 {
return Ok(None);
}
let mut offset = 0usize;
// paraCount (SInt4) - 4 bytes (read but not used)
offset += 4;
let list_header_property = UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);
offset += 4;
let vertical_align = match (list_header_property >> 5) & 0x03 {
0 => CaptionVAlign::Top,
1 => CaptionVAlign::Middle,
2 => CaptionVAlign::Bottom,
_ => CaptionVAlign::Middle,
};
let caption_property_value =
UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);
offset += 4;
let align = match caption_property_value & 0x03 {
0 => CaptionAlign::Left,
1 => CaptionAlign::Right,
2 => CaptionAlign::Top,
3 => CaptionAlign::Bottom,
_ => CaptionAlign::Bottom,
};
let include_margin = (caption_property_value & 0x04) != 0;
let width = HWPUNIT::from(UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]));
offset += 4;
let gap = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let last_width =
HWPUNIT::from(UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]));
Ok(Some(Caption {
align,
include_margin,
width,
gap,
last_width,
vertical_align: Some(vertical_align),
}))
}
/// ์บก์
ํ์ฑ (ํ 72 - 14๋ฐ์ดํธ) / Parse caption (Table 72 - 14 bytes)
#[allow(dead_code)]
fn parse_caption(data: &[u8]) -> Result<Caption, HwpError> {
if data.len() < 14 {
return Err(HwpError::insufficient_data("Caption", 14, data.len()));
}
let mut offset = 0usize;
let attribute_value =
UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);
offset += 4;
let align = match attribute_value & 0x03 {
0 => CaptionAlign::Left,
1 => CaptionAlign::Right,
2 => CaptionAlign::Top,
3 => CaptionAlign::Bottom,
_ => CaptionAlign::Bottom,
};
let include_margin = (attribute_value & 0x04) != 0;
let width = HWPUNIT::from(UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]));
offset += 4;
let gap = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
offset += 2;
let last_width =
HWPUNIT::from(UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]));
Ok(Caption {
align,
include_margin,
width,
gap,
last_width,
vertical_align: None,
})
}
/// ์บก์
ํ์ฑ (ํ 72 - 12๋ฐ์ดํธ ๋ฒ์ ) / Parse caption (Table 72 - 12 bytes version)
#[allow(dead_code)]
fn parse_caption_12bytes(data: &[u8]) -> Result<Caption, HwpError> {
if data.len() < 12 {
return Err(HwpError::insufficient_data(
"Caption (12 bytes)",
12,
data.len(),
));
}
let mut offset = 0usize;
let attribute_value =
UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);
offset += 4;
let align = match attribute_value & 0x03 {
0 => CaptionAlign::Left,
1 => CaptionAlign::Right,
2 => CaptionAlign::Top,
3 => CaptionAlign::Bottom,
_ => CaptionAlign::Bottom,
};
let include_margin = (attribute_value & 0x04) != 0;
let width = HWPUNIT::from(UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]));
offset += 4;
let gap = HWPUNIT16::from_le_bytes([data[offset], data[offset + 1]]);
let last_width = HWPUNIT::from(0);
Ok(Caption {
align,
include_margin,
width,
gap,
last_width,
vertical_align: None,
})
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bodytext/ctrl_header/comment.rs | crates/hwp-core/src/document/bodytext/ctrl_header/comment.rs | use crate::error::HwpError;
use crate::types::decode_utf16le;
use crate::types::{UINT16, UINT32};
use super::types::CtrlHeaderData;
/// ๋ง๋ง ํ์ฑ (ํ 151) / Parse comment (Table 151)
pub(crate) fn parse_comment(data: &[u8]) -> Result<CtrlHeaderData, HwpError> {
if data.len() < 18 {
return Err(HwpError::insufficient_data("Comment", 18, data.len()));
}
let mut offset = 0usize;
let main_text_len = UINT16::from_le_bytes([data[offset], data[offset + 1]]) as usize;
offset += 2;
let main_text = if main_text_len > 0 && offset + (main_text_len * 2) <= data.len() {
let main_text_bytes = &data[offset..offset + (main_text_len * 2)];
decode_utf16le(main_text_bytes).unwrap_or_default()
} else {
String::new()
};
offset += main_text_len.max(1) * 2;
let sub_text_len = if offset + 2 <= data.len() {
UINT16::from_le_bytes([data[offset], data[offset + 1]]) as usize
} else {
0
};
offset += 2;
let sub_text = if sub_text_len > 0 && offset + (sub_text_len * 2) <= data.len() {
let sub_text_bytes = &data[offset..offset + (sub_text_len * 2)];
decode_utf16le(sub_text_bytes).unwrap_or_default()
} else {
String::new()
};
offset += sub_text_len.max(1) * 2;
let position = if offset + 4 <= data.len() {
UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]])
} else {
0
};
offset += 4;
let fsize_ratio = if offset + 4 <= data.len() {
UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]])
} else {
0
};
offset += 4;
let option = if offset + 4 <= data.len() {
UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]])
} else {
0
};
offset += 4;
let style_number = if offset + 4 <= data.len() {
UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]])
} else {
0
};
offset += 4;
let alignment = if offset + 4 <= data.len() {
UINT32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]])
} else {
0
};
Ok(CtrlHeaderData::Comment {
main_text,
sub_text,
position,
fsize_ratio,
option,
style_number,
alignment,
})
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/bindata/mod.rs | crates/hwp-core/src/document/bindata/mod.rs | /// BinData parsing module
///
/// This module handles parsing of HWP BinData storage.
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 2 - ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ (BinData ์คํ ๋ฆฌ์ง)
use crate::decompress::decompress_deflate;
use crate::document::docinfo::BinDataRecord;
use crate::error::HwpError;
use crate::types::WORD;
use base64::{engine::general_purpose::STANDARD, Engine as _};
use cfb::CompoundFile;
use serde::{Deserialize, Serialize};
use std::io::{Cursor, Read};
use std::path::Path;
/// Binary data output format
/// ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ ์ถ๋ ฅ ํ์
#[derive(Debug, Clone)]
pub enum BinaryDataFormat {
/// Base64 encoded string / Base64๋ก ์ธ์ฝ๋ฉ๋ ๋ฌธ์์ด
Base64,
/// File path where binary data is saved / ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ๊ฐ ์ ์ฅ๋ ํ์ผ ๊ฒฝ๋ก
File(String),
}
/// Binary data structure
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BinData {
/// Binary data items (BinaryData0, BinaryData1, etc.)
pub items: Vec<BinaryDataItem>,
}
/// Binary data item
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BinaryDataItem {
/// Item index
pub index: WORD,
/// Base64 encoded data or file path / Base64๋ก ์ธ์ฝ๋ฉ๋ ๋ฐ์ดํฐ ๋๋ ํ์ผ ๊ฒฝ๋ก
pub data: String,
}
impl BinData {
/// Parse BinData storage from CFB structure
/// CFB ๊ตฌ์กฐ์์ BinData ์คํ ๋ฆฌ์ง๋ฅผ ํ์ฑํฉ๋๋ค.
///
/// # Arguments
/// * `cfb` - CompoundFile structure (mutable reference required) / CompoundFile ๊ตฌ์กฐ์ฒด (๊ฐ๋ณ ์ฐธ์กฐ ํ์)
/// * `output_format` - Output format for binary data / ๋ฐ์ด๋๋ฆฌ ๋ฐ์ดํฐ ์ถ๋ ฅ ํ์
/// * `bin_data_records` - BinData records from DocInfo (ํ 17) / DocInfo์ BinData ๋ ์ฝ๋ (ํ 17)
///
/// # Returns
/// Parsed BinData structure / ํ์ฑ๋ BinData ๊ตฌ์กฐ์ฒด
///
/// # Notes
/// ํ 17์ HWPTAG_BIN_DATA ๋ ์ฝ๋์์ EMBEDDING ํ์
์ธ ๊ฒฝ์ฐ `binary_data_id`์ `extension` ์ ๋ณด๋ฅผ ์ฌ์ฉํฉ๋๋ค.
/// When BinDataRecord type is EMBEDDING, we use `binary_data_id` and `extension` from Table 17.
pub fn parse(
cfb: &mut CompoundFile<Cursor<&[u8]>>,
output_format: BinaryDataFormat,
bin_data_records: &[BinDataRecord],
) -> Result<Self, HwpError> {
let mut items = Vec::new();
// ํ 17์ bin_data_records๋ฅผ ์ฌ์ฉํ์ฌ ์คํธ๋ฆผ์ ์ฐพ์ต๋๋ค (EMBEDDING/STORAGE ํ์
๋ง)
// Use bin_data_records from Table 17 to find streams (only EMBEDDING/STORAGE types)
for record in bin_data_records {
let (binary_data_id, extension_opt) = match record {
BinDataRecord::Embedding { embedding, .. } => {
(embedding.binary_data_id, Some(embedding.extension.clone()))
}
BinDataRecord::Storage { storage, .. } => (storage.binary_data_id, None),
BinDataRecord::Link { .. } => {
// LINK ํ์
์ BinData ์คํ ๋ฆฌ์ง์ ์์ผ๋ฏ๋ก ๊ฑด๋๋
// LINK type is not in BinData storage, so skip
continue;
}
};
let base_stream_name = format!("BIN{:04X}", binary_data_id);
// Try different path formats
// ๋ค์ํ ๊ฒฝ๋ก ํ์ ์๋
let mut paths = vec![
format!("BinData/{}", base_stream_name),
format!("Root Entry/BinData/{}", base_stream_name),
base_stream_name.clone(),
];
// ํ 17์ extension ์ ๋ณด๊ฐ ์์ผ๋ฉด ํ์ฅ์ ํฌํจ ๊ฒฝ๋ก๋ ์๋
// If extension info from Table 17 exists, also try paths with extension
if let Some(ext) = &extension_opt {
paths.push(format!("BinData/{}.{}", base_stream_name, ext));
paths.push(format!("Root Entry/BinData/{}.{}", base_stream_name, ext));
}
let mut found = false;
for path in &paths {
match cfb.open_stream(path) {
Ok(mut stream) => {
let mut buffer = Vec::new();
match stream.read_to_end(&mut buffer) {
Ok(_) => {
if !buffer.is_empty() {
// BinData ์คํธ๋ฆผ์ ์์ถ๋์ด ์์ผ๋ฏ๋ก ์์ถ ํด์ ํ์
// BinData streams are compressed, so decompression is required
// ๋ ๊ฑฐ์ ์ฝ๋ ์ฐธ๊ณ : hwpjs.js๋ pako.inflate(..., { windowBits: -15 })
// pyhwp๋ zlib.decompress(..., -15) ์ฌ์ฉ
// Reference: hwpjs.js uses pako.inflate(..., { windowBits: -15 })
// pyhwp uses zlib.decompress(..., -15)
let _compressed_size = buffer.len();
let decompressed_buffer = match decompress_deflate(&buffer) {
Ok(decompressed) => decompressed,
Err(e) => {
#[cfg(debug_assertions)]
eprintln!(
"Warning: Failed to decompress BinData stream '{}' (id={}): {}. Using raw data.",
path, binary_data_id, e
);
buffer.clone() // ์์ถ ํด์ ์คํจ ์ ์๋ณธ ๋ฐ์ดํฐ ์ฌ์ฉ
}
};
let data = match &output_format {
BinaryDataFormat::Base64 => {
STANDARD.encode(&decompressed_buffer)
}
BinaryDataFormat::File(dir_path) => {
let ext = extension_opt.as_deref().unwrap_or("bin");
let file_name = format!("{}.{}", base_stream_name, ext);
let file_path = Path::new(dir_path).join(&file_name);
std::fs::create_dir_all(dir_path).map_err(|e| {
format!(
"Failed to create directory '{}': {}",
dir_path, e
)
})?;
std::fs::write(&file_path, &decompressed_buffer)
.map_err(|e| {
format!(
"Failed to write file '{}': {}",
file_path.display(),
e
)
})?;
file_path.to_string_lossy().to_string()
}
};
items.push(BinaryDataItem {
index: binary_data_id,
data,
});
found = true;
break;
}
}
Err(_) => continue,
}
}
Err(_) => continue,
}
}
if !found {
// ์คํธ๋ฆผ์ ์ฐพ์ง ๋ชปํ์ง๋ง ๊ณ์ ์งํ (๋ค๋ฅธ ๋ ์ฝ๋๋ ์์ ์ ์์)
// Stream not found, but continue (other records may exist)
}
}
Ok(BinData { items })
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/fileheader/serialize.rs | crates/hwp-core/src/document/fileheader/serialize.rs | use crate::types::DWORD;
use serde::Serializer;
use super::constants::{document_flags, license_flags};
/// Serialize version DWORD as "M.n.P.r" format string
pub fn serialize_version<S>(version: &DWORD, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format_version(*version))
}
/// Format version DWORD to "M.n.P.r" string
/// Format: 0xMMnnPPrr (e.g., 0x05000300 = "5.0.3.0")
fn format_version(version: DWORD) -> String {
let major = (version >> 24) & 0xFF;
let minor = (version >> 16) & 0xFF;
let patch = (version >> 8) & 0xFF;
let revision = version & 0xFF;
format!("{}.{}.{}.{}", major, minor, patch, revision)
}
/// Serialize document_flags DWORD as array of flag constants
pub fn serialize_document_flags<S>(flags: &DWORD, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
use serde::ser::SerializeSeq;
let mut active_flags = Vec::new();
if (*flags & 0x01) != 0 {
active_flags.push(document_flags::COMPRESSED);
}
if (*flags & 0x02) != 0 {
active_flags.push(document_flags::ENCRYPTED);
}
if (*flags & 0x04) != 0 {
active_flags.push(document_flags::DISTRIBUTION);
}
if (*flags & 0x08) != 0 {
active_flags.push(document_flags::SCRIPT);
}
if (*flags & 0x10) != 0 {
active_flags.push(document_flags::DRM);
}
if (*flags & 0x20) != 0 {
active_flags.push(document_flags::XML_TEMPLATE);
}
if (*flags & 0x40) != 0 {
active_flags.push(document_flags::HISTORY);
}
if (*flags & 0x80) != 0 {
active_flags.push(document_flags::ELECTRONIC_SIGNATURE);
}
if (*flags & 0x100) != 0 {
active_flags.push(document_flags::CERTIFICATE_ENCRYPTION);
}
if (*flags & 0x200) != 0 {
active_flags.push(document_flags::SIGNATURE_PREVIEW);
}
if (*flags & 0x400) != 0 {
active_flags.push(document_flags::CERTIFICATE_DRM);
}
if (*flags & 0x800) != 0 {
active_flags.push(document_flags::CCL);
}
if (*flags & 0x1000) != 0 {
active_flags.push(document_flags::MOBILE_OPTIMIZED);
}
if (*flags & 0x2000) != 0 {
active_flags.push(document_flags::PRIVACY_SECURITY);
}
if (*flags & 0x4000) != 0 {
active_flags.push(document_flags::TRACK_CHANGE);
}
if (*flags & 0x8000) != 0 {
active_flags.push(document_flags::KOGL);
}
if (*flags & 0x10000) != 0 {
active_flags.push(document_flags::VIDEO_CONTROL);
}
if (*flags & 0x20000) != 0 {
active_flags.push(document_flags::TABLE_OF_CONTENTS);
}
let mut seq = serializer.serialize_seq(Some(active_flags.len()))?;
for flag in active_flags {
seq.serialize_element(flag)?;
}
seq.end()
}
/// Serialize license_flags DWORD as array of flag constants
pub fn serialize_license_flags<S>(flags: &DWORD, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
use serde::ser::SerializeSeq;
let mut active_flags = Vec::new();
if (*flags & 0x01) != 0 {
active_flags.push(license_flags::CCL_KOGL);
}
if (*flags & 0x02) != 0 {
active_flags.push(license_flags::COPY_RESTRICTED);
}
if (*flags & 0x04) != 0 {
active_flags.push(license_flags::COPY_ALLOWED_SAME_CONDITION);
}
let mut seq = serializer.serialize_seq(Some(active_flags.len()))?;
for flag in active_flags {
seq.serialize_element(flag)?;
}
seq.end()
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/fileheader/mod.rs | crates/hwp-core/src/document/fileheader/mod.rs | /// FileHeader parsing module
///
/// This module handles parsing of HWP FileHeader structure.
/// According to HWP 5.0 spec, FileHeader is 256 bytes.
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 2 - ํ์ผ ์ธ์ ์ ๋ณด (FileHeader ์คํธ๋ฆผ)
use crate::error::HwpError;
use crate::types::{BYTE, DWORD};
use serde::{Deserialize, Serialize};
mod constants;
mod serialize;
use serialize::{serialize_document_flags, serialize_license_flags, serialize_version};
/// FileHeader structure for HWP 5.0
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileHeader {
/// Signature: "HWP Document File" (32 bytes)
pub signature: String,
/// File version (4 bytes, DWORD)
/// Format: 0xMMnnPPrr (e.g., 0x05000300 = 5.0.3.0)
#[serde(serialize_with = "serialize_version")]
pub version: DWORD,
/// Document flags (4 bytes, DWORD)
/// Bit flags: compression, encryption, distribution, script, DRM, electronic signature, etc.
#[serde(serialize_with = "serialize_document_flags")]
pub document_flags: DWORD,
/// License flags (4 bytes, DWORD)
/// Bit flags: CCL, KOGL license, copy restriction, etc.
#[serde(serialize_with = "serialize_license_flags")]
pub license_flags: DWORD,
/// Encryption version (4 bytes, DWORD)
pub encrypt_version: DWORD,
/// KOGL license country (1 byte, BYTE)
pub kogl_country: BYTE,
/// Reserved (207 bytes) - excluded from JSON serialization
#[serde(skip_serializing)]
pub reserved: Vec<u8>,
}
impl FileHeader {
/// Parse FileHeader from byte array
///
/// # Arguments
/// * `data` - 256-byte FileHeader data
///
/// # Returns
/// Parsed FileHeader structure
pub fn parse(data: &[u8]) -> Result<Self, HwpError> {
if data.len() < 256 {
return Err(HwpError::insufficient_data("FileHeader", 256, data.len()));
}
// Parse signature (32 bytes)
let signature_bytes = &data[0..32];
let signature = String::from_utf8_lossy(signature_bytes)
.trim_end_matches('\0')
.to_string();
// Validate signature
if signature != "HWP Document File" {
return Err(HwpError::InvalidSignature { found: signature });
}
// Parse version (4 bytes, DWORD, little-endian)
let version = DWORD::from_le_bytes([data[32], data[33], data[34], data[35]]);
// Parse document_flags (4 bytes, DWORD, little-endian)
let document_flags = DWORD::from_le_bytes([data[36], data[37], data[38], data[39]]);
// Parse license_flags (4 bytes, DWORD, little-endian)
let license_flags = DWORD::from_le_bytes([data[40], data[41], data[42], data[43]]);
// Parse encrypt_version (4 bytes, DWORD, little-endian)
let encrypt_version = DWORD::from_le_bytes([data[44], data[45], data[46], data[47]]);
// Parse kogl_country (1 byte, BYTE)
let kogl_country = data[48];
// Parse reserved (207 bytes)
let reserved = data[49..256].to_vec();
Ok(FileHeader {
signature,
version,
document_flags,
license_flags,
encrypt_version,
kogl_country,
reserved,
})
}
/// Check if file is compressed
pub fn is_compressed(&self) -> bool {
(self.document_flags & 0x01) != 0
}
/// Check if file is encrypted
pub fn is_encrypted(&self) -> bool {
(self.document_flags & 0x02) != 0
}
/// Check if XMLTemplate storage exists
/// XMLTemplate ์คํ ๋ฆฌ์ง ์กด์ฌ ์ฌ๋ถ ํ์ธ
pub fn has_xml_template(&self) -> bool {
(self.document_flags & 0x20) != 0 // Bit 5
}
/// Convert FileHeader to JSON string
pub fn to_json(&self) -> Result<String, HwpError> {
serde_json::to_string_pretty(self).map_err(HwpError::from)
}
/// Get version as string (e.g., "5.0.3.0")
pub fn version_string(&self) -> String {
let major = (self.version >> 24) & 0xFF;
let minor = (self.version >> 16) & 0xFF;
let patch = (self.version >> 8) & 0xFF;
let revision = self.version & 0xFF;
format!("{}.{}.{}.{}", major, minor, patch, revision)
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/src/document/fileheader/constants.rs | crates/hwp-core/src/document/fileheader/constants.rs | /// Document flag constants
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 3 - ์์ฑ (์ฒซ ๋ฒ์งธ DWORD)
pub mod document_flags {
/// Bit 0: ์์ถ ์ฌ๋ถ
pub const COMPRESSED: &str = "compressed";
/// Bit 1: ์ํธ ์ค์ ์ฌ๋ถ
pub const ENCRYPTED: &str = "encrypted";
/// Bit 2: ๋ฐฐํฌ์ฉ ๋ฌธ์ ์ฌ๋ถ
pub const DISTRIBUTION: &str = "distribution";
/// Bit 3: ์คํฌ๋ฆฝํธ ์ ์ฅ ์ฌ๋ถ
pub const SCRIPT: &str = "script";
/// Bit 4: DRM ๋ณด์ ๋ฌธ์ ์ฌ๋ถ
pub const DRM: &str = "drm";
/// Bit 5: XMLTemplate ์คํ ๋ฆฌ์ง ์กด์ฌ ์ฌ๋ถ
pub const XML_TEMPLATE: &str = "xml_template";
/// Bit 6: ๋ฌธ์ ์ด๋ ฅ ๊ด๋ฆฌ ์กด์ฌ ์ฌ๋ถ
pub const HISTORY: &str = "history";
/// Bit 7: ์ ์ ์๋ช
์ ๋ณด ์กด์ฌ ์ฌ๋ถ
pub const ELECTRONIC_SIGNATURE: &str = "electronic_signature";
/// Bit 8: ๊ณต์ธ ์ธ์ฆ์ ์ํธํ ์ฌ๋ถ
pub const CERTIFICATE_ENCRYPTION: &str = "certificate_encryption";
/// Bit 9: ์ ์ ์๋ช
์๋น ์ ์ฅ ์ฌ๋ถ
pub const SIGNATURE_PREVIEW: &str = "signature_preview";
/// Bit 10: ๊ณต์ธ ์ธ์ฆ์ DRM ๋ณด์ ๋ฌธ์ ์ฌ๋ถ
pub const CERTIFICATE_DRM: &str = "certificate_drm";
/// Bit 11: CCL ๋ฌธ์ ์ฌ๋ถ
pub const CCL: &str = "ccl";
/// Bit 12: ๋ชจ๋ฐ์ผ ์ต์ ํ ์ฌ๋ถ
pub const MOBILE_OPTIMIZED: &str = "mobile_optimized";
/// Bit 13: ๊ฐ์ธ ์ ๋ณด ๋ณด์ ๋ฌธ์ ์ฌ๋ถ
pub const PRIVACY_SECURITY: &str = "privacy_security";
/// Bit 14: ๋ณ๊ฒฝ ์ถ์ ๋ฌธ์ ์ฌ๋ถ
pub const TRACK_CHANGE: &str = "track_change";
/// Bit 15: ๊ณต๊ณต๋๋ฆฌ(KOGL) ์ ์๊ถ ๋ฌธ์
pub const KOGL: &str = "kogl";
/// Bit 16: ๋น๋์ค ์ปจํธ๋กค ํฌํจ ์ฌ๋ถ
pub const VIDEO_CONTROL: &str = "video_control";
/// Bit 17: ์ฐจ๋ก ํ๋ ์ปจํธ๋กค ํฌํจ ์ฌ๋ถ
pub const TABLE_OF_CONTENTS: &str = "table_of_contents";
}
/// License flag constants
///
/// ์คํ ๋ฌธ์ ๋งคํ: ํ 3 - ์์ฑ (๋ ๋ฒ์งธ DWORD)
pub mod license_flags {
/// Bit 0: CCL, ๊ณต๊ณต๋๋ฆฌ ๋ผ์ด์ ์ค ์ ๋ณด
pub const CCL_KOGL: &str = "ccl_kogl";
/// Bit 1: ๋ณต์ ์ ํ ์ฌ๋ถ
pub const COPY_RESTRICTED: &str = "copy_restricted";
/// Bit 2: ๋์ผ ์กฐ๊ฑด ํ์ ๋ณต์ ํ๊ฐ ์ฌ๋ถ (๋ณต์ ์ ํ์ธ ๊ฒฝ์ฐ ๋ฌด์)
pub const COPY_ALLOWED_SAME_CONDITION: &str = "copy_allowed_same_condition";
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/tests/parser_tests.rs | crates/hwp-core/tests/parser_tests.rs | /// HwpParser ํ
์คํธ
/// HwpParser tests
mod common;
use hwp_core::*;
#[test]
fn test_hwp_parser_new() {
let _parser = HwpParser::new();
}
#[test]
fn test_hwp_parser_parse_with_actual_file() {
// Test with actual HWP file if available
use crate::common::find_fixture_file;
if let Some(path) = find_fixture_file("noori.hwp") {
if let Ok(data) = std::fs::read(path) {
let parser = HwpParser::new();
let result = parser.parse(&data);
if let Err(e) = &result {
eprintln!("Parse error: {}", e);
}
assert!(result.is_ok(), "Should parse actual HWP file");
let document = result.unwrap();
// Validate document structure
assert_eq!(
document.file_header.signature.trim_end_matches('\0'),
"HWP Document File"
);
assert!(document.file_header.version > 0);
}
}
}
#[test]
fn test_hwp_parser_parse_fileheader_json() {
// Test FileHeader JSON output
use crate::common::find_fixture_file;
if let Some(path) = find_fixture_file("noori.hwp") {
if let Ok(data) = std::fs::read(path) {
let parser = HwpParser::new();
let result = parser.parse_fileheader_json(&data);
assert!(result.is_ok(), "Should return FileHeader as JSON");
let json = result.unwrap();
// Validate JSON contains expected fields
assert!(json.contains("signature"));
assert!(json.contains("version"));
assert!(json.contains("document_flags"));
assert!(json.contains("license_flags"));
assert!(json.contains("encrypt_version"));
assert!(json.contains("kogl_country"));
}
}
}
#[test]
fn test_hwp_parser_parse_with_invalid_data() {
let parser = HwpParser::new();
let data = b"invalid hwp file content";
let result = parser.parse(data);
// Should fail because it's not a valid CFB structure
assert!(result.is_err(), "Should fail for invalid CFB data");
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/tests/fileheader_tests.rs | crates/hwp-core/tests/fileheader_tests.rs | /// FileHeader ํ์ฑ ํ
์คํธ
/// FileHeader parsing tests
mod common;
use hwp_core::*;
#[test]
fn test_fileheader_parse_basic() {
// Create a minimal valid FileHeader
let mut data = vec![0u8; 256];
// Set signature "HWP Document File"
let signature = b"HWP Document File\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
data[0..signature.len()].copy_from_slice(signature);
// Set version (5.0.3.0 = 0x05000300)
data[32..36].copy_from_slice(&0x05000300u32.to_le_bytes());
// Set document_flags (compressed flag)
data[36..40].copy_from_slice(&0x01u32.to_le_bytes());
let fileheader = FileHeader::parse(&data).expect("Should parse FileHeader");
assert_eq!(
fileheader.signature.trim_end_matches('\0'),
"HWP Document File"
);
assert_eq!(fileheader.version, 0x05000300);
assert!(fileheader.is_compressed());
}
#[test]
fn test_fileheader_parse_too_short() {
let data = vec![0u8; 100];
let result = FileHeader::parse(&data);
assert!(
result.is_err(),
"Should fail for data shorter than 256 bytes"
);
}
#[test]
fn test_fileheader_parse_from_actual_file() {
// Test with actual HWP file if available
use crate::common::find_fixture_file;
let file_path = match find_fixture_file("noori.hwp") {
Some(p) => p,
None => {
println!("HWP test file not found in fixtures directory");
return;
}
};
match std::fs::read(file_path) {
Ok(data) => {
let mut cfb = CfbParser::parse(&data).expect("Should parse CFB");
match CfbParser::read_stream(&mut cfb, "FileHeader") {
Ok(fileheader_data) => {
let fileheader = FileHeader::parse(&fileheader_data)
.expect("Should parse FileHeader from actual file");
// Validate signature (must be exactly "HWP Document File")
let signature_trimmed = fileheader.signature.trim_end_matches('\0');
assert_eq!(
signature_trimmed, "HWP Document File",
"Signature must be 'HWP Document File'"
);
// Validate signature bytes (original data should be 32 bytes)
// The signature field is a String, but we check the original bytes
let signature_bytes = &fileheader_data[0..32];
assert_eq!(
signature_bytes.len(),
32,
"Signature bytes must be exactly 32 bytes"
);
let signature_str = String::from_utf8_lossy(signature_bytes)
.trim_end_matches('\0')
.to_string();
assert_eq!(
signature_str, "HWP Document File",
"Signature content must be 'HWP Document File'"
);
// Validate version format (0xMMnnPPrr)
// MM should be 5 for HWP 5.0
let major = (fileheader.version >> 24) & 0xFF;
let minor = (fileheader.version >> 16) & 0xFF;
let patch = (fileheader.version >> 8) & 0xFF;
let revision = fileheader.version & 0xFF;
assert_eq!(major, 5, "Major version should be 5 for HWP 5.0");
assert!(
minor <= 0xFF && patch <= 0xFF && revision <= 0xFF,
"Version components should be valid (0-255)"
);
// Validate document_flags (check bit flags)
// Bit 0: ์์ถ ์ฌ๋ถ
let is_compressed = (fileheader.document_flags & 0x01) != 0;
assert_eq!(
is_compressed,
fileheader.is_compressed(),
"is_compressed() should match bit 0"
);
// Bit 1: ์ํธ ์ค์ ์ฌ๋ถ
let is_encrypted = (fileheader.document_flags & 0x02) != 0;
assert_eq!(
is_encrypted,
fileheader.is_encrypted(),
"is_encrypted() should match bit 1"
);
// Validate EncryptVersion (should be 0-4 according to spec)
assert!(
fileheader.encrypt_version <= 4,
"EncryptVersion should be 0-4, got {}",
fileheader.encrypt_version
);
// Validate KOGL Country (should be 0, 6, or 15 according to spec)
// Valid values: 0 (Not set), 6 (KOR), 15 (US)
assert!(
fileheader.kogl_country == 0
|| fileheader.kogl_country == 6
|| fileheader.kogl_country == 15,
"KOGL Country should be 0, 6, or 15, got {}",
fileheader.kogl_country
);
// Validate reserved field (should be exactly 207 bytes)
assert_eq!(
fileheader.reserved.len(),
207,
"Reserved field must be exactly 207 bytes, got {}",
fileheader.reserved.len()
);
// Validate total structure size
let total_size = 32 // signature
+ 4 // version
+ 4 // document_flags
+ 4 // license_flags
+ 4 // encrypt_version
+ 1 // kogl_country
+ 207; // reserved
assert_eq!(total_size, 256, "Total FileHeader size should be 256 bytes");
}
Err(e) => {
panic!("Should be able to read FileHeader stream: {}", e);
}
}
}
Err(_) => {
// Skip test if file not available
}
}
}
#[test]
fn test_fileheader_is_compressed() {
let mut data = vec![0u8; 256];
let signature = b"HWP Document File\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
data[0..signature.len()].copy_from_slice(signature);
data[32..36].copy_from_slice(&0x05000300u32.to_le_bytes());
// Test with compression flag set
data[36..40].copy_from_slice(&0x01u32.to_le_bytes());
let fileheader = FileHeader::parse(&data).unwrap();
assert!(fileheader.is_compressed());
// Test without compression flag
data[36..40].copy_from_slice(&0x00u32.to_le_bytes());
let fileheader = FileHeader::parse(&data).unwrap();
assert!(!fileheader.is_compressed());
}
#[test]
fn test_fileheader_is_encrypted() {
let mut data = vec![0u8; 256];
let signature = b"HWP Document File\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
data[0..signature.len()].copy_from_slice(signature);
data[32..36].copy_from_slice(&0x05000300u32.to_le_bytes());
// Test with encryption flag set
data[36..40].copy_from_slice(&0x02u32.to_le_bytes());
let fileheader = FileHeader::parse(&data).unwrap();
assert!(fileheader.is_encrypted());
// Test without encryption flag
data[36..40].copy_from_slice(&0x00u32.to_le_bytes());
let fileheader = FileHeader::parse(&data).unwrap();
assert!(!fileheader.is_encrypted());
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/tests/common.rs | crates/hwp-core/tests/common.rs | /// ๊ณตํต ํ
์คํธ ํฌํผ ํจ์๋ค
/// Common test helper functions
use std::path::PathBuf;
/// Helper function to find test HWP files directory
pub fn find_fixtures_dir() -> Option<PathBuf> {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
.ok()
.map(PathBuf::from)
.unwrap_or_else(|| std::path::PathBuf::from("."));
let fixtures_path = manifest_dir.join("tests").join("fixtures");
if fixtures_path.exists() && fixtures_path.is_dir() {
return Some(fixtures_path);
}
// Fallback for backward compatibility
let possible_paths = ["tests/fixtures", "./tests/fixtures"];
for path_str in &possible_paths {
let path = std::path::Path::new(path_str);
if path.exists() && path.is_dir() {
return Some(path.to_path_buf());
}
}
None
}
/// Helper function to find test HWP file (for snapshot tests, uses noori.hwp)
pub fn find_test_file() -> Option<String> {
if let Some(dir) = find_fixtures_dir() {
let file_path = dir.join("noori.hwp");
if file_path.exists() {
return Some(file_path.to_string_lossy().to_string());
}
}
None
}
/// Helper function to find headerfooter.hwp file
pub fn find_headerfooter_file() -> Option<String> {
if let Some(dir) = find_fixtures_dir() {
let file_path = dir.join("headerfooter.hwp");
if file_path.exists() {
return Some(file_path.to_string_lossy().to_string());
}
}
None
}
/// Helper function to get all HWP files in fixtures directory
pub fn find_all_hwp_files() -> Vec<String> {
if let Some(dir) = find_fixtures_dir() {
let mut files = Vec::new();
if let Ok(entries) = std::fs::read_dir(&dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("hwp") {
if let Some(path_str) = path.to_str() {
files.push(path_str.to_string());
}
}
}
}
files.sort();
return files;
}
Vec::new()
}
/// Helper function to find a specific HWP file in fixtures directory
pub fn find_fixture_file(filename: &str) -> Option<String> {
if let Some(dir) = find_fixtures_dir() {
let file_path = dir.join(filename);
if file_path.exists() {
return Some(file_path.to_string_lossy().to_string());
}
}
None
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/tests/cfb_tests.rs | crates/hwp-core/tests/cfb_tests.rs | /// CFB ํ์ ํ
์คํธ
/// CFB parser tests
mod common;
use hwp_core::*;
use std::fs;
#[test]
fn test_cfb_parse_basic() {
// Test with actual HWP file from fixtures directory
use crate::common::find_fixture_file;
if let Some(path) = find_fixture_file("noori.hwp") {
if let Ok(data) = fs::read(path) {
let result = CfbParser::parse(&data);
assert!(
result.is_ok(),
"CFB parsing should succeed for valid HWP file"
);
}
}
}
#[test]
fn test_cfb_read_fileheader() {
// Test reading FileHeader stream from CFB
use crate::common::find_fixture_file;
if let Some(path) = find_fixture_file("noori.hwp") {
if let Ok(data) = fs::read(path) {
let mut cfb = CfbParser::parse(&data).expect("Should parse CFB");
let result = CfbParser::read_stream(&mut cfb, "FileHeader");
assert!(result.is_ok(), "Should be able to read FileHeader stream");
let fileheader = result.unwrap();
assert!(!fileheader.is_empty(), "FileHeader should not be empty");
assert_eq!(fileheader.len(), 256, "FileHeader should be 256 bytes");
}
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/tests/decompress_tests.rs | crates/hwp-core/tests/decompress_tests.rs | /// ์์ถ ํด์ ํ
์คํธ
/// Decompression tests
use hwp_core::*;
#[test]
fn test_decompress_zlib_basic() {
// Create a simple test: compress "hello" using zlib format and then decompress it
use flate2::write::ZlibEncoder;
use flate2::Compression;
use std::io::Write;
let original = b"hello world";
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
encoder.write_all(original).unwrap();
let compressed = encoder.finish().unwrap();
let decompressed = decompress_zlib(&compressed).expect("Should decompress");
assert_eq!(
decompressed, original,
"Decompressed data should match original"
);
}
#[test]
fn test_decompress_zlib_empty() {
// Empty data should still work (though it might error, which is fine)
let result = decompress_zlib(b"");
// Either Ok with empty vec or Err is acceptable
if let Ok(data) = result {
assert!(data.is_empty() || !data.is_empty());
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/crates/hwp-core/tests/snapshot_tests.rs | crates/hwp-core/tests/snapshot_tests.rs | /// ์ค๋
์ท ํ
์คํธ
/// Snapshot tests
mod common;
use common::*;
use hwp_core::*;
use hwp_core::document::ParagraphRecord;
use insta::{assert_snapshot, with_settings};
// insta๊ฐ tests/snapshots ๋๋ ํ ๋ฆฌ๋ฅผ ์ฌ์ฉํ๋๋ก ์ค์ ํ๋ ํฌํผ ๋งคํฌ๋ก
macro_rules! assert_snapshot_with_path {
($name:expr, $value:expr) => {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let snapshots_dir = std::path::Path::new(manifest_dir)
.join("tests")
.join("snapshots");
with_settings!({
snapshot_path => snapshots_dir
}, {
assert_snapshot!($name, $value);
});
};
}
#[test]
fn test_full_document_json_snapshot() {
let file_path = match find_test_file() {
Some(path) => path,
None => return, // Skip test if file not available
};
// ํ์ผ๋ช
์์ ์ค๋
์ท ์ด๋ฆ ์ถ์ถ / Extract snapshot name from filename
let file_name = std::path::Path::new(&file_path)
.file_stem()
.and_then(|n| n.to_str())
.unwrap_or("unknown");
let snapshot_name = file_name.replace(['-', '.'], "_");
let snapshot_name_json = format!("{}_json", snapshot_name);
if let Ok(data) = std::fs::read(&file_path) {
let parser = HwpParser::new();
let result = parser.parse(&data);
if let Err(e) = &result {
eprintln!("Parse error: {:?}", e);
}
assert!(result.is_ok(), "Should parse HWP document");
let document = result.unwrap();
// Verify BodyText is parsed correctly
// BodyText๊ฐ ์ฌ๋ฐ๋ฅด๊ฒ ํ์ฑ๋์๋์ง ๊ฒ์ฆ
assert!(
!document.body_text.sections.is_empty(),
"BodyText should have at least one section"
);
assert!(
document.body_text.sections[0].index == 0,
"First section should have index 0"
);
assert!(
!document.body_text.sections[0].paragraphs.is_empty(),
"First section should have at least one paragraph"
);
// Convert to JSON
// serde_json already outputs unicode characters as-is (not escaped)
// Only control characters are escaped according to JSON standard
let json =
serde_json::to_string_pretty(&document).expect("Should serialize document to JSON");
assert_snapshot_with_path!(snapshot_name_json.as_str(), json);
// ์ค์ JSON ํ์ผ๋ก๋ ์ ์ฅ / Also save as actual JSON file
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let snapshots_dir = std::path::Path::new(manifest_dir)
.join("tests")
.join("snapshots");
std::fs::create_dir_all(&snapshots_dir).unwrap_or(());
let json_file = snapshots_dir.join(format!("{}.json", file_name));
std::fs::write(&json_file, &json).unwrap_or_else(|e| {
eprintln!("Failed to write JSON file: {}", e);
});
}
}
#[test]
fn test_all_fixtures_json_snapshots() {
// ๋ชจ๋ fixtures ํ์ผ์ ๋ํด JSON ์ค๋
์ท ์์ฑ / Generate JSON snapshots for all fixtures files
let hwp_files = find_all_hwp_files();
if hwp_files.is_empty() {
println!("No HWP files found in fixtures directory");
return;
}
let parser = HwpParser::new();
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let snapshots_dir = std::path::Path::new(manifest_dir)
.join("tests")
.join("snapshots");
for file_path in &hwp_files {
let file_name = std::path::Path::new(file_path)
.file_stem()
.and_then(|n| n.to_str())
.unwrap_or("unknown");
// ํ์ผ๋ช
์ ์ค๋
์ท ์ด๋ฆ์ผ๋ก ์ฌ์ฉ (ํน์ ๋ฌธ์ ์ ๊ฑฐ) / Use filename as snapshot name (remove special chars)
let snapshot_name = file_name.replace(['-', '.'], "_");
let snapshot_name_json = format!("{}_json", snapshot_name);
match std::fs::read(file_path) {
Ok(data) => {
match parser.parse(&data) {
Ok(document) => {
// Convert to JSON
let json = serde_json::to_string_pretty(&document)
.expect("Should serialize document to JSON");
// ์ค๋
์ท ์์ฑ / Create snapshot
assert_snapshot_with_path!(snapshot_name_json.as_str(), json);
// ์ค์ JSON ํ์ผ๋ก๋ ์ ์ฅ / Also save as actual JSON file
let json_file = snapshots_dir.join(format!("{}.json", file_name));
std::fs::create_dir_all(&snapshots_dir).unwrap_or(());
std::fs::write(&json_file, &json).unwrap_or_else(|e| {
eprintln!("Failed to write JSON file {}: {}", json_file.display(), e);
});
}
Err(e) => {
eprintln!("Skipping {} due to parse error: {}", file_name, e);
}
}
}
Err(e) => {
eprintln!("Failed to read {}: {}", file_name, e);
}
}
}
}
#[test]
fn test_debug_record_levels() {
let file_path = match find_test_file() {
Some(path) => path,
None => return,
};
if let Ok(data) = std::fs::read(&file_path) {
let mut cfb = CfbParser::parse(&data).expect("Should parse CFB");
let fileheader = FileHeader::parse(
&CfbParser::read_stream(&mut cfb, "FileHeader").expect("Should read FileHeader"),
)
.expect("Should parse FileHeader");
let section_data = CfbParser::read_nested_stream(&mut cfb, "BodyText", "Section0")
.expect("Should read Section0");
let decompressed = if fileheader.is_compressed() {
hwp_core::decompress_deflate(§ion_data).expect("Should decompress section data")
} else {
section_data
};
let mut offset = 0;
let mut record_count = 0;
let mut table_records = Vec::new();
let mut list_header_records = Vec::new();
while offset < decompressed.len() {
let remaining_data = &decompressed[offset..];
match RecordHeader::parse(remaining_data) {
Ok((header, header_size)) => {
record_count += 1;
let tag_id = header.tag_id;
let level = header.level;
let size = header.size as usize;
if tag_id == 0x43 {
table_records.push((record_count, level, offset));
println!(
"Record {}: TABLE (0x43) at offset {}, level {}",
record_count, offset, level
);
}
if tag_id == 0x44 {
list_header_records.push((record_count, level, offset));
println!(
"Record {}: LIST_HEADER (0x44) at offset {}, level {}",
record_count, offset, level
);
}
offset += header_size + size;
}
Err(_) => break,
}
}
println!("\n=== Summary ===");
println!("Total records: {}", record_count);
println!("TABLE records: {}", table_records.len());
println!("LIST_HEADER records: {}", list_header_records.len());
for (table_idx, table_level, table_offset) in &table_records {
println!(
"\nTABLE at record {} (offset {}, level {}):",
table_idx, table_offset, table_level
);
for (list_idx, list_level, list_offset) in &list_header_records {
if *list_offset > *table_offset && *list_offset < *table_offset + 1000 {
println!(
" -> LIST_HEADER at record {} (offset {}, level {})",
list_idx, list_offset, list_level
);
}
}
}
}
}
#[test]
fn test_debug_list_header_children() {
let file_path = match find_test_file() {
Some(path) => path,
None => return,
};
if let Ok(data) = std::fs::read(&file_path) {
let parser = HwpParser::new();
let result = parser.parse(&data);
if let Err(e) = &result {
eprintln!("Parse error: {:?}", e);
}
assert!(result.is_ok(), "Should parse HWP document");
let _document = result.unwrap();
use hwp_core::decompress::decompress_deflate;
use hwp_core::document::bodytext::record_tree::RecordTreeNode;
use hwp_core::CfbParser;
use hwp_core::FileHeader;
let mut cfb = CfbParser::parse(&data).expect("Should parse CFB");
let fileheader = FileHeader::parse(
&CfbParser::read_stream(&mut cfb, "FileHeader").expect("Should read FileHeader"),
)
.expect("Should parse FileHeader");
let section_data = CfbParser::read_nested_stream(&mut cfb, "BodyText", "Section0")
.expect("Should read Section0");
let decompressed = if fileheader.is_compressed() {
decompress_deflate(§ion_data).expect("Should decompress section data")
} else {
section_data
};
let tree = RecordTreeNode::parse_tree(&decompressed).expect("Should parse tree");
// LIST_HEADER ์ฐพ๊ธฐ ๋ฐ ์์ ํ์ธ / Find LIST_HEADER and check children
fn find_list_headers(node: &RecordTreeNode, depth: usize) {
if node.tag_id() == 0x44 {
// HWPTAG_LIST_HEADER
println!(
"{}LIST_HEADER (level {}): {} children",
" ".repeat(depth),
node.level(),
node.children().len()
);
for (i, child) in node.children().iter().enumerate() {
println!(
"{} Child {}: tag_id={}, level={}",
" ".repeat(depth),
i,
child.tag_id(),
child.level()
);
if child.tag_id() == 0x32 {
// HWPTAG_PARA_HEADER
println!("{} -> PARA_HEADER found!", " ".repeat(depth));
}
}
}
for child in node.children() {
find_list_headers(child, depth + 1);
}
}
println!("=== LIST_HEADER Children Debug ===");
find_list_headers(&tree, 0);
}
}
#[test]
fn test_document_markdown_snapshot() {
let file_path = match find_test_file() {
Some(path) => path,
None => return, // Skip test if file not available
};
// ํ์ผ๋ช
์์ ์ค๋
์ท ์ด๋ฆ ์ถ์ถ / Extract snapshot name from filename
let file_name = std::path::Path::new(&file_path)
.file_stem()
.and_then(|n| n.to_str())
.unwrap_or("unknown");
let snapshot_name = file_name.replace(['-', '.'], "_");
let snapshot_name_md = format!("{}_markdown", snapshot_name);
if let Ok(data) = std::fs::read(&file_path) {
let parser = HwpParser::new();
let result = parser.parse(&data);
if let Err(e) = &result {
eprintln!("Parse error: {:?}", e);
}
assert!(result.is_ok(), "Should parse HWP document");
let document = result.unwrap();
// Convert to markdown with image files (not base64)
// ์ด๋ฏธ์ง๋ฅผ ํ์ผ๋ก ์ ์ฅํ๊ณ ํ์ผ ๊ฒฝ๋ก๋ฅผ ์ฌ์ฉ / Save images as files and use file paths
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let snapshots_dir = std::path::Path::new(manifest_dir)
.join("tests")
.join("snapshots");
let images_dir = snapshots_dir.join("images").join(file_name);
std::fs::create_dir_all(&images_dir).unwrap_or(());
let options = hwp_core::viewer::markdown::MarkdownOptions {
image_output_dir: images_dir.to_str().map(|s| s.to_string()),
use_html: Some(true),
include_version: Some(true),
include_page_info: Some(true),
};
let markdown = document.to_markdown(&options);
assert_snapshot_with_path!(snapshot_name_md.as_str(), markdown);
// ์ค์ Markdown ํ์ผ๋ก๋ ์ ์ฅ / Also save as actual Markdown file
let md_file = snapshots_dir.join(format!("{}.md", file_name));
std::fs::write(&md_file, &markdown).unwrap_or_else(|e| {
eprintln!("Failed to write Markdown file: {}", e);
});
}
}
#[test]
fn test_headerfooter_markdown() {
// headerfooter.hwp ํ์ผ์ ๋ํด Markdown ์ค๋
์ท ์์ฑ / Generate Markdown snapshot for headerfooter.hwp
let file_path = match find_headerfooter_file() {
Some(path) => path,
None => {
eprintln!("headerfooter.hwp not found, skipping test");
return;
}
};
let parser = HwpParser::new();
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let snapshots_dir = std::path::Path::new(manifest_dir)
.join("tests")
.join("snapshots");
let file_name = std::path::Path::new(&file_path)
.file_stem()
.and_then(|n| n.to_str())
.unwrap_or("unknown");
let snapshot_name = file_name.replace(['-', '.'], "_");
let snapshot_name_md = format!("{}_markdown", snapshot_name);
match std::fs::read(&file_path) {
Ok(data) => {
match parser.parse(&data) {
Ok(document) => {
// Convert to markdown with image files (not base64)
// ์ด๋ฏธ์ง๋ฅผ ํ์ผ๋ก ์ ์ฅํ๊ณ ํ์ผ ๊ฒฝ๋ก๋ฅผ ์ฌ์ฉ / Save images as files and use file paths
let images_dir = snapshots_dir.join("images").join(file_name);
std::fs::create_dir_all(&images_dir).unwrap_or(());
let options = hwp_core::viewer::markdown::MarkdownOptions {
image_output_dir: images_dir.to_str().map(|s| s.to_string()),
use_html: Some(true),
include_version: Some(true),
include_page_info: Some(true),
};
let markdown = document.to_markdown(&options);
// ์ค๋
์ท ์์ฑ / Create snapshot
assert_snapshot_with_path!(snapshot_name_md.as_str(), markdown);
// ์ค์ Markdown ํ์ผ๋ก๋ ์ ์ฅ / Also save as actual Markdown file
let md_file = snapshots_dir.join(format!("{}.md", file_name));
std::fs::create_dir_all(&snapshots_dir).unwrap_or(());
std::fs::write(&md_file, &markdown).unwrap_or_else(|e| {
eprintln!("Failed to write Markdown file {}: {}", md_file.display(), e);
});
}
Err(e) => {
eprintln!("Failed to parse {}: {:?}", file_path, e);
}
}
}
Err(e) => {
eprintln!("Failed to read {}: {}", file_path, e);
}
}
}
#[test]
fn test_all_fixtures_markdown_snapshots() {
// ๋ชจ๋ fixtures ํ์ผ์ ๋ํด Markdown ์ค๋
์ท ์์ฑ / Generate Markdown snapshots for all fixtures files
let hwp_files = find_all_hwp_files();
if hwp_files.is_empty() {
println!("No HWP files found in fixtures directory");
return;
}
let parser = HwpParser::new();
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let snapshots_dir = std::path::Path::new(manifest_dir)
.join("tests")
.join("snapshots");
for file_path in &hwp_files {
let file_name = std::path::Path::new(file_path)
.file_stem()
.and_then(|n| n.to_str())
.unwrap_or("unknown");
// ํ์ผ๋ช
์ ์ค๋
์ท ์ด๋ฆ์ผ๋ก ์ฌ์ฉ (ํน์ ๋ฌธ์ ์ ๊ฑฐ) / Use filename as snapshot name (remove special chars)
let snapshot_name = file_name.replace(['-', '.'], "_");
let snapshot_name_md = format!("{}_markdown", snapshot_name);
match std::fs::read(file_path) {
Ok(data) => {
match parser.parse(&data) {
Ok(document) => {
// Convert to markdown with image files (not base64)
// ์ด๋ฏธ์ง๋ฅผ ํ์ผ๋ก ์ ์ฅํ๊ณ ํ์ผ ๊ฒฝ๋ก๋ฅผ ์ฌ์ฉ / Save images as files and use file paths
let images_dir = snapshots_dir.join("images").join(file_name);
std::fs::create_dir_all(&images_dir).unwrap_or(());
let options = hwp_core::viewer::markdown::MarkdownOptions {
image_output_dir: images_dir.to_str().map(|s| s.to_string()),
use_html: Some(true),
include_version: Some(true),
include_page_info: Some(true),
};
let markdown = document.to_markdown(&options);
// ์ค๋
์ท ์์ฑ / Create snapshot
assert_snapshot_with_path!(snapshot_name_md.as_str(), markdown);
// ์ค์ Markdown ํ์ผ๋ก๋ ์ ์ฅ / Also save as actual Markdown file
let md_file = snapshots_dir.join(format!("{}.md", file_name));
std::fs::create_dir_all(&snapshots_dir).unwrap_or(());
std::fs::write(&md_file, &markdown).unwrap_or_else(|e| {
eprintln!("Failed to write Markdown file {}: {}", md_file.display(), e);
});
}
Err(e) => {
eprintln!("Skipping {} due to parse error: {}", file_name, e);
}
}
}
Err(e) => {
eprintln!("Failed to read {}: {}", file_name, e);
}
}
}
}
#[test]
fn test_document_html_snapshot() {
let file_path = match find_fixture_file("linespacing.hwp") {
Some(path) => path,
None => return, // Skip test if file not available
};
// ํ์ผ๋ช
์์ ์ค๋
์ท ์ด๋ฆ ์ถ์ถ / Extract snapshot name from filename
let file_name = std::path::Path::new(&file_path)
.file_stem()
.and_then(|n| n.to_str())
.unwrap_or("unknown");
let snapshot_name = file_name.replace(['-', '.'], "_");
let snapshot_name_html = format!("{}_html", snapshot_name);
if let Ok(data) = std::fs::read(&file_path) {
let parser = HwpParser::new();
let result = parser.parse(&data);
if let Err(e) = &result {
eprintln!("Parse error: {:?}", e);
}
assert!(result.is_ok(), "Should parse HWP document");
let document = result.unwrap();
// Convert to HTML with image files (not base64)
// ์ด๋ฏธ์ง๋ฅผ ํ์ผ๋ก ์ ์ฅํ๊ณ ํ์ผ ๊ฒฝ๋ก๋ฅผ ์ฌ์ฉ / Save images as files and use file paths
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let snapshots_dir = std::path::Path::new(manifest_dir)
.join("tests")
.join("snapshots");
let images_dir = snapshots_dir.join("images").join(file_name);
std::fs::create_dir_all(&images_dir).unwrap_or(());
let options = hwp_core::viewer::HtmlOptions {
image_output_dir: images_dir.to_str().map(|s| s.to_string()),
html_output_dir: snapshots_dir.to_str().map(|s| s.to_string()),
include_version: Some(true),
include_page_info: Some(true),
css_class_prefix: "ohah-hwpjs-".to_string(),
};
let html = document.to_html(&options);
assert_snapshot_with_path!(snapshot_name_html.as_str(), html);
// ์ค์ HTML ํ์ผ๋ก๋ ์ ์ฅ / Also save as actual HTML file
let html_file = snapshots_dir.join(format!("{}.html", file_name));
std::fs::write(&html_file, &html).unwrap_or_else(|e| {
eprintln!("Failed to write HTML file: {}", e);
});
}
}
#[test]
fn test_headerfooter_html() {
// headerfooter.hwp ํ์ผ์ ๋ํด HTML ์ค๋
์ท ์์ฑ / Generate HTML snapshot for headerfooter.hwp
let file_path = match find_headerfooter_file() {
Some(path) => path,
None => {
eprintln!("headerfooter.hwp not found, skipping test");
return;
}
};
let parser = HwpParser::new();
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let snapshots_dir = std::path::Path::new(manifest_dir)
.join("tests")
.join("snapshots");
let file_name = std::path::Path::new(&file_path)
.file_stem()
.and_then(|n| n.to_str())
.unwrap_or("unknown");
let snapshot_name = file_name.replace(['-', '.'], "_");
let snapshot_name_html = format!("{}_html", snapshot_name);
match std::fs::read(&file_path) {
Ok(data) => {
match parser.parse(&data) {
Ok(document) => {
// Convert to HTML with image files (not base64)
// ์ด๋ฏธ์ง๋ฅผ ํ์ผ๋ก ์ ์ฅํ๊ณ ํ์ผ ๊ฒฝ๋ก๋ฅผ ์ฌ์ฉ / Save images as files and use file paths
let images_dir = snapshots_dir.join("images").join(file_name);
std::fs::create_dir_all(&images_dir).unwrap_or(());
let options = hwp_core::viewer::html::HtmlOptions {
image_output_dir: images_dir.to_str().map(|s| s.to_string()),
html_output_dir: snapshots_dir.to_str().map(|s| s.to_string()),
include_version: Some(true),
include_page_info: Some(true),
css_class_prefix: "ohah-hwpjs-".to_string(),
};
let html = document.to_html(&options);
// ์ค๋
์ท ์์ฑ / Create snapshot
assert_snapshot_with_path!(snapshot_name_html.as_str(), html);
// ์ค์ HTML ํ์ผ๋ก๋ ์ ์ฅ / Also save as actual HTML file
let html_file = snapshots_dir.join(format!("{}.html", file_name));
std::fs::create_dir_all(&snapshots_dir).unwrap_or(());
std::fs::write(&html_file, &html).unwrap_or_else(|e| {
eprintln!("Failed to write HTML file {}: {}", html_file.display(), e);
});
}
Err(e) => {
eprintln!("Failed to parse {}: {:?}", file_path, e);
}
}
}
Err(e) => {
eprintln!("Failed to read {}: {}", file_path, e);
}
}
}
#[test]
fn test_all_fixtures_html_snapshots() {
// ๋ชจ๋ fixtures ํ์ผ์ ๋ํด HTML ์ค๋
์ท ์์ฑ / Generate HTML snapshots for all fixtures files
let hwp_files = find_all_hwp_files();
if hwp_files.is_empty() {
println!("No HWP files found in fixtures directory");
return;
}
let parser = HwpParser::new();
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let snapshots_dir = std::path::Path::new(manifest_dir)
.join("tests")
.join("snapshots");
for file_path in &hwp_files {
let file_name = std::path::Path::new(file_path)
.file_stem()
.and_then(|n| n.to_str())
.unwrap_or("unknown");
// ํ์ผ๋ช
์ ์ค๋
์ท ์ด๋ฆ์ผ๋ก ์ฌ์ฉ (ํน์ ๋ฌธ์ ์ ๊ฑฐ) / Use filename as snapshot name (remove special chars)
let snapshot_name = file_name.replace(['-', '.'], "_");
let snapshot_name_html = format!("{}_html", snapshot_name);
match std::fs::read(file_path) {
Ok(data) => {
match parser.parse(&data) {
Ok(document) => {
// Convert to HTML with image files (not base64)
// ์ด๋ฏธ์ง๋ฅผ ํ์ผ๋ก ์ ์ฅํ๊ณ ํ์ผ ๊ฒฝ๋ก๋ฅผ ์ฌ์ฉ / Save images as files and use file paths
let images_dir = snapshots_dir.join("images").join(file_name);
std::fs::create_dir_all(&images_dir).unwrap_or(());
let options = hwp_core::viewer::html::HtmlOptions {
image_output_dir: images_dir.to_str().map(|s| s.to_string()),
html_output_dir: snapshots_dir.to_str().map(|s| s.to_string()),
include_version: Some(true),
include_page_info: Some(true),
css_class_prefix: String::new(), // table.html๊ณผ ์ผ์นํ๋๋ก ๋น ๋ฌธ์์ด ์ฌ์ฉ
};
if file_name == "table" {
eprintln!("DEBUG: Processing table.hwp file");
}
let html = document.to_html(&options);
// ์ค๋
์ท ์์ฑ / Create snapshot
assert_snapshot_with_path!(snapshot_name_html.as_str(), html);
// ์ค์ HTML ํ์ผ๋ก๋ ์ ์ฅ / Also save as actual HTML file
let html_file = snapshots_dir.join(format!("{}.html", file_name));
std::fs::create_dir_all(&snapshots_dir).unwrap_or(());
std::fs::write(&html_file, &html).unwrap_or_else(|e| {
eprintln!("Failed to write HTML file {}: {}", html_file.display(), e);
});
}
Err(e) => {
eprintln!("Skipping {} due to parse error: {}", file_name, e);
}
}
}
Err(e) => {
eprintln!("Failed to read {}: {}", file_name, e);
}
}
}
}
#[test]
fn test_table2_html_snapshot() {
// table2.hwp ํ์ผ๋ง ํ
์คํธ / Test only table2.hwp file
let manifest_dir = env!("CARGO_MANIFEST_DIR");
let fixtures_dir = std::path::Path::new(manifest_dir)
.join("tests")
.join("fixtures");
let file_path = fixtures_dir.join("table2.hwp");
if !file_path.exists() {
eprintln!("table2.hwp not found, skipping test");
return;
}
let parser = HwpParser::new();
let snapshots_dir = std::path::Path::new(manifest_dir)
.join("tests")
.join("snapshots");
let file_name = "table2";
let snapshot_name_html = "table2_html";
match std::fs::read(&file_path) {
Ok(data) => {
match parser.parse(&data) {
Ok(document) => {
// Convert to HTML with image files (not base64)
// ์ด๋ฏธ์ง๋ฅผ ํ์ผ๋ก ์ ์ฅํ๊ณ ํ์ผ ๊ฒฝ๋ก๋ฅผ ์ฌ์ฉ / Save images as files and use file paths
let images_dir = snapshots_dir.join("images").join(file_name);
std::fs::create_dir_all(&images_dir).unwrap_or(());
let options = hwp_core::viewer::html::HtmlOptions {
image_output_dir: images_dir.to_str().map(|s| s.to_string()),
html_output_dir: snapshots_dir.to_str().map(|s| s.to_string()),
include_version: Some(true),
include_page_info: Some(true),
css_class_prefix: String::new(), // table.html๊ณผ ์ผ์นํ๋๋ก ๋น ๋ฌธ์์ด ์ฌ์ฉ
};
eprintln!("DEBUG: Processing table2.hwp file");
let html = document.to_html(&options);
// ์ค๋
์ท ์์ฑ / Create snapshot
assert_snapshot_with_path!(snapshot_name_html, html);
// ์ค์ HTML ํ์ผ๋ก๋ ์ ์ฅ / Also save as actual HTML file
let html_file = snapshots_dir.join(format!("{}.html", file_name));
std::fs::create_dir_all(&snapshots_dir).unwrap_or(());
std::fs::write(&html_file, &html).unwrap_or_else(|e| {
eprintln!("Failed to write HTML file {}: {}", html_file.display(), e);
});
}
Err(e) => {
eprintln!("Parse error for table2.hwp: {}", e);
panic!("Failed to parse table2.hwp: {}", e);
}
}
}
Err(e) => {
eprintln!("Failed to read table2.hwp: {}", e);
panic!("Failed to read table2.hwp: {}", e);
}
}
}
#[test]
fn test_parse_all_fixtures() {
// ๋ชจ๋ fixtures ํ์ผ์ ํ์ฑํ์ฌ ์๋ฌ๊ฐ ์๋์ง ํ์ธ / Parse all fixtures files to check for errors
let hwp_files = find_all_hwp_files();
if hwp_files.is_empty() {
println!("No HWP files found in fixtures directory");
return;
}
let parser = HwpParser::new();
let mut success_count = 0;
let mut error_count = 0;
let mut error_files: Vec<(String, String, String)> = Vec::new(); // (file, version, error)
for file_path in &hwp_files {
match std::fs::read(file_path) {
Ok(data) => {
// FileHeader ๋ฒ์ ํ์ธ / Check FileHeader version
use hwp_core::CfbParser;
use hwp_core::FileHeader;
let version_str = match CfbParser::parse(&data) {
Ok(mut cfb) => match CfbParser::read_stream(&mut cfb, "FileHeader") {
Ok(fileheader_data) => match FileHeader::parse(&fileheader_data) {
Ok(fh) => {
let major = (fh.version >> 24) & 0xFF;
let minor = (fh.version >> 16) & 0xFF;
let patch = (fh.version >> 8) & 0xFF;
let revision = fh.version & 0xFF;
format!("{}.{}.{}.{}", major, minor, patch, revision)
}
Err(_) => "unknown".to_string(),
},
Err(_) => "unknown".to_string(),
},
Err(_) => "unknown".to_string(),
};
match parser.parse(&data) {
Ok(_document) => {
success_count += 1;
}
Err(e) => {
error_count += 1;
let file_name = std::path::Path::new(file_path)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(file_path);
error_files.push((file_name.to_string(), version_str, e.to_string()));
eprintln!("Failed to parse {}: {}", file_path, e);
}
}
}
Err(e) => {
error_count += 1;
eprintln!("Failed to read {}: {}", file_path, e);
}
}
}
println!("\n=== Summary ===",);
println!(
"Parsed {} files successfully, {} errors",
success_count, error_count
);
// ์๋ฌ ์ ํ๋ณ ํต๊ณ / Statistics by error type
let mut object_common_errors: Vec<(String, String, String)> = Vec::new();
let mut other_errors: Vec<(String, String, String)> = Vec::new();
for (file, version, error) in &error_files {
if error.contains("Object common properties must be at least 42 bytes") {
object_common_errors.push((file.clone(), version.clone(), error.clone()));
} else {
other_errors.push((file.clone(), version.clone(), error.clone()));
}
}
if !object_common_errors.is_empty() {
println!(
"\n=== Object common properties 40-byte errors ({} files) ===",
object_common_errors.len()
);
for (file, version, error) in &object_common_errors {
println!(" {} (version: {}): {}", file, version, error);
}
}
if !other_errors.is_empty() {
println!("\n=== Other errors ({} files) ===", other_errors.len());
for (file, version, error) in &other_errors {
println!(" {} (version: {}): {}", file, version, error);
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | true |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/packages/hwpjs/build.rs | packages/hwpjs/build.rs | fn main() {
napi_build::setup();
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/packages/hwpjs/src/lib.rs | packages/hwpjs/src/lib.rs | #![deny(clippy::all)]
use base64::{engine::general_purpose::STANDARD, Engine as _};
use hwp_core::HwpParser;
use napi::bindgen_prelude::Buffer;
use napi_derive::napi;
/// Convert HWP file to JSON
///
/// # Arguments
/// * `data` - Byte array containing HWP file data (Buffer or Uint8Array)
///
/// # Returns
/// Parsed HWP document as JSON string
#[napi]
pub fn to_json(data: Buffer) -> Result<String, napi::Error> {
let parser = HwpParser::new();
let data_vec: Vec<u8> = data.into();
let document = parser.parse(&data_vec).map_err(napi::Error::from_reason)?;
// Convert to JSON
serde_json::to_string(&document)
.map_err(|e| napi::Error::from_reason(format!("Failed to serialize to JSON: {}", e)))
}
/// Image format option for markdown conversion
/// ๋งํฌ๋ค์ด ๋ณํ ์ ์ด๋ฏธ์ง ํ์ ์ต์
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageFormat {
/// Base64 data URI embedded directly in markdown
/// ๋งํฌ๋ค์ด์ base64 ๋ฐ์ดํฐ URI๋ฅผ ์ง์ ํฌํจ
Base64,
/// Image data as separate blob array
/// ์ด๋ฏธ์ง๋ฅผ ๋ณ๋ blob ๋ฐฐ์ด๋ก ๋ฐํ
Blob,
}
/// Markdown conversion options
#[napi(object)]
pub struct ToMarkdownOptions {
/// Optional directory path to save images as files. If None, images are embedded as base64 data URIs.
/// ์ด๋ฏธ์ง๋ฅผ ํ์ผ๋ก ์ ์ฅํ ๋๋ ํ ๋ฆฌ ๊ฒฝ๋ก (์ ํ). None์ด๋ฉด base64 ๋ฐ์ดํฐ URI๋ก ์๋ฒ ๋๋ฉ๋๋ค.
pub image_output_dir: Option<String>,
/// Image format: 'base64' to embed base64 data URI directly in markdown, 'blob' to return as separate ImageData array (default: 'blob')
/// ์ด๋ฏธ์ง ํ์: 'base64'๋ ๋งํฌ๋ค์ด์ base64 ๋ฐ์ดํฐ URI๋ฅผ ์ง์ ํฌํจ, 'blob'์ ๋ณ๋ ImageData ๋ฐฐ์ด๋ก ๋ฐํ (๊ธฐ๋ณธ๊ฐ: 'blob')
pub image: Option<String>,
/// Whether to use HTML tags (if Some(true), use <br> tags in areas where line breaks are not possible, such as tables)
/// HTML ํ๊ทธ ์ฌ์ฉ ์ฌ๋ถ (Some(true)์ธ ๊ฒฝ์ฐ ํ
์ด๋ธ ๋ฑ ๊ฐํ ๋ถ๊ฐ ์์ญ์ <br> ํ๊ทธ ์ฌ์ฉ)
pub use_html: Option<bool>,
/// Whether to include version information
/// ๋ฒ์ ์ ๋ณด ํฌํจ ์ฌ๋ถ
pub include_version: Option<bool>,
/// Whether to include page information
/// ํ์ด์ง ์ ๋ณด ํฌํจ ์ฌ๋ถ
pub include_page_info: Option<bool>,
}
/// Image data structure
#[napi(object)]
pub struct ImageData {
/// Image ID (e.g., "image-0")
/// ์ด๋ฏธ์ง ID (์: "image-0")
pub id: String,
/// Image data as Uint8Array
/// ์ด๋ฏธ์ง ๋ฐ์ดํฐ (Uint8Array)
pub data: Buffer,
/// Image format (e.g., "jpg", "png", "bmp")
/// ์ด๋ฏธ์ง ํ์ (์: "jpg", "png", "bmp")
pub format: String,
}
/// Markdown conversion result
#[napi(object)]
pub struct ToMarkdownResult {
/// Markdown string with image references (e.g., "")
/// ์ด๋ฏธ์ง ์ฐธ์กฐ๊ฐ ํฌํจ๋ ๋งํฌ๋ค์ด ๋ฌธ์์ด (์: "")
pub markdown: String,
/// Extracted image data
/// ์ถ์ถ๋ ์ด๋ฏธ์ง ๋ฐ์ดํฐ
pub images: Vec<ImageData>,
}
/// Convert HWP file to Markdown format
///
/// # Arguments
/// * `data` - Byte array containing HWP file data (Buffer or Uint8Array)
/// * `options` - Optional markdown conversion options
///
/// # Returns
/// ToMarkdownResult containing markdown string and image data
#[napi]
pub fn to_markdown(
data: Buffer,
options: Option<ToMarkdownOptions>,
) -> Result<ToMarkdownResult, napi::Error> {
let parser = HwpParser::new();
let data_vec: Vec<u8> = data.into();
let document = parser.parse(&data_vec).map_err(napi::Error::from_reason)?;
// Determine image format option (default: 'blob')
let image_format = options
.as_ref()
.and_then(|o| o.image.as_ref())
.map(|s| s.to_lowercase())
.map(|s| match s.as_str() {
"base64" => ImageFormat::Base64,
"blob" => ImageFormat::Blob,
_ => ImageFormat::Blob, // Default to blob for invalid values
})
.unwrap_or(ImageFormat::Blob);
// Build markdown options
let markdown_options = hwp_core::viewer::markdown::MarkdownOptions {
image_output_dir: None, // Force base64 mode for internal processing
use_html: options.as_ref().and_then(|o| o.use_html),
include_version: options.as_ref().and_then(|o| o.include_version),
include_page_info: options.as_ref().and_then(|o| o.include_page_info),
};
// Convert to markdown with base64 images
let mut markdown = document.to_markdown(&markdown_options);
// Extract images from BinData
let mut images = Vec::new();
match image_format {
ImageFormat::Base64 => {
// For base64 format, we need to ensure all image placeholders are replaced with base64 URIs
// to_markdown should already generate base64 URIs, but we'll make sure by replacing any placeholders
for (index, bin_item) in document.bin_data.items.iter().enumerate() {
let mime_type = get_mime_type_from_bindata_id(&document, bin_item.index);
let base64_data_uri = format!("data:{};base64,{}", mime_type, bin_item.data);
let image_id = format!("image-{}", index);
// Replace any placeholder with base64 URI
let placeholder_pattern = format!("", image_id);
if markdown.contains(&placeholder_pattern) {
markdown = markdown.replace(
&placeholder_pattern,
&format!("", base64_data_uri),
);
}
// Also check if there's already a base64 URI and ensure it's correct
// (This handles the case where to_markdown already generated base64)
// No need to do anything if base64 is already there
}
// Don't add to images array for base64 format
}
ImageFormat::Blob => {
// Extract all images and replace base64 URIs with placeholders
for (index, bin_item) in document.bin_data.items.iter().enumerate() {
// Get extension and mime type from bin_data_records
let extension = get_extension_from_bindata_id(&document, bin_item.index);
let mime_type = get_mime_type_from_bindata_id(&document, bin_item.index);
let base64_data_uri = format!("data:{};base64,{}", mime_type, bin_item.data);
let image_id = format!("image-{}", index);
// Decode base64 data for blob format
let image_data = STANDARD.decode(&bin_item.data).map_err(|e| {
napi::Error::from_reason(format!("Failed to decode base64 image data: {}", e))
})?;
images.push(ImageData {
id: image_id.clone(),
data: Buffer::from(image_data),
format: extension,
});
// Replace base64 data URIs in markdown with placeholders
// Pattern: 
let pattern = format!("", base64_data_uri);
let replacement = format!("", image_id);
markdown = markdown.replace(&pattern, &replacement);
// Also handle cases where the pattern might be split across lines or have different formatting
let pattern2 = format!(
"",
base64_data_uri.replace("(", "\\(").replace(")", "\\)")
);
markdown = markdown.replace(&pattern2, &replacement);
}
}
}
Ok(ToMarkdownResult { markdown, images })
}
/// Get file extension from BinData ID
fn get_extension_from_bindata_id(
document: &hwp_core::HwpDocument,
bindata_id: hwp_core::WORD,
) -> String {
for record in &document.doc_info.bin_data {
if let hwp_core::BinDataRecord::Embedding { embedding, .. } = record {
if embedding.binary_data_id == bindata_id {
return embedding.extension.clone();
}
}
}
"jpg".to_string()
}
/// Get MIME type from BinData ID
fn get_mime_type_from_bindata_id(
document: &hwp_core::HwpDocument,
bindata_id: hwp_core::WORD,
) -> String {
for record in &document.doc_info.bin_data {
if let hwp_core::BinDataRecord::Embedding { embedding, .. } = record {
if embedding.binary_data_id == bindata_id {
return match embedding.extension.to_lowercase().as_str() {
"jpg" | "jpeg" => "image/jpeg",
"png" => "image/png",
"gif" => "image/gif",
"bmp" => "image/bmp",
_ => "image/jpeg",
}
.to_string();
}
}
}
"image/jpeg".to_string()
}
/// HTML conversion options
#[napi(object)]
pub struct ToHtmlOptions {
/// Optional directory path to save images as files. If None, images are embedded as base64 data URIs.
/// ์ด๋ฏธ์ง๋ฅผ ํ์ผ๋ก ์ ์ฅํ ๋๋ ํ ๋ฆฌ ๊ฒฝ๋ก (์ ํ). None์ด๋ฉด base64 ๋ฐ์ดํฐ URI๋ก ์๋ฒ ๋๋ฉ๋๋ค.
pub image_output_dir: Option<String>,
/// Directory path where HTML file is saved (used for calculating relative image paths)
/// HTML ํ์ผ์ด ์ ์ฅ๋๋ ๋๋ ํ ๋ฆฌ ๊ฒฝ๋ก (์ด๋ฏธ์ง ์๋ ๊ฒฝ๋ก ๊ณ์ฐ์ ์ฌ์ฉ)
pub html_output_dir: Option<String>,
/// Whether to include version information
/// ๋ฒ์ ์ ๋ณด ํฌํจ ์ฌ๋ถ
pub include_version: Option<bool>,
/// Whether to include page information
/// ํ์ด์ง ์ ๋ณด ํฌํจ ์ฌ๋ถ
pub include_page_info: Option<bool>,
/// CSS class prefix (default: "" - noori.html style)
/// CSS ํด๋์ค ์ ๋์ฌ (๊ธฐ๋ณธ๊ฐ: "" - noori.html ์คํ์ผ)
pub css_class_prefix: Option<String>,
}
/// Convert HWP file to HTML format
///
/// # Arguments
/// * `data` - Byte array containing HWP file data (Buffer or Uint8Array)
/// * `options` - Optional HTML conversion options
///
/// # Returns
/// HTML string representation of the document
#[napi]
pub fn to_html(data: Buffer, options: Option<ToHtmlOptions>) -> Result<String, napi::Error> {
let parser = HwpParser::new();
let data_vec: Vec<u8> = data.into();
let document = parser.parse(&data_vec).map_err(napi::Error::from_reason)?;
// Build HTML options
let html_options = hwp_core::viewer::html::HtmlOptions {
image_output_dir: options.as_ref().and_then(|o| o.image_output_dir.clone()),
html_output_dir: options.as_ref().and_then(|o| o.html_output_dir.clone()),
include_version: options.as_ref().and_then(|o| o.include_version),
include_page_info: options.as_ref().and_then(|o| o.include_page_info),
css_class_prefix: options
.as_ref()
.and_then(|o| o.css_class_prefix.clone())
.unwrap_or_default(),
};
// Convert to HTML
let html = document.to_html(&html_options);
Ok(html)
}
/// Extract FileHeader from HWP file as JSON
///
/// # Arguments
/// * `data` - Byte array containing HWP file data (Buffer or Uint8Array)
///
/// # Returns
/// FileHeader as JSON string
#[napi]
pub fn file_header(data: Buffer) -> Result<String, napi::Error> {
let parser = HwpParser::new();
let data_vec: Vec<u8> = data.into();
parser
.parse_fileheader_json(&data_vec)
.map_err(napi::Error::from_reason)
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/packages/hwpjs/crates/lib/build.rs | packages/hwpjs/crates/lib/build.rs | fn main() {
craby_build::setup();
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/packages/hwpjs/crates/lib/src/lib.rs | packages/hwpjs/crates/lib/src/lib.rs | #[rustfmt::skip]
pub(crate) mod ffi;
pub(crate) mod generated;
pub(crate) mod hwpjs_impl;
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/packages/hwpjs/crates/lib/src/hwpjs_impl.rs | packages/hwpjs/crates/lib/src/hwpjs_impl.rs | use craby::{prelude::*, throw};
use crate::ffi::bridging::*;
use crate::generated::*;
use hwp_core::HwpParser;
pub struct Hwpjs {
ctx: Context,
}
#[craby_module]
impl HwpjsSpec for Hwpjs {
fn new(ctx: Context) -> Self {
Self { ctx }
}
fn id(&self) -> usize {
self.ctx.id
}
fn to_json(&mut self, data: Vec<u8>) -> String {
let parser = HwpParser::new();
let document = parser.parse(&data).unwrap_or_else(|e| throw!("{}", e));
serde_json::to_string(&document)
.unwrap_or_else(|e| throw!("Failed to serialize to JSON: {}", e))
}
fn to_markdown(&mut self, data: Vec<u8>, options: ToMarkdownOptions) -> ToMarkdownResult {
let parser = HwpParser::new();
let document = parser.parse(&data).unwrap_or_else(|e| throw!("{}", e));
// ToMarkdownOptions๋ฅผ hwp_core::viewer::markdown::MarkdownOptions๋ก ๋ณํ
let image_output_dir: Nullable<String> = options.image_output_dir.into();
let use_html = Some(options.use_html);
let include_version = Some(options.include_version);
let include_page_info = Some(options.include_page_info);
let markdown_options = hwp_core::viewer::markdown::MarkdownOptions {
image_output_dir: image_output_dir.into_value(),
use_html,
include_version,
include_page_info,
};
// ๋งํฌ๋ค์ด ๋ณํ (์ด๋ฏธ์ง๋ base64๋ก ์๋ฒ ๋)
let markdown = document.to_markdown(&markdown_options);
ToMarkdownResult { markdown }
}
fn file_header(&mut self, data: Vec<u8>) -> String {
let parser = HwpParser::new();
parser
.parse_fileheader_json(&data)
.unwrap_or_else(|e| throw!("{}", e))
}
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
ohah/hwpjs | https://github.com/ohah/hwpjs/blob/19df26a209c6e780b4c3b03d2ab628209e1ae311/packages/hwpjs/crates/lib/src/ffi.rs | packages/hwpjs/crates/lib/src/ffi.rs | // Auto generated by Craby. DO NOT EDIT.
#[rustfmt::skip]
use craby::prelude::*;
use crate::generated::*;
use crate::hwpjs_impl::*;
use bridging::*;
#[cxx::bridge(namespace = "craby::hwpjs::bridging")]
pub mod bridging {
#[derive(Clone)]
struct NullableString {
null: bool,
val: String,
}
#[derive(Clone)]
struct ToMarkdownResult {
markdown: String,
}
#[derive(Clone)]
struct ToMarkdownOptions {
image_output_dir: NullableString,
image: NullableString,
use_html: bool,
include_version: bool,
include_page_info: bool,
}
extern "Rust" {
type Hwpjs;
#[cxx_name = "createHwpjs"]
fn create_hwpjs(id: usize, data_path: &str) -> Box<Hwpjs>;
#[cxx_name = "createVecFromSlice"]
fn create_vec_from_slice(data: &[u8]) -> Vec<u8>;
#[cxx_name = "fileHeader"]
fn hwpjs_file_header(it_: &mut Hwpjs, data: Vec<u8>) -> Result<String>;
#[cxx_name = "toJson"]
fn hwpjs_to_json(it_: &mut Hwpjs, data: Vec<u8>) -> Result<String>;
#[cxx_name = "toMarkdown"]
fn hwpjs_to_markdown(
it_: &mut Hwpjs,
data: Vec<u8>,
options: ToMarkdownOptions,
) -> Result<ToMarkdownResult>;
}
}
fn create_hwpjs(id: usize, data_path: &str) -> Box<Hwpjs> {
let ctx = Context::new(id, data_path);
Box::new(Hwpjs::new(ctx))
}
fn create_vec_from_slice(data: &[u8]) -> Vec<u8> {
data.to_vec()
}
fn hwpjs_file_header(it_: &mut Hwpjs, data: Vec<u8>) -> Result<String, anyhow::Error> {
craby::catch_panic!({
let ret = it_.file_header(data);
ret
})
}
fn hwpjs_to_json(it_: &mut Hwpjs, data: Vec<u8>) -> Result<String, anyhow::Error> {
craby::catch_panic!({
let ret = it_.to_json(data);
ret
})
}
fn hwpjs_to_markdown(
it_: &mut Hwpjs,
data: Vec<u8>,
options: ToMarkdownOptions,
) -> Result<ToMarkdownResult, anyhow::Error> {
craby::catch_panic!({
let ret = it_.to_markdown(data, options);
ret
})
}
| rust | MIT | 19df26a209c6e780b4c3b03d2ab628209e1ae311 | 2026-01-04T20:24:59.575438Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.