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
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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
//! 텍스트와 TAC 표의 공통 물리 줄 배치. 원본 LineSeg/문자 offset은 변경하지 않는다.
//!
//! 페이지 배치 소유자가 원점과 선행 제외 영역을 전달하고, 확정 결과의 높이와 좌표를
//! 함께 소비한다. 이 모듈은 RenderNode를 만들거나 문서 캐시를 수정하지 않는다.

use std::ops::Range;

mod alignment;
use alignment::RowEnding;
pub(crate) mod floating_shapes;
mod picture_rows;
pub(crate) use picture_rows::supports_picture_rows;
mod separator_spaces;
mod source_addresses;
pub(crate) use source_addresses::text_logical_starts;
mod table_rows;
pub(crate) use table_rows::{
    standalone_table_fragment_owner, standalone_table_fragment_owner_with_storage,
    supports_page_square_table_rows, supports_table_text_rows,
    supports_table_text_rows_with_storage,
};

mod stored_host;
mod stored_square_rows;
pub(crate) use stored_host::{plan_stored_body_wide_host, plan_stored_empty_square_host};

use crate::model::{control::Control, paragraph::Paragraph, style::Alignment};

use super::{
    float_placement::ObjectPlacementFrame,
    height_measurer::MeasuredTable,
    hwpunit_to_px,
    layout::{estimate_text_width_unrounded, resolved_to_text_style},
    layout_frame::{FrameExclusion, LayoutFrame},
    px_to_hwpunit,
    style_resolver::{detect_lang_category, ResolvedParaStyle, ResolvedStyleSet},
};

/// 문자 또는 표. 식별자는 paragraph.text의 scalar index / control index다.
#[derive(Debug, Clone, PartialEq)]
pub enum InlineFlowContent {
    Text {
        range: Range<usize>,
        style: u32,
        lang: usize,
        /// 줄 안 정렬점과 실제 글꼴 기준선을 구분한다.
        alignment_baseline: Option<f64>,
    },
    Table {
        control: usize,
        margin_left: f64,
        margin_top: f64,
    },
    /// Width-neutral object anchored to the physical text row.
    FloatingTable {
        control: usize,
        /// 쪽 기준 개체는 줄 회피와 동일한 프레임에서 확정한 본체 원점을 소비한다.
        resolved_position: Option<(f64, f64)>,
    },
    FloatingShape {
        control: usize,
    },
    /// 글자처럼 그림의 줄 상자와 실제 잉크 사이 바깥 여백.
    Picture {
        control: usize,
        margin_left: f64,
        margin_top: f64,
        affect_line_spacing: bool,
    },
}

#[derive(Debug, Clone, PartialEq)]
pub struct InlineFlowBox {
    pub content: InlineFlowContent,
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
    pub baseline: f64,
}
crate::storage::clone_fields!(InlineFlowBox, {content, x, y, width, height, baseline});

impl crate::storage::CloneWithStorage for InlineFlowContent {
    fn clone_with_storage<S: crate::storage::Storage>(
        &self,
        _storage: &S,
    ) -> Result<Self, S::Error> {
        Ok(self.clone())
    }
}
impl InlineFlowBox {
    fn alignment_baseline(&self) -> f64 {
        match self.content {
            InlineFlowContent::Text {
                alignment_baseline: Some(value),
                ..
            } => value,
            _ => self.baseline,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(crate) struct InlineFlowRow {
    pub boxes: Range<usize>,
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
    pub baseline: f64,
}
crate::storage::clone_fields!(InlineFlowRow, {boxes, x, y, width, height, baseline});

/// 좌표와 높이는 같은 계산의 결과다. 확정 후 단 상대 좌표로 보관한다.
#[derive(Debug, Clone, PartialEq)]
pub struct InlineFlowPlan {
    /// 정상 저장 증언으로 확정한 빈 부동 개체 호스트의 실제 줄 예약.
    pub(crate) stored_empty_host: bool,
    /// 절대 전폭 개체의 예약 뒤에서 시작하는 첫 저장 부분 문단.
    pub(crate) stored_float_host: bool,
    /// NO_LS 본문의 확정 frame 행. 원본 IR은 바꾸지 않고 fit와 paint에 함께 전달한다.
    pub(crate) text_rows: Option<Vec<crate::model::paragraph::LineSeg>>,
    /// Square table owns the object; this plan owns only its host text rows.
    pub(crate) square_host_control: Option<usize>,
    pub(crate) text_spacing_before: Option<f64>,
    pub(crate) square_host_placement: Option<super::float_placement::ParagraphFloatPlacement>,
    /// Host-relative object geometry; survives after the host text has ended.
    pub(crate) square_host_exclusion: Option<FrameExclusion>,
    pub(crate) floating_shapes: Vec<floating_shapes::FloatingShapePlacement>,
    pub start: f64,
    pub end: f64,
    pub boxes: Vec<InlineFlowBox>,
    pub(crate) rows: Vec<InlineFlowRow>,
    /// 원래 가용 폭/높이에 실제로 간섭한 제외 영역이 있었는가.
    pub(crate) carved: bool,
    next_row_top: f64,
    fallback_font_size: f64,
}
crate::storage::clone_fields!(InlineFlowPlan, {stored_empty_host, stored_float_host, text_rows, square_host_control, text_spacing_before, square_host_placement, square_host_exclusion, floating_shapes, start, end, boxes, rows, carved, next_row_top, fallback_font_size});

impl InlineFlowPlan {
    /// 확정한 행의 물리 하단. 다음 줄 전진과 문단 뒤 여백을 구분한다.
    pub(crate) fn occupied_end(&self) -> f64 {
        // 별도 text_rows 소유자는 기존 측정 끝을 유지한다. 공통 inline
        // 행은 실제 배제 영역을 반영한 행 상자의 하단을 그대로 소비한다.
        if self.rows.is_empty() {
            return self.end;
        }
        self.rows
            .iter()
            .map(|row| row.y + row.height)
            .fold(self.start, f64::max)
    }

    /// 배제 영역이 실제로 줄을 바꿨고, 주어진 영역 중 하나가 이 문단의 세로 범위와 겹치는가.
    /// 영역은 용지 좌표(HU), 이 plan 은 단 상대 좌표(px)다.
    pub(crate) fn carved_by_any<'a>(
        &self,
        exclusions: impl IntoIterator<Item = &'a FrameExclusion>,
        column_y: f64,
        dpi: f64,
    ) -> bool {
        self.carved
            && exclusions.into_iter().any(|exclusion| {
                let top = hwpunit_to_px(exclusion.vertical.start, dpi) - column_y;
                let bottom = hwpunit_to_px(exclusion.vertical.end, dpi) - column_y;
                top < self.end && self.start < bottom
            })
    }

    pub(crate) fn relative_to(&mut self, x: f64, y: f64) {
        floating_shapes::relative_to(&mut self.floating_shapes, y);
        self.start -= y;
        self.end -= y;
        self.next_row_top -= y;
        if let Some(p) = &mut self.square_host_placement {
            p.anchor_y -= y;
            p.table_top -= y;
            p.occupied_bottom -= y;
            p.table_left = p.table_left.map(|left| left - x);
        }
        for item in &mut self.boxes {
            if let InlineFlowContent::FloatingTable {
                resolved_position: Some((left, top)),
                ..
            } = &mut item.content
            {
                *left -= x;
                *top -= y;
            }
            item.x -= x;
            item.y -= y;
        }
        for row in &mut self.rows {
            row.x -= x;
            row.y -= y;
        }
    }
}

enum Atom {
    Box(InlineFlowBox),
    Float(FrameExclusion),
    Break(InlineFlowBox),
}

#[derive(Clone, Copy, Default)]
struct RowMetrics {
    width: f64,
    baseline: f64,
    descent: f64,
}

impl RowMetrics {
    fn combined(self, other: Self) -> Self {
        Self {
            width: self.width + other.width,
            baseline: self.baseline.max(other.baseline),
            descent: self.descent.max(other.descent),
        }
    }

    fn with(self, item: &InlineFlowBox) -> Self {
        let baseline = item.alignment_baseline();
        Self {
            width: self.width + item.width,
            baseline: self.baseline.max(baseline),
            descent: self.descent.max(item.height - baseline),
        }
    }
}

/// 현재 연결된 계약은 본문의 텍스트 / TAC 표 / 그림 / 구조 marker다.
/// 다른 소유자의 수식·각주·필드를 누락시키지 않고 연결 전까지 기존 경로로 반환한다.
pub(crate) fn supports(para: &Paragraph, width_hu: i32) -> bool {
    if supports_picture_rows(para) {
        return true;
    }
    para.controls.iter().any(|c| {
        matches!(c, Control::Table(t)
        if super::height_measurer::is_tac_table_inline_in_para(t, width_hu, para))
    }) && para.controls.iter().all(|c| match c {
        Control::Table(t) => t.common.treat_as_char,
        Control::Picture(p) => !p.common.treat_as_char,
        Control::Header(_)
        | Control::Footer(_)
        | Control::SectionDef(_)
        | Control::ColumnDef(_)
        | Control::PageNumberPos(_)
        | Control::PageNumCtrl(_) => true,
        _ => false,
    })
}

/// 호출자가 측정한 표 높이와 기존 text measurer의 advance를 사용한다.
pub(crate) fn plan(
    para: &Paragraph,
    para_index: usize,
    styles: &ResolvedStyleSet,
    tables: &[MeasuredTable],
    frame: &ObjectPlacementFrame<'_>,
    preceding: &[FrameExclusion],
) -> Option<InlineFlowPlan> {
    match plan_with_storage(
        para,
        para_index,
        styles,
        tables,
        frame,
        preceding,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn plan_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    para_index: usize,
    styles: &ResolvedStyleSet,
    tables: &[MeasuredTable],
    frame: &ObjectPlacementFrame<'_>,
    preceding: &[FrameExclusion],
    storage: &S,
) -> Result<Option<InlineFlowPlan>, S::Error> {
    let Some(style) = styles.para_styles.get(para.para_shape_id as usize) else {
        return Ok(None);
    };
    let picture_rows = supports_picture_rows(para);
    let top = frame.paragraph_y + style.spacing_before;
    // 가시 글자가 없는 문단의 개체 순번은 문자 위치가 아니다. 각 개체의
    // 순서를 유지해 토큰으로 넣고, 공통 줄 구성 결과가 같은 줄 수용 여부와 줄 소유를 결정한다.
    let positions = if para.text.is_empty() {
        storage.filled(para.controls.len(), 0)?
    } else {
        para.try_control_text_positions(storage)?
    };
    let chars: Vec<_> = storage.collect(para.text.chars())?;
    let mut controls: Vec<_> = storage.collect(positions.iter().copied().enumerate())?;
    storage.stable_sort_by(&mut controls, |a, b| (a.1, a.0).cmp(&(b.1, b.0)))?;
    let mut controls = controls.into_iter().peekable();
    let mut atoms = Vec::new();
    for position in 0..=chars.len() {
        while controls.peek().is_some_and(|&(_, p)| p <= position) {
            let Some((ci, _)) = controls.next() else {
                return Ok(None);
            };
            match &para.controls[ci] {
                Control::Table(table) if !table.common.treat_as_char => {
                    storage.push(
                        &mut atoms,
                        Atom::Box(InlineFlowBox {
                            content: InlineFlowContent::FloatingTable {
                                control: ci,
                                resolved_position: None,
                            },
                            x: 0.0,
                            y: 0.0,
                            width: 0.0,
                            height: 0.0,
                            baseline: 0.0,
                        }),
                    )?;
                }
                Control::Shape(_) => atoms.push(Atom::Box(floating_shapes::anchor(ci))),
                Control::Table(table) => {
                    let measured = tables
                        .iter()
                        .find(|m| m.para_index == para_index && m.control_index == ci);
                    let Some(measured) = measured else {
                        return Ok(None);
                    };
                    let left = hwpunit_to_px(i32::from(table.outer_margin_left), frame.dpi);
                    let right = hwpunit_to_px(i32::from(table.outer_margin_right), frame.dpi);
                    let top = hwpunit_to_px(i32::from(table.outer_margin_top), frame.dpi);
                    let bottom = hwpunit_to_px(i32::from(table.outer_margin_bottom), frame.dpi);
                    let height = measured.total_height + top + bottom;
                    let metrics = super::composer::frame_metrics_for_line(
                        height,
                        height,
                        style.line_spacing_type,
                        style.line_spacing,
                        frame.dpi,
                    );
                    storage.push(
                        &mut atoms,
                        Atom::Box(InlineFlowBox {
                            content: InlineFlowContent::Table {
                                control: ci,
                                margin_left: left,
                                margin_top: top,
                            },
                            x: 0.0,
                            y: 0.0,
                            width: hwpunit_to_px(table.common.width as i32, frame.dpi)
                                + left
                                + right,
                            height,
                            baseline: hwpunit_to_px(metrics.baseline_distance, frame.dpi),
                        }),
                    )?;
                }
                Control::Picture(picture) => {
                    if picture.common.treat_as_char {
                        storage.push(
                            &mut atoms,
                            Atom::Box(picture_rows::picture_box(picture, ci, style, frame.dpi)),
                        )?;
                    } else if let Some(exclusion) =
                        frame.picture_exclusion(picture, para, ci, styles)
                    {
                        storage.push(&mut atoms, Atom::Float(exclusion))?;
                    }
                }
                _ => {}
            }
        }
        let Some(&ch) = chars.get(position) else {
            break;
        };
        // CharShapeRef and char_offsets share the original UTF-16 stream,
        // including the control slots removed from the visible text.
        let stream_position = para
            .char_offsets
            .get(position)
            .copied()
            .unwrap_or(position as u32);
        let cs = super::composer::find_active_char_shape(&para.char_shapes, stream_position);
        let lang = detect_lang_category(ch);
        let text_style = super::layout::try_resolved_to_text_style(styles, cs, lang, storage)?;
        // 같은 글리프 전진량을 줄 수용과 실제 box 원점에 보존한다.
        // 문자마다 정수 px로 반올림하면 긴 prefix의 줄 경계가 달라진다.
        let text = storage.chars(std::iter::once(ch))?;
        let width = estimate_text_width_unrounded(&text, &text_style);
        // 표시 relSz는 글리프 크기다. 새 그림 글줄도 일반 문단과 같이
        // 선언 글자 크기를 줄 상자·간격에 사용하고 표시 크기는 style에 보존한다.
        let line_font_size = if picture_rows {
            styles
                .char_styles
                .get(cs as usize)
                .map_or(text_style.font_size, |s| s.font_size)
        } else {
            text_style.font_size
        };
        let metrics = super::composer::frame_metrics_for_line(
            line_font_size,
            12.0,
            style.line_spacing_type,
            style.line_spacing,
            frame.dpi,
        );
        let height = hwpunit_to_px(metrics.line_height, frame.dpi);
        let alignment_baseline = (picture_rows && style.vertical_alignment != 0).then(|| {
            height * super::composer::inline_picture_ascent_ratio(style.vertical_alignment)
        });
        let mut item = InlineFlowBox {
            content: InlineFlowContent::Text {
                range: position..position + 1,
                style: cs,
                lang,
                alignment_baseline,
            },
            x: 0.0,
            y: 0.0,
            width,
            height,
            baseline: hwpunit_to_px(metrics.baseline_distance, frame.dpi),
        };
        if ch == '\n' || ch == '\r' {
            item.content = InlineFlowContent::Text {
                range: position..position,
                style: cs,
                lang,
                alignment_baseline,
            };
            item.width = 0.0;
            storage.push(&mut atoms, Atom::Break(item))?;
        } else {
            storage.push(&mut atoms, Atom::Box(item))?;
        }
    }
    if controls.peek().is_some() {
        // 범위 밖 anchor를 누락시킨 부분 결과를 확정하지 않는다.
        return Ok(None);
    }
    if picture_rows {
        if let Some(anchor) = picture_rows::empty_host_text_box(para, styles, style, frame.dpi) {
            atoms.push(Atom::Box(anchor));
        }
    }
    // 글자처럼 그림으로 끝나는 문단은 문단 끝 표시의 글자 모양이 마지막 줄 높이와
    // 끝 캐럿을 정한다. 저장 줄 경로와 같도록 폭 0인 끝 상자를 둔다. 표로 끝나는 문단은
    // 한컴 인쇄처럼 표 줄 높이만 쓴다(issue_6776).
    if matches!(
        atoms.last(),
        Some(Atom::Box(InlineFlowBox {
            content: InlineFlowContent::Picture { .. },
            ..
        }))
    ) {
        let end = chars.len();
        let cs = super::composer::find_active_char_shape(
            &para.char_shapes,
            para.char_count.saturating_sub(1),
        );
        let font_size = styles
            .char_styles
            .get(cs as usize)
            .map_or(12.0, |s| s.font_size);
        let metrics = super::composer::frame_metrics_for_line(
            font_size,
            12.0,
            style.line_spacing_type,
            style.line_spacing,
            frame.dpi,
        );
        let height = hwpunit_to_px(metrics.line_height, frame.dpi);
        let alignment_baseline = (picture_rows && style.vertical_alignment != 0).then(|| {
            height * super::composer::inline_picture_ascent_ratio(style.vertical_alignment)
        });
        storage.push(
            &mut atoms,
            Atom::Box(InlineFlowBox {
                content: InlineFlowContent::Text {
                    range: end..end,
                    style: cs,
                    lang: 0,
                    alignment_baseline,
                },
                x: 0.0,
                y: 0.0,
                width: 0.0,
                height,
                baseline: hwpunit_to_px(metrics.baseline_distance, frame.dpi),
            }),
        )?;
    }
    // Reuse the composer's language/style word boundaries. A word that fits
    // a whole line moves together; an overlong word retains character fallback.
    let word_ranges = super::composer::text_word_ranges_with_storage(para, styles, storage)?;
    let mut words = word_ranges.iter().peekable();
    let mut word_metrics = std::collections::BTreeMap::new();
    let mut attached_word_metrics = std::collections::BTreeMap::new();
    let spaces = separator_spaces::classify_with_storage(&atoms, &chars, storage)?;
    let mut index = 0;
    while index < atoms.len() {
        let Atom::Box(first) = &atoms[index] else {
            index += 1;
            continue;
        };
        let InlineFlowContent::Text {
            range: first_range, ..
        } = &first.content
        else {
            index += 1;
            continue;
        };
        while words
            .peek()
            .is_some_and(|word| word.end <= first_range.start)
        {
            words.next();
        }
        let Some(word) = words
            .peek()
            .filter(|word| word.contains(&first_range.start))
        else {
            index += 1;
            continue;
        };
        let start = first_range.start;
        let mut metrics = RowMetrics::default();
        while let Some(Atom::Box(item)) = atoms.get(index) {
            let InlineFlowContent::Text { range, .. } = &item.content else {
                break;
            };
            if !word.contains(&range.start) {
                break;
            }
            metrics = metrics.with(item);
            index += 1;
        }
        storage.insert_tree_map(&mut word_metrics, start, metrics)?;
        if let Some(Atom::Box(next)) = atoms.get(index) {
            if matches!(next.content, InlineFlowContent::Table { .. }) {
                // 구분 공백 없이 붙은 TAC는 앞 어절의 수용 후보에 속한다.
                // 후보가 한 줄보다 크면 새 줄에서 개체 앞 경계를 분리한다.
                storage.insert_tree_map(&mut attached_word_metrics, start, metrics.with(next))?;
            }
        }
    }
    let mut exclusions = storage.collect(preceding.iter().cloned())?;
    let horizontal = frame.container.x..frame.container.x + frame.container.width;
    let mut result = InlineFlowPlan {
        stored_empty_host: false,
        stored_float_host: false,
        text_rows: None,
        square_host_control: None,
        text_spacing_before: None,
        square_host_placement: None,
        square_host_exclusion: None,
        floating_shapes: Vec::new(),
        start: frame.paragraph_y,
        end: top,
        boxes: Vec::new(),
        rows: Vec::new(),
        carved: false,
        next_row_top: top,
        fallback_font_size: para
            .char_shapes
            .first()
            .and_then(|r| styles.char_styles.get(r.char_shape_id as usize))
            .map_or(12.0, |s| s.font_size),
    };
    let mut row = Vec::new();
    let mut row_metrics = RowMetrics::default();
    for atom in atoms {
        match atom {
            Atom::Float(exclusion) => {
                // 후행 anchor가 선행 텍스트/표를 소급 이동시키지 않는다.
                let Some(()) = finish_row_with_storage(
                    &mut result,
                    &mut row,
                    &horizontal,
                    &exclusions,
                    style,
                    frame.dpi,
                    RowEnding::Forced(&chars),
                    storage,
                )?
                else {
                    return Ok(None);
                };
                storage.push(&mut exclusions, exclusion)?;
                row_metrics = RowMetrics::default();
            }
            Atom::Break(empty_line) => {
                // 작성 개행의 글자 크기도 현재 줄의 기준선·높이를 소유한다.
                // 폭 0 상자로 빈 줄과 연속 개행의 공간도 같은 결과에 보존한다.
                storage.push(&mut row, empty_line)?;
                let Some(()) = finish_row_with_storage(
                    &mut result,
                    &mut row,
                    &horizontal,
                    &exclusions,
                    style,
                    frame.dpi,
                    RowEnding::Forced(&chars),
                    storage,
                )?
                else {
                    return Ok(None);
                };
                row_metrics = RowMetrics::default();
            }
            Atom::Box(mut item) => {
                if ![item.width, item.height, item.baseline]
                    .iter()
                    .all(|v| v.is_finite())
                    || item.width < 0.0
                    || (item.height <= 0.0
                        && !matches!(
                            item.content,
                            InlineFlowContent::FloatingTable { .. }
                                | InlineFlowContent::FloatingShape { .. }
                        ))
                {
                    return Ok(None);
                }
                let row_horizontal =
                    paragraph_row_horizontal(&horizontal, style, result.boxes.is_empty());
                let row_width = row_horizontal.end - row_horizontal.start;
                // 개체 앞 작성 공백 그룹의 첫 공백만 우단 밖으로 전진한다.
                // 그룹의 후속 공백이 처음 넘쳤다는 이유로 hanging하지 않는다.
                let object_separator = matches!(&item.content, InlineFlowContent::Text { range, .. }
                    if spaces.object.contains(&range.start));
                let first_overhang_space = matches!(&item.content, InlineFlowContent::Text { range, .. }
                    if spaces.first_object.contains(&range.start))
                    && separator_spaces::has_flow_content(&row, &chars)
                    && row_metrics.width <= row_width + 0.01
                    && row_metrics.width + item.width > row_width + 0.01;
                // 줄보다 넓은 첫 개체와 같은 위치의 공백은 개체와 함께
                // 소유한다. 다음 공백의 cut은 기존 재조판과 같은 계약으로 정한다.
                let oversized_cut = match (&item.content, row.first()) {
                    (InlineFlowContent::Text { range, .. }, Some(first))
                        if spaces.wrap.contains(&range.start) && first.width > row_width =>
                    {
                        let control = match &first.content {
                            InlineFlowContent::Table { control, .. }
                            | InlineFlowContent::Picture { control, .. } => Some(*control),
                            _ => None,
                        };
                        control.and_then(|control| {
                            positions.get(control).map(|&start| {
                                let object_end = (range.start == start)
                                    .then(|| (px_to_hwpunit(first.width, frame.dpi), 0));
                                super::composer::overflowing_space_cut(
                                    start,
                                    range.start,
                                    px_to_hwpunit(row_metrics.width + item.width, frame.dpi),
                                    0,
                                    px_to_hwpunit(row_width, frame.dpi),
                                    object_end,
                                )
                            })
                        })
                    }
                    _ => None,
                };
                let keep_oversized_space = matches!(oversized_cut, Some(None));
                let absorb_oversized_space = matches!(oversized_cut,
                    Some(Some(cut)) if matches!(&item.content,
                        InlineFlowContent::Text { range, .. } if cut == range.end));
                // A separator consumed by a soft wrap remains in the source
                // row. It must not create a whitespace-only row before the
                // next word/table. Space-only paragraphs and authored breaks
                // retain their real line boxes.
                if matches!(&item.content, InlineFlowContent::Text { range, .. }
                    if spaces.wrap.contains(&range.start))
                    && row_metrics.width + item.width > row_width + 0.01
                    && !first_overhang_space
                    && !keep_oversized_space
                    && separator_spaces::has_flow_content(&row, &chars)
                {
                    item.width = 0.0;
                    // 개체 앞의 넘친 공백은 앞 줄에서 소비하고 그 줄을 끝낸다.
                    // 이후 작성된 공백은 다음 물리 줄에 남아 개체의 전진량과
                    // 함께 fit한다. 모두 폭 0으로 흡수하면 표 소유 줄을 잃는다.
                    if object_separator || absorb_oversized_space {
                        storage.push(&mut row, item)?;
                        let Some(()) = finish_row_with_storage(
                            &mut result,
                            &mut row,
                            &horizontal,
                            &exclusions,
                            style,
                            frame.dpi,
                            RowEnding::Soft(&chars),
                            storage,
                        )?
                        else {
                            return Ok(None);
                        };
                        row_metrics = RowMetrics::default();
                        continue;
                    }
                }
                let lookahead = match &item.content {
                    InlineFlowContent::Text { range, .. } => attached_word_metrics
                        .get(&range.start)
                        .copied()
                        .or_else(|| {
                            word_metrics
                                .get(&range.start)
                                .filter(|metrics| metrics.width <= row_width + 0.01)
                                .copied()
                        })
                        .unwrap_or_else(|| RowMetrics::default().with(&item)),
                    _ => RowMetrics::default().with(&item),
                };
                let moves_existing_row = if row.is_empty() {
                    false
                } else {
                    let Some(old) = row_geometry_with_storage(
                        row_metrics,
                        &row_horizontal,
                        result.next_row_top,
                        &exclusions,
                        style,
                        frame.dpi,
                        storage,
                    )?
                    else {
                        return Ok(None);
                    };
                    let Some(next) = row_geometry_with_storage(
                        row_metrics.combined(lookahead),
                        &row_horizontal,
                        result.next_row_top,
                        &exclusions,
                        style,
                        frame.dpi,
                        storage,
                    )?
                    else {
                        return Ok(None);
                    };
                    next.1 > old.1 + 0.01
                };
                if !row.is_empty()
                    && ((row_metrics.width + lookahead.width > row_width + 0.01
                        && !first_overhang_space
                        && !keep_oversized_space)
                        || (moves_existing_row && !keep_oversized_space))
                {
                    let Some(()) = finish_row_with_storage(
                        &mut result,
                        &mut row,
                        &horizontal,
                        &exclusions,
                        style,
                        frame.dpi,
                        RowEnding::Soft(&chars),
                        storage,
                    )?
                    else {
                        return Ok(None);
                    };
                    row_metrics = RowMetrics::default();
                }
                row_metrics = row_metrics.with(&item);
                storage.push(&mut row, item)?;
            }
        }
    }
    let Some(()) = finish_row_with_storage(
        &mut result,
        &mut row,
        &horizontal,
        &exclusions,
        style,
        frame.dpi,
        RowEnding::ParagraphEnd(&chars),
        storage,
    )?
    else {
        return Ok(None);
    };
    // Percent 간격의 다음 원점은 물리 점유 하단과 다르다. 음수 간격도
    // 줄 구성 결과대로 전진시키며 쪽 수용은 occupied_end로 따로 판단한다.
    result.end = if style.line_spacing_type == crate::model::style::LineSpacingType::Percent {
        result.next_row_top
    } else {
        result.end.max(result.next_row_top)
    } + style.spacing_after;

    Ok((result.start.is_finite() && result.end.is_finite()).then_some(result))
}

fn finish_row_with_storage<S: crate::storage::Storage>(
    plan: &mut InlineFlowPlan,
    row: &mut Vec<InlineFlowBox>,
    horizontal: &Range<f64>,
    exclusions: &[FrameExclusion],
    style: &ResolvedParaStyle,
    dpi: f64,
    ending: RowEnding<'_>,
    storage: &S,
) -> Result<Option<()>, S::Error> {
    if row.is_empty() {
        return Ok(Some(()));
    }
    let mut row_metrics = row
        .iter()
        .fold(RowMetrics::default(), |metrics, item| metrics.with(item));
    if row_metrics.baseline + row_metrics.descent == 0.0 {
        // A row containing only a floating anchor still has a paragraph line.
        let metrics = super::composer::frame_metrics_for_line(
            plan.fallback_font_size,
            plan.fallback_font_size,
            style.line_spacing_type,
            style.line_spacing,
            dpi,
        );
        row_metrics.baseline = hwpunit_to_px(metrics.baseline_distance, dpi);
        row_metrics.descent = hwpunit_to_px(metrics.line_height - metrics.baseline_distance, dpi);
    }
    let baseline = row_metrics.baseline;
    let height = row_metrics.baseline + row_metrics.descent;
    if let Some(chars) = ending.trimmed_chars() {
        // 개행 메트릭 상자는 폭 0이며 후행 공백 조회를 막지 않는다.
        // 줄 경계에서 소비한 공백은 가운데·오른쪽 잉크 정렬을 밀지 않는다.
        row_metrics.width -= row
            .iter()
            .rev()
            .take_while(|item| {
                matches!(&item.content, InlineFlowContent::Text { range, .. }
                    if chars[range.clone()].iter().all(|ch| *ch == ' '))
            })
            .map(|item| item.width)
            .sum::<f64>();
    }
    let row_horizontal = paragraph_row_horizontal(horizontal, style, plan.boxes.is_empty());
    let Some((mut x, y, carved, available_width)) = row_geometry_with_storage(
        row_metrics,
        &row_horizontal,
        plan.next_row_top,
        exclusions,
        style,
        dpi,
        storage,
    )?
    else {
        return Ok(None);
    };
    plan.carved |= carved;
    // 같은 확정 줄의 분배 전진을 측정 결과와 실제 글자 원점에 함께 보존한다.
    let gaps = alignment::gaps_with_storage(
        row,
        ending,
        style.alignment,
        available_width - row_metrics.width,
        storage,
    )?;
    row_metrics.width += gaps.iter().sum::<f64>();
    let has_table = row
        .iter()
        .any(|b| matches!(b.content, InlineFlowContent::Table { .. }));
    let row_font_size = row
        .iter()
        .filter(|item| {
            matches!(
                item.content,
                InlineFlowContent::Text { .. }
                    | InlineFlowContent::Picture {
                        affect_line_spacing: true,
                        ..
                    }
            )
        })
        .map(|item| item.height)
        .reduce(f64::max)
        .unwrap_or(plan.fallback_font_size);
    let first_box = plan.boxes.len();
    let row_x = x;
    for (index, mut item) in row.drain(..).enumerate() {
        item.x = x;
        item.y = if matches!(
            item.content,
            InlineFlowContent::FloatingTable { .. } | InlineFlowContent::FloatingShape { .. }
        ) {
            y
        } else {
            y + baseline - item.alignment_baseline()
        };
        let advance = item.width + gaps[index];
        if matches!(item.content, InlineFlowContent::Text { .. }) {
            item.width = advance;
        }
        x += advance;
        storage.push(&mut plan.boxes, item)?;
    }
    storage.push(
        &mut plan.rows,
        InlineFlowRow {
            boxes: first_box..plan.boxes.len(),
            x: row_x,
            y,
            width: row_metrics.width,
            height,
            baseline,
        },
    )?;
    let metrics = super::composer::frame_metrics_for_line(
        row_font_size,
        plan.fallback_font_size,
        style.line_spacing_type,
        style.line_spacing,
        dpi,
    );
    let gap = hwpunit_to_px(metrics.line_spacing, dpi);
    // 표도 Percent의 부호 있는 간격을 소비한다. 표의 실제 점유 높이는
    // rows에 보존하므로 다음 줄 원점을 물리 하단으로 clamp하지 않는다.
    let signed_gap =
        !has_table || style.line_spacing_type == crate::model::style::LineSpacingType::Percent;
    plan.next_row_top = y + height + if signed_gap { gap } else { gap.max(0.0) };
    plan.end = plan.end.max(y + height);
    Ok(Some(()))
}

fn paragraph_row_horizontal(
    horizontal: &Range<f64>,
    style: &ResolvedParaStyle,
    first: bool,
) -> Range<f64> {
    let indent = super::equation_tac_flow::paragraph_effective_margin_left(
        0.0,
        style.indent,
        usize::from(!first),
    );
    horizontal.start + indent..horizontal.end
}

fn row_geometry_with_storage<S: crate::storage::Storage>(
    metrics: RowMetrics,
    horizontal: &Range<f64>,
    top: f64,
    exclusions: &[FrameExclusion],
    style: &ResolvedParaStyle,
    dpi: f64,
    storage: &S,
) -> Result<Option<(f64, f64, bool, f64)>, S::Error> {
    let width = metrics.width;
    let height = metrics.baseline + metrics.descent;
    let base = px_to_hwpunit(horizontal.start, dpi)..px_to_hwpunit(horizontal.end, dpi);
    let Some(base_width) = base.end.checked_sub(base.start).filter(|w| *w > 0) else {
        return Ok(None);
    };
    let mut frame = LayoutFrame::new(
        base.clone(),
        px_to_hwpunit(top, dpi),
        storage.collect(exclusions.iter().cloned())?,
    );
    frame.minimum_width = px_to_hwpunit(width, dpi).max(1).min(base_width);
    let intervals = frame.try_carve(px_to_hwpunit(height, dpi).max(1), storage)?;
    let lane = if style.alignment == Alignment::Right {
        intervals.last()
    } else {
        intervals.first()
    };
    let Some(lane) = lane.cloned() else {
        return Ok(None);
    };
    let left = hwpunit_to_px(lane.start, dpi);
    let spare = (hwpunit_to_px(lane.end - lane.start, dpi) - width).max(0.0);
    let x = left
        + match style.alignment {
            Alignment::Right => spare,
            Alignment::Center => spare / 2.0,
            _ => 0.0,
        };
    let y = hwpunit_to_px(frame.top, dpi).max(top);
    let carved = y > top + 0.01 || lane.start > base.start || lane.end < base.end;
    Ok(Some((
        x,
        y,
        carved,
        hwpunit_to_px(lane.end - lane.start, dpi),
    )))
}

/// 저장 행과 자체 inline 소유자가 없는 본문만 현재 물리 frame에서 재조판한다.
///
/// [#7548] 저장 LineSeg 가 없는 HWPX 문단은 로드 시 합성 줄(구현 태그)을 받는다.
/// 합성 줄은 앞 개체의 배제 영역을 모르는 전폭 재조판 결과라 저장 증거가 아니다 —
/// 저장 줄이 하나도 없으면 빈 줄 목록과 같이 이 frame 에서 다시 조판한다.
pub(crate) fn supports_plain_text(para: &Paragraph) -> bool {
    super::para_has_no_stored_line_segs(para)
        && !para.text.trim().is_empty()
        && para.controls.is_empty()
}

pub(crate) fn plan_plain_text(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
    placement: &ObjectPlacementFrame<'_>,
    preceding: &[FrameExclusion],
) -> Option<InlineFlowPlan> {
    match plan_plain_text_with_storage(
        para,
        styles,
        placement,
        preceding,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn plan_plain_text_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
    placement: &ObjectPlacementFrame<'_>,
    preceding: &[FrameExclusion],
    storage: &S,
) -> Result<Option<InlineFlowPlan>, S::Error> {
    if !supports_plain_text(para) && !supports_stored_plain_text(para) {
        return Ok(None);
    }
    plan_text_rows_with_storage(para, styles, placement, preceding, storage)
}

/// [#8282] 저장 줄이 있는 개체 없는 본문. 저장 줄 없는 host 의 어울림 개체는 한/글이 배치한
/// 적이 없어 이 저장 줄이 그 개체를 피했다는 증언이 될 수 없다. 호출자가 그런 개체와 실제로
/// 겹칠 때만 현재 frame 에서 다시 짠다.
pub(crate) fn supports_stored_plain_text(para: &Paragraph) -> bool {
    !super::para_has_no_stored_line_segs(para)
        && !para.text.trim().is_empty()
        && para.controls.is_empty()
}

/// [#8282] 저장 줄 없는 문단의 자기 어울림 그림·도형도 그 문단 줄의 배제 영역이다.
/// 한/글은 개체 앵커가 문단 끝에 있어도 앞 줄부터 개체 옆으로 흘린다(같은 입력의
/// 2020 Print PDF). 개체 상자는 기존 개체 소유자가 배치하고, 이 frame 은 글자와 글자처럼
/// 그림의 줄만 짠다. 어울림 개체가 없거나 frame 이 받지 않는 문단은 사양한다.
pub(crate) fn supports_square_float_host(para: &Paragraph) -> bool {
    super::para_has_no_stored_line_segs(para)
        && !para.text.trim().is_empty()
        && para
            .controls
            .iter()
            .any(super::composer::control_is_square_float_object)
        && para.controls.iter().all(|control| match control {
            Control::Picture(picture) => picture.caption.is_none(),
            Control::Shape(shape) => {
                super::composer::control_is_square_float_object(control)
                    && super::composer::shape_caption_for_layout(shape).is_none()
            }
            Control::SectionDef(_)
            | Control::ColumnDef(_)
            | Control::PageNumberPos(_)
            | Control::PageNumCtrl(_) => true,
            _ => false,
        })
        && super::composer::supports_picture_band_frame_controls(para)
}

pub(crate) fn plan_square_float_host_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
    placement: &ObjectPlacementFrame<'_>,
    preceding: &[FrameExclusion],
    storage: &S,
) -> Result<Option<InlineFlowPlan>, S::Error> {
    if !supports_square_float_host(para) {
        return Ok(None);
    }
    let mut exclusions = storage.collect(preceding.iter().cloned())?;
    for (index, control) in para.controls.iter().enumerate() {
        let own = match control {
            Control::Picture(picture) => placement.picture_exclusion(picture, para, index, styles),
            Control::Shape(shape) => placement.shape_exclusion(shape),
            _ => None,
        };
        if let Some(own) = own {
            storage.push(&mut exclusions, own)?;
        }
    }
    plan_text_rows_with_storage(para, styles, placement, &exclusions, storage)
}

/// 앞 개체와 자기 개체의 배제 영역을 받은 현재 물리 frame 에서 본문 줄을 한 번 짠다.
fn plan_text_rows_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
    placement: &ObjectPlacementFrame<'_>,
    preceding: &[FrameExclusion],
    storage: &S,
) -> Result<Option<InlineFlowPlan>, S::Error> {
    use super::composer::{layout_paragraph_in_frame_with_storage, ParagraphBox};
    let Some(style) = styles.para_styles.get(para.para_shape_id as usize) else {
        return Ok(None);
    };
    if style.head_type != crate::model::style::HeadType::None {
        return Ok(None);
    }
    let mut exclusions = storage.collect(preceding.iter().cloned())?;
    let text_top = placement.paragraph_y + style.spacing_before;
    let dx = px_to_hwpunit(placement.column.x, placement.dpi);
    let dy = px_to_hwpunit(text_top, placement.dpi);
    for e in &mut exclusions {
        e.horizontal = e.horizontal.start.saturating_sub(dx)..e.horizontal.end.saturating_sub(dx);
        e.vertical = e.vertical.start.saturating_sub(dy)..e.vertical.end.saturating_sub(dy);
    }
    let paragraph_box =
        ParagraphBox::body_for_style(placement.column.width, Some(style), placement.dpi);
    if !paragraph_box.is_usable() {
        return Ok(None);
    }
    let mut frame = paragraph_box.frame_with(0, exclusions);
    let Some(rows) =
        layout_paragraph_in_frame_with_storage(para, &mut frame, styles, placement.dpi, storage)?
    else {
        return Ok(None);
    };
    // 배제 없는 frame과 행이 같으면 기존 owner를 유지한다.
    let mut clear_frame = paragraph_box.frame(0);
    let Some(clear_rows) = layout_paragraph_in_frame_with_storage(
        para,
        &mut clear_frame,
        styles,
        placement.dpi,
        storage,
    )?
    else {
        return Ok(None);
    };
    let same_rows = rows.len() == clear_rows.len()
        && rows.iter().zip(&clear_rows).all(|(a, b)| {
            a.text_start == b.text_start
                && a.vertical_pos == b.vertical_pos
                && a.column_start == b.column_start
                && a.segment_width == b.segment_width
        });
    let end = text_top + hwpunit_to_px(frame.top, placement.dpi) + style.spacing_after;
    Ok(Some(InlineFlowPlan {
        stored_empty_host: false,
        stored_float_host: false,
        start: placement.paragraph_y,
        end,
        boxes: Vec::new(),
        rows: Vec::new(),
        carved: !same_rows,
        next_row_top: end,
        fallback_font_size: 12.0,
        text_rows: Some(rows),
        square_host_control: None,
        text_spacing_before: None,
        square_host_placement: None,
        square_host_exclusion: None,
        floating_shapes: Vec::new(),
    }))
}

/// 실제 단일 어울림 표의 배제 영역으로 호스트 줄을 fit·paint 전에 한 번 확정한다.
/// Inline controls and other object owners keep their existing transaction.
pub(crate) fn plan_square_table_host(
    para: &Paragraph,
    para_index: usize,
    styles: &ResolvedStyleSet,
    tables: &[MeasuredTable],
    column_width: f64,
    dpi: f64,
) -> Option<InlineFlowPlan> {
    use super::float_placement::{signed_hwpunit, ParagraphFloatFlow, ParagraphFloatPlacement};
    use super::layout_frame::FrameExclusionPolicy;
    use crate::model::shape::{HorzAlign, HorzRelTo, TextFlow, VertAlign, VertRelTo};
    let uncached = super::is_no_lineseg_visible_text_host(para);
    if !uncached
        && (!para
            .text
            .chars()
            .any(|ch| ch > '\u{001F}' && ch != '\u{FFFC}' && !ch.is_whitespace())
            || styles.hwp3_variant
            || super::composer::stored_rows_cross_physical_frame(para))
    {
        // 하나의 배제 프레임은 다른 쪽/단에 속한 저장 줄을 재구성하지 않는다.
        return None;
    }
    let control = para.controls.iter().position(|c| {
        matches!(c, Control::Table(t)
        if !t.common.treat_as_char && t.common.text_wrap == crate::model::shape::TextWrap::Square)
    })?;
    if para.controls.iter().enumerate().any(|(i, c)| {
        i != control
            && !super::composer::control_is_width_neutral_marker(c)
            && !matches!(c, Control::Picture(p) if !p.common.treat_as_char
                    && matches!(p.common.text_wrap,
                        crate::model::shape::TextWrap::InFrontOfText
                            | crate::model::shape::TextWrap::BehindText))
    }) {
        return None;
    }
    let style = styles.para_styles.get(para.para_shape_id as usize)?;
    // The floating table has its own paint owner and contributes no inline token.
    // Keep text/shape offsets intact; only the text frame is projected here.
    let mut text = para.clone();
    // Overlay pictures keep their separate Shape paint owners. They neither
    // consume inline width nor carve the text frame; preserve source offsets.
    text.controls
        .retain(super::composer::control_is_width_neutral_marker);
    text.line_segs.clear();
    let Control::Table(table) = &para.controls[control] else {
        return None;
    };
    let measured = tables
        .iter()
        .find(|m| m.para_index == para_index && m.control_index == control)?;
    let c = &table.common;
    if c.vert_rel_to != VertRelTo::Para
        || !matches!(c.vert_align, VertAlign::Top | VertAlign::Inside)
    {
        return None;
    }
    // Side captions own a second horizontal box; retain their existing owner.
    if table.caption.as_ref().is_some_and(|cap| {
        matches!(
            cap.direction,
            crate::model::shape::CaptionDirection::Left
                | crate::model::shape::CaptionDirection::Right
        )
    }) {
        return None;
    }
    let (ref_left, ref_width) = match c.horz_rel_to {
        HorzRelTo::Column => (0.0, column_width),
        HorzRelTo::Para => (
            style.margin_left,
            column_width - style.margin_left - style.margin_right,
        ),
        _ => return None,
    };
    let ml = hwpunit_to_px(i32::from(table.outer_margin_left), dpi);
    let mr = hwpunit_to_px(i32::from(table.outer_margin_right), dpi);
    let object_width = hwpunit_to_px(c.width as i32, dpi) + ml + mr;
    let offset = hwpunit_to_px(signed_hwpunit(c.horizontal_offset), dpi);
    let outer_left = match c.horz_align {
        HorzAlign::Left | HorzAlign::Inside => ref_left + offset,
        HorzAlign::Center => ref_left + (ref_width - object_width) / 2.0 + offset,
        HorzAlign::Right | HorzAlign::Outside => ref_left + ref_width - object_width - offset,
    };
    let box_ = super::composer::ParagraphBox::body_for_style(column_width, Some(style), dpi);
    let stored_rows = stored_square_rows::source(para, control, table, measured, &box_, dpi);
    let spacing_before =
        if para.line_segs.is_empty() && std::env::var("RHWP_EXP_BODY_FRESH").is_err() {
            0.0
        } else {
            style.spacing_before
        };
    let geometry = |anchor_offset_hwp| {
        let outer_top = hwpunit_to_px(
            signed_hwpunit(c.vertical_offset).saturating_add(anchor_offset_hwp),
            dpi,
        );
        let table_top = outer_top + hwpunit_to_px(i32::from(table.outer_margin_top), dpi);
        let occupied_bottom = table_top
            + measured.total_height
            + hwpunit_to_px(i32::from(table.outer_margin_bottom), dpi);
        let placement = ParagraphFloatPlacement {
            flow: ParagraphFloatFlow::Exclusion,
            anchor_y: 0.0,
            stored_host_origin: None,
            stored_successor_line_origin: None,
            table_left: Some(outer_left + ml),
            table_top,
            occupied_bottom,
        };
        let exclusion = FrameExclusion {
            horizontal: px_to_hwpunit(outer_left, dpi)
                ..px_to_hwpunit(outer_left + object_width, dpi),
            vertical: px_to_hwpunit(outer_top, dpi)..px_to_hwpunit(occupied_bottom, dpi),
            policy: match c.text_flow {
                TextFlow::BothSides => FrameExclusionPolicy::BothSides,
                TextFlow::LargestOnly => FrameExclusionPolicy::LargestSide,
                TextFlow::LeftOnly => FrameExclusionPolicy::LeftSide,
                TextFlow::RightOnly => FrameExclusionPolicy::RightSide,
            },
        };
        let mut text_exclusion = exclusion.clone();
        let spacing_hu = px_to_hwpunit(spacing_before, dpi);
        text_exclusion.vertical.start -= spacing_hu;
        text_exclusion.vertical.end -= spacing_hu;
        (
            placement,
            exclusion,
            box_.frame_with(0, vec![text_exclusion]),
        )
    };
    let (mut placement, mut exclusion, mut frame) = geometry(
        stored_rows
            .as_ref()
            .map_or(0, |source| source.anchor_offset_hwp),
    );
    let projected = stored_rows
        .as_ref()
        .and_then(|source| stored_square_rows::project(para, source, &mut frame));
    let uses_stored_rows = projected.is_some();
    let rows = if let Some(rows) = projected {
        rows
    } else {
        (placement, exclusion, frame) = geometry(0);
        super::composer::layout_paragraph_in_frame(&text, &mut frame, styles, dpi)?
    };
    if !uses_stored_rows
        && !uncached
        && rows.len() == para.line_segs.len()
        && rows.iter().zip(&para.line_segs).all(|(row, source)| {
            row.column_start == source.column_start && row.segment_width == source.segment_width
        })
    {
        // 같은 물리 구간의 저장 줄은 기존 소유자에게 남긴다.
        return None;
    }
    // Following paragraphs can use the free side of the same object. The
    // object remains an exclusion and fit budget; it is not a text advance.
    let end = spacing_before + hwpunit_to_px(frame.top, dpi) + style.spacing_after;
    Some(InlineFlowPlan {
        stored_empty_host: false,
        stored_float_host: false,
        text_rows: Some(rows),
        square_host_control: Some(control),
        text_spacing_before: Some(spacing_before),
        square_host_placement: Some(placement),
        square_host_exclusion: Some(exclusion),
        floating_shapes: Vec::new(),
        start: 0.0,
        end,
        boxes: Vec::new(),
        rows: Vec::new(),
        carved: true,
        next_row_top: end,
        fallback_font_size: 12.0,
    })
}