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
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
//! 소유 문단 안의 컨트롤 배치 경로 조정.
//!
//! 저장 TAC 줄의 수용·계산은 stored_tac, 확정 좌표와 흐름 반영은 state가 소유한다.
//! 일반 TAC의 배치 전 판단은 tac_fit, 공유 판별은 tac_flow가 소유한다.
//! 컨트롤 순서와 첫/마지막 표 선택은 order가 소유한다.
//! 같은 문단의 형제 표 이월 판별·후보 선택·flush 시점 조회는 deferred가 소유한다.
//! 지연 큐 순회는 이 모듈이, 큐·vpos 상태 반영은 state가 소유한다.
//! 빈 호스트 float lane 조회는 empty_float가, 확정 예약은 state가 소유한다.
//! 표 문단의 그림·도형·수식 흐름 조회는 shape_flow가 소유하고 이 모듈이 배치를 조정한다.
//! 배치 후 TAC 높이 보정은 tac_reconcile 조회와 state 확정을 이 모듈에서 조정한다.
//! 데코레이션 host 텍스트의 항목/전진량은 decoration_host가 조회하고 state가 확정한다.
//! 표 진입의 저장 줄 이월·데코레이션 선택은 table_entry가 조회하고 이 모듈이 순서를 조정한다.
//! 장식 표의 컷/예약량은 decoration_table이 조회하고 이 모듈이 발행·포맷·확정을 조정한다.
//! 일반/TAC 표의 포맷·배치 선택과 후행 표 지연 등록은 flow_table이 조정한다.
//! 표 소유 문단 전체의 진입·컨트롤 순회·후처리는 paragraph_flow가 연결한다.
//! 개별 지연 표의 재조회·포맷·배치는 deferred_placement가 조정한다.
//! 표 없는 host 밴드 준비는 host_wrap의 조회와 state 적용을 순서대로 연결한다.
//! 후속 문단의 저장 어울림 매칭·그림 anchor 조회는 wrap_match가 소유한다.
//! 표 옆 문단의 흡수 기록·저장 끝점 조회는 wrap_absorption이, 적용은 state가 소유한다.
//! 전폭 꼬리와 매칭 실패의 저장 쪽 경계는 wrap_tail이 조회한다.
//! 후속 문단의 매칭·흡수·꼬리 배치 연결 순서는 wrap_flow가 조정한다.
//! 다음 쪽 Square 그림 후보와 저장 밴드 소유 문단 조회는 deferred_picture가 담당한다.
//! 표 포맷/분할 본체와 나머지 float 경로는 상위 구현에 남아 있다.

mod composed_tail;
pub(super) mod decoration_host;
pub(super) mod decoration_table;
pub(super) mod deferred;
pub(super) mod deferred_picture;
pub(super) mod deferred_placement;
pub(super) mod empty_float;
pub(super) mod flow_table;
pub(super) mod host_wrap;
pub(super) mod mixed_host_line;
pub(super) mod order;
pub(super) mod paragraph_flow;
pub(super) mod physical_tac;
pub(super) mod shape_flow;
mod square_host_frame;
pub(super) mod stored_tac;
pub(super) mod table_entry;
pub(super) mod tac_fit;
pub(super) mod tac_flow;
pub(super) mod tac_reconcile;
pub(super) mod wrap_absorption;
pub(super) mod wrap_flow;
pub(super) mod wrap_match;
pub(super) mod wrap_tail;

use super::paragraph::metrics::FormattedParagraph;
use super::{FormattedTable, TypesetState};
use crate::model::control::Control;
use crate::model::paragraph::Paragraph;
use crate::model::table::Table;
use crate::renderer::composer::ComposedParagraph;
use crate::renderer::float_placement::FloatLaneSet;
use crate::renderer::height_measurer::MeasuredTable;
use crate::renderer::hwpunit_to_px;
use crate::renderer::style_resolver::ResolvedStyleSet;

/// 저장 밴드 적용 → 자기 anchor 등록 → 비활성 상태의 유도 lane 준비.
pub(super) fn prepare_no_table_host_wrap(
    st: &mut TypesetState,
    page_def: &crate::model::page::PageDef,
    para: &Paragraph,
    para_idx: usize,
    has_table: bool,
) {
    if !has_table {
        if let Some(band) = host_wrap::stored_candidate(para) {
            let col_w_hu = st.host_wrap_column_width_hu();
            if host_wrap::can_arm(band, col_w_hu) {
                st.arm_stored_host_wrap(para_idx, band);
                if let Some(anchor) = host_wrap::host_anchor(para, page_def, para_idx, band) {
                    st.register_host_wrap_anchor(para_idx, anchor);
                }
            }
        }

        // [#6175] 저장 밴드를 적용하지 못했고 기존 밴드도 없을 때만 자기 기하로 유도한다.
        // 저장 cs/sw와 달리 any_seg를 켜지 않으며, 그룹 개체도 기존 helper가 판별한다.
        if st.host_wrap_needs_derived_lane() {
            let col_w_hu = st.host_wrap_column_width_hu();
            if let Some(lane) = super::square_float_left_lane_width(para, col_w_hu) {
                st.arm_derived_host_wrap(para_idx, lane);
            }
        }
    }
}

/// Shape 발행 → 포맷 → 컷 조회/진단 → 대기열·앵커 확정 순서를 보존한다.
#[allow(clippy::too_many_arguments)]
pub(super) fn place_decoration_table(
    st: &mut TypesetState,
    para_idx: usize,
    ctrl_idx: usize,
    para: &Paragraph,
    table: &Table,
    next_para: Option<&Paragraph>,
    paragraphs: &[Paragraph],
    dpi: f64,
    anchor_origin: Option<f64>,
    format: impl FnOnce(bool) -> FormattedTable,
    engine: &super::TypesetEngine,
    styles: &ResolvedStyleSet,
) {
    match place_decoration_table_with_storage(
        st,
        para_idx,
        ctrl_idx,
        para,
        table,
        next_para,
        paragraphs,
        dpi,
        anchor_origin,
        |top| Ok(format(top)),
        engine,
        styles,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(super) fn place_decoration_table_with_storage<S: crate::storage::Storage>(
    st: &mut TypesetState,
    para_idx: usize,
    ctrl_idx: usize,
    para: &Paragraph,
    table: &Table,
    next_para: Option<&Paragraph>,
    paragraphs: &[Paragraph],
    dpi: f64,
    anchor_origin: Option<f64>,
    format: impl FnOnce(bool) -> Result<FormattedTable, S::Error>,
    engine: &super::TypesetEngine,
    styles: &ResolvedStyleSet,
    storage: &S,
) -> Result<(), S::Error> {
    if anchor_origin.is_none()
        && !st.profile.session_edited()
        && (st.profile.hwp5_stored_pagination_layout() || st.profile.hwpx_stored_layout())
        && st.col_count == 1
        && st.current_zone_y_offset.abs() < f64::EPSILON
        && st.current_items.iter().skip(1).all(|item| {
            matches!(item, crate::renderer::pagination::PageItem::FullParagraph { para_index }
                if st.hidden_empty_paras.contains(para_index))
        })
    {
        let anchor = st.current_items.first().and_then(|item| match item {
            crate::renderer::pagination::PageItem::PartialTable {
                para_index,
                is_continuation: true,
                ..
            } => Some(*para_index),
            _ => None,
        });
        let placement = anchor.and_then(|anchor| {
            crate::renderer::float_placement::ParagraphFloatPlacement::from_stored_overlay_guide_chain(
                paragraphs, anchor, para_idx, st.current_height,
                st.layout.body_area.height, styles, dpi,
            )
        });
        if let Some(placement) = placement {
            st.align_flow_to(placement.anchor_y);
            let base = para.line_segs.first().map(|line| {
                line.vertical_pos - crate::renderer::px_to_hwpunit(placement.anchor_y, dpi)
            });
            st.record_vpos_lazy_origin(base);
            st.record_paragraph_float_placement_with_storage(
                (para_idx, ctrl_idx),
                placement,
                storage,
            )?;
        }
    }
    st.emit_decoration_table_with_storage(para_idx, ctrl_idx, storage)?;
    // [#4568] 현재 쪽을 넘는 잔여 행만 다음 쪽 대기열에 남긴다.
    // 포맷은 Shape 발행 뒤, 앵커/가용 영역 조회 전에 수행한다.
    let origin = anchor_origin.unwrap_or_else(|| st.decoration_table_flow_height());
    let ft = format(origin < 1.0)?;
    let continuation = decoration_table::continuation(
        para,
        table,
        next_para,
        &ft,
        origin,
        dpi,
        || st.base_available_height(),
        |row, available| {
            decoration_table::partial_row_query(engine, st, table, &ft, styles, row, available)
        },
    );
    if let Some(ref continuation) = continuation {
        if std::env::var("RHWP_TABLE_DRIFT").is_ok() {
            eprintln!(
                "OVERLAY_CONT: pi={} ci={} start_row={} remaining={:.1} reserve={:.1} room={:.1}",
                para_idx,
                ctrl_idx,
                continuation.first_unfit,
                continuation.remaining_px,
                continuation.reserve_px,
                continuation.room,
            );
        }
    }
    st.finish_decoration_table_with_storage(para_idx, ctrl_idx, continuation, storage)?;

    Ok(())
}

/// 저장 줄 경계의 이월을 먼저 적용한 뒤, 갱신된 단 상태로 장식 표 경로를 선택한다.
#[allow(clippy::too_many_arguments)]
pub(super) fn prepare_table_control(
    st: &mut TypesetState,
    para: &Paragraph,
    table: &Table,
    para_idx: usize,
    ctrl_idx: usize,
    order_pos: usize,
    next_para: Option<&Paragraph>,
    measured_tables: &[MeasuredTable],
    has_tac: bool,
    host_col_w: f64,
    dpi: f64,
    original_hwpx: impl FnOnce() -> bool,
) -> bool {
    match prepare_table_control_with_storage(
        st,
        para,
        table,
        para_idx,
        ctrl_idx,
        order_pos,
        next_para,
        measured_tables,
        has_tac,
        host_col_w,
        dpi,
        original_hwpx,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(super) fn prepare_table_control_with_storage<S: crate::storage::Storage>(
    st: &mut TypesetState,
    para: &Paragraph,
    table: &Table,
    para_idx: usize,
    ctrl_idx: usize,
    order_pos: usize,
    next_para: Option<&Paragraph>,
    measured_tables: &[MeasuredTable],
    has_tac: bool,
    host_col_w: f64,
    dpi: f64,
    original_hwpx: impl FnOnce() -> bool,
    storage: &S,
) -> Result<bool, S::Error> {
    let page = st.table_control_page();
    let follows_tac_frame = !page.profile.session_edited()
        && (page.profile.hwpx_stored_layout() || page.profile.hwp5_stored_pagination_layout())
        && crate::renderer::stored_control_frame::following_first_tac_frame(
            para,
            (st.base_available_height() * 7200.0 / dpi).round() as i32,
        )
        .is_some_and(|frame| {
            crate::renderer::layout::control_line_seg_index(para, ctrl_idx) == Some(frame.line)
                && st.coanchored_table_page().1.iter().any(|item| {
                    use crate::renderer::pagination::PageItem;
                    matches!(item,
                        PageItem::Table { para_index, control_index }
                        | PageItem::PartialTable { para_index, control_index, .. }
                        | PageItem::Shape { para_index, control_index }
                        if *para_index == para_idx && *control_index == frame.before_control)
                })
        });
    // 앞 줄 개체가 현재 쪽에 남아 있을 때만 경계를 건넌다. 새 줄 형제는 다시 넘기지 않는다.
    if follows_tac_frame {
        st.advance_column_or_new_page_with_storage(storage)?;
    }
    if table_entry::needs_stored_line_advance(
        para,
        table,
        order_pos,
        st.table_control_page().has_items,
        dpi,
    ) {
        st.advance_column_or_new_page_with_storage(storage)?;
    }
    let frame = st.inline_flow_input(0.0, false);
    Ok(table_entry::uses_decoration_placement(
        para,
        table,
        para_idx,
        ctrl_idx,
        next_para,
        measured_tables,
        st.table_control_page().col_count,
        has_tac,
        host_col_w,
        *frame.body,
        frame.page_height,
        dpi,
        || st.base_available_height(),
        original_hwpx,
    ))
}

/// 모든 컨트롤 앵커 확정 뒤, TAC 높이 정산 전에 host 텍스트를 한 번 반영한다.
#[allow(clippy::too_many_arguments)]
pub(super) fn place_decoration_host_text(
    st: &mut TypesetState,
    para_idx: usize,
    para: &Paragraph,
    next_para: Option<&Paragraph>,
    fmt: &FormattedParagraph,
    decoration_host_text_pending: bool,
    flow_table_owns_host_text: bool,
    styles: &ResolvedStyleSet,
    dpi: f64,
    stored_layout: impl FnOnce() -> bool,
) {
    match place_decoration_host_text_with_storage(
        st,
        para_idx,
        para,
        next_para,
        fmt,
        decoration_host_text_pending,
        flow_table_owns_host_text,
        styles,
        dpi,
        stored_layout,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(super) fn place_decoration_host_text_with_storage<S: crate::storage::Storage>(
    st: &mut TypesetState,
    para_idx: usize,
    para: &Paragraph,
    next_para: Option<&Paragraph>,
    fmt: &FormattedParagraph,
    decoration_host_text_pending: bool,
    flow_table_owns_host_text: bool,
    styles: &ResolvedStyleSet,
    dpi: f64,
    stored_layout: impl FnOnce() -> bool,
    storage: &S,
) -> Result<(), S::Error> {
    let _: () = if let Some(fragment) = decoration_host::plan(
        para_idx,
        para,
        next_para,
        fmt,
        decoration_host_text_pending,
        flow_table_owns_host_text,
        styles,
        dpi,
        stored_layout,
    ) {
        st.commit_decoration_host_text_with_storage(fragment, storage)?;
    };
    Ok(())
}

/// TAC 높이 조회 → 누락 표시/진단/무효화 → 앵커·상한 확정 순서를 보존한다.
#[allow(clippy::too_many_arguments)]
pub(super) fn reconcile_tac_height(
    st: &mut TypesetState,
    para_idx: usize,
    para: &Paragraph,
    next_para: Option<&Paragraph>,
    fmt: &FormattedParagraph,
    styles: &ResolvedStyleSet,
    measured_tables: &[MeasuredTable],
    tac_count: usize,
    height_before: f64,
    measured_tac_floor: Option<f64>,
    flow: tac_flow::TacFlowQuery<'_>,
) {
    let dpi = flow.dpi();
    let tac_reconcile::TacHeightCap {
        tac_seg_total,
        cap,
        stored_step_px,
        ladder_total,
        ladder_omits_spacing,
    } = tac_reconcile::measure(
        para_idx,
        para,
        next_para,
        fmt,
        styles,
        measured_tables,
        tac_count,
        height_before,
        st.tac_height_page().profile,
        &flow,
        |ci, prior_tac_count, lh, ls_extra| {
            if std::env::var("RHWP_DIAG_TACSIB").is_ok() {
                eprintln!(
                    "DIAG_TACSIB pi={} ci={} line_idx={} add={:.1} first_seg={:.1}",
                    para_idx,
                    ci,
                    prior_tac_count,
                    lh + ls_extra,
                    para.line_segs
                        .first()
                        .map(|s0| hwpunit_to_px(
                            s0.line_height.saturating_add(s0.line_spacing),
                            dpi
                        ))
                        .unwrap_or(0.0),
                );
            }
        },
    );
    if ladder_omits_spacing {
        st.commit_tac_spacing_omission(|| {
            if std::env::var("RHWP_DIAG_LADSP").is_ok() {
                eprintln!(
                    "DIAG_LADSP pi={} OMIT step={:.1} cap={:.1} fmt_total={:.1} sb={:.1} sa={:.1}",
                    para_idx,
                    stored_step_px.unwrap_or(0.0),
                    cap,
                    fmt.total_height,
                    fmt.spacing_before,
                    fmt.spacing_after
                );
            }
        });
    }
    let snapped_base = tac_reconcile::snapped_base(
        para,
        height_before,
        ladder_omits_spacing,
        st.tac_height_page(),
        dpi,
    );
    let cap =
        tac_reconcile::effective_cap(cap, ladder_total, ladder_omits_spacing, measured_tac_floor);
    // 현재 조판한 단일 표 줄의 확정 끝점에는 바깥 여백과 후행 간격도 들어 있다.
    // 셀 실측 본체만으로 다시 상한을 걸면 이미 예약한 물리 공간을 회수하게 된다.
    let cap = if measured_tac_floor.is_some()
        && para
            .controls
            .iter()
            .enumerate()
            .any(|(control_index, control)| match control {
                Control::Table(table) => {
                    let measured = measured_tables.iter().find(|measured| {
                        measured.para_index == para_idx && measured.control_index == control_index
                    });
                    flow.single_tac_line_has_current_cell_rows(
                        para,
                        table,
                        fmt,
                        tac_count,
                        measured.map_or(&[], |measured| measured.cells.as_slice()),
                    )
                }
                _ => false,
            }) {
        cap.max(st.tac_height_page().current_height - snapped_base)
    } else {
        cap
    };
    if std::env::var("RHWP_DIAG_TACCAP").is_ok() {
        eprintln!(
            "DIAG_TACCAP pi={} tac_seg_total={:.1} cap={:.1} fmt_total={:.1} sb={:.1} cur_h={:.1} snapped_base={:.1} clamp={}",
            para_idx,
            tac_seg_total,
            cap,
            fmt.total_height,
            fmt.spacing_before,
            st.tac_height_page().current_height,
            snapped_base,
            st.tac_height_page().current_height - snapped_base > cap
        );
    }

    let capped_bottom =
        tac_reconcile::capped_bottom(para_idx, snapped_base, cap, st.tac_height_page());
    st.commit_tac_capped_bottom(capped_bottom);
}

/// 표 문단의 비표 개체 배치 순서만 조정한다. 뒤쪽 문단 높이 보정은 호출자에 남는다.
#[allow(clippy::too_many_arguments)]
pub(super) fn place_table_host_shape(
    st: &mut TypesetState,
    para_idx: usize,
    ctrl_idx: usize,
    ctrl: &Control,
    para: &Paragraph,
    para_start_height: f64,
    styles: &ResolvedStyleSet,
    dpi: f64,
) {
    match place_table_host_shape_with_storage(
        st,
        para_idx,
        ctrl_idx,
        ctrl,
        para,
        para_start_height,
        styles,
        dpi,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(super) fn place_table_host_shape_with_storage<S: crate::storage::Storage>(
    st: &mut TypesetState,
    para_idx: usize,
    ctrl_idx: usize,
    ctrl: &Control,
    para: &Paragraph,
    para_start_height: f64,
    styles: &ResolvedStyleSet,
    dpi: f64,
    storage: &S,
) -> Result<(), S::Error> {
    // [#6146] 저장 리셋 경계에서 떠나는 쪽의 흐름 말미에 이미 흘려
    // 놓은 자리차지 밴드는 다시 배치하지 않는다.
    if st.has_spilled_page_tail_float(para_idx, ctrl_idx) {
        return Ok(());
    }
    // [#8660] 쪽 영역 안으로 제한한 문단 기준 개체가 본문 아래 끝을 넘으면 개체만 다음 쪽
    // 본문 맨 위에 놓는다. 표를 품은 기준 문단도 본문 문단과 같다(표 칸 안 개체는 무관).
    if st.col_count == 1 {
        if let Some(placement) = st
            .restricted_object_host_top(para_idx, para, para_start_height, dpi)
            .and_then(|host_top| {
                crate::renderer::float_placement::overflow_para_object_next_page_placement(
                    ctrl,
                    host_top,
                    st.available_height(),
                    dpi,
                )
            })
        {
            st.defer_stored_frame(super::DeferredStoredFrameControl {
                following_body_para_index: None,
                kind: super::DeferredStoredFrameKind::Picture,
                para_index: para_idx,
                control_index: ctrl_idx,
                placement,
                target_page: None,
            });
            return Ok(());
        }
    }
    let mut flow = shape_flow::prepare(ctrl, para, ctrl_idx, dpi);
    // [#8458] 자기 줄이 이미 글줄 항목으로 이 쪽에 놓였으면 그 줄 높이는 소비됐다.
    // 글자처럼 취급한 개체는 그 줄 안에 있으므로 줄 높이를 다시 판정·누적하지 않는다
    // (156759019 pi=29 줄1: 공백 글자 + TAC 로고, 글줄 53.1px 를 두 번 세어 로고만 다음 쪽).
    if flow.tac_separate_line_h.is_some()
        && shape_flow::own_line_already_placed(para_idx, para, ctrl_idx, &st.current_items)
    {
        flow.tac_separate_line_h = None;
    }
    // [#8462] 문단 위끝에서 용지 밖에 놓인 비-TAC 개체는 이 쪽 본문 흐름을 밀지 않는다.
    let offpage_top = (matches!(ctrl, Control::Shape(_)) && flow.non_tac_pushdown_h.is_some())
        .then(|| shape_flow::para_offset_top_px(ctrl, dpi))
        .flatten()
        .filter(|top| para_start_height + top >= st.available_height());
    // [#8491] 자기 저장 줄들 아래에서 시작하는 개체는 자기 줄을 밀지 않고
    // 개체 띠를 뒤 문단의 배제 영역으로 남긴다.
    let below_own_lines = if offpage_top.is_none() {
        flow.non_tac_pushdown_h
            .and_then(|height| {
                shape_flow::below_own_lines_top_px(ctrl, para, dpi).map(|top| (top, height))
            })
            .map(|(top, height)| (para_start_height + top, height))
    } else {
        None
    };
    if offpage_top.is_some() || below_own_lines.is_some() {
        flow.non_tac_pushdown_h = None;
    }
    if st.defer_table_host_ole_to_next_column(para_idx, ctrl_idx, ctrl, dpi) {
        return Ok(());
    }
    // [#8446] 앵커 줄이 저장 사다리에서 다음 쪽으로 되감긴(vpos 리셋) 비-TAC 자리차지 개체는
    // 그 줄을 따라 넘기지 않고 떠나는 쪽의 흐름 말미에 남긴다. 줄 머리 리셋의 #6146 과 같은
    // 규칙을 문단 중간 줄 리셋에 적용한다(156571452 로고: 한컴 1쪽 y 1030.7, 본문 아래끝 1028.1).
    // 개체 아래끝이 용지 안에 남을 때만이다. 같은 줄의 뒤 내용은 리셋대로 다음 쪽에 놓인다.
    let spills_to_leaving_page = flow.non_tac_pushdown_h.is_some_and(|extra| {
        shape_flow::anchor_line_rewinds_to_next_page(para, ctrl_idx)
            && shape_flow::page_still_holds_lines_before_anchor(
                para_idx,
                para,
                ctrl_idx,
                &st.current_items,
            )
            && st.layout.body_area.y + st.current_height + extra <= st.layout.page_height + 0.5
    });
    while !spills_to_leaving_page
        && flow.needs_advance(st.table_host_shape_page(), || st.available_height())
    {
        // 단 기준 개체가 다음 단에 들어가면 개체만 이월한다. 뒤 본문은 남은
        // 현재 단을 채우며, 저장 줄의 단 경계에서 예약 개체 뒤로 이어진다.
        let common = match ctrl {
            Control::Shape(shape) => Some(shape.common()),
            Control::Picture(picture) => Some(&picture.common),
            _ => None,
        };
        let column_frame = common.is_some_and(|common| {
            matches!(common.horz_rel_to, crate::model::shape::HorzRelTo::Column)
                && common.width as f64 <= st.layout.column_width_hu() as f64
        });
        if column_frame && st.defer_table_host_shape_to_next_column(para_idx, ctrl_idx, flow) {
            return Ok(());
        }
        st.advance_column_or_new_page_with_storage(storage)?;
    }
    // [#8435] 앞 TAC 줄 뒤 줄을 밀어낸 개체의 원점은 저장 사다리의 앵커 줄 자리다.
    // TAC 줄의 흐름 전진은 마지막 줄 간격을 쓸 수 있어 그 자리와 다를 수 있다.
    let pushed_anchor_origin = match ctrl {
        Control::Shape(shape) => {
            let common = shape.common();
            crate::renderer::layout::stored_pushed_anchor_line_offset_hu(
                para,
                common,
                i64::from(common.margin.top) + i64::from(common.margin.bottom),
                ctrl_idx,
            )
            .filter(|_| crate::renderer::layout::has_line_taking_tac_sibling_before(para, ctrl_idx))
            .map(|hu| para_start_height + crate::renderer::hwpunit_to_px(hu, dpi))
        }
        _ => None,
    };
    let accepted_frame = if let Some(top) = offpage_top {
        Some(shape_flow::offpage_shape_frame(
            para_start_height,
            top,
            st.current_height,
        ))
    } else if let Some((top, _)) = below_own_lines {
        Some(shape_flow::below_own_lines_frame(
            para_start_height,
            top,
            st.current_height,
        ))
    } else {
        match pushed_anchor_origin {
            Some(origin) => flow.pushed_anchor_shape_frame(ctrl, origin, dpi),
            None => flow.accepted_shape_frame(ctrl, st.current_height),
        }
    };
    st.commit_table_host_shape_with_storage(para_idx, ctrl_idx, flow, accepted_frame, storage)?;
    if let Some((top, height)) = below_own_lines {
        st.add_visible_float_exclusion(super::VisibleFloatExclusion {
            para_index: para_idx,
            top,
            bottom: top + height,
        });
    }
    st.register_side_wrap_picture(para_idx, ctrl_idx, para, Some(para_start_height), styles);
    if spills_to_leaving_page {
        // 개체만 남기고 그 줄은 저장 리셋대로 다음 쪽에서 시작한다. 줄에 다른 내용이 없어도
        // 쪽은 열린다(156569782: 한컴 2쪽은 빈 줄 하나뿐인 쪽).
        st.advance_column_or_new_page_with_storage(storage)?;
    }

    Ok(())
}

/// 조회가 후보를 수용한 경우에만 표 항목·lane·흐름 상태를 함께 반영한다.
#[allow(clippy::too_many_arguments)]
pub(super) fn try_place_empty_para_float_table(
    st: &mut TypesetState,
    para_idx: usize,
    ctrl_idx: usize,
    para: &Paragraph,
    table: &crate::model::table::Table,
    ft: &FormattedTable,
    composed: Option<&ComposedParagraph>,
    prev_para: Option<&Paragraph>,
    next_para: Option<&Paragraph>,
    styles: &ResolvedStyleSet,
    para_start_height: f64,
    lanes: &mut FloatLaneSet,
    paragraphs: &[Paragraph],
    table_reflowed: bool,
    preceding_fragment_reflowed: bool,
    dpi: f64,
) -> bool {
    let Some(placement) = empty_float::prepare(
        para_idx,
        ctrl_idx,
        para,
        table,
        ft,
        composed,
        prev_para,
        next_para,
        styles,
        para_start_height,
        lanes,
        st.empty_float_page(paragraphs),
        table_reflowed,
        preceding_fragment_reflowed,
        || st.empty_float_available_height(ft.table_footnote_height, ft.table_footnote_count),
        dpi,
    ) else {
        return false;
    };
    st.commit_empty_float_table(para_idx, ctrl_idx, placement, lanes);
    true
}

/// 큐 처리 순서만 조정한다. 표 하나의 측정·배치는 기존 엔진 경로가 담당한다.
pub(super) fn flush_deferred_tables(
    st: &mut TypesetState,
    paragraphs: &[Paragraph],
    flush_point: deferred::DeferredTableFlushPoint,
    mut place: impl FnMut(&mut TypesetState, deferred::DeferredTableControl),
) {
    if !st.has_deferred_table_controls() {
        return;
    }
    let pending = st.take_deferred_table_controls();
    let mut remaining = Vec::new();
    for deferred in pending {
        let keep_pending = flush_point.keeps_pending(&deferred, paragraphs);
        if keep_pending {
            remaining.push(deferred);
            continue;
        }
        // 지연 표의 원래 host 뒤 문단은 이미 출력됐을 수 있다. 배치 시점의
        // 실제 문단 cursor를 마지막 조각의 후속 줄 조회에 전달한다.
        let previous = st.replace_deferred_table_successor_start(Some(
            flush_point.successor_start(paragraphs.len()),
        ));
        place(st, deferred);
        st.replace_deferred_table_successor_start(previous);
    }
    st.restore_deferred_table_controls(remaining);
}

/// Query 결과를 확정한 뒤에만 기존 페이지 전이를 수행한다.
pub(super) fn prepare_tac_paragraph(
    st: &mut TypesetState,
    para_idx: usize,
    para: &Paragraph,
    fmt: &FormattedParagraph,
    measured_tables: &[MeasuredTable],
    flow: tac_flow::TacFlowQuery<'_>,
) -> tac_fit::TacFitPlan {
    let plan = tac_fit::prepare(
        para_idx,
        para,
        fmt,
        measured_tables,
        st.tac_fit_page(),
        || st.available_height(),
        flow,
    );
    if plan.advance_before_place {
        st.advance_column_or_new_page();
    }
    plan
}

/// 기존 저장 줄 경로가 문단 전체를 수용한 경우에만 일반 컨트롤 경로를 생략한다.
#[allow(clippy::too_many_arguments)]
pub(super) fn try_place_stored_tac_paragraph(
    st: &mut TypesetState,
    para_idx: usize,
    para: &Paragraph,
    fmt: &FormattedParagraph,
    measured_tables: &[MeasuredTable],
    engine: &super::TypesetEngine,
    paragraphs: &[Paragraph],
    styles: &crate::renderer::style_resolver::ResolvedStyleSet,
    composed: Option<&ComposedParagraph>,
) -> bool {
    let dpi = engine.dpi;
    // 커진 인라인 줄은 원본 저장 TAC 계획의 수용 증거가 아니다.
    // 공통 표 경로가 실제 상자와 뒤 본문의 전체 점유를 함께 검사한다.
    if para.controls.iter().any(|control| {
        matches!(control, Control::Table(table)
            if engine.render_normalization.inline_host_frame_expanded(table))
    }) {
        return false;
    }
    let source_frame = st.stored_tac_line_frame(para, paragraphs.get(para_idx + 1), styles);
    if let Some(placement) = stored_tac::prepare_computed(
        para_idx,
        para,
        paragraphs.get(para_idx + 1),
        paragraphs
            .get(para_idx + 1)
            .and_then(|next| styles.para_styles.get(next.para_shape_id as usize))
            .map_or(0.0, |style| style.spacing_before),
        fmt,
        measured_tables,
        styles,
        st.stored_tac_page(paragraphs),
        || st.available_height(),
        source_frame,
        dpi,
    ) {
        // 합성 표 줄의 간격은 확정 끝에 이미 포함된다. 같은 끝점에서 좌표축을
        // 연결해 다음 문단의 lazy 역산이 그 간격을 다시 더하지 않게 한다.
        let rebase_line_origin = placement.rebase_line_origin;
        let lazy_origin = para.line_segs.first().map(|seg| {
            seg.vertical_pos
                .saturating_add(seg.line_height)
                .saturating_add(seg.line_spacing)
                .saturating_sub(crate::renderer::px_to_hwpunit(placement.end, dpi))
        });
        // 일반 표 문단 경로는 장식 개체도 원래 컨트롤 순서대로 발행한다.
        // 줄 계획의 단축이 그 경로를 생략해도, 흐름을 점유하지 않는 장식의
        // paint 소유권은 남는다. 표의 저장 pen을 같은 문단 앵커로 전달한다.
        let owner = placement.control_index;
        let host_origin = placement.inline.y;
        let emit_decoration = |st: &mut TypesetState, index: usize, control: &Control| {
            if let Control::Table(table) = control {
                place_decoration_table(
                    st,
                    para_idx,
                    index,
                    para,
                    table,
                    paragraphs.get(para_idx + 1),
                    paragraphs,
                    dpi,
                    Some(host_origin),
                    |is_column_top| {
                        engine.format_table(
                            para,
                            para_idx,
                            index,
                            table,
                            measured_tables,
                            styles,
                            composed,
                            paragraphs.get(para_idx + 1),
                            is_column_top,
                        )
                    },
                    engine,
                    styles,
                );
            } else {
                place_table_host_shape(
                    st,
                    para_idx,
                    index,
                    control,
                    para,
                    host_origin,
                    styles,
                    dpi,
                );
            }
        };
        for (index, control) in para.controls.iter().enumerate().take(owner) {
            emit_decoration(st, index, control);
        }
        st.commit_stored_tac_control(para_idx, placement);
        for (index, control) in para.controls.iter().enumerate().skip(owner + 1) {
            emit_decoration(st, index, control);
        }
        // 원본 저장 줄의 좌표축은 이미 확립돼 있다. 합성 줄의 확정 끝만
        // lazy 원점으로 역산하며, 실제 저장 표 뒤 사다리는 유지한다.
        if rebase_line_origin {
            st.commit_deferred_table_anchor(para_idx, paragraphs);
            st.record_vpos_lazy_origin(lazy_origin);
            st.mark_vpos_ladder_dirty();
        }
        return true;
    }
    // A closed preceding object frame already owns its successor's leading
    // spacing. The stored TAC plan must use that same origin for fit and paint.
    let shared_spacing_before =
        crate::renderer::float_placement::stored_frame_successor_shared_spacing_px(
            &st.paragraph_float_placements,
            para_idx,
            fmt.spacing_before,
            st.current_height,
        );
    let Some(plan) = stored_tac::prepare(
        para_idx,
        para,
        fmt,
        measured_tables,
        styles,
        st.stored_tac_page(paragraphs),
        shared_spacing_before,
        para_idx
            .checked_sub(1)
            .and_then(|index| paragraphs.get(index)),
        para_idx
            .checked_sub(1)
            .and_then(|index| paragraphs.get(index))
            .and_then(|previous| styles.para_styles.get(previous.para_shape_id as usize))
            .map_or(0.0, |shape| shape.spacing_after),
        paragraphs.get(para_idx + 1),
        paragraphs
            .get(para_idx + 1)
            .and_then(|next| styles.para_styles.get(next.para_shape_id as usize))
            .map_or(0.0, |shape| shape.spacing_before),
        styles
            .para_styles
            .get(para.para_shape_id as usize)
            .is_some_and(|style| style.page_break_before),
        || st.available_height(),
        source_frame,
        dpi,
    ) else {
        return false;
    };
    for line in &plan.lines {
        let placement = plan.placement(line, fmt.spacing_after, dpi);
        st.commit_stored_tac_control(para_idx, placement);
    }
    if let Some(frame) = plan.source_frame {
        st.commit_deferred_table_anchor(para_idx, paragraphs);
        st.record_vpos_page_origin(Some(frame.source_origin_hu));
        st.record_vpos_column_anchor(frame.column_anchor_y);
        st.record_vpos_origin_provenance(true);
        st.record_vpos_lazy_origin(None);
    }
    true
}