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
//! The opening table frame and a later source cell use different vertical origins.

use crate::model::table::{Cell, Table};
use crate::renderer::hwpunit_to_px;

use super::{CellUnit, LayoutEngine, ResolvedStyleSet};

impl LayoutEngine {
    /// 원본 문단 안의 저장 재시작은 선언 높이가 있는 중첩 행도 분할한다.
    /// 문단마다 시작하는 로컬 좌표와 편집 후 만든 줄 정보는 이 근거가 아니다.
    pub(super) fn stored_nested_row_has_in_paragraph_cut(
        &self,
        table: &Table,
        cells: &[&Cell],
        units: &[std::sync::Arc<Vec<CellUnit>>],
    ) -> bool {
        let profile = self.profile.get();
        if profile.session_edited()
            || !(profile.hwpx_stored_layout() || profile.hwp5_stored_pagination_layout())
        {
            return false;
        }
        cells.iter().zip(units).any(|(cell, units)| {
            !self
                .render_normalization
                .borrow()
                .cell_frame_reflowed(table, cell)
                && units.iter().any(|unit| {
                    self.stored_in_paragraph_unit_is_original_restart(table, cell, unit)
                })
        })
    }

    /// 행 분해와 상위 투영은 동일한 원본 줄의 재시작을 판별한다.
    pub(super) fn stored_in_paragraph_unit_is_original_restart(
        &self,
        table: &Table,
        cell: &Cell,
        unit: &CellUnit,
    ) -> bool {
        if cell.dirty_flag
            || !unit.page_frame_reset_before
            || unit.vis_start == 0
            || unit.vis_end <= unit.vis_start
        {
            return false;
        }
        let Some(paragraph) = cell.paragraphs.get(unit.para_idx) else {
            return false;
        };
        if paragraph.stored_text_partition_is_dirty()
            || paragraph.cell_format_vpos_dirty
            || !crate::renderer::cell_paragraph_has_only_text_metadata(paragraph)
        {
            return false;
        }
        let Some(previous) = paragraph.line_segs.get(unit.vis_start - 1) else {
            return false;
        };
        let Some(current) = paragraph.line_segs.get(unit.vis_start) else {
            return false;
        };
        let synthetic = crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY;
        previous.tag & synthetic == 0
            && current.tag & synthetic == 0
            && (previous.vertical_pos > 0
                || (previous.vertical_pos == 0
                    && unit.stored_frame_break_before
                    && matches!(
                        self.stored_zero_origin_text_frame_break_witness(
                            table, cell, previous, current,
                        ),
                        Some(super::stored_zero_origin::SavedZeroOriginWitness::OpeningFrame)
                    )))
            && current.vertical_pos == 0
            && previous.line_height > 0
            && current.line_height > 0
            && current.text_start > previous.text_start
    }

    /// Normalize the original opening box into the ordinary source row. This
    /// only supplies the existing saved-cut tail calculation; accepted physical
    /// rows and the table's occupied extent remain in their original ledger.
    pub(super) fn stored_first_cell_frame_height(&self, table: &Table, cell: &Cell) -> Option<f64> {
        (cell.row_span == 1)
            .then(|| self.source_first_cell_frame_height(table, cell))
            .flatten()
    }

    fn source_first_cell_frame_height(&self, table: &Table, cell: &Cell) -> Option<f64> {
        // 첫 행의 원점도 0으로 정규화한다. 원본 줄과 같은 물리 상자를
        // 인증하는 조건은 아래에서 뒤 행과 동일하게 적용한다.
        if !self.stored_plain_text_cell_frame(table, cell)
            || self
                .render_normalization
                .borrow()
                .nested_table_has_reflowed_host(table)
            || table.common.height == 0
            || table.common.height > i32::MAX as u32
        {
            return None;
        }
        let rows = table.get_raw_row_heights();
        let row = usize::from(cell.row);
        let prefix = rows.get(..row)?;
        let span_end = row.checked_add(usize::from(cell.row_span))?;
        let source_span = rows.get(row..span_end)?;
        if prefix
            .iter()
            .chain(source_span)
            .any(|&height| height == 0 || height > i32::MAX as u32)
        {
            return None;
        }
        let (origin, current) = self
            .stored_frame_row_plans
            .borrow()
            .get(&(table as *const Table as usize))
            .and_then(|rows| {
                Some((
                    rows.get(..row)?.iter().sum::<f64>(),
                    rows.get(row..span_end)?.iter().sum::<f64>(),
                ))
            })
            .unwrap_or_else(|| {
                (
                    prefix
                        .iter()
                        .map(|&height| hwpunit_to_px(height as i32, self.dpi))
                        .sum(),
                    source_span
                        .iter()
                        .map(|&height| hwpunit_to_px(height as i32, self.dpi))
                        .sum(),
                )
            });
        let origin = origin + hwpunit_to_px(table.cell_spacing as i32, self.dpi) * row as f64;
        let current = current
            + hwpunit_to_px(table.cell_spacing as i32, self.dpi)
                * usize::from(cell.row_span).saturating_sub(1) as f64;
        let end = hwpunit_to_px(table.common.height as i32, self.dpi);
        if std::env::var_os("RHWP_DIAG_SCAN").is_some() {
            eprintln!(
                "DIAG_SCAN STORED_CELL_FRAME table={:p} row={} span={} origin={:.6} current={:.6} end={:.6} cached={}",
                table,
                row,
                cell.row_span,
                origin,
                current,
                end,
                self.stored_frame_row_plans
                    .borrow()
                    .contains_key(&(table as *const Table as usize)),
            );
        }
        // A completed opening row or a later frame cannot authenticate this
        // partial source row. Unknown zero-height rows are not a physical origin.
        if !origin.is_finite() || !current.is_finite() || end <= origin || end >= origin + current {
            return None;
        }
        Some(end - origin)
    }

    pub(super) fn first_source_frame_owner(
        &self,
        table: &Table,
        cell: &Cell,
        styles: &ResolvedStyleSet,
    ) -> Option<(usize, f64)> {
        let opening = self.source_first_cell_frame_height(table, cell)?;
        let units = self.cell_units(cell, table, styles);
        // 저장 상자는 실제 컷과 같은 유효 안여백으로 인증한다. 선언 셀 높이로
        // 축소된 여백 대신 원본 여백을 더하면 현재 배치에 없는 물리 띠가 생긴다.
        let (_, _, top, bottom) = self.resolve_cell_padding(cell, table);
        let padding = top + bottom;
        let epsilon = hwpunit_to_px(2, self.dpi);
        let source_padding = cell.effective_padding(&table.padding);
        let source_padding = hwpunit_to_px(
            i32::from(source_padding.top) + i32::from(source_padding.bottom),
            self.dpi,
        );
        // 원본 Common 상자의 좌표는 저장 안여백을 포함한다. 실제 컷에서 그
        // 여백을 축소했다면 원본 상자를 같은 좌표의 물리 프레임으로 재사용할 수 없다.
        if (source_padding - padding).abs() > epsilon {
            return None;
        }
        let mut previous: Option<&crate::model::paragraph::LineSeg> = None;
        let mut advance = 0.0;
        for (index, unit) in units.iter().enumerate() {
            let paragraph = cell.paragraphs.get(unit.para_idx)?;
            // 글자가 없는 물리 전진 유닛은 가시 줄 범위가 비어 있어도 실제 저장
            // 줄 하나를 대표할 수 있다. 아래의 원본 원점·높이·간격 대조를 그대로
            // 통과해야 하며, 높이 없는 보조 꼬리를 근거 없이 인증하지 않는다.
            let source_only_empty_line = unit.empty_spacer
                && unit.vis_start == 0
                && unit.vis_end == 0
                && paragraph.text.trim().is_empty()
                && paragraph.line_segs.len() == 1;
            if unit.vis_end != unit.vis_start + 1 && !source_only_empty_line {
                return None;
            }
            let line = paragraph.line_segs.get(unit.vis_start)?;
            if let Some(before) = previous {
                if line.vertical_pos == 0
                    && (before.vertical_pos > 0
                        || (unit.stored_frame_break_before
                            && units[index - 1].para_idx == unit.para_idx
                            && matches!(
                                self.stored_zero_origin_text_frame_break_witness(
                                    table, cell, before, line,
                                ),
                                Some(
                                    super::stored_zero_origin::SavedZeroOriginWitness::OpeningFrame
                                )
                            )))
                {
                    let ink = hwpunit_to_px(
                        before.vertical_pos.checked_add(before.line_height)?,
                        self.dpi,
                    ) + padding;
                    // A stored empty line owns the same line box and following
                    // advance as text. The opening box ends in that final gap.
                    // A span can cross complete rows before the first partial
                    // row. Its source restart still owns the same Common frame
                    // when an independent ordinary cell closes that frame.
                    let independently_closed_span = cell.row_span > 1
                        && unit.stored_frame_break_before
                        && unit.page_frame_reset_before
                        && opening <= hwpunit_to_px(cell.height as i32, self.dpi)
                        && table.cells.iter().any(|peer| {
                            peer.row_span == 1
                                && peer.row >= cell.row
                                && usize::from(peer.row)
                                    < usize::from(cell.row) + usize::from(cell.row_span)
                                && peer.col != cell.col
                                && self.first_source_frame_owner(table, peer, styles).is_some()
                        });
                    // 같은 여백 좌표에서 인증한 Common 상자는 내용 전진 뒤의 빈
                    // 물리 공간도 소유할 수 있다. 같은 문단의 실제 쪽 프레임 재시작을
                    // 요구하며, 그 공간을 줄 전진의 상한으로 다시 잘라내지 않는다.
                    let ordinary_source_restart = cell.row_span == 1
                        && unit.page_frame_reset_before
                        && units[index - 1].para_idx == unit.para_idx;
                    let accepted = opening + epsilon >= ink
                        && (opening <= advance + padding + epsilon
                            || independently_closed_span
                            || ordinary_source_restart);
                    return accepted.then_some((index, opening));
                }
                if i64::from(line.vertical_pos)
                    != i64::from(before.vertical_pos)
                        + i64::from(before.line_height)
                        + i64::from(before.line_spacing)
                {
                    return None;
                }
            } else {
                // A real paragraph's leading spacing is part of its first
                // line origin. Authenticate it against the independent style
                // instead of treating every positive origin as stale alignment.
                let before = styles
                    .para_styles
                    .get(cell.paragraphs.get(unit.para_idx)?.para_shape_id as usize)?
                    .spacing_before;
                let origin = hwpunit_to_px(line.vertical_pos, self.dpi);
                if origin < 0.0 || (origin != 0.0 && (origin - before).abs() > epsilon) {
                    return None;
                }
            }
            let source_advance =
                hwpunit_to_px(line.line_height.checked_add(line.line_spacing)?, self.dpi)
                    + if previous.is_none() {
                        hwpunit_to_px(line.vertical_pos, self.dpi)
                    } else {
                        0.0
                    };
            if (unit.height - source_advance).abs() > epsilon {
                return None;
            }
            advance += unit.height;
            previous = Some(line);
        }
        None
    }

    /// A partial opening row has one physical height even when a sibling has
    /// finished. Every unfinished owner must restart at this same source cut.
    pub(crate) fn row_cut_first_source_frame_height(
        &self,
        table: &Table,
        row: usize,
        start_cut: &[usize],
        end_cut: &[usize],
        styles: &ResolvedStyleSet,
    ) -> Option<f64> {
        if !start_cut.is_empty() || end_cut.is_empty() {
            return None;
        }
        let cells = Self::row_cut_cell_order(table, row);
        if cells.len() != end_cut.len() {
            return None;
        }
        let epsilon = hwpunit_to_px(2, self.dpi);
        let mut frame: Option<f64> = None;
        let mut completed_height = 0.0f64;
        for (&index, &end) in cells.iter().zip(end_cut) {
            let cell = &table.cells[index];
            if !self.stored_plain_text_cell_frame(table, cell) {
                return None;
            }
            let units = self.cell_units(cell, table, styles);
            if units.is_empty() || end == 0 || end > units.len() {
                return None;
            }
            if end < units.len() {
                let (owner, opening) = self.first_source_frame_owner(table, cell, styles)?;
                if owner != end || frame.is_some_and(|height| (height - opening).abs() > epsilon) {
                    return None;
                }
                frame = Some(opening);
            } else {
                let (_, _, top, bottom) = self.resolve_cell_padding(cell, table);
                let height = units.iter().map(|unit| unit.height).sum::<f64>() + top + bottom;
                completed_height = completed_height.max(height);
            }
        }
        frame.filter(|height| completed_height <= *height)
    }

    /// 온전한 행의 내용이 개체가 저장한 첫 조각 끝에서 완결되는가.
    /// 선언 행의 빈 꼬리는 이 첫 상자에 포함되지 않는다. 실제 잔여와
    /// 저장 상자가 같은 경계를 가리킬 때만 정렬한 내용까지 확인한다.
    pub(crate) fn completed_row_closes_opening_source_frame(
        &self,
        table: &Table,
        row: usize,
        end_cut: &[usize],
        natural_height: f64,
        available: f64,
        styles: &ResolvedStyleSet,
    ) -> Option<f64> {
        let order = Self::row_cut_cell_order(table, row);
        if order.is_empty() || order.len() != end_cut.len() || !available.is_finite() {
            return None;
        }
        let epsilon = hwpunit_to_px(2, self.dpi);
        let mut frame: Option<f64> = None;
        for (&index, &end) in order.iter().zip(end_cut) {
            let cell = &table.cells[index];
            let units = self.cell_units(cell, table, styles);
            if units.is_empty() || end != units.len() {
                return None;
            }
            let height = self.source_first_cell_frame_height(table, cell)?;
            if (height - available).abs() > epsilon
                || frame.is_some_and(|before| (height - before).abs() > epsilon)
            {
                return None;
            }
            frame = Some(height);
        }
        let height = frame?;
        // 내용 완료가 위 정렬 행의 물리 빈 밴드까지 소진한 것은 아니다.
        // 기존 닫힘 계약이 정렬·패딩·후행 전진을 구분한 점유 끝을 함께 쓴다.
        let required =
            self.stored_closing_row_occupancy(table, row, natural_height, height, styles)?;
        (required <= height).then_some(height)
    }

    pub(super) fn stored_span_partial_first_frame_owner(
        &self,
        table: &Table,
        cell: &Cell,
        row: usize,
        cut: &[usize],
        measured_rows: &[f64],
        styles: &ResolvedStyleSet,
    ) -> Option<usize> {
        if cell.row_span <= 1 || usize::from(cell.row) != row || cut.is_empty() {
            return None;
        }
        let (owner, opening) = self.first_source_frame_owner(table, cell, styles)?;
        let epsilon = hwpunit_to_px(2, self.dpi);
        let origin = measured_rows.get(..row)?.iter().sum::<f64>()
            + hwpunit_to_px(table.cell_spacing as i32, self.dpi) * row as f64;
        if (origin + opening - hwpunit_to_px(table.common.height as i32, self.dpi)).abs() > epsilon
            || (self.row_cut_content_height(table, row, &[], cut, styles) - opening).abs() > epsilon
        {
            return None;
        }
        table
            .cells
            .iter()
            .any(|peer| {
                peer.row == cell.row
                    && peer.col != cell.col
                    && self
                        .first_source_frame_owner(table, peer, styles)
                        .is_some_and(|(_, height)| (height - opening).abs() <= epsilon)
            })
            .then_some(owner)
    }

    /// A source cut consumes the opening physical box, not the row's entire
    /// trailing band. The next fragment reserves and paints this same remainder.
    pub(crate) fn stored_first_frame_row_remainder(
        &self,
        table: &Table,
        row: usize,
        cut: &[usize],
        measured_rows: &[f64],
        styles: &ResolvedStyleSet,
    ) -> Option<f64> {
        let mut cells: Vec<_> = table
            .cells
            .iter()
            .filter(|cell| usize::from(cell.row) == row && cell.row_span == 1)
            .collect();
        cells.sort_by_key(|cell| cell.col);
        if cells.len() != cut.len() || row >= measured_rows.len() {
            return None;
        }
        let epsilon = hwpunit_to_px(2, self.dpi);
        let mut opening: Option<f64> = None;
        for (cell, &end) in cells.into_iter().zip(cut) {
            let units = self.cell_units(cell, table, styles);
            if end >= units.len() {
                continue;
            }
            if end == 0 {
                return None;
            }
            let height = self.stored_first_cell_frame_height(table, cell)?;
            let before = units[..end - 1].iter().map(|unit| unit.height).sum();
            if self.native_intra_para_saved_reset_trailing_trim(
                table,
                cell,
                &units,
                end,
                before,
                units[end - 1].height,
                styles,
            ) <= 0.0
                || opening.is_some_and(|other| (other - height).abs() > epsilon)
            {
                return None;
            }
            opening = Some(height);
        }
        let opening = opening?;
        let origin = measured_rows[..row].iter().sum::<f64>()
            + hwpunit_to_px(table.cell_spacing as i32, self.dpi) * row as f64;
        let source_end = hwpunit_to_px(table.common.height as i32, self.dpi);
        let accepted = self.row_cut_content_height(table, row, &[], cut, styles);
        // Source and measured coordinates must identify the same opening box.
        // A grown prefix cannot be replaced with raw row minima to certify it.
        if (origin + opening - source_end).abs() > epsilon || (accepted - opening).abs() > epsilon {
            return None;
        }
        // 넘길 물리 잔여는 행 **상자**의 남은 몫이다. 측정 행 높이가 선언 상자보다 크면
        // 그 초과분은 내용(마지막 줄의 줄간격 포함)이 만든 높이라 빈 물리 띠가 아니다 —
        // 남은 내용은 다음 조각이 제 높이로 재므로 여기서 다시 넘기지 않는다.
        // 80168 hwp 5쪽: 선언 869px · 측정 929.6px 행의 이어받기가 33.6px(내용 22.4px)로
        // 늘어 한/글 2024 PDF(≈21px)보다 상자가 11px 길었다.
        let declared = table
            .get_raw_row_heights()
            .get(row)
            .copied()
            .filter(|&height| height > 0 && height <= i32::MAX as u32)
            .map(|height| hwpunit_to_px(height as i32, self.dpi));
        let physical = declared.map_or(measured_rows[row], |declared| {
            declared.min(measured_rows[row])
        });
        let remaining = physical - opening;
        let content = self.row_cut_content_height(table, row, cut, &[], styles);
        (remaining > content + epsilon).then_some(remaining)
    }
}