rhwp 0.9.0

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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! 줄 끝 재결합과 같은 원본 물리 프레임의 후속 원점을 함께 발행한다.
use crate::model::{
    control::Control,
    page::{ColumnDef, PageDef},
    paragraph::{ColumnBreakType, LineSeg, Paragraph},
};
use crate::renderer::{
    composer::{
        project_current_body_box_rows, project_current_marker_height_rows,
        project_current_source_program_rows, project_stored_soft_wraps,
        projects_current_marker_geometry, ParagraphBox,
    },
    page_layout::PageLayoutInfo,
    px_to_hwpunit,
    style_resolver::ResolvedStyleSet,
};

fn uniform_column_width(page: &PageDef, columns: &ColumnDef, dpi: f64) -> Option<f64> {
    let layout = PageLayoutInfo::from_page_def(page, columns, dpi);
    let width = layout.column_areas.first()?.width;
    // 너비가 다른 단은 현재 문단의 실제 소유 단 없이 첫 단으로 추측하지 않는다.
    layout
        .column_areas
        .iter()
        .all(|column| px_to_hwpunit(column.width, dpi) == px_to_hwpunit(width, dpi))
        .then_some(width)
}

fn frame_advance(lines: &[LineSeg]) -> Option<i32> {
    let first = lines.first()?;
    let last = lines.last()?;
    last.vertical_pos
        .checked_add(last.line_height)?
        .checked_add(last.line_spacing)?
        .checked_sub(first.vertical_pos)
}

/// 겹쳐 그리는 개체는 보이더라도 문단 글줄의 간격을 대신 소비하지 않는다.
fn paragraph_owns_line_spacing(paragraph: &Paragraph) -> bool {
    use crate::model::shape::TextWrap;
    paragraph
        .controls
        .iter()
        .enumerate()
        .all(|(index, control)| {
            if crate::renderer::cell_control_is_text_metadata(control) {
                return true;
            }
            if let Control::Picture(picture) = control {
                if picture.common.treat_as_char {
                    let (_, height) =
                        crate::renderer::composer::inline_picture_occupied_size_hu(picture);
                    // 인라인 그림은 줄 안에서 이미 점유한다. 소유 줄이 그 높이를
                    // 담고 있으면 다음 문단의 간격을 대신 소비하는 block이 아니다.
                    return height > 0
                        && crate::renderer::layout::control_line_seg_index(paragraph, index)
                            .and_then(|line| paragraph.line_segs.get(line))
                            .is_some_and(|line| line.line_height >= height);
                }
            }
            let common = match control {
                Control::Shape(shape) => shape.common(),
                Control::Picture(picture) => &picture.common,
                Control::Table(table) => &table.common,
                _ => return false,
            };
            !common.treat_as_char
                && matches!(
                    common.text_wrap,
                    TextWrap::InFrontOfText | TextWrap::BehindText
                )
        })
}

/// 셀 선언보다 긴 정상 저장 줄들도 표 전체의 선언 상자를 정확히 닫을 수 있다.
/// 온전한 원본 격자의 실제 줄 끝·안 여백으로 닫히는 행은 짧은 셀 선언만으로
/// 낡은 캐시라고 판정하지 않는다. 쪽 재시작·병합·편집 셀은 이 인증을 갖지 않는다.
fn stored_closed_table_row_frames(
    table: &crate::model::table::Table,
) -> Option<std::collections::HashMap<u16, u32>> {
    match stored_closed_table_row_frames_with_storage(table, &crate::storage::Unbounded) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn stored_closed_table_row_frames_with_storage<S: crate::storage::Storage>(
    table: &crate::model::table::Table,
    storage: &S,
) -> Result<Option<std::collections::HashMap<u16, u32>>, S::Error> {
    crate::storage::with_optional(|failure| {
        if table.common.height == 0
            || !crate::renderer::float_placement::stored_complete_column_frame(table)
        {
            return None;
        }
        let mut rows = std::collections::HashMap::<u16, u32>::new();
        for cell in &table.cells {
            if cell.row_span != 1 || cell.line_wrap != 0 {
                return None;
            }
            let padding = cell.effective_padding(&table.padding);
            if padding.top < 0 || padding.bottom < 0 {
                return None;
            }
            let ink = crate::renderer::float_placement::stored_plain_cell_ink_height(cell)?;
            let end = u32::try_from(ink)
                .ok()?
                .checked_add(padding.top as u32)?
                .checked_add(padding.bottom as u32)?;
            if !rows.contains_key(&cell.row) {
                crate::storage::optional(storage.reserve_map(&mut rows, 1), failure)?;
            }
            let height = rows.entry(cell.row).or_default();
            *height = (*height).max(cell.height).max(end);
        }
        let total = (0..table.row_count).try_fold(0_u64, |sum, row| {
            sum.checked_add(u64::from(*rows.get(&row)?))
        })?;
        let spacing = u64::try_from(table.cell_spacing)
            .ok()?
            .checked_mul(u64::from(table.row_count.saturating_sub(1)))?;
        (total.checked_add(spacing)? == u64::from(table.common.height)).then_some(rows)
    })
}

#[derive(Clone, Copy)]
struct NormalizationPolicy<'a> {
    refresh_markers: bool,
    previous_margin_styles: Option<&'a ResolvedStyleSet>,
}

pub(crate) fn normalize(
    original: &[Paragraph],
    styles: &ResolvedStyleSet,
    page: &PageDef,
    initial_columns: &ColumnDef,
    refresh_markers: bool,
    dpi: f64,
    previous_margin_styles: Option<&ResolvedStyleSet>,
) -> Option<Vec<Paragraph>> {
    match normalize_with_storage(
        original,
        styles,
        page,
        initial_columns,
        refresh_markers,
        dpi,
        previous_margin_styles,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn normalize_with_storage<S: crate::storage::Storage>(
    original: &[Paragraph],
    styles: &ResolvedStyleSet,
    page: &PageDef,
    initial_columns: &ColumnDef,
    refresh_markers: bool,
    dpi: f64,
    previous_margin_styles: Option<&ResolvedStyleSet>,
    storage: &S,
) -> Result<Option<Vec<Paragraph>>, S::Error> {
    normalize_flow_with_storage(
        original,
        styles,
        uniform_column_width(page, initial_columns, dpi),
        Some(page),
        true,
        NormalizationPolicy {
            refresh_markers,
            previous_margin_styles,
        },
        dpi,
        storage,
    )
}

/// 문단의 새 줄 구성과 뒤 문단의 원점은 같은 흐름에서 함께 발행한다.
/// 본문은 단의 폭을, 셀은 자신의 정수 내용 상자를 소유한다.
fn normalize_flow(
    original: &[Paragraph],
    styles: &ResolvedStyleSet,
    mut width: Option<f64>,
    body_page: Option<&PageDef>,
    refresh_text: bool,
    policy: NormalizationPolicy<'_>,
    dpi: f64,
) -> Option<Vec<Paragraph>> {
    match normalize_flow_with_storage(
        original,
        styles,
        width,
        body_page,
        refresh_text,
        policy,
        dpi,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}
fn normalize_flow_with_storage<S: crate::storage::Storage>(
    original: &[Paragraph],
    styles: &ResolvedStyleSet,
    mut width: Option<f64>,
    body_page: Option<&PageDef>,
    refresh_text: bool,
    policy: NormalizationPolicy<'_>,
    dpi: f64,
    storage: &S,
) -> Result<Option<Vec<Paragraph>>, S::Error> {
    crate::storage::with_optional(|failure| {
        let NormalizationPolicy {
            refresh_markers,
            previous_margin_styles,
        } = policy;
        // 본문 상자의 모순과 실제 문자 경계 이동이 함께 확인된 흐름만 현재
        // 문단 간격 축을 발행한다. 유효한 저장 상자는 더 적게 채워져도 유지한다.
        let mut probe_width = width;
        let mut rebuild_body_spacing = false;
        if body_page.is_some() {
            for paragraph in original {
                for control in &paragraph.controls {
                    if let (Some(page), Control::ColumnDef(columns)) = (body_page, control) {
                        probe_width = uniform_column_width(page, columns, dpi);
                    }
                }
                if let Some(width) = probe_width {
                    let style = styles.para_styles.get(paragraph.para_shape_id as usize);
                    let box_ = ParagraphBox::body_for_style(width, style, dpi);
                    if crate::storage::optional(
                        crate::renderer::composer::project_current_body_box_rows_with_storage(
                            paragraph, &box_, styles, dpi, storage,
                        ),
                        failure,
                    )?
                    .is_some()
                    {
                        rebuild_body_spacing = true;
                        break;
                    }
                }
            }
        }
        let mut shift = 0_i32;
        let mut previous_source_vpos = None;
        let mut result = crate::storage::optional(storage.vec(original.len()), failure)?;
        let mut changed = false;
        for (source_index, source) in original.iter().enumerate() {
            if source.column_type != ColumnBreakType::None
                || styles
                    .para_styles
                    .get(source.para_shape_id as usize)
                    .is_some_and(|style| style.page_break_before)
            {
                shift = 0;
            }
            for control in &source.controls {
                if let (Some(page), Control::ColumnDef(columns)) = (body_page, control) {
                    width = uniform_column_width(page, columns, dpi);
                    shift = 0;
                }
            }
            if rebuild_body_spacing
                && source.column_type == ColumnBreakType::None
                && !styles
                    .para_styles
                    .get(source.para_shape_id as usize)
                    .is_some_and(|style| style.page_break_before)
            {
                if let Some(previous) = source_index.checked_sub(1).and_then(|i| original.get(i)) {
                    // 실제 개체가 소유한 간격은 이 문자 사다리로 추측하지 않는다.
                    if paragraph_owns_line_spacing(previous)
                        && paragraph_owns_line_spacing(source)
                        && !previous.stored_text_partition_is_dirty()
                        && !source.stored_text_partition_is_dirty()
                    {
                        if let Some((last, first)) =
                            previous.line_segs.last().zip(source.line_segs.first())
                        {
                            let gap = i64::from(first.vertical_pos)
                                - i64::from(last.vertical_pos)
                                - i64::from(last.line_height)
                                - i64::from(last.line_spacing);
                            let after = styles
                                .para_styles
                                .get(previous.para_shape_id as usize)
                                .map_or(0, |style| px_to_hwpunit(style.spacing_after, dpi));
                            let before = styles
                                .para_styles
                                .get(source.para_shape_id as usize)
                                .map_or(0, |style| px_to_hwpunit(style.spacing_before, dpi));
                            let declared = i64::from(after) + i64::from(before);
                            if after >= 0
                                && before >= 0
                                && gap < declared
                                && (gap == 0 || gap == i64::from(after) || gap == i64::from(before))
                                && !first.is_first_line_of_page()
                                && !first.is_first_line_of_column()
                                && first.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                                && last.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                            {
                                shift = shift.checked_add(i32::try_from(declared - gap).ok()?)?;
                            }
                        }
                    }
                }
            }
            let mut paragraph = crate::storage::optional(storage.clone_paragraph(source), failure)?;
            for control in &mut paragraph.controls {
                let Control::Table(table) = control else {
                    continue;
                };
                let mut row_frames = std::collections::HashMap::<u16, u32>::new();
                for cell in &table.cells {
                    if cell.row_span == 1 {
                        if !row_frames.contains_key(&cell.row) {
                            crate::storage::optional(
                                storage.reserve_map(&mut row_frames, 1),
                                failure,
                            )?;
                        }
                        let height = row_frames.entry(cell.row).or_default();
                        *height = (*height).max(cell.height);
                    }
                }
                if let Some(closed) = crate::storage::optional(
                    stored_closed_table_row_frames_with_storage(table, storage),
                    failure,
                )? {
                    row_frames = closed;
                }
                for cell in &mut table.cells {
                    if cell.text_direction != 0 || cell.line_wrap != 0 {
                        continue;
                    }
                    let padding = cell.effective_padding(&table.padding);
                    let Some(inner_hu) = i32::try_from(cell.width).ok().and_then(|width| {
                        width
                            .checked_sub(i32::from(padding.left))?
                            .checked_sub(i32::from(padding.right))
                    }) else {
                        continue;
                    };
                    if inner_hu <= 0 {
                        continue;
                    }
                    // 괘선의 누적 px 좌표를 다시 빼면 정수 폭이 1HU 작아질 수 있다.
                    // 원본의 정수 길이에서 내용 폭을 계산한 뒤 기존 셀 폭 계약에 전달한다.
                    let inner = crate::renderer::composer::cell_inner_text_width(
                        crate::renderer::hwpunit_to_px(inner_hu, dpi),
                        0.0,
                        0.0,
                        dpi,
                    );
                    let frame = if cell.row_span == 1 {
                        row_frames.get(&cell.row).copied().unwrap_or(cell.height)
                    } else {
                        cell.height
                    };
                    if let Some(previous) = previous_margin_styles {
                        if let Some(projected) =
                            crate::storage::optional(crate::renderer::composer::stored_margin_context::project_cell_with_storage(
                                &cell.paragraphs,
                                inner,
                                styles,
                                previous,
                                dpi, storage,
                            ), failure)?
                        {
                            cell.paragraphs = projected;
                            changed = true;
                            continue;
                        }
                    }
                    let stale = stored_text_exceeds_frame(cell, frame, &padding);
                    if let Some(projected) = crate::storage::optional(
                        normalize_flow_with_storage(
                            &cell.paragraphs,
                            styles,
                            Some(inner),
                            None,
                            stale,
                            policy,
                            dpi,
                            storage,
                        ),
                        failure,
                    )? {
                        cell.paragraphs = projected;
                        changed = true;
                    }
                }
            }
            let mut origin_changed = false;
            for line in &mut paragraph.line_segs {
                let source_vpos = line.vertical_pos;
                if line.is_first_line_of_page()
                    || line.is_first_line_of_column()
                    || previous_source_vpos.is_some_and(|previous| source_vpos < previous)
                {
                    shift = 0;
                }
                previous_source_vpos = Some(source_vpos);
                line.vertical_pos = source_vpos.checked_add(shift)?;
                origin_changed |= shift != 0;
            }
            if origin_changed {
                // 원문 문자 축은 그대로지만 물리 원점은 새 프레임 소유다.
                // 이전 원점 snapshot을 남겨 같은 파생 줄을 서로 다른 축으로
                // 판정하지 않는다. 원본 document의 snapshot은 보존된다.
                paragraph.source_line_seg_vertical_pos = None;
            }
            if let Some(width) = width {
                if let Some(previous) = previous_margin_styles.filter(|_| body_page.is_some()) {
                    if let Some(projected) = crate::storage::optional(
                        crate::renderer::composer::stored_margin_context::project_body_with_storage(
                            &paragraph, width, styles, previous, dpi, storage,
                        ),
                        failure,
                    )? {
                        let old_advance = frame_advance(&paragraph.line_segs)?;
                        let new_advance = frame_advance(&projected.line_segs)?;
                        shift = shift.checked_add(new_advance.checked_sub(old_advance)?)?;
                        paragraph = projected;
                        changed = true;
                    }
                }
                let style = styles.para_styles.get(paragraph.para_shape_id as usize);
                let box_ = if body_page.is_some() {
                    ParagraphBox::body_for_style(width, style, dpi)
                } else {
                    ParagraphBox::content_for_style(width, style, dpi)
                };
                // 현재 측정으로 더 적은 줄에 들어간다는 사실만으로 정상 저장 줄을
                // 무효화하지 않는다. 원문 문자에 없는 목록 마커는 문서 순서에서
                // 해소한 실제 기하를 갱신해야 하며, 같은 결과가 채움·높이에 참여한다.
                let spans_physical_frames =
                    crate::renderer::composer::stored_rows_cross_physical_frame(&paragraph);
                let mut current_rows = if body_page.is_some() {
                    crate::storage::optional(
                        crate::renderer::composer::project_current_body_box_rows_with_storage(
                            &paragraph, &box_, styles, dpi, storage,
                        ),
                        failure,
                    )?
                } else {
                    None
                };
                if current_rows.is_none() {
                    current_rows = crate::storage::optional(
                        crate::renderer::composer::project_current_source_program_rows_with_storage(
                            &paragraph, &box_, styles, dpi, storage,
                        ),
                        failure,
                    )?;
                }
                if current_rows.is_none() {
                    current_rows = crate::storage::optional(
                        crate::renderer::composer::project_current_marker_height_rows_with_storage(
                            &paragraph, &box_, styles, dpi, storage,
                        ),
                        failure,
                    )?;
                }
                let selected_program_rows = crate::storage::optional(crate::renderer::composer::project_stored_rows_with_selected_program_with_storage(&paragraph, &box_, styles, dpi, storage), failure)?;
                let marker_rows = || {
                    if !refresh_markers
                        || !(refresh_text || spans_physical_frames)
                        || !projects_current_marker_geometry(&paragraph, &box_, styles)
                    {
                        return None;
                    }
                    let first = paragraph.line_segs[0].vertical_pos;
                    let frame = box_.frame(first);
                    crate::storage::optional(
                        crate::renderer::composer::project_stored_soft_wraps_with_storage(
                            &paragraph, &frame, styles, dpi, false, storage,
                        ),
                        failure,
                    )?
                };
                if let Some((lines, spaces)) =
                    selected_program_rows.or(current_rows).or_else(marker_rows)
                {
                    let old_advance = frame_advance(&paragraph.line_segs)?;
                    let new_advance = frame_advance(&lines)?;
                    shift = shift.checked_add(new_advance.checked_sub(old_advance)?)?;
                    paragraph.replace_line_segs_with_space_metrics(lines, spaces);
                    changed = true;
                }
            }
            crate::storage::optional(storage.push(&mut result, paragraph), failure)?;
        }
        changed.then_some(result)
    })
}

fn stored_text_exceeds_frame(
    cell: &crate::model::table::Cell,
    frame_height: u32,
    padding: &crate::model::Padding,
) -> bool {
    if cell.dirty_flag || frame_height == 0 || frame_height > i32::MAX as u32 {
        return false;
    }
    let mut end = 0_i64;
    let mut first = true;
    for para in &cell.paragraphs {
        if !para.controls.is_empty()
            || para.column_type != ColumnBreakType::None
            || para.stored_text_partition_is_dirty()
            || para.cell_format_vpos_dirty
            || para.line_segs.is_empty()
        {
            return false;
        }
        for line in &para.line_segs {
            if line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
                || line.line_height <= 0
                || line.line_spacing < 0
                || i64::from(line.vertical_pos) < end
                || (!first && (line.is_first_line_of_page() || line.is_first_line_of_column()))
            {
                return false;
            }
            end = i64::from(line.vertical_pos) + i64::from(line.line_height);
            first = false;
        }
    }
    !first && end + i64::from(padding.top) + i64::from(padding.bottom) > i64::from(frame_height)
}