unhwp 0.4.0

A high-performance library for extracting HWP/HWPX documents into structured Markdown
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! HWPX (OWPML) XML format parser.
//!
//! HWPX files are ZIP archives containing XML documents following the
//! KS X 6101 OWPML standard.

mod container;
mod header;
mod section;
mod styles;

pub use container::HwpxContainer;

use crate::error::Result;
use crate::model::Document;
use crate::streaming::{ParseEvent, SectionStreamOptions};
use quick_xml::events::Event;
use quick_xml::Reader;
#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;
use std::io::{Read, Seek};
use std::ops::ControlFlow;
use std::path::Path;

/// HWPX XML namespaces.
pub mod ns {
    /// Hancom Paragraph namespace
    pub const HP: &str = "http://www.hancom.co.kr/hwpml/2011/paragraph";
    /// Hancom Core namespace
    pub const HC: &str = "http://www.hancom.co.kr/hwpml/2011/core";
    /// Hancom Head namespace
    pub const HH: &str = "http://www.hancom.co.kr/hwpml/2011/head";
    /// Hancom Master namespace
    pub const HM: &str = "http://www.hancom.co.kr/hwpml/2011/master";
}

/// HWPX document parser.
pub struct HwpxParser {
    container: HwpxContainer,
}

impl HwpxParser {
    /// Opens an HWPX document from a file path.
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        let container = HwpxContainer::open(path)?;
        Ok(Self { container })
    }

    /// Opens an HWPX document from a reader.
    pub fn from_reader<R: Read + Seek>(reader: R) -> Result<Self> {
        let container = HwpxContainer::from_reader(reader)?;
        Ok(Self { container })
    }

    /// Parses the document into the unified document model.
    pub fn parse(&mut self) -> Result<Document> {
        let mut document = Document::new();

        // Set format info
        document.metadata.format_version = Some("HWPX".to_string());

        // Parse metadata from content.hpf
        self.parse_metadata(&mut document)?;

        // Parse header options (distribution flag)
        self.parse_header_options(&mut document)?;

        // Parse styles
        self.parse_styles(&mut document)?;

        // Parse sections
        self.parse_sections(&mut document)?;

        // Extract resources
        self.extract_resources(&mut document)?;

        Ok(document)
    }

    /// Parses the document in streaming mode, emitting events for each section.
    ///
    /// This is the bounded-memory alternative to [`parse`](Self::parse). Each
    /// section is parsed and emitted individually; its memory is freed before
    /// the next section is loaded. The `rayon` parallel path used by `parse()`
    /// is not used here — sections are always processed sequentially.
    ///
    /// See [`crate::streaming::parse_file_streaming`] for the public API.
    pub fn for_each_section<F>(&mut self, opts: SectionStreamOptions, mut f: F) -> Result<()>
    where
        F: FnMut(ParseEvent<'_>) -> ControlFlow<()>,
    {
        // Phase 1: parse prerequisites using a temporary Document.
        // We move metadata and styles out so they become owned stack locals,
        // giving us the stack-frame lifetime that satisfies ParseEvent<'doc>.
        let (metadata, styles) = {
            let mut tmp = Document::new();
            tmp.metadata.format_version = Some("HWPX".to_string());
            self.parse_metadata(&mut tmp)?;
            self.parse_header_options(&mut tmp)?;
            self.parse_styles(&mut tmp)?;
            (tmp.metadata, tmp.styles)
        };

        let section_files = self.container.list_sections()?;
        let section_count = section_files.len();
        let image_map = self.container.build_image_map();

        if f(ParseEvent::DocumentStart {
            metadata: &metadata,
            styles: &styles,
            section_count,
            image_map,
        }) == ControlFlow::Break(())
        {
            return Ok(());
        }

        // Phase 2: parse and emit sections one at a time (no rayon).
        for (index, path) in section_files.iter().enumerate() {
            match self.container.read_file(path) {
                Err(e) if opts.error_mode == crate::parse_options::ErrorMode::Lenient => {
                    if f(ParseEvent::SectionFailed { index, error: e }) == ControlFlow::Break(()) {
                        return Ok(());
                    }
                }
                Err(e) => return Err(e),
                Ok(xml) => match section::parse_section(&xml, index, &styles) {
                    Err(e) if opts.error_mode == crate::parse_options::ErrorMode::Lenient => {
                        if f(ParseEvent::SectionFailed { index, error: e })
                            == ControlFlow::Break(())
                        {
                            return Ok(());
                        }
                    }
                    Err(e) => return Err(e),
                    Ok(sec) => {
                        if f(ParseEvent::SectionParsed(&sec)) == ControlFlow::Break(()) {
                            return Ok(());
                        }
                        // `sec` is dropped here — memory reclaimed before
                        // the next section is loaded.
                    }
                },
            }
        }

        // Phase 3: emit DocumentEnd before resources.
        if f(ParseEvent::DocumentEnd) == ControlFlow::Break(()) {
            return Ok(());
        }

        // Phase 4: resource extraction (after DocumentEnd).
        if opts.extract_resources {
            if let Ok(resources) = self.container.list_bindata() {
                for resource_path in resources {
                    if let Ok(data) = self.container.read_binary(&resource_path) {
                        let name = resource_path
                            .rsplit('/')
                            .next()
                            .unwrap_or(&resource_path)
                            .to_string();
                        if f(ParseEvent::ResourceExtracted { name, data }) == ControlFlow::Break(())
                        {
                            return Ok(());
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Parses document metadata from content.hpf.
    fn parse_metadata(&mut self, document: &mut Document) -> Result<()> {
        let content_hpf = self.container.read_content_hpf()?;

        // Parse basic metadata from content.hpf
        // Title, author, etc. are in the opf:metadata element

        if let Some(title) = extract_metadata_field(&content_hpf, "title") {
            document.metadata.title = Some(title);
        }
        if let Some(author) = extract_metadata_field(&content_hpf, "creator") {
            document.metadata.author = Some(author);
        }
        if let Some(subject) = extract_metadata_field(&content_hpf, "description") {
            document.metadata.subject = Some(subject);
        }
        if let Some(date) = extract_metadata_field(&content_hpf, "date") {
            document.metadata.created = Some(date);
        }
        if let Some(modified) = extract_metadata_field(&content_hpf, "modified") {
            document.metadata.modified = Some(modified);
        }

        // Extract keywords
        let keywords = extract_keywords(&content_hpf);
        if !keywords.is_empty() {
            document.metadata.keywords = keywords;
        }

        // Try to get application info
        if let Some(generator) = extract_metadata_field(&content_hpf, "generator") {
            document.metadata.creator_app = Some(generator);
        }

        Ok(())
    }

    /// Parses styles from header.xml or section header.
    fn parse_styles(&mut self, document: &mut Document) -> Result<()> {
        if let Ok(styles_xml) = self.container.read_file("Contents/header.xml") {
            styles::parse_styles(&styles_xml, &mut document.styles)?;
        }
        Ok(())
    }

    /// Parses header options from header.xml.
    fn parse_header_options(&mut self, document: &mut Document) -> Result<()> {
        if let Ok(header_xml) = self.container.read_file("Contents/header.xml") {
            let is_distribution = header::parse_header(&header_xml)?;
            document.metadata.is_distribution = is_distribution;
        }
        Ok(())
    }

    /// Parses all sections.
    ///
    /// Uses parallel processing when there are multiple sections.
    fn parse_sections(&mut self, document: &mut Document) -> Result<()> {
        let section_files = self.container.list_sections()?;

        // Read all section XML content first (requires mutable borrow)
        let section_data: Vec<(usize, String)> = section_files
            .iter()
            .enumerate()
            .filter_map(|(index, path)| self.container.read_file(path).ok().map(|xml| (index, xml)))
            .collect();

        // Clone styles for parallel access
        let styles = document.styles.clone();

        // Use parallel processing only when there are enough sections to benefit
        // Threshold of 3 sections avoids parallel overhead for small documents
        #[cfg(not(target_arch = "wasm32"))]
        const PARALLEL_THRESHOLD: usize = 3;

        #[cfg(not(target_arch = "wasm32"))]
        let mut sections: Vec<_> = if section_data.len() >= PARALLEL_THRESHOLD {
            section_data
                .par_iter()
                .filter_map(|(index, xml)| section::parse_section(xml, *index, &styles).ok())
                .collect()
        } else {
            section_data
                .iter()
                .filter_map(|(index, xml)| section::parse_section(xml, *index, &styles).ok())
                .collect()
        };

        #[cfg(target_arch = "wasm32")]
        let mut sections: Vec<_> = section_data
            .iter()
            .filter_map(|(index, xml)| section::parse_section(xml, *index, &styles).ok())
            .collect();

        // Sort by index to maintain order
        sections.sort_by_key(|s| s.index);

        document.sections = sections;
        Ok(())
    }

    /// Extracts binary resources from BinData folder.
    fn extract_resources(&mut self, document: &mut Document) -> Result<()> {
        let resources = self.container.list_bindata()?;

        for resource_path in resources {
            if let Ok(data) = self.container.read_binary(&resource_path) {
                let filename = resource_path
                    .rsplit('/')
                    .next()
                    .unwrap_or(&resource_path)
                    .to_string();

                let mime_type = guess_mime_type(&filename);

                let size = data.len();
                let resource = crate::model::Resource {
                    resource_type: crate::model::ResourceType::Image,
                    filename: Some(filename.clone()),
                    mime_type,
                    data,
                    size,
                };

                document.resources.insert(filename, resource);
            }
        }

        Ok(())
    }
}

/// Metadata extraction result from content.hpf.
#[derive(Default)]
struct MetadataResult {
    title: Option<String>,
    creator: Option<String>,
    description: Option<String>,
    date: Option<String>,
    modified: Option<String>,
    generator: Option<String>,
    keywords: Vec<String>,
}

/// Extracts all metadata fields from content.hpf XML using proper XML parsing.
/// This replaces the naive string-based extraction with quick-xml parsing.
fn parse_metadata_xml(xml: &str) -> MetadataResult {
    let mut result = MetadataResult::default();
    let mut reader = Reader::from_str(xml);
    reader.config_mut().trim_text(true);

    let mut buf = Vec::new();
    let mut current_element: Option<String> = None;
    let mut current_meta_name: Option<String> = None;

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
                let name = get_local_name(&e);
                match name.as_str() {
                    "title" | "creator" | "description" | "date" | "modified" | "generator"
                    | "subject" | "keywords" => {
                        current_element = Some(name);
                    }
                    "meta" => {
                        // Check for name attribute
                        for attr in e.attributes().flatten() {
                            if attr.key.local_name().as_ref() == b"name" {
                                if let Ok(value) = attr.unescape_value() {
                                    current_meta_name = Some(value.to_string());
                                }
                            }
                        }
                    }
                    _ => {
                        current_element = None;
                    }
                }
            }
            Ok(Event::Text(e)) => {
                if let Ok(text) = e.unescape() {
                    let text = text.trim().to_string();
                    if !text.is_empty() {
                        // Handle element-based metadata
                        if let Some(ref elem) = current_element {
                            match elem.as_str() {
                                "title" => result.title = Some(text.clone()),
                                "creator" => result.creator = Some(text.clone()),
                                "description" => result.description = Some(text.clone()),
                                "date" => result.date = Some(text.clone()),
                                "modified" => result.modified = Some(text.clone()),
                                "generator" => result.generator = Some(text.clone()),
                                "subject" | "keywords" => {
                                    // Split by common delimiters
                                    for kw in text.split([',', ';', '|']) {
                                        let kw = kw.trim();
                                        if !kw.is_empty()
                                            && !result.keywords.contains(&kw.to_string())
                                        {
                                            result.keywords.push(kw.to_string());
                                        }
                                    }
                                }
                                _ => {}
                            }
                        }
                        // Handle meta name-based metadata
                        else if let Some(ref meta_name) = current_meta_name {
                            match meta_name.as_str() {
                                "title" => result.title = Some(text.clone()),
                                "creator" => result.creator = Some(text.clone()),
                                "description" => result.description = Some(text.clone()),
                                "date" => result.date = Some(text.clone()),
                                "modified" => result.modified = Some(text.clone()),
                                "generator" => result.generator = Some(text.clone()),
                                "subject" | "keywords" => {
                                    for kw in text.split([',', ';', '|']) {
                                        let kw = kw.trim();
                                        if !kw.is_empty()
                                            && !result.keywords.contains(&kw.to_string())
                                        {
                                            result.keywords.push(kw.to_string());
                                        }
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                }
            }
            Ok(Event::End(_)) => {
                current_element = None;
                current_meta_name = None;
            }
            Ok(Event::Eof) => break,
            Err(_) => break,
            _ => {}
        }
        buf.clear();
    }

    result
}

/// Extracts a single metadata field from content.hpf XML.
fn extract_metadata_field(xml: &str, field: &str) -> Option<String> {
    let metadata = parse_metadata_xml(xml);
    match field {
        "title" => metadata.title,
        "creator" => metadata.creator,
        "description" => metadata.description,
        "date" => metadata.date,
        "modified" => metadata.modified,
        "generator" => metadata.generator,
        "subject" | "keywords" => {
            if metadata.keywords.is_empty() {
                None
            } else {
                Some(metadata.keywords.join(", "))
            }
        }
        _ => None,
    }
}

/// Extracts keywords from content.hpf XML.
fn extract_keywords(xml: &str) -> Vec<String> {
    parse_metadata_xml(xml).keywords
}

/// Gets the local name from an XML element (strips namespace prefix).
fn get_local_name(e: &quick_xml::events::BytesStart) -> String {
    let name = e.name();
    let local = name.local_name();
    String::from_utf8_lossy(local.as_ref()).to_string()
}

/// Guesses MIME type from filename extension.
fn guess_mime_type(filename: &str) -> Option<String> {
    let ext = filename.rsplit('.').next()?.to_lowercase();
    match ext.as_str() {
        "png" => Some("image/png".to_string()),
        "jpg" | "jpeg" => Some("image/jpeg".to_string()),
        "gif" => Some("image/gif".to_string()),
        "bmp" => Some("image/bmp".to_string()),
        "webp" => Some("image/webp".to_string()),
        "svg" => Some("image/svg+xml".to_string()),
        "wmf" => Some("image/x-wmf".to_string()),
        "emf" => Some("image/x-emf".to_string()),
        _ => None,
    }
}