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
//! 표 포맷의 읽기 전용 준비·결과 조립과 측정 결과 수용 Query.
//! host 간격은 하위 Query가, 각주 예약·분할/배치는 호출자가 소유한다.

use super::{
    native_hwp5_footnote_reset_fragments, para_has_non_whitespace_text,
    queued_table_footnote_content_height, FormattedTable, TableCellFootnote,
};
use crate::model::control::Control;
use crate::model::{paragraph::Paragraph, provenance::LayoutCompatibilityProfile, table::Table};
use crate::renderer::composer::ComposedParagraph;
use crate::renderer::float_placement::is_para_topbottom_float;
use crate::renderer::height_measurer::{
    fit_measured_table_declared_tail_to_declared_height,
    fit_measured_table_nested_tail_to_declared_height, fit_measured_table_to_declared_height,
    fit_stored_hwpx_no_adjust_rowspans, fit_stored_inline_picture_frame,
    trim_stored_hwpx_inline_row_trailing_spacing, MeasuredTable,
};
use crate::renderer::hwpunit_to_px;
use crate::renderer::pagination::estimate_footnote_note_height;
use crate::renderer::style_resolver::ResolvedStyleSet;

pub(super) mod block;
pub(super) mod continuation;
pub(super) mod deferred_float_flow;
pub(super) mod footnotes;
mod host_spacing;
pub(super) mod scan;
mod source_frame_fit;

/// 포맷 경계의 기존 IR 참조와 관측값. 페이지/단의 가변 상태를 전달하지 않는다.
pub(super) struct TableFormatInput<'a> {
    pub(super) para: &'a Paragraph,
    pub(super) para_idx: usize,
    pub(super) ctrl_idx: usize,
    pub(super) table: &'a Table,
    pub(super) measured_tables: &'a [MeasuredTable],
    pub(super) styles: &'a ResolvedStyleSet,
    pub(super) composed: Option<&'a ComposedParagraph>,
    pub(super) next_para: Option<&'a Paragraph>,
    pub(super) is_column_top: bool,
    pub(super) external_flow: Option<crate::renderer::float_placement::ReflowExternalTableFlow>,
    pub(super) unchanged_coanchored_frame: bool,
}

/// 측정 선택 → host 간격 → 측정값 복제 → 각주 수집 → 결과 조립 순서를 유지한다.
/// profile과 TAC 질의는 원래 평가 위치에서만 호출한다. 각주 예약/페이지 배치는 하지 않는다.
pub(super) fn format(
    input: TableFormatInput<'_>,
    dpi: f64,
    profile: impl Fn() -> LayoutCompatibilityProfile,
    uses_tac_flow: impl FnOnce() -> bool,
) -> FormattedTable {
    match format_with_storage(
        input,
        dpi,
        profile,
        uses_tac_flow,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(super) fn format_with_storage<S: crate::storage::Storage>(
    input: TableFormatInput<'_>,
    dpi: f64,
    profile: impl Fn() -> LayoutCompatibilityProfile,
    uses_tac_flow: impl FnOnce() -> bool,
    storage: &S,
) -> Result<FormattedTable, S::Error> {
    let TableFormatInput {
        para,
        para_idx,
        ctrl_idx,
        table,
        measured_tables,
        styles,
        composed,
        next_para,
        is_column_top,
        external_flow,
        unchanged_coanchored_frame,
    } = input;
    let mt = measured_tables
        .iter()
        .find(|mt| mt.para_index == para_idx && mt.control_index == ctrl_idx);
    // 편집 세션 여부는 이 표의 줄 재배치 증거가 아니다. 같은 저장 host와
    // 수직 줄 프레임을 유지했다면 저장·paint와 같은 닫힌 끝 행을 먼저 쓴다.
    // 실제 줄바꿈·높이 변화는 호출자가 제외하며 내용 하한은 공통 fit이 검증한다.
    let closed_coanchored_mt = if unchanged_coanchored_frame {
        mt.map(|measured| {
            crate::renderer::height_measurer::fit_measured_table_declared_tail_to_declared_height_with_storage(
                measured, table, dpi, storage,
            )
        })
        .transpose()?
        .flatten()
    } else {
        None
    };
    let fitted_visible_mt = match closed_coanchored_mt {
        Some(closed) => Some(closed),
        None => fit_measured_for_host_with_storage(
            para, next_para, table, mt, dpi, styles, &profile, storage,
        )?,
    };
    let mt = fitted_visible_mt.as_ref().or(mt);

    let is_tac = uses_tac_flow();
    let host_spacing::HostSpacingResult {
        host_spacing,
        strict_following_plain_text_fit,
    } = host_spacing::resolve(
        host_spacing::HostSpacingInput {
            para,
            ctrl_idx,
            table,
            styles,
            composed,
            next_para,
            is_column_top,
            is_tac,
        },
        dpi,
        &profile,
    );

    let (
        row_heights,
        cell_spacing,
        effective_height,
        caption_height,
        cumulative_heights,
        page_break,
        cells,
        header_row_count,
    ) = if let Some(mt) = mt {
        let hrc = if mt.repeat_header && mt.has_header_cells {
            1
        } else {
            0
        };
        (
            crate::storage::try_clone(&mt.row_heights, storage)?,
            mt.cell_spacing,
            mt.total_height,
            mt.caption_height,
            crate::storage::try_clone(&mt.cumulative_heights, storage)?,
            mt.page_break,
            crate::storage::try_clone(&mt.cells, storage)?,
            hrc,
        )
    } else {
        (
            Vec::new(),
            0.0,
            0.0,
            0.0,
            storage.collect([0.0])?,
            Default::default(),
            Vec::new(),
            0,
        )
    };

    let effective_height = crate::renderer::height_measurer::whole_table_frame_height(
        table,
        effective_height,
        dpi,
        profile().hwp5_stored_pagination_layout() || profile().hwpx_stored_layout(),
        styles,
    );
    let effective_height = external_flow.map_or(effective_height, |flow| flow.effective_height);
    let total_height = effective_height + host_spacing.before + host_spacing.after;

    // 표 셀 내 각주 높이 사전 계산 (Paginator engine.rs:565-581 동일)
    let mut table_footnote_height = 0.0;
    let source_notes =
        crate::renderer::pagination::table_cell_footnotes_with_storage(table, storage)?;
    let table_footnote_count = source_notes.len();
    let mut table_footnotes = Vec::new();
    for (cell_path, fn_ctrl) in source_notes {
        let owner = cell_path[0];
        let fn_height = estimate_footnote_note_height(fn_ctrl, dpi);
        table_footnote_height += fn_height;
        // 두 저장 컨테이너 모두 같은 명시적 각주 줄 재시작을 보존한다.
        // 조회는 저장 줄과 구성 줄의 일대일 대응을 확인하며,
        // 편집·합성 메타데이터를 분할 신호로 쓰지 않는다.
        let fragment_split = (profile().hwp5_stored_pagination_layout()
            || (profile().hwpx_stored_layout() && !profile().session_edited()))
        .then(|| native_hwp5_footnote_reset_fragments(fn_ctrl, dpi))
        .flatten();
        storage.push(
            &mut table_footnotes,
            TableCellFootnote {
                number: fn_ctrl.number,
                row: table.cells[owner.cell_index].row as usize,
                cell_path,
                content_height: queued_table_footnote_content_height(fn_ctrl, dpi),
                fragment_split,
            },
        )?;
    }

    Ok(FormattedTable {
        row_heights,
        cell_spacing,
        header_row_count,
        host_spacing,
        effective_height,
        total_height,
        caption_height,
        is_tac,
        cumulative_heights,
        page_break,
        cells,
        table_footnote_height,
        table_footnote_count,
        table_footnotes,
        strict_following_plain_text_fit,
        external_flow,
    })
}

/// 첫 조각의 세로 시작 기준(흐름 원점). 빈 호스트의 문단 기준 양수 오프셋 표는
/// `문단 시작 + 오프셋` 에 놓이므로(#1860), 같은 문단의 앞선 인라인 개체가 흐름을 내려도
/// 기준은 문단 시작이다. 이월 판정과 분할 예산이 같은 원점을 소비해야 한다(#4599).
/// 문단 시작은 그 앞선 개체가 현재 단에 놓였을 때만 이 단의 좌표다(`anchor_items_on_frame`).
/// 지연 배치로 단을 넘긴 표에는 앞 쪽의 낡은 문단 시작이 남아 있어 쓰지 않는다
/// (1543000 282쪽: 낡은 원점으로 잔여를 과대평가해 남의 표 아래에 첫 조각을 끼워 넣었다).
pub(super) fn first_fragment_flow_origin(
    para: &Paragraph,
    table: &Table,
    para_start_height: f64,
    current_height: f64,
    anchor_items_on_frame: bool,
) -> f64 {
    use crate::model::shape::VertRelTo;
    let empty_host_para_offset_float = !table.common.treat_as_char
        && matches!(table.common.vert_rel_to, VertRelTo::Para)
        && (table.common.vertical_offset as i32) > 0
        && !para_has_non_whitespace_text(para);
    if empty_host_para_offset_float && anchor_items_on_frame {
        para_start_height.min(current_height)
    } else {
        current_height
    }
}

/// 기존 측정값에 대한 보정 후보를 반환한다. 원본 fallback과 결과 수명은 호출자가 관리한다.
/// profile 관측은 기존 guard의 단락 평가 위치를 보존한다.
pub(crate) fn fit_measured_for_host(
    para: &Paragraph,
    next_para: Option<&Paragraph>,
    table: &Table,
    mt: Option<&MeasuredTable>,
    dpi: f64,
    styles: &ResolvedStyleSet,
    profile: impl Fn() -> LayoutCompatibilityProfile,
) -> Option<MeasuredTable> {
    match fit_measured_for_host_with_storage(
        para,
        next_para,
        table,
        mt,
        dpi,
        styles,
        profile,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn fit_measured_for_host_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    next_para: Option<&Paragraph>,
    table: &Table,
    mt: Option<&MeasuredTable>,
    dpi: f64,
    styles: &ResolvedStyleSet,
    profile: impl Fn() -> LayoutCompatibilityProfile,
    storage: &S,
) -> Result<Option<MeasuredTable>, S::Error> {
    crate::storage::with_optional(|failure| {
        // An outer wrapper's height is a physical frame, not a target height for
        // proportional rescaling of the unwrapped child's rows.
        if crate::renderer::height_measurer::transparent_table_wrapper_child(table, styles)
            .is_some_and(|nested| {
                profile().hwp5_stored_pagination_layout()
                    || profile().hwpx_stored_layout()
                    || crate::renderer::height_measurer::unrestricted_wrapper_frame(
                        table, nested, dpi,
                    )
                    .is_some()
            })
        {
            return crate::storage::optional(
                mt.map(|value| crate::storage::try_clone(value, storage))
                    .transpose(),
                failure,
            )?;
        }
        if profile().hwpx_stored_layout() && !profile().session_edited() {
            if let Some(fitted) = mt.and_then(|measured| {
                crate::storage::optional(
                    crate::renderer::height_measurer::fit_stored_inline_picture_frame_with_storage(
                        measured, table, dpi, storage,
                    ),
                    failure,
                )?
            }) {
                return Some(fitted);
            }
            if let Some(fitted) =
            mt.and_then(|measured| crate::storage::optional(crate::renderer::height_measurer::fit_stored_hwpx_no_adjust_rowspans_with_storage(measured, table, dpi, storage), failure)?)
        {
            return Some(fitted);
        }
        }
        if table.common.treat_as_char
            && profile().hwpx_stored_layout()
            && !profile().session_edited()
        {
            if let Some(fitted) = mt
            .and_then(|measured| crate::storage::optional(crate::renderer::height_measurer::trim_stored_hwpx_inline_row_trailing_spacing_with_storage(measured, table, dpi, storage), failure)?)
        {
            return Some(fitted);
        }
        }
        // [#2195] 빈 앵커(자리차지 표 표준형)에도 선언높이 fit 적용 — 한글은 콘텐츠가
        // 선언보다 작아도 표 선언높이를 유지한다 (80168 pi=419 행 걷기 151.1 = 선언,
        // 콘텐츠 143.5 사용 시 페이지 끝 razor -1쪽). fit 자체의 0.75~1.35 가드(#1510)
        // 가 과대 압축/팽창을 차단한다.
        if is_para_topbottom_float(&table.common) {
            mt.and_then(|measured| {
            // 개체 높이가 첫 조각만 기록한 경우 전체 행을 그 높이로 누르지 않는다.
            // 뒤 원본 줄의 쪽 원점이 잔여를 정확히 증명할 때 format과 paint가 같은 행을 쓴다.
            if crate::storage::optional(
                source_frame_fit::stored_following_tail_owns_rows(
                    para, next_para, table, measured, profile(), dpi, storage,
                ),
                failure,
            )? {
                return crate::storage::optional(crate::storage::try_clone(measured, storage), failure);
            }
            let body_height = measured.row_heights.iter().sum::<f64>()
                + measured.cell_spacing * measured.row_heights.len().saturating_sub(1) as f64;
            if !profile().session_edited()
                && (profile().hwp5_stored_pagination_layout() || profile().hwpx_stored_layout())
                && hwpunit_to_px(table.common.height as i32, dpi) > body_height
                && crate::renderer::table_row_frame::stored_rows_own_body(
                    table,
                    &measured.row_heights,
                    dpi,
                )
            {
                // 실제 내용을 담은 행 선언을 개체의 낡은 전체 캐시로 다시 늘리지 않는다.
                return crate::storage::optional(crate::storage::try_clone(measured, storage), failure);
            }
            let (fitted, shrink_blocked_by_content) =
                crate::storage::optional(crate::renderer::height_measurer::fit_measured_table_to_declared_height_with_outcome_with_storage(measured, table, dpi, storage), failure)?;
            // 빈 앵커는 **확대 방향만**: 한글 규칙 = max(선언, 콘텐츠) — 콘텐츠가
            // 선언보다 큰 표(pi=15 조문대비표 929.6>928.4)를 압축하면 분할 경계가
            // 당겨져 pi16 -1쪽. 압축(fit-down)은 종전대로 비공백 텍스트 앵커 한정.
            let shrunk = fitted.row_heights.iter().sum::<f64>()
                < measured.row_heights.iter().sum::<f64>() - 0.01;
            // 텍스트 앵커의 fit-down(선언 높이 압축)은 저장 시점 형상 전용
            // 보정이다 — 편집 세션(session_edited)이나 실제 성장 행(중첩 표
            // 없는 텍스트 행이 선언 행높이를 1.5배 초과) 판정 시 압축하지
            // 않는다. 압축하면 커진 행의 몫을 다른 행이 빼앗겨 내부가 위로
            // 밀리고 fit 판정이 과소해져 RowBreak 분할이 시작되지 않는다
            // (셀 Enter 재현: 한글은 행을 키우고 넘친 부분을 다음 쪽으로
            // 분할). 빈 host 는 아래 분기(측정 복원·tail-fit)가 종전대로
            // 처리한다.
            if shrunk
                && para_has_non_whitespace_text(para)
                && (profile().session_edited()
                    || crate::storage::optional(crate::renderer::height_measurer::measured_table_has_grown_text_row_with_storage(
                        measured, table, dpi,
                     storage), failure)?)
            {
                return crate::storage::optional(crate::storage::try_clone(measured, storage), failure);
            }
            // The host's caption does not change the physical row frame.
            // Use the same authenticated closing-row plan for text and empty
            // hosts before proportional fitting can compress earlier rows.
            let stored_declared_tail = !profile().session_edited()
                && (profile().hwp5_stored_pagination_layout()
                    || profile().hwpx_stored_layout())
                && matches!(
                    table.layout_page_break(),
                    crate::model::table::TablePageBreak::RowBreak
                        | crate::model::table::TablePageBreak::CellBreak
                )
                && table.row_count > 1;
            if (shrunk || shrink_blocked_by_content) && stored_declared_tail {
                if let Some(closed) =
                    crate::storage::optional(crate::renderer::height_measurer::fit_measured_table_declared_tail_to_declared_height_with_storage(measured, table, dpi, storage), failure)?
                {
                    return Some(closed);
                }
            }
            Some(if (shrunk || shrink_blocked_by_content) && !para_has_non_whitespace_text(para) {
                // HWP5 빈 TopAndBottom host의 다행 RowBreak 표는 통상 콘텐츠가
                // 선언높이를 넘으면 축소하지 않는다. 다만 마지막 행 하나가 비-TAC
                // 1×1 자식 표이고, 그 parent viewport의 Center 정렬이 만든 작은
                // over-measure인 경우에는 한컴 PDF가 앞 행 경계는 보존한 채 마지막
                // 행만 선언 총높이에 맞춘다 (76076 p81→82). 전체 비율 축소는 정상
                // 헤더/짧은 행까지 줄이므로 금지하고, helper가 마지막 행만 줄일 수
                // 있는 구조·64px 이내 drift를 다시 확인한다.
                let native_empty_rowbreak_nested_tail = profile().hwp5_stored_pagination_layout()
                    && !table.common.treat_as_char
                    && matches!(
                        table.layout_page_break(),
                        crate::model::table::TablePageBreak::RowBreak
                    )
                    && table.row_count > 1
                    && table.cells.iter().all(|cell| cell.row_span == 1);
                let adjusted = if native_empty_rowbreak_nested_tail {
                    crate::storage::optional(crate::renderer::height_measurer::fit_measured_table_nested_tail_to_declared_height_with_storage(measured, table, dpi, storage), failure)?
                } else { None };
                match adjusted {
                    Some(adjusted) => adjusted,
                    None => crate::storage::optional(crate::storage::try_clone(measured, storage), failure)?,
                }
            } else {
                fitted
            })
        })
        } else {
            None
        }
    })
}