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
454
//! 원본 행 선언을 이미 충족한 표의 본체와 닫힌 후속 줄 프레임.
//! 측정이 보존한 행 본체를 format·paint와 후속 줄 원점이 함께 소비한다.

use crate::model::{
    control::Control,
    paragraph::{ColumnBreakType, LineSeg, Paragraph},
    table::Table,
};
use crate::renderer::float_placement::ParagraphFloatPlacement;
use crate::renderer::hwpunit_to_px;

/// 첫 조각과 종료 쪽의 저장 원점이 전체 원본 행 본체를 정확히 나눈다.
/// 다음 원점에 남은 본체를 독립 빈 간격으로 다시 더하지 않기 위한 정수 단위 근거다.
/// 문단 지역 원점·편집 여부와 실제 조각 종료 여부는 각 호출자가 확인한다.
pub(crate) fn stored_rows_close_at_successor(
    rows: &[crate::model::HwpUnit],
    cell_spacing: i16,
    first_fragment: u32,
    successor_top: i32,
) -> bool {
    rows.len() >= 2
        && first_fragment > 0
        && first_fragment <= i32::MAX as u32
        && successor_top > 0
        && rows
            .iter()
            .all(|&height| height > 0 && height <= i32::MAX as u32)
        && rows.iter().map(|&height| i64::from(height)).sum::<i64>()
            + i64::from(cell_spacing) * (rows.len() - 1) as i64
            == i64::from(first_fragment) + i64::from(successor_top)
}

/// 저장 rowspan의 쪽 되감김으로 입증한 첫 물리 프레임을 행 원장에 투영한다.
///
/// 표의 선언 높이는 이 경우 전체 행 합이 아니라 첫 조각의 끝이다. 끝 행의
/// 저장 여유만 첫 프레임에 맞추고, 걸침 셀의 남은 높이는 실제 종료 행에서
/// 이어받는다. 내용 하한과 전체 걸침 높이는 줄이지 않는다.
/// HWPX 문단 지역 vpos를 쪽 되감김으로 읽지 않도록 호출자가 HWP5 출처를 확인한다.
pub(crate) fn project_first_rowspan_frame(
    table: &Table,
    rows: &mut [f64],
    content_floors: &[f64],
    span_content_floors: &[(usize, f64)],
    dpi: f64,
) -> bool {
    if table.common.treat_as_char
        || table.page_break != crate::model::table::TablePageBreak::RowBreak
        || table.common.height == 0
        || table.common.height > i32::MAX as u32
        || rows.len() < 2
        || rows.len() != usize::from(table.row_count)
        || rows.len() != content_floors.len()
        || !dpi.is_finite()
        || dpi <= 0.0
        || !table.cells.iter().any(|cell| cell.row_span > 1)
    {
        return false;
    }
    let declared = hwpunit_to_px(table.common.height as i32, dpi);
    let spacing = hwpunit_to_px(i32::from(table.cell_spacing), dpi);
    let mut origin = spacing;
    let Some((closing_row, remaining)) = rows.iter().enumerate().find_map(|(row, &height)| {
        let end = origin + height + spacing;
        let result =
            (origin < declared && declared < end).then_some((row, declared - origin - spacing));
        origin = end;
        result
    }) else {
        return false;
    };
    if remaining < content_floors[closing_row] || remaining <= 0.0 || remaining >= rows[closing_row]
    {
        return false;
    }
    let mut witnessed_rewind = false;
    let mut carry_row = rows.len();
    for cell in &table.cells {
        let start = usize::from(cell.row);
        let end = start + usize::from(cell.row_span);
        if start > closing_row || end <= closing_row + 1 || end > rows.len() {
            continue;
        }
        // 같은 물리 행이 여러 rowspan을 지지해도 높이는 한 번만 예약한다.
        carry_row = carry_row.min(end - 1);
        let mut previous = None;
        for segment in cell
            .paragraphs
            .iter()
            .flat_map(|paragraph| &paragraph.line_segs)
        {
            if segment.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
                || segment.vertical_pos < 0
                || segment.line_height <= 0
            {
                return false;
            }
            witnessed_rewind |= previous.is_some_and(|position| segment.vertical_pos < position);
            previous = Some(segment.vertical_pos);
        }
    }
    if !witnessed_rewind || carry_row >= rows.len() {
        return false;
    }
    let carried = rows[closing_row] - remaining;
    // 이 경계에서 끝나는 다른 병합 셀의 실제 내용도 같은 높이 제약이다.
    // 이어받지 않는 셀은 뒤 행의 보충 높이를 사용할 수 없다.
    if span_content_floors.iter().any(|&(index, floor)| {
        let Some(cell) = table.cells.get(index) else {
            return true;
        };
        let start = usize::from(cell.row);
        let end = start + usize::from(cell.row_span);
        start <= closing_row
            && end == closing_row + 1
            && rows[start..end].iter().sum::<f64>() - carried < floor
    }) || table.cells.iter().any(|cell| {
        cell.dirty_flag
            || cell.paragraphs.iter().any(|paragraph| {
                paragraph.stored_text_partition_is_dirty() || paragraph.cell_format_vpos_dirty
            })
    }) {
        return false;
    }
    rows[closing_row] = remaining;
    rows[carry_row] += carried;
    true
}

/// 모든 저장 행이 실제 측정 결과와 같으면 더 큰 개체 캐시로 다시 늘리지 않는다.
/// 보호 크기, 병합 행, 실제 행 성장과 편집으로 무효가 된 칸은 기존 계약을 유지한다.
///
/// 칸 문단에 저장 줄이 없어(HWPX `linesegarray` 생략) rhwp 가 줄을 계산했더라도, 판정의
/// 근거는 측정 행과 칸 선언의 일치다([#8968]). 계산한 줄이 칸 선언을 넘으면 행이 자라
/// 아래 비교에서 빠지고, 선언 안에 들면 행은 선언 높이 그대로다.
pub(crate) fn stored_rows_own_body(table: &Table, rows: &[f64], dpi: f64) -> bool {
    if !dpi.is_finite()
        || dpi <= 0.0
        || table.common.treat_as_char
        || table.common.size_protect
        || rows.len() < 2
        || rows.len() != usize::from(table.row_count)
        || table.cells.is_empty()
        || table.cells.iter().any(|cell| {
            cell.row_span != 1
                || cell.height == 0
                || cell.height > i32::MAX as u32
                || cell.dirty_flag
                || cell.paragraphs.is_empty()
                || cell.paragraphs.iter().any(|para| {
                    para.stored_text_partition_is_dirty() || para.cell_format_vpos_dirty
                })
        })
    {
        return false;
    }
    let unit = dpi / 7200.0;
    // 행마다 표 전체를 훑지 않고 행별 선언 높이 최댓값을 한 번에 모은다.
    let mut declared_rows: Vec<Option<u32>> = vec![None; rows.len()];
    for cell in &table.cells {
        if let Some(declared) = declared_rows.get_mut(usize::from(cell.row)) {
            *declared = Some(declared.map_or(cell.height, |height| height.max(cell.height)));
        }
    }
    rows.iter().zip(&declared_rows).all(|(measured, declared)| {
        let declared = declared.map(|height| hwpunit_to_px(height as i32, dpi));
        declared.is_some_and(|height| {
            measured.is_finite()
                && (measured - height).abs()
                    <= unit * 0.5 + (measured.abs() + height.abs()) * f64::EPSILON
        })
    })
}

/// 한컴 저장 상자가 후속 줄에서 정확히 닫히면 정규화된 본체 차이만 투영한다.
/// 원점은 현재 단의 실제 흐름이며 앞 단이나 문서 전체의 저장 원점을 이식하지 않는다.
pub(crate) fn normalized_empty_control_frame(
    host: &Paragraph,
    successor: &Paragraph,
    table: &Table,
    rows: &[f64],
    flow_origin: f64,
    dpi: f64,
    hwpx_object_frame: bool,
) -> Option<ParagraphFloatPlacement> {
    if !stored_rows_own_body(table, rows, dpi)
        || table.caption.is_some()
        || !flow_origin.is_finite()
        || table.common.height == 0
        || table.common.height > i32::MAX as u32
    {
        return None;
    }
    let anchor = host.line_segs.first()?;
    let source_origin = host
        .source_line_seg_vertical_pos
        .as_ref()
        .and_then(|positions| positions.first().copied())
        .unwrap_or(anchor.vertical_pos);
    let declared = hwpunit_to_px(table.common.height as i32, dpi);
    let body = rows.iter().sum::<f64>()
        + hwpunit_to_px(i32::from(table.cell_spacing), dpi) * rows.len().saturating_sub(1) as f64;
    if body >= declared {
        return None;
    }
    let mut frame = crate::renderer::float_placement::stored_empty_control_table_frame(
        host,
        successor,
        table,
        declared,
        0.0,
        source_origin,
        dpi,
        hwpx_object_frame,
    )?;
    let change = body - declared;
    frame.anchor_y += flow_origin;
    frame.table_top += flow_origin;
    frame.occupied_bottom += flow_origin + change;
    frame.stored_host_origin = frame.stored_host_origin.map(|origin| origin + flow_origin);
    frame.stored_successor_line_origin = frame
        .stored_successor_line_origin
        .map(|origin| origin + flow_origin + change);
    Some(frame)
}

fn clean_single_saved_line(para: &Paragraph) -> Option<&LineSeg> {
    let [line] = para.line_segs.as_slice() else {
        return None;
    };
    (!para.stored_text_partition_is_dirty()
        && !para.cell_format_vpos_dirty
        && para.column_type == ColumnBreakType::None
        && line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
        && line.text_start == 0
        && line.vertical_pos >= 0
        && line.text_height > 0
        && line.text_height <= line.line_height
        && line.segment_width > 0
        && para
            .source_line_seg_vertical_pos
            .as_ref()
            .is_none_or(|source| source.as_slice() == [line.vertical_pos]))
    .then_some(line)
}

/// 서로 다른 문단의 지역 원점을 한 셀의 누적 끝점으로 오인하지 않는다.
/// 닫힌 저장 줄 사다리만 내용 하한의 근거로 사용한다.
fn saved_single_line_ladder_end(paragraphs: &[Paragraph]) -> Option<i64> {
    let mut end = None;
    for paragraph in paragraphs {
        let line = clean_single_saved_line(paragraph)?;
        let top = i64::from(line.vertical_pos);
        if end.is_some_and(|previous| top < previous) {
            return None;
        }
        end = Some(top + i64::from(line.line_height));
    }
    end
}

/// The host line owns the child's complete painted box, including outside margins.
fn stored_inline_tail_table_fits_line(para: &Paragraph) -> bool {
    let [Control::Table(child)] = para.controls.as_slice() else {
        return false;
    };
    let Some(line) = clean_single_saved_line(para) else {
        return false;
    };
    let height = i64::from(child.common.height);
    if !para.text.is_empty()
        || !child.common.treat_as_char
        || !child.common.flow_with_text
        || child.caption.is_some()
        || child.row_count != 1
        || child.cells.is_empty()
        || child.cells.len() != usize::from(child.col_count)
        || child.cell_spacing < 0
        || child.common.width > i32::MAX as u32
        || height == 0
        || [
            child.outer_margin_left,
            child.outer_margin_right,
            child.outer_margin_top,
            child.outer_margin_bottom,
        ]
        .iter()
        .any(|&margin| margin < 0)
        || i64::from(child.common.width)
            + i64::from(child.outer_margin_left)
            + i64::from(child.outer_margin_right)
            > i64::from(line.segment_width)
        || height + i64::from(child.outer_margin_top) + i64::from(child.outer_margin_bottom)
            != i64::from(line.line_height)
    {
        return false;
    }

    let mut width = u64::from(child.cell_spacing as u16) * (child.cells.len() - 1) as u64;
    for (col, cell) in child.cells.iter().enumerate() {
        let Some(content_end) = saved_single_line_ladder_end(&cell.paragraphs) else {
            return false;
        };
        let padding = cell.effective_padding(&child.padding);
        let inside_width =
            i64::from(cell.width) - i64::from(padding.left) - i64::from(padding.right);
        if cell.dirty_flag
            || cell.row != 0
            || usize::from(cell.col) != col
            || cell.row_span != 1
            || cell.col_span != 1
            || cell.width == 0
            || cell.height > child.common.height
            || [padding.left, padding.right, padding.top, padding.bottom]
                .iter()
                .any(|&value| value < 0)
            || cell.paragraphs.iter().any(|paragraph| {
                let line = &paragraph.line_segs[0];
                !paragraph.controls.is_empty()
                    || line.column_start < 0
                    || i64::from(line.column_start) + i64::from(line.segment_width) > inside_width
            })
            // 빈 공간도 자식의 선언 상자가 소유한다. 내용이 상자를 채울 필요는 없다.
            || content_end + i64::from(padding.top) + i64::from(padding.bottom) > height
        {
            return false;
        }
        width += u64::from(cell.width);
    }
    width == u64::from(child.common.width)
}

/// 원본 저장 줄과 선언 상자로 입증한 마지막 행의 빈 띠만 회수한다.
/// 측정 유무와 무관하게 같은 행 벡터를 소비하며, 쪽을 가른 행에는 호출하지 않는다.
pub(crate) fn declared_tail_row_height(
    table: &Table,
    row_heights: &[f64],
    cell_spacing: f64,
    dpi: f64,
) -> Option<f64> {
    let row_count = row_heights.len();
    if row_count < 2 || table.row_count as usize != row_count || table.common.height == 0 {
        return None;
    }
    let last_row = row_count - 1;

    // 셀 저장 줄 사다리가 되감기면(다음 줄 vpos 가 앞 줄보다 작다) 한/글이 그 표를 쪽에서
    // 갈랐다는 저장 사실이다. 그 표의 선언 높이는 첫 조각 프레임일 뿐 표 전체가 아니고,
    // 아래 내용 하한도 되감긴 사다리로는 잴 수 없다(pic-in-head-01 pi=65 3×3: 선언 905.8 =
    // 18쪽 조각, 마지막 행 내용은 19쪽으로 이어진다).
    let has_stored_page_rewind = table.cells.iter().any(|cell| {
        let mut previous: Option<i32> = None;
        cell.paragraphs
            .iter()
            .flat_map(|paragraph| paragraph.line_segs.iter())
            .filter(|seg| seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0)
            .any(|seg| {
                let rewinds = previous.is_some_and(|vpos| seg.vertical_pos < vpos);
                previous = Some(seg.vertical_pos);
                rewinds
            })
    });
    if has_stored_page_rewind {
        return None;
    }

    // 마지막 행이 저장 선언으로만 잡힌 행인지 — 콘텐츠가 밀어 키운 행이면 여유가 없다.
    let declared_tail = table
        .cells
        .iter()
        .filter(|cell| {
            cell.row as usize == last_row && cell.row_span == 1 && cell.height < 0x8000_0000
        })
        .map(|cell| hwpunit_to_px(cell.height as i32, dpi))
        .fold(0.0f64, f64::max);
    if declared_tail <= 0.0 || (row_heights[last_row] - declared_tail).abs() > 0.5 {
        return None;
    }

    // 축소 하한 = 마지막 행 셀들의 저장 줄 내용 높이 + 상하 패딩.
    let mut content_floor = 0.0f64;
    let mut has_inline_tail_table = false;
    for cell in &table.cells {
        if cell.row as usize != last_row || cell.row_span != 1 {
            continue;
        }
        if cell
            .paragraphs
            .iter()
            .any(crate::renderer::para_has_no_stored_line_segs)
        {
            return None;
        }
        let mut cell_has_inline_tail_table = false;
        for paragraph in &cell.paragraphs {
            if !paragraph
                .controls
                .iter()
                .any(|control| matches!(control, Control::Table(_)))
            {
                continue;
            }
            if cell.dirty_flag || !stored_inline_tail_table_fits_line(paragraph) {
                return None;
            }
            has_inline_tail_table = true;
            cell_has_inline_tail_table = true;
        }
        let content_hu = if cell_has_inline_tail_table {
            saved_single_line_ladder_end(&cell.paragraphs)?
        } else {
            cell.paragraphs
                .iter()
                .flat_map(|paragraph| paragraph.line_segs.iter())
                .map(|seg| i64::from(seg.vertical_pos) + i64::from(seg.line_height))
                .max()
                .unwrap_or(0)
        };
        let pad = hwpunit_to_px(cell.effective_vertical_padding_hu(&table.padding), dpi);
        let floor = hwpunit_to_px(i32::try_from(content_hu).ok()?, dpi) + pad;
        if floor > content_floor {
            content_floor = floor;
        }
    }
    if content_floor <= 0.0
        || (has_inline_tail_table
            && table.cells.iter().any(|cell| {
                cell.row_span > 1 && usize::from(cell.row) + usize::from(cell.row_span) > last_row
            }))
    {
        return None;
    }

    let spacing_total = cell_spacing * row_count.saturating_sub(1) as f64;
    let target_body_height = hwpunit_to_px(table.common.height as i32, dpi);
    let target_row_sum = (target_body_height - spacing_total).max(0.0);
    let current_row_sum = row_heights.iter().sum::<f64>();
    let reduction = current_row_sum - target_row_sum;
    // 반올림 급(≤0.5px)은 건드리지 않는다. 회수량의 상한은 비율이 아니라 마지막 행의 저장
    // 내용 하한(아래 검사)과 되감기 없는 사다리(위 검사)다 — 한/글은 표 선언 높이를 지키며
    // 앞 행이 커진 만큼을 마지막 행의 빈 공간에서 거둔다. 2025 행정업무운영 편람 구역 10
    // pi=85(6×5): 정본 괘선 행 12.3/33.3/20.2/13.3/308.1/**9.6** = 396.9 ≒ 선언 397.0,
    // 마지막 행 선언 21.5 · 내용 하한 8.9(감소 11.8px, 선언의 3%). 하한 아래로는 줄이지 않으므로
    // 거둘 공간이 모자라면 회수하지 않는다(issue3587 labnote pi=12: 감소 13.7 > 여유 7.5,
    // 정본도 마지막 행 24.6 그대로 표가 커진다).
    if reduction <= 0.5 {
        return None;
    }
    let target_tail = row_heights[last_row] - reduction;
    if target_tail < content_floor - 0.5 {
        return None;
    }

    Some(target_tail)
}