rhwp 0.9.1

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
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
//! 부모의 저장 쪽 경계로 확인한 작은 중첩 글자 표의 물리 프레임.

use crate::model::{
    control::Control,
    document::Document,
    paragraph::{LineSeg, Paragraph},
    shape::{TextWrap, VertRelTo},
    table::{Cell, Table, TablePageBreak},
};
use std::{collections::HashMap, sync::Arc};

#[derive(Clone, Debug)]
pub(crate) struct StoredTextFrameUnit {
    pub paragraph: usize,
    pub line: usize,
    pub physical_height_hu: i32,
    pub starts_frame: bool,
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct StoredTextFrame {
    pub start: usize,
    pub end: usize,
    pub body_height_hu: i32,
}

#[derive(Clone, Debug)]
pub(crate) struct StoredNestedTextFrames {
    pub units: Vec<StoredTextFrameUnit>,
    pub frames: Vec<StoredTextFrame>,
    /// 부모 선언이 자식 첫 프레임과 부모 상하 안 여백을 함께 닫는다.
    pub parent_opening_owns_bottom_padding: bool,
}

impl StoredNestedTextFrames {
    pub fn frame_for_cut(&self, start: usize, end: usize) -> Option<StoredTextFrame> {
        self.frames
            .iter()
            .copied()
            .find(|frame| frame.start == start && frame.end == end.min(self.units.len()))
    }
}

fn original(paragraph: &Paragraph) -> bool {
    !paragraph.stored_text_partition_is_dirty()
        && !paragraph.cell_format_vpos_dirty
        && !paragraph.line_segs.is_empty()
        && paragraph.line_segs.iter().all(|line| {
            line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                && line.vertical_pos >= 0
                && line.line_height > 0
                && line.line_spacing >= 0
                && line.segment_width > 0
        })
}

fn prove(
    document: &Document,
    owner: &Table,
    parent: &Cell,
    host_index: usize,
    child: &Table,
) -> Option<StoredNestedTextFrames> {
    match prove_with_storage(
        document,
        owner,
        parent,
        host_index,
        child,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn prove_with_storage<S: crate::storage::Storage>(
    document: &Document,
    owner: &Table,
    parent: &Cell,
    host_index: usize,
    child: &Table,
    storage: &S,
) -> Result<Option<StoredNestedTextFrames>, S::Error> {
    crate::storage::with_optional(|failure| {
        let host = parent.paragraphs.get(host_index)?;
        let successor = parent.paragraphs.get(host_index + 1)?;
        if owner.layout_page_break() != TablePageBreak::RowBreak
        || owner.common.treat_as_char
        || parent.dirty_flag
        || host.stored_text_partition_is_dirty()
        || host.cell_format_vpos_dirty
        || successor.stored_text_partition_is_dirty()
        || successor.cell_format_vpos_dirty
        || !host.text.trim().is_empty()
        || host.controls.len() != 1
        || host.line_segs.len() != 1
        || successor.line_segs.is_empty()
        || host.line_segs[0].tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
        || successor.line_segs[0].tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
        // HWPX의 CELL은 내부 RowBreak다. serializer의 문자열과 내부 enum을 혼동하지 않는다.
        || child.layout_page_break() != TablePageBreak::RowBreak
        || child.common.treat_as_char
        || !child.common.flow_with_text
        || child.common.text_wrap != TextWrap::TopAndBottom
        || child.common.vert_rel_to != VertRelTo::Para
        || child.common.vertical_offset != 0
        || child.caption.is_some()
        || child.row_count != 1
        || child.col_count != 1
        || child.cells.len() != 1
        || child.common.height == 0
        || child.common.height > i32::MAX as u32
        || child.outer_margin_top < 0
        || child.outer_margin_bottom < 0
        {
            return None;
        }
        let cell = &child.cells[0];
        if cell.dirty_flag
            || cell.row_span != 1
            || cell.col_span != 1
            || cell.height <= child.common.height
            || cell.paragraphs.iter().any(|paragraph| {
                !original(paragraph)
                    || !paragraph.controls.is_empty()
                    || paragraph.text.trim().is_empty()
            })
        {
            return None;
        }
        let spacing = |index: usize| {
            let paragraph = cell.paragraphs.get(index)?;
            let shape = document
                .doc_info
                .para_shapes
                .get(usize::from(paragraph.para_shape_id))?;
            let physical = |raw| {
                crate::renderer::style_resolver::paragraph_margin_hwpunit(raw, &document.doc_info)
            };
            Some((
                physical(shape.spacing_before).round() as i32,
                physical(shape.spacing_after).round() as i32,
            ))
        };
        let lines: Vec<_> = crate::storage::optional(
            storage.collect(
                cell.paragraphs
                    .iter()
                    .enumerate()
                    .flat_map(|(pi, paragraph)| {
                        paragraph
                            .line_segs
                            .iter()
                            .enumerate()
                            .map(move |(li, line)| (pi, li, line))
                    }),
            ),
            failure,
        )?;
        let first = lines.first()?;
        if first.2.vertical_pos != spacing(first.0)?.0 {
            return None;
        }
        let mut restart = None;
        for (index, pair) in lines.windows(2).enumerate() {
            let (pi, _, previous) = pair[0];
            let (next_pi, next_li, next) = pair[1];
            if next.vertical_pos < previous.vertical_pos {
                if restart.is_some()
                    || next_li != 0
                    || pi == next_pi
                    || next.vertical_pos != spacing(next_pi)?.0
                {
                    return None;
                }
                restart = Some(index + 1);
            } else {
                let advance = i64::from(previous.line_height)
                    + i64::from(previous.line_spacing)
                    + if pi == next_pi {
                        0
                    } else {
                        i64::from(spacing(pi)?.1) + i64::from(spacing(next_pi)?.0)
                    };
                if i64::from(next.vertical_pos) - i64::from(previous.vertical_pos) != advance {
                    return None;
                }
            }
        }
        let restart = restart?;
        let padding = cell.effective_padding(&child.padding);
        let pad_top = i32::from(padding.top);
        let pad_bottom = i32::from(padding.bottom);
        if pad_top < 0 || pad_bottom < 0 {
            return None;
        }
        let opening_ink_end = lines[restart - 1]
            .2
            .vertical_pos
            .checked_add(lines[restart - 1].2.line_height)?
            .checked_add(pad_top)?
            .checked_add(pad_bottom)?;
        let opening = i32::try_from(child.common.height).ok()?;
        if opening < opening_ink_end {
            return None;
        }
        let last = lines.last()?.2;
        let tail = last
            .vertical_pos
            .checked_add(last.line_height)?
            .checked_add(pad_top)?
            .checked_add(pad_bottom)?;
        let outer_top = i32::from(child.outer_margin_top);
        let outer_bottom = i32::from(child.outer_margin_bottom);
        // 부모 뒤 줄의 새 원점이 자식 마지막 상자와 사방 여백을 정확히 닫는다.
        // 작은 로컬 되감김이나 선언 높이만으로 쪽 경계를 승격하지 않는다.
        if successor.line_segs[0].vertical_pos
            != tail.checked_add(outer_top)?.checked_add(outer_bottom)?
            || successor.line_segs[0].vertical_pos >= host.line_segs[0].vertical_pos
        {
            return None;
        }
        let frames = crate::storage::optional(
            storage.collect([
                StoredTextFrame {
                    start: 0,
                    end: restart,
                    body_height_hu: opening,
                },
                StoredTextFrame {
                    start: restart,
                    end: lines.len(),
                    body_height_hu: tail,
                },
            ]),
            failure,
        )?;
        for frame in &frames {
            frame
                .body_height_hu
                .checked_add(outer_top)?
                .checked_add(outer_bottom)?;
        }
        let mut units = crate::storage::optional(storage.vec(lines.len()), failure)?;
        for frame in &frames {
            for index in frame.start..frame.end {
                let (paragraph, line, source) = lines[index];
                let end = index + 1 == frame.end;
                let mut height = if end {
                    source.line_height
                } else {
                    lines[index + 1].2.vertical_pos - source.vertical_pos
                };
                if index == frame.start {
                    height += source.vertical_pos + pad_top + outer_top;
                }
                if end {
                    height += pad_bottom + outer_bottom;
                    if frame.start == 0 {
                        height += opening - opening_ink_end;
                    }
                }
                crate::storage::optional(
                    storage.push(
                        &mut units,
                        StoredTextFrameUnit {
                            paragraph,
                            line,
                            physical_height_hu: height,
                            starts_frame: index == frame.start,
                        },
                    ),
                    failure,
                )?;
            }
        }
        Some(StoredNestedTextFrames {
            units,
            frames,
            parent_opening_owns_bottom_padding: false,
        })
    })
}

// 기존 부모 행 합과 후속 줄이 닫는 두 프레임을 정규화 원장으로 옮긴다.
// HWP5 prove의 저장 host 계약을 완화하지 않고 독립된 원본 종료 증명을 사용한다.
fn prove_parent_closed(
    owner: &Table,
    parent: &Cell,
    child: &Table,
) -> Option<StoredNestedTextFrames> {
    match prove_parent_closed_with_storage(owner, parent, child, &crate::storage::Unbounded) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn prove_parent_closed_with_storage<S: crate::storage::Storage>(
    owner: &Table,
    parent: &Cell,
    child: &Table,
    storage: &S,
) -> Result<Option<StoredNestedTextFrames>, S::Error> {
    crate::storage::with_optional(|failure| {
        let plan = crate::storage::optional(
            crate::renderer::float_placement::stored_nested_row_frames_with_storage(
                owner, parent, child, storage,
            ),
            failure,
        )??;
        let cell = child.cells.first()?;
        let padding = cell.effective_padding(&child.padding);
        let top_pad = i32::from(padding.top);
        let bottom_pad = i32::from(padding.bottom);
        let frames = crate::storage::optional(
            storage.collect([
                StoredTextFrame {
                    start: 0,
                    end: plan.reset,
                    body_height_hu: plan.opening_height_hu,
                },
                StoredTextFrame {
                    start: plan.reset,
                    end: plan.lines.len(),
                    body_height_hu: plan.closing_height_hu,
                },
            ]),
            failure,
        )?;
        let mut units = crate::storage::optional(storage.vec(plan.lines.len()), failure)?;
        for frame in &frames {
            for index in frame.start..frame.end {
                let (paragraph, line, top) = plan.lines[index];
                let starts = index == frame.start;
                let ends = index + 1 == frame.end;
                let end = if ends {
                    frame.body_height_hu - top_pad - bottom_pad
                } else {
                    plan.lines[index + 1].2
                };
                let body = end.checked_sub(top)?;
                if body <= 0 {
                    return None;
                }
                let height = body
                    .checked_add(if starts { top.checked_add(top_pad)? } else { 0 })?
                    .checked_add(if ends { bottom_pad } else { 0 })?;
                if height <= 0 {
                    return None;
                }
                crate::storage::optional(
                    storage.push(
                        &mut units,
                        StoredTextFrameUnit {
                            paragraph,
                            line,
                            physical_height_hu: height,
                            starts_frame: starts,
                        },
                    ),
                    failure,
                )?;
            }
        }
        // 이 별도 증명은 child의 바깥 여백 0을 요구한다. 각 physical unit과
        // 실제 child frame의 높이가 정확히 같은 합으로 닫혀야 한다.
        if frames.iter().any(|frame| {
            units[frame.start..frame.end]
                .iter()
                .map(|unit| i64::from(unit.physical_height_hu))
                .sum::<i64>()
                != i64::from(frame.body_height_hu)
        }) {
            return None;
        }
        Some(StoredNestedTextFrames {
            units,
            frames,
            parent_opening_owns_bottom_padding: true,
        })
    })
}

pub(super) fn collect(document: &Document) -> HashMap<usize, Arc<StoredNestedTextFrames>> {
    match collect_with_storage(document, &crate::storage::Unbounded) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn collect_with_storage<S: crate::storage::Storage>(
    document: &Document,
    storage: &S,
) -> Result<HashMap<usize, Arc<StoredNestedTextFrames>>, S::Error> {
    Ok({
        fn visit_with_storage<S: crate::storage::Storage>(
            document: &Document,
            table: &Table,
            result: &mut HashMap<usize, Arc<StoredNestedTextFrames>>,
            storage: &S,
        ) -> Result<(), S::Error> {
            for cell in &table.cells {
                for (pi, paragraph) in cell.paragraphs.iter().enumerate() {
                    for control in &paragraph.controls {
                        if let Control::Table(child) = control {
                            let native_frames =
                                if document.layout_profile().hwp5_stored_pagination_layout() {
                                    prove_with_storage(document, table, cell, pi, child, storage)?
                                } else {
                                    None
                                };
                            let frames = match native_frames {
                                Some(frames) => Some(frames),
                                None if pi == 0 => {
                                    prove_parent_closed_with_storage(table, cell, child, storage)?
                                }
                                None => None,
                            };
                            if let Some(frames) = frames {
                                storage.reserve_map(result, 1)?;
                                storage.bytes(std::mem::size_of::<StoredNestedTextFrames>())?;
                                result.insert(
                                    child.as_ref() as *const Table as usize,
                                    Arc::new(frames),
                                );
                            }
                            visit_with_storage(document, child, result, storage)?;
                        }
                    }
                }
            }

            Ok(())
        }
        let mut result = HashMap::new();
        let profile = document.layout_profile();
        if (profile.hwp5_stored_pagination_layout() || profile.hwpx_stored_layout())
            && !profile.session_edited()
        {
            for section in &document.sections {
                for paragraph in &section.paragraphs {
                    for control in &paragraph.controls {
                        if let Control::Table(table) = control {
                            visit_with_storage(document, table, &mut result, storage)?;
                        }
                    }
                }
            }
        }
        result
    })
}