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
//! PaginationState: paginate_with_measured의 가변 상태를 캡슐화

use super::{ColumnContent, PageContent, PageItem, WrapAroundPara};
use crate::renderer::page_layout::PageLayoutInfo;
use std::collections::HashMap;

/// 페이지당 방어 로직 최대 실행 횟수.
/// 정상 문서에서는 절대 도달하지 않는 값. 이 값을 초과하면 무한 루프로 판단하고 강제 배치.
/// TODO: current_height 누적이 정확해지면 방어 로직과 함께 제거 가능.
const DEFENSE_MAX_PER_PAGE: u32 = 100;

/// paginate_with_measured의 12+ 가변 상태 변수를 구조체로 통합
pub(super) struct PaginationState {
    pub pages: Vec<PageContent>,
    pub current_items: Vec<PageItem>,
    pub current_height: f64,
    pub current_column: u16,
    pub current_footnote_height: f64,
    pub footnote_placement: crate::model::footnote::FootnotePlacement,
    pub footnote_frames: Vec<crate::renderer::footnote_frames::Reservation>,
    pub is_first_footnote_on_page: bool,
    pub col_count: u16,
    pub layout: PageLayoutInfo,
    pub current_zone_y_offset: f64,
    pub current_zone_layout: Option<PageLayoutInfo>,
    pub on_first_multicolumn_page: bool,
    pub section_index: usize,
    pub footnote_separator_overhead: f64,
    pub footnote_between_notes_margin: f64,
    pub footnote_safety_margin: f64,
    /// 현재 단에 축적된 어울림 리턴 문단 목록
    pub current_column_wrap_around_paras: Vec<WrapAroundPara>,
    /// [Task #604 R3] 현재 단의 wrap text 문단 ↔ anchor 메타데이터
    pub current_column_wrap_anchors: std::collections::HashMap<usize, super::WrapAnchorRef>,
    /// 현재 페이지의 vpos 기준점 (첫 문단의 vertical_pos, HWPUNIT)
    /// layout의 vpos 보정과 동기화하기 위해 사용
    pub page_vpos_base: Option<i32>,
    /// 현재 페이지에 비-TAC 블록 표가 존재하는지 (vpos drift 보정용)
    pub page_has_block_table: bool,
    // --- 방어 로직 (TODO: current_height 누적이 정확해지면 제거 가능) ---
    /// 페이지별 방어 로직 실행 횟수 (레이어 1·2 공통).
    /// key: page_index (= pages.len() at time of defense), value: 실행 횟수
    pub defense_counts: HashMap<usize, u32>,
    /// 페이지 전환 시 overflow로 판정된 마지막 항목을 다음 페이지/단으로 이월
    pub overflow_carry: Option<PageItem>,
    /// 레이어 1이 advance_column_or_new_page를 호출 중임을 표시.
    /// 이 플래그가 true이면 레이어 2(check_last_item_overflow)를 스킵하여 이중 이동 방지.
    pub layer1_advancing: bool,
}

impl PaginationState {
    pub fn new(
        layout: PageLayoutInfo,
        col_count: u16,
        section_index: usize,
        footnote_separator_overhead: f64,
        footnote_between_notes_margin: f64,
        footnote_safety_margin: f64,
    ) -> Self {
        Self {
            pages: Vec::new(),
            current_items: Vec::new(),
            current_height: 0.0,
            current_column: 0,
            current_footnote_height: 0.0,
            footnote_placement: Default::default(),
            footnote_frames: Vec::new(),
            is_first_footnote_on_page: true,
            col_count,
            layout,
            current_zone_y_offset: 0.0,
            current_zone_layout: None,
            on_first_multicolumn_page: false,
            section_index,
            footnote_separator_overhead,
            footnote_between_notes_margin,
            footnote_safety_margin,
            current_column_wrap_around_paras: Vec::new(),
            current_column_wrap_anchors: std::collections::HashMap::new(),
            page_vpos_base: None,
            page_has_block_table: false,
            defense_counts: HashMap::new(),
            overflow_carry: None,
            layer1_advancing: false,
        }
    }

    /// 현재 항목을 ColumnContent로 만들어 마지막 페이지에 push
    pub fn flush_column_with_storage<S: crate::storage::Storage>(
        &mut self,
        storage: &S,
    ) -> Result<(), S::Error> {
        if self.current_items.is_empty() {
            return Ok(());
        }
        let col_content = ColumnContent {
            paragraph_origins: Default::default(),
            computed_paragraphs: Default::default(),
            column_index: self.current_column,
            start_height: 0.0,
            endnote_flow: false,
            items: std::mem::take(&mut self.current_items),
            zone_layout: crate::storage::try_clone(&self.current_zone_layout, storage)?,
            zone_y_offset: self.current_zone_y_offset,
            wrap_around_paras: std::mem::take(&mut self.current_column_wrap_around_paras),
            used_height: self.current_height,
            wrap_anchors: std::mem::take(&mut self.current_column_wrap_anchors),
            // [#4568] Paginator 경로(RHWP_USE_PAGINATOR fallback)는 overlay 잔여 행을
            // 아직 만들지 않는다 — TypesetEngine 경로만 채운다.
            overlay_continuations: Vec::new(),
            overlay_cuts: Vec::new(),
            inline_placements: Default::default(),
            inline_flow_plans: Default::default(),
            stored_paragraph_flow_ends: Default::default(),
            host_compositions: Default::default(),
            stored_column_top_spacings: Default::default(),
            paragraph_float_placements: Default::default(),
            float_pushed_line_spacings: Default::default(),
            page_band_flow_starts: Default::default(),
        };
        if let Some(page) = self.pages.last_mut() {
            storage.push(&mut page.column_contents, col_content)?;
        } else {
            let page =
                self.new_page_content_with_storage(storage.collect([col_content])?, storage)?;
            storage.push(&mut self.pages, page)?;
        }

        Ok(())
    }

    /// 현재 항목을 ColumnContent로 만들어 (비어있어도) 마지막 페이지에 push
    pub fn flush_column_always_with_storage<S: crate::storage::Storage>(
        &mut self,
        storage: &S,
    ) -> Result<(), S::Error> {
        let col_content = ColumnContent {
            paragraph_origins: Default::default(),
            computed_paragraphs: Default::default(),
            column_index: self.current_column,
            start_height: 0.0,
            endnote_flow: false,
            items: std::mem::take(&mut self.current_items),
            zone_layout: crate::storage::try_clone(&self.current_zone_layout, storage)?,
            zone_y_offset: self.current_zone_y_offset,
            wrap_around_paras: std::mem::take(&mut self.current_column_wrap_around_paras),
            used_height: self.current_height,
            wrap_anchors: std::mem::take(&mut self.current_column_wrap_anchors),
            // [#4568] Paginator 경로(RHWP_USE_PAGINATOR fallback)는 overlay 잔여 행을
            // 아직 만들지 않는다 — TypesetEngine 경로만 채운다.
            overlay_continuations: Vec::new(),
            overlay_cuts: Vec::new(),
            inline_placements: Default::default(),
            inline_flow_plans: Default::default(),
            stored_paragraph_flow_ends: Default::default(),
            host_compositions: Default::default(),
            stored_column_top_spacings: Default::default(),
            paragraph_float_placements: Default::default(),
            float_pushed_line_spacings: Default::default(),
            page_band_flow_starts: Default::default(),
        };
        if let Some(page) = self.pages.last_mut() {
            storage.push(&mut page.column_contents, col_content)?;
        } else {
            let page =
                self.new_page_content_with_storage(storage.collect([col_content])?, storage)?;
            storage.push(&mut self.pages, page)?;
        }

        Ok(())
    }

    /// 다음 단으로 이동하거나, 마지막 단이면 새 페이지 생성
    pub fn advance_column_or_new_page_with_storage<S: crate::storage::Storage>(
        &mut self,
        storage: &S,
    ) -> Result<(), S::Error> {
        self.flush_column_with_storage(storage)?;
        if self.current_column + 1 < self.col_count {
            self.current_column += 1;
            self.select_footnote_frame();
            self.current_height = 0.0;
        } else {
            self.push_new_page_with_storage(storage)?;
        }

        Ok(())
    }

    /// 페이지 전환 시 마지막 문단 항목이 overflow인지 점검.
    /// overflow이면 해당 항목을 overflow_carry로 이월하여 다음 페이지/단에 재삽입.
    /// FullParagraph / PartialParagraph만 대상 (표·글상자 제외).
    fn check_last_item_overflow_with_storage<S: crate::storage::Storage>(
        &mut self,
        storage: &S,
    ) -> Result<(), S::Error> {
        // carry가 이미 있으면 중복 방지
        if self.overflow_carry.is_some() {
            return Ok(());
        }
        let is_para_item = self.current_items.last().map_or(false, |item| {
            matches!(
                item,
                PageItem::FullParagraph { .. } | PageItem::PartialParagraph { .. }
            )
        });
        if !is_para_item {
            return Ok(());
        }
        let available = self.available_height();
        if self.current_height <= available + 0.5 {
            return Ok(());
        }
        // overflow 감지: 방어 횟수 기록
        let page_idx = self.pages.len();
        if !self.defense_counts.contains_key(&page_idx) {
            storage.reserve_map(&mut self.defense_counts, 1)?;
        }
        let count = self.defense_counts.entry(page_idx).or_insert(0);
        *count += 1;
        if *count > DEFENSE_MAX_PER_PAGE {
            // 상한 초과: 무한 루프 최종 차단, carry 발동 안 함
            return Ok(());
        }
        self.overflow_carry = self.current_items.pop();

        Ok(())
    }

    /// overflow_carry 항목을 현재 페이지/단에 재삽입하고 current_height를 보정.
    /// page_vpos_base 설정은 호출자(engine.rs)가 para.line_segs 접근 후 수행.
    pub fn reinsert_carry_with_height_with_storage<S: crate::storage::Storage>(
        &mut self,
        carry_height: f64,
        storage: &S,
    ) -> Result<(), S::Error> {
        if let Some(carry) = self.overflow_carry.take() {
            storage.push(&mut self.current_items, carry)?;
            self.current_height += carry_height;
        }

        Ok(())
    }

    /// 강제 새 페이지 (쪽 나누기)
    pub fn force_new_page_with_storage<S: crate::storage::Storage>(
        &mut self,
        storage: &S,
    ) -> Result<(), S::Error> {
        self.flush_column_with_storage(storage)?;
        self.push_new_page_with_storage(storage)?;

        Ok(())
    }

    /// 페이지가 비어있으면 첫 페이지 생성
    pub fn ensure_page_with_storage<S: crate::storage::Storage>(
        &mut self,
        storage: &S,
    ) -> Result<(), S::Error> {
        if self.pages.is_empty() {
            let page = self.new_page_content_with_storage(Vec::new(), storage)?;
            storage.push(&mut self.pages, page)?;
        }

        Ok(())
    }

    /// 사용 가능한 본문 높이 (각주 영역, 안전 여백, 존 오프셋 제외)
    pub fn available_height(&self) -> f64 {
        let base = self.layout.available_body_height();
        let fn_margin = if self.current_footnote_height > 0.0 {
            self.footnote_safety_margin
        } else {
            0.0
        };
        (base - self.current_footnote_height - fn_margin - self.current_zone_y_offset).max(0.0)
    }

    /// base_available_height (각주/존 오프셋 미차감)
    pub fn base_available_height(&self) -> f64 {
        self.layout.available_body_height()
    }

    /// 각주 높이 추가
    fn footnote_frame_policy(&self) -> crate::renderer::footnote_frames::FramePolicy {
        crate::renderer::footnote_frames::FramePolicy {
            placement: self.footnote_placement,
            columns: self.col_count,
        }
    }

    fn select_footnote_frame(&mut self) {
        let policy = self.footnote_frame_policy();
        if policy.spans_page() {
            return;
        }
        let frame = if policy.charges_column(self.current_column) {
            self.footnote_frames
                .get(usize::from(policy.target(self.current_column)))
                .copied()
                .unwrap_or_default()
        } else {
            Default::default()
        };
        self.current_footnote_height = frame.height;
        self.is_first_footnote_on_page = frame.count == 0;
    }

    /// 수용한 각주의 소유 프레임에 높이를 예약한다.
    pub fn add_footnote_height(&mut self, height: f64) {
        let policy = self.footnote_frame_policy();
        if !policy.spans_page() {
            self.footnote_frames
                .resize(usize::from(self.col_count), Default::default());
            self.footnote_frames[usize::from(policy.target(self.current_column))].add(
                height,
                true,
                self.footnote_separator_overhead,
                self.footnote_between_notes_margin,
            );
            let maximum = self
                .footnote_frames
                .iter()
                .map(|frame| frame.height)
                .fold(0.0, f64::max);
            if let Some(page) = self.pages.last_mut() {
                page.layout.update_footnote_area(maximum);
            }
            self.select_footnote_frame();
            return;
        }
        if self.is_first_footnote_on_page {
            self.current_footnote_height += self.footnote_separator_overhead;
            self.is_first_footnote_on_page = false;
        } else {
            self.current_footnote_height += self.footnote_between_notes_margin;
        }
        self.current_footnote_height += height;
        self.sync_current_page_footnote_area();
    }

    pub fn projected_footnote_height(&self, note_content_height: f64, note_count: usize) -> f64 {
        let policy = self.footnote_frame_policy();
        if !policy.spans_page() {
            let frame = self
                .footnote_frames
                .get(usize::from(policy.target(self.current_column)))
                .copied()
                .unwrap_or_default();
            let projected = frame.projected(
                note_content_height,
                note_count,
                true,
                self.footnote_separator_overhead,
                self.footnote_between_notes_margin,
            );
            return if policy.charges_column(self.current_column)
                || projected > self.base_available_height()
            {
                projected
            } else {
                0.0
            };
        }
        if note_count == 0 {
            return self.current_footnote_height;
        }
        let separator = if self.is_first_footnote_on_page {
            self.footnote_separator_overhead
        } else {
            0.0
        };
        let between_count = if self.is_first_footnote_on_page {
            note_count.saturating_sub(1)
        } else {
            note_count
        };
        self.current_footnote_height
            + separator
            + self.footnote_between_notes_margin * between_count as f64
            + note_content_height
    }

    fn sync_current_page_footnote_area(&mut self) {
        if self.current_footnote_height <= 0.0 {
            return;
        }
        if let Some(page) = self.pages.last_mut() {
            page.layout
                .update_footnote_area(self.current_footnote_height);
        }
    }

    /// 새 페이지 push + 상태 리셋
    fn push_new_page_with_storage<S: crate::storage::Storage>(
        &mut self,
        storage: &S,
    ) -> Result<(), S::Error> {
        let page = self.new_page_content_with_storage(Vec::new(), storage)?;
        storage.push(&mut self.pages, page)?;
        self.reset_for_new_page();

        Ok(())
    }

    /// 새 페이지 상태 리셋
    fn reset_for_new_page(&mut self) {
        self.current_column = 0;
        self.current_height = 0.0;
        self.current_footnote_height = 0.0;
        self.footnote_frames.clear();
        self.is_first_footnote_on_page = true;
        self.page_vpos_base = None;
        self.page_has_block_table = false;
        self.current_zone_y_offset = 0.0;
        self.current_zone_layout = None;
        self.on_first_multicolumn_page = false;
        self.current_column_wrap_around_paras.clear();
        self.current_column_wrap_anchors.clear();
    }

    /// PageContent 생성 헬퍼
    fn new_page_content_with_storage<S: crate::storage::Storage>(
        &self,
        column_contents: Vec<ColumnContent>,
        storage: &S,
    ) -> Result<PageContent, S::Error> {
        Ok(PageContent {
            page_index: self.pages.len() as u32,
            page_number: 0,
            page_number_restarted: false,
            section_index: self.section_index,
            layout: crate::storage::try_clone(&self.layout, storage)?,
            column_contents,
            active_header: None,
            active_footer: None,
            page_number_pos: None,
            page_hide: None,
            footnotes: Vec::new(),
            active_master_page: None,
            extra_master_pages: Vec::new(),
            ladder_band_tables: Vec::new(),
        })
    }
}