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 &paragraph.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 &paragraph.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.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, &paragraph.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 &section.paragraphs { for record in &paragraph.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(&section_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(&section_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., "![์ด๋ฏธ์ง€](image-0)") /// ์ด๋ฏธ์ง€ ์ฐธ์กฐ๊ฐ€ ํฌํ•จ๋œ ๋งˆํฌ๋‹ค์šด ๋ฌธ์ž์—ด (์˜ˆ: "![์ด๋ฏธ์ง€](image-0)") 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: ![์ด๋ฏธ์ง€](data:image/...;base64,...) 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