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
//! Editable layout: recognized body paragraphs leave their positioned frames
//! and become the section's own text flow.
//!
//! The fidelity layout keeps one positioned text box per recognized body
//! region, so a paragraph cannot continue from one column or page into the
//! next. This layout stores the same paragraphs the way a word processor
//! does: one section per run of equally sized pages, page margins and column
//! definitions measured from the observed text, a page break per source page
//! and a column break per source column. Stored line positions are rebased
//! from each frame to its column, so the first layout matches the source.
//!
//! Everything that is not a recognized body paragraph (retained spans,
//! tables, pictures, rules) keeps its paper position and is anchored to the
//! page's first paragraph, a minimal empty line at the top of the body.
use super::{allocation::Allocation, value_macro::request_json, PdfImportError};
use crate::model::control::Control;
use crate::model::document::Document;
use crate::model::page::{ColumnDef, ColumnDirection, ColumnType};
use crate::model::paragraph::{ColumnBreakType, Paragraph};
use crate::model::shape::ShapeObject;
use crate::model::style::LineSpacingType;
use crate::storage::Storage;
use serde_json::Value;

/// A committed body frame and its observed text extent in page points.
pub(super) struct BodyFrame {
    pub inst_id: u32,
    pub left: f32,
    pub top: f32,
    pub right: f32,
    pub bottom: f32,
    /// Widest source line of each paragraph, in frame order.
    pub paragraph_rights: Vec<f32>,
}

/// Frames committed on one output section (one source page).
pub(super) struct PageFrames {
    pub section: usize,
    pub frames: Vec<BodyFrame>,
}

/// Frames from one page's lowering report (`bodyParagraphMapping`).
pub(super) fn page_frames(
    section: usize,
    report: &Value,
    allocation: Allocation<'_>,
) -> Result<PageFrames, PdfImportError> {
    let frames = allocation.collect(
        report["bodyParagraphMapping"]["frames"]
            .as_array()
            .into_iter()
            .flatten()
            .filter(|f| f["status"] == "paragraph_ir")
            .filter_map(|f| {
                let b = f["textBox"].as_array()?;
                let n = |i: usize| b.get(i)?.as_f64().map(|v| v as f32);
                let paragraph_rights = f["paragraphRights"]
                    .as_array()
                    .into_iter()
                    .flatten()
                    .filter_map(|v| v.as_f64().map(|v| v as f32))
                    .collect();
                Some(BodyFrame {
                    inst_id: u32::try_from(f["instanceId"].as_u64()?).ok()?,
                    left: n(0)?,
                    top: n(1)?,
                    right: n(2)?,
                    bottom: n(3)?,
                    paragraph_rights,
                })
            }),
    )?;
    Ok(PageFrames { section, frames })
}

/// Height in HWPUNIT that an anchor line (no text) takes in its column.
const ANCHOR_HEIGHT: i32 = 100;

/// HWPUNIT a row keeps beyond its widest source line, so that the substitute
/// font's rounding does not push the line's last character to the next row.
const ROW_END_SLACK: i32 = 100;

fn hu(points: f32) -> i32 {
    (points * 100.0).round() as i32
}

/// Column of each frame on one page, or `None` for a frame that spans
/// several columns (a title band, a wide box) and stays positioned. Tall
/// frames found the columns first, so a short spanning line cannot merge two
/// columns into one.
fn page_columns(
    frames: &[BodyFrame],
    allocation: Allocation<'_>,
) -> Result<(Vec<(f32, f32)>, Vec<Option<usize>>), PdfImportError> {
    let mut order = allocation.collect(0..frames.len())?;
    allocation.sort_by(&mut order, |&a, &b| {
        let h = |i: usize| frames[i].bottom - frames[i].top;
        h(b).total_cmp(&h(a))
    })?;
    let mut columns: Vec<(f32, f32)> = Vec::new();
    let mut owner = allocation.filled(frames.len(), None)?;
    for i in order {
        let f = &frames[i];
        let hits = allocation.collect(
            (0..columns.len()).filter(|&c| f.left < columns[c].1 && columns[c].0 < f.right),
        )?;
        match hits.as_slice() {
            [] => {
                allocation.push(&mut columns, (f.left, f.right))?;
                owner[i] = Some(columns.len() - 1);
            }
            [c] => {
                columns[*c].0 = columns[*c].0.min(f.left);
                columns[*c].1 = columns[*c].1.max(f.right);
                owner[i] = Some(*c);
            }
            _ => {}
        }
    }
    // Number columns left to right.
    let mut rank = allocation.collect(0..columns.len())?;
    allocation.sort_by(&mut rank, |&a, &b| columns[a].0.total_cmp(&columns[b].0))?;
    let mut position = allocation.filled(columns.len(), 0)?;
    for (to, &from) in rank.iter().enumerate() {
        position[from] = to;
    }
    let sorted = allocation.collect(rank.iter().map(|&c| columns[c]))?;
    Ok((
        sorted,
        allocation.collect(owner.into_iter().map(|c| c.map(|c| position[c])))?,
    ))
}

fn take_frame(paragraph: &mut Paragraph, inst_id: u32) -> Option<Vec<Paragraph>> {
    let at = paragraph.controls.iter().position(|c| {
        matches!(c, Control::Shape(s) if matches!(&**s, ShapeObject::Rectangle(r)
            if r.drawing.inst_id == inst_id && r.drawing.text_box.is_some()))
    })?;
    if paragraph.ctrl_data_records.len() == paragraph.controls.len() {
        paragraph.ctrl_data_records.remove(at);
    }
    let Control::Shape(shape) = paragraph.controls.remove(at) else {
        unreachable!()
    };
    let ShapeObject::Rectangle(rect) = *shape else {
        unreachable!()
    };
    // The anchor's control count shrinks with the removed frame.
    paragraph.char_count = paragraph.char_count.saturating_sub(8);
    rect.drawing.text_box.map(|b| b.paragraphs)
}

/// A retained text owner in the column's leading band must travel with its
/// first flow paragraph. Otherwise joining that paragraph to the previous
/// column/page discards the band when pagination selects a continuation origin.
fn take_positioned_prefix(
    anchor: &mut Paragraph,
    committed: &std::collections::BTreeSet<u32>,
    column: (i32, i32),
    body_top: i32,
    flow_top: i32,
    allocation: Allocation<'_>,
) -> Result<Option<Paragraph>, PdfImportError> {
    use crate::model::shape::{HorzRelTo, VertRelTo};
    let owns_prefix = |control: &Control| {
        let Control::Shape(shape) = control else {
            return false;
        };
        let ShapeObject::Rectangle(rect) = &**shape else {
            return false;
        };
        if rect.drawing.text_box.is_none()
            || committed.contains(&rect.drawing.inst_id)
            || rect.common.vert_rel_to != VertRelTo::Paper
            || rect.common.horz_rel_to != HorzRelTo::Paper
        {
            return false;
        }
        let left = i64::from(rect.common.horizontal_offset);
        let top = i64::from(rect.common.vertical_offset);
        let right = left + i64::from(rect.common.width);
        let bottom = top + i64::from(rect.common.height);
        left < i64::from(column.1)
            && right > i64::from(column.0)
            && top < i64::from(flow_top)
            && bottom > i64::from(body_top)
            && bottom <= i64::from(flow_top)
    };
    let count = anchor.controls.iter().filter(|c| owns_prefix(c)).count();
    if count == 0 {
        return Ok(None);
    }
    let mut prefix = Paragraph::new_empty();
    allocation.reserve(&mut prefix.controls, count)?;
    let aligned_records = anchor.ctrl_data_records.len() == anchor.controls.len();
    if aligned_records {
        allocation.reserve(&mut prefix.ctrl_data_records, count)?;
    }
    for index in (0..anchor.controls.len()).rev() {
        if owns_prefix(&anchor.controls[index]) {
            prefix.controls.push(anchor.controls.remove(index));
            if aligned_records {
                prefix
                    .ctrl_data_records
                    .push(anchor.ctrl_data_records.remove(index));
            }
        }
    }
    prefix.controls.reverse();
    prefix.ctrl_data_records.reverse();
    let slots = 8 * count as u32;
    prefix.char_count += slots;
    anchor.char_count -= slots;
    Ok(Some(prefix))
}

/// Move every control of `anchor` to the front of `paragraph`. Each extended
/// control takes eight stream units ahead of the first character, so text,
/// character shape and line start positions shift with it.
fn attach_leading_controls(
    paragraph: &mut Paragraph,
    mut anchor: Paragraph,
    allocation: Allocation<'_>,
) -> Result<(), PdfImportError> {
    let count = anchor.controls.len();
    if count == 0 {
        return Ok(());
    }
    let mut records = std::mem::take(&mut anchor.ctrl_data_records);
    let extra = count.saturating_sub(records.len());
    allocation.reserve(&mut records, extra)?;
    records.resize(count, None);
    let mut own = std::mem::take(&mut paragraph.ctrl_data_records);
    let extra = paragraph.controls.len().saturating_sub(own.len());
    allocation.reserve(&mut own, extra)?;
    own.resize(paragraph.controls.len(), None);
    allocation.extend(&mut records, own)?;
    let mut controls = std::mem::take(&mut anchor.controls);
    allocation.reserve(&mut controls, paragraph.controls.len())?;
    controls.append(&mut paragraph.controls);
    paragraph.controls = controls;
    paragraph.ctrl_data_records = records;
    paragraph.char_count += 8 * count as u32;
    paragraph.reserve_leading_extended_control_slots(count);
    Ok(())
}

/// Columns as (left, right) boxes in HWPUNIT from the page edge. Unequal
/// columns store widths and gaps as proportions of the body (sum 32768), the
/// HWP 5.0 and HWPX convention; absolute values would overflow 16 bits.
/// Whether `next`, the first paragraph of a column or page, continues
/// `previous` from the column or page before. The column boundary cut a
/// paragraph when `next` starts on the continuation edge of `previous` without
/// an item marker, and either `previous` stops mid-sentence or it is an
/// indented paragraph, whose successors would start indented.
fn continues(doc: &Document, previous: &Paragraph, next: &Paragraph) -> bool {
    if previous.text.trim().is_empty()
        || next.text.trim().is_empty()
        || !next.controls.is_empty()
        || !next.tab_extended.is_empty()
        || super::recognition::starts_item(&next.text)
    {
        return false;
    }
    let shapes = &doc.doc_info.para_shapes;
    let (Some(p), Some(n)) = (
        shapes.get(previous.para_shape_id as usize),
        shapes.get(next.para_shape_id as usize),
    ) else {
        return false;
    };
    // Measures are twice HWPUNIT. A negative indent advances later lines.
    let continuation_left = p.margin_left + (-p.indent).max(0);
    let first_left = n.margin_left + n.indent.max(0);
    if (first_left - continuation_left).abs() > 200 {
        return false;
    }
    let ends_sentence = previous.text.trim_end().ends_with(|c: char| {
        matches!(
            c,
            '.' | '?' | '!' | ':' | '"' | '”' | '’' | '」' | '』' | ')' | ')'
        )
    });
    !ends_sentence || p.indent > 0
}

/// Append `next` to `previous`, keeping the stored rows of both: the rows of
/// `next` keep their own (column-relative) positions, as a paragraph that
/// continues in the next column stores them.
fn join(
    previous: &mut Paragraph,
    next: &Paragraph,
    allocation: Allocation<'_>,
) -> Result<(), PdfImportError> {
    use super::text_analysis::{line_join, LineJoin};
    let last_line = previous.text.lines().last().unwrap_or("");
    let mut rows = std::mem::take(&mut previous.line_segs);
    if matches!(
        line_join(last_line, &next.text),
        LineJoin::InferredWordSpace
    ) {
        let end = previous.char_offsets.last().map_or(0, |&o| {
            o + previous
                .text
                .chars()
                .last()
                .map_or(1, |c| c.len_utf16() as u32)
        });
        allocation.push_char(&mut previous.text, ' ')?;
        allocation.push(&mut previous.char_offsets, end)?;
    }
    let at = previous.merge_from_with_storage(next, &allocation)?;
    let shift = previous.char_offsets.get(at).copied().unwrap_or(0);
    allocation.extend(
        &mut rows,
        next.line_segs.iter().map(|seg| {
            let mut seg = seg.clone();
            seg.text_start += shift;
            seg
        }),
    )?;
    previous.line_segs = rows;
    Ok(())
}

/// The pieces of a joined paragraph were measured in their own frames, so
/// their rows can end at different edges. One paragraph shape serves all the
/// rows: every row takes the widest piece's end, and the right margin follows.
fn unify_row_end(doc: &mut Document, paragraph: &mut Paragraph) {
    let (Some(first), Some(end)) = (
        paragraph.line_segs.first(),
        paragraph
            .line_segs
            .iter()
            .map(|seg| seg.column_start + seg.segment_width)
            .max(),
    ) else {
        return;
    };
    let grown = end - (first.column_start + first.segment_width);
    if let Some(shape) = doc
        .doc_info
        .para_shapes
        .get_mut(paragraph.para_shape_id as usize)
    {
        // Paragraph measures are stored as twice HWPUNIT.
        shape.margin_right -= 2 * grown;
    }
    for seg in &mut paragraph.line_segs {
        seg.segment_width = end - seg.column_start;
    }
}

/// [#8355] 한/글은 고정 줄간격 문단의 마지막 줄도 고정 피치를 차지한다. 이어 붙인 문단의
/// 마지막 줄은 뒤 조각(한 줄짜리면 피치를 관측하지 못한 조각)에서 왔으므로 남은 문단 모양의
/// 피치로 꼬리 줄간격을 다시 두고, 늘어난 몫을 돌려준다.
///
/// 한/글은 고정값 하나로 문단 전체를 짠다. 앞 조각(한두 줄)에서 잰 피치를 그대로 두면 뒤
/// 조각의 줄마다 그 차이가 쌓이므로(12쪽 24줄 +17px), 이어 붙인 문단의 줄 피치 중앙값으로
/// 고정값을 다시 잡는다. 저장 줄 되감기(다음 단·쪽)는 피치가 아니다.
fn restore_fixed_trailing(
    doc: &mut Document,
    paragraph: &mut Paragraph,
    allocation: Allocation<'_>,
) -> Result<i32, PdfImportError> {
    let Some(shape) = doc
        .doc_info
        .para_shapes
        .get_mut(paragraph.para_shape_id as usize)
    else {
        return Ok(0);
    };
    if shape.line_spacing_type != crate::model::style::LineSpacingType::Fixed {
        return Ok(0);
    }
    if let Some(pitch) = median_row_pitch(&paragraph.line_segs, allocation)? {
        shape.line_spacing = 2 * pitch;
    }
    let pitch = shape.line_spacing / 2;
    let end = |rows: &[crate::model::paragraph::LineSeg]| {
        rows.last().map_or(0, |s| {
            s.vertical_pos + s.line_height + s.line_spacing.max(0)
        })
    };
    let before = end(&paragraph.line_segs);
    let observed_tail = paragraph.line_segs.last().map(|seg| seg.line_spacing);
    // [#8361] 조각마다(저장 줄 되감기 사이) 한/글처럼 `조각 첫 줄 + 줄 번호 × 피치` 로 다시 둔다.
    let mut base = 0;
    let mut row = 0;
    let mut previous = i32::MIN;
    for seg in &mut paragraph.line_segs {
        if seg.vertical_pos < previous || previous == i32::MIN {
            base = seg.vertical_pos;
            row = 0;
        }
        previous = seg.vertical_pos;
        seg.vertical_pos = base + row * pitch;
        seg.line_spacing = (pitch - seg.line_height).max(0);
        row += 1;
    }
    // [#8362] 음수 아래 간격은 뒤 조각 마지막 줄의 꼬리를 관측 구간으로 줄인 몫이다. 한/글은
    // 마지막 줄을 피치로 다시 짜고 그 간격을 빼지만 rhwp는 저장 꼬리를 따르고 음수 간격을
    // 무시한다. 관측 꼬리를 그대로 두고 아래 간격을 다시 맞춘 피치에서 잰 몫으로 고쳐야 두
    // 엔진이 다음 문단을 같은 자리에 둔다(2010판 7쪽 «물론 르포르도» 뒤 rhwp 만 57 아래).
    if shape.spacing_after < 0 {
        if let (Some(last), Some(tail)) = (paragraph.line_segs.last_mut(), observed_tail) {
            let tail = tail.max(0);
            if tail < last.line_spacing {
                // Paragraph measures are stored as twice HWPUNIT.
                shape.spacing_after = 2 * (tail - last.line_spacing);
                last.line_spacing = tail;
            }
        }
    }
    Ok(end(&paragraph.line_segs) - before)
}

/// [#8361] 단 기준 저장 줄로 본 원본 본문 아래 끝(HWPUNIT, 본문 위 끝 기준). 들어간 줄 바닥의
/// 최댓값 이상이고, 문단 안에서 다음 단·쪽으로 넘어간 줄(저장 줄 되감기 직후 줄)이 앞 단에 놓였을
/// 바닥의 최솟값보다 1 작다. 그 최솟값이 들어간 줄보다 위인 경우(다른 이유로 일찍 끊긴 단)는
/// 아래 끝으로 설명되지 않아 쓰지 않는다.
fn column_cut_bottom(paragraphs: &[Paragraph]) -> Option<i32> {
    let rows = || paragraphs.iter().flat_map(|p| &p.line_segs);
    let filled = rows().map(|seg| seg.vertical_pos + seg.line_height).max()?;
    paragraphs
        .iter()
        .flat_map(|p| p.line_segs.windows(2))
        .filter(|pair| pair[1].vertical_pos < pair[0].vertical_pos)
        .map(|pair| {
            pair[0].vertical_pos
                + pair[0].line_height
                + pair[0].line_spacing.max(0)
                + pair[1].line_height
        })
        .filter(|&spilled| spilled > filled)
        .min()
        .map(|spilled| spilled - 1)
}

/// [#8361] 한/글은 단 안 문단을 `앞 문단 끝(마지막 줄 + 꼬리 줄간격) + 아래 간격 + 앞 간격` 에
/// 차례로 쌓는다. PDF 관측 위치는 글자 상자 기준이라 문단 마지막 줄이 피치보다 짧게 관측되고(한
/// 쪽 13·5쪽 문단 경계마다 110HU), 그 자리를 그대로 저장하면 한/글만 문단 경계마다 내려가 단
/// 끝 줄이 다음 단으로 넘어갔다. 단 첫 문단은 원래 자리에 두고 나머지 저장 줄을 같은 규칙으로
/// 다시 매긴다(앞 간격은 이미 PDF 간격에서 앞 문단 끝을 뺀 값이다).
fn restack_columns(doc: &Document, body: &mut [Paragraph]) {
    let mut end: Option<i32> = None;
    for paragraph in body.iter_mut() {
        if paragraph.column_type != ColumnBreakType::None {
            end = None;
        }
        let Some(shape) = doc
            .doc_info
            .para_shapes
            .get(paragraph.para_shape_id as usize)
        else {
            continue;
        };
        let Some(first) = paragraph.line_segs.first().map(|seg| seg.vertical_pos) else {
            continue;
        };
        // Paragraph measures are stored as twice HWPUNIT.
        if let Some(previous_end) = end {
            let shift = previous_end + shape.spacing_before.max(0) / 2 - first;
            // 이어 붙인 문단의 되감기(다음 단·쪽) 뒤 줄은 그 단의 자리에 둔다.
            let mut previous = i32::MIN;
            for seg in &mut paragraph.line_segs {
                if seg.vertical_pos < previous {
                    break;
                }
                previous = seg.vertical_pos;
                seg.vertical_pos += shift;
            }
        }
        end = paragraph.line_segs.last().map(|seg| {
            seg.vertical_pos
                + seg.line_height
                + seg.line_spacing.max(0)
                + shape.spacing_after.max(0) / 2
        });
    }
}

/// 같은 단 안에서 이어지는 저장 줄 사이 피치(HWPUNIT). PDF 관측 피치는 반올림으로 한두
/// HWPUNIT 씩 오가므로(1919/1931) 중앙값 근처(±5%) 피치의 평균을 쓴다 — 한/글은 이 값 하나로
/// 모든 줄을 짜므로 한쪽 값을 고르면 줄마다 그 반올림 차이가 쌓인다.
fn median_row_pitch(
    rows: &[crate::model::paragraph::LineSeg],
    allocation: Allocation<'_>,
) -> Result<Option<i32>, PdfImportError> {
    let mut pitches = allocation.collect(
        rows.windows(2)
            .map(|pair| pair[1].vertical_pos - pair[0].vertical_pos)
            .filter(|&pitch| pitch > 0),
    )?;
    if pitches.is_empty() {
        return Ok(None);
    }
    allocation.sort_by(&mut pitches, i32::cmp)?;
    let median = pitches[pitches.len() / 2];
    let (sum, count) = pitches
        .iter()
        .filter(|&&pitch| (pitch - median).abs() * 20 <= median)
        .fold((0_i64, 0_i64), |(sum, count), &pitch| {
            (sum + i64::from(pitch), count + 1)
        });
    Ok(Some((sum as f64 / count as f64).round() as i32))
}

/// Body rows take the paragraph indent from the row tag, not from their
/// start position: a positive indent marks the first row, a negative
/// (hanging) indent the rows after it. Frame rows stored the indent in
/// their start instead, and joined rows came from separate paragraphs.
fn mark_indented_rows(doc: &Document, paragraphs: &mut [Paragraph]) {
    use crate::model::paragraph::LineSeg;
    for p in paragraphs.iter_mut() {
        let Some(shape) = doc.doc_info.para_shapes.get(p.para_shape_id as usize) else {
            continue;
        };
        let indent = shape.indent;
        for (row, seg) in p.line_segs.iter_mut().enumerate() {
            let indented = (indent > 0 && row == 0) || (indent < 0 && row > 0);
            if indented {
                seg.tag |= LineSeg::TAG_INDENTATION;
            } else {
                seg.tag &= !LineSeg::TAG_INDENTATION;
            }
        }
    }
}

/// Lay the pages' paragraphs into one flow. Paragraphs cut by a column or
/// page boundary are joined. Each page's positioned content rides on the
/// first paragraph that starts on that page, or on its own anchor line.
fn assemble(
    doc: &mut Document,
    out: &mut Vec<Paragraph>,
    pages: Vec<(Paragraph, Vec<Paragraph>, bool)>,
    allocation: Allocation<'_>,
) -> Result<usize, PdfImportError> {
    let mut joined = 0;
    for (page_no, (mut anchor, mut body, keep_anchor)) in pages.into_iter().enumerate() {
        if page_no == 0 {
            // The section's first paragraph carries only the section and
            // column definitions on one minimal line, as stored sections do.
            // HWPX stores the first paragraph's row starts on an axis without
            // those two definitions, so text rows never start in it.
            let lead = anchor
                .controls
                .iter()
                .take_while(|c| matches!(c, Control::SectionDef(_) | Control::ColumnDef(_)))
                .count();
            let mut rest = Paragraph::new_empty();
            allocation.payload::<Control>(anchor.controls.len() - lead)?;
            rest.controls = anchor.controls.split_off(lead);
            if anchor.ctrl_data_records.len() > lead {
                allocation.bytes(
                    (anchor.ctrl_data_records.len() - lead)
                        * std::mem::size_of_val(&anchor.ctrl_data_records[0]),
                )?;
                rest.ctrl_data_records = anchor.ctrl_data_records.split_off(lead);
            }
            anchor.char_count -= 8 * rest.controls.len() as u32;
            rest.para_shape_id = anchor.para_shape_id;
            rest.char_shapes = allocation.clone_record(&anchor.char_shapes)?;
            rest.line_segs = allocation.clone_record(&anchor.line_segs)?;
            rest.char_count = 1 + 8 * rest.controls.len() as u32;
            allocation.push(out, anchor)?;
            anchor = rest;
        }
        if !keep_anchor && page_no > 0 {
            if let Some(first) = body.first_mut() {
                first.column_type = ColumnBreakType::Page;
            }
        }
        let mut cut = allocation.filled(body.len(), false)?;
        for j in 0..body.len() {
            if !matches!(
                body[j].column_type,
                ColumnBreakType::Column | ColumnBreakType::Page
            ) {
                continue;
            }
            let previous = if j > 0 { body.get(j - 1) } else { out.last() };
            cut[j] = previous.is_some_and(|p| continues(doc, p, &body[j]));
        }
        let host = (!keep_anchor)
            .then(|| cut.iter().position(|c| !c))
            .flatten();
        match host {
            Some(h) => {
                attach_leading_controls(&mut body[h], std::mem::take(&mut anchor), allocation)?;
            }
            None => {
                // The anchor opens the page, so nothing joins across its start.
                if page_no > 0 {
                    anchor.column_type = ColumnBreakType::Page;
                }
                if let Some(first) = cut.first_mut() {
                    *first = false;
                }
                if let Some(first) = body.first_mut() {
                    if first.column_type == ColumnBreakType::Page {
                        first.column_type = ColumnBreakType::None;
                    }
                }
                allocation.push(out, anchor)?;
            }
        }
        // [#8355] 이어 붙인 문단이 마지막 줄에 새로 차지한 꼬리 줄간격(HWPUNIT). 다음 문단의
        // 앞 간격은 이어 붙이기 전 조각의 줄 바닥에서 잰 값이라 그만큼 뺀다.
        let mut carried_trailing = 0;
        for (j, paragraph) in body.into_iter().enumerate() {
            match out.last_mut() {
                Some(previous) if cut[j] => {
                    // The joined paragraph ends where `paragraph` ended: its
                    // spacing to the following paragraph comes along.
                    let after =
                        doc.doc_info.para_shapes[paragraph.para_shape_id as usize].spacing_after;
                    doc.doc_info.para_shapes[previous.para_shape_id as usize].spacing_after = after;
                    join(previous, &paragraph, allocation)?;
                    unify_row_end(doc, previous);
                    carried_trailing = restore_fixed_trailing(doc, previous, allocation)?;
                    // [#8362] 뒤 조각의 다음 글이 그림으로 시작하면 사이 간격은 이 문단의 아래
                    // 간격에 들어 있다. 늘어난 꼬리 몫은 거기서 먼저 뺀다 — 다음 문단 앞 간격에서만
                    // 빼면 같은 몫이 두 번 들어가 원본보다 한 줄간격 벌어졌다(2010판 6쪽 첫 줄 뒤).
                    if carried_trailing > 0 {
                        let shape = &mut doc.doc_info.para_shapes[previous.para_shape_id as usize];
                        // Paragraph measures are stored as twice HWPUNIT.
                        let taken = (2 * carried_trailing).min(shape.spacing_after.max(0));
                        shape.spacing_after -= taken;
                        carried_trailing -= taken / 2;
                    }
                    joined += 1;
                }
                _ => {
                    if carried_trailing != 0 {
                        let shape = &mut doc.doc_info.para_shapes[paragraph.para_shape_id as usize];
                        // Paragraph measures are stored as twice HWPUNIT.
                        shape.spacing_before = (shape.spacing_before - 2 * carried_trailing).max(0);
                    }
                    carried_trailing = 0;
                    allocation.push(out, paragraph)?;
                }
            }
        }
    }
    Ok(joined)
}

fn column_def(
    boxes: &[(i32, i32)],
    allocation: Allocation<'_>,
) -> Result<ColumnDef, PdfImportError> {
    const TOTAL: i64 = 32768;
    let body = i64::from((boxes[boxes.len() - 1].1 - boxes[0].0).max(1));
    let mut parts = Vec::new();
    for (i, &(left, right)) in boxes.iter().enumerate() {
        allocation.push(&mut parts, i64::from(right - left))?;
        allocation.push(
            &mut parts,
            boxes.get(i + 1).map_or(0, |next| i64::from(next.0 - right)),
        )?;
    }
    // Cumulative rounding keeps the proportions summing to exactly 32768.
    let mut edges = allocation.vec(parts.len())?;
    let mut acc = 0;
    for part in &parts {
        acc += part;
        allocation.push(&mut edges, acc * TOTAL / body)?;
    }
    let mut previous = 0;
    let scaled = allocation.collect(edges.iter().map(|&edge| {
        let value = (edge - previous).clamp(0, i64::from(i16::MAX)) as i16;
        previous = edge;
        value
    }))?;
    let widths = allocation.collect(scaled.iter().step_by(2).copied())?;
    let gaps = allocation.collect(scaled.iter().skip(1).step_by(2).copied())?;
    let spacing = boxes.windows(2).next().map_or(0, |w| {
        (w[1].0 - w[0].1).clamp(0, i32::from(i16::MAX)) as i16
    });
    Ok(ColumnDef {
        column_type: ColumnType::Normal,
        column_count: boxes.len() as u16,
        direction: ColumnDirection::LeftToRight,
        same_width: false,
        spacing,
        widths,
        gaps,
        proportional_widths: true,
        ..Default::default()
    })
}

/// Replace each page's positioned body frames with section text flow.
pub(super) fn reflow(
    doc: &mut Document,
    pages: &[PageFrames],
    allocation: Allocation<'_>,
) -> Result<Value, PdfImportError> {
    if pages.is_empty() {
        return Ok(request_json!(allocation, {"layout":"editable","sections":0})?);
    }
    let base = pages[0].section;
    // Runs of consecutive pages with the same paper become one section each.
    let mut runs: Vec<Vec<&PageFrames>> = Vec::new();
    for page in pages {
        let pd = &doc.sections[page.section].section_def.page_def;
        let same = runs.last().and_then(|run| run.last()).is_some_and(|prev| {
            let q = &doc.sections[prev.section].section_def.page_def;
            (q.width, q.height, q.landscape) == (pd.width, pd.height, pd.landscape)
        });
        if same {
            allocation.push(runs.last_mut().unwrap(), page)?;
        } else {
            let run = allocation.collect([page])?;
            allocation.push(&mut runs, run)?;
        }
    }
    let mut old = allocation.collect(doc.sections.drain(base..))?;
    let mut report = Vec::new();
    let mut anchor_shape = None;
    for run in runs {
        let first = run[0].section - base;
        let pd = allocation.clone_record(&old[first].section_def.page_def)?;
        let width = if pd.landscape { pd.height } else { pd.width } as i32;
        let height = if pd.landscape { pd.width } else { pd.height } as i32;
        let layouts =
            allocation.try_collect(run.iter().map(|p| page_columns(&p.frames, allocation)))?;
        // The section's column grid is the most common page grid.
        let mut counts = std::collections::BTreeMap::new();
        for (columns, _) in &layouts {
            if !columns.is_empty() {
                let value = counts.get(&columns.len()).copied().unwrap_or(0usize) + 1;
                allocation.insert(&mut counts, columns.len(), value)?;
            }
        }
        let Some((&count, _)) = counts.iter().max_by_key(|(n, c)| (**c, **n)) else {
            // Nothing recognized: keep the positioned pages as they were.
            for page in &run {
                let section = allocation.clone_section(&old[page.section - base])?;
                allocation.push(&mut doc.sections, section)?;
            }
            continue;
        };
        let grid =
            allocation.collect(layouts.iter().map(|(c, _)| c).filter(|c| c.len() == count))?;
        let median = |values: Vec<f32>| -> Result<f32, PdfImportError> {
            let mut v = values;
            allocation.sort_by(&mut v, f32::total_cmp)?;
            Ok(v[v.len() / 2])
        };
        let lefts = allocation.try_collect((0..count).map(|c| -> Result<i32, PdfImportError> {
            Ok(hu(median(
                allocation.collect(grid.iter().map(|g| g[c].0))?,
            )?))
        }))?;
        let rights =
            allocation.try_collect((0..count).map(|c| -> Result<i32, PdfImportError> {
                Ok(hu(median(
                    allocation.collect(grid.iter().map(|g| g[c].1))?,
                )?))
            }))?;
        let gap = if count > 1 {
            (0..count - 1)
                .map(|c| lefts[c + 1] - rights[c])
                .sum::<i32>()
                / (count as i32 - 1)
        } else {
            0
        };
        // Each column keeps its observed text edges. The renderer admits the
        // stored rows only for this exact frame; a wider box re-breaks them.
        let boxes =
            allocation.collect((0..count).map(|c| (lefts[c].max(0), rights[c].min(width))))?;
        let margin_left = boxes[0].0;
        let margin_right = (width - boxes[count - 1].1).max(0);
        let column_left = |c: usize| boxes[c].0;
        let column_width_of = |c: usize| boxes[c].1 - boxes[c].0;
        // A frame joins the flow when its column maps onto one grid column.
        let mut placed =
            allocation.try_collect(run.iter().zip(&layouts).map(|(page, (columns, owner))| {
                let grid_of = |c: usize| {
                    let center = hu((columns[c].0 + columns[c].1) / 2.);
                    (0..count).min_by_key(|&g| ((boxes[g].0 + boxes[g].1) / 2 - center).abs())
                };
                let mapped = allocation.collect((0..columns.len()).map(grid_of))?;
                allocation.collect(page.frames.iter().zip(owner).map(|(frame, o)| {
                    let c = (*o)?;
                    let g = mapped[c]?;
                    // Text outside the column box (a page number in the
                    // gutter) is not column flow; it keeps its position.
                    let (left, right) = boxes[g];
                    if hu(frame.left) < left - 100 || hu(frame.right) > right + 100 {
                        return None;
                    }
                    // Two page columns on one grid column are not a column flow.
                    (mapped.iter().filter(|m| **m == Some(g)).count() == 1).then_some(g)
                }))
            }))?;
        // A short frame that recurs at one height on half the pages or more
        // is a running header or footer (page number, booklet marks). It
        // keeps its page position instead of opening a column.
        let band = |f: &BodyFrame| (hu(f.top) / 200, hu(f.bottom) / 200);
        let mut recurring = std::collections::BTreeMap::new();
        for page in &run {
            let bands = allocation.set_from(
                page.frames
                    .iter()
                    .filter(|f| f.bottom - f.top < 30.0)
                    .map(band),
            )?;
            for b in bands {
                let value = recurring.get(&b).copied().unwrap_or(0usize) + 1;
                allocation.insert(&mut recurring, b, value)?;
            }
        }
        let running = run.len() >= 2;
        for (page, owners) in run.iter().zip(placed.iter_mut()) {
            for (frame, owner) in page.frames.iter().zip(owners.iter_mut()) {
                let repeats = recurring.get(&band(frame)).copied().unwrap_or(0);
                if running && frame.bottom - frame.top < 30.0 && 2 * repeats >= run.len() {
                    *owner = None;
                }
            }
        }
        // Body text starts at one height on most pages. A cover page whose
        // text starts higher keeps that text positioned, so every column top
        // is the page body top and a paragraph continued into the next column
        // starts there, as stored rows of a continued paragraph do.
        let page_tops = allocation.collect(run.iter().zip(&placed).filter_map(|(p, owners)| {
            p.frames
                .iter()
                .zip(owners)
                .filter(|(_, g)| g.is_some())
                .map(|(f, _)| f.top)
                .reduce(f32::min)
        }))?;
        let body_top = median(page_tops)?;
        for (page, owners) in run.iter().zip(placed.iter_mut()) {
            for (frame, owner) in page.frames.iter().zip(owners.iter_mut()) {
                if frame.top < body_top - 2.0 {
                    *owner = None;
                }
            }
        }
        let flowing = || {
            run.iter()
                .zip(&placed)
                .flat_map(|(p, owners)| p.frames.iter().zip(owners))
                .filter(|(_, g)| g.is_some())
                .map(|(f, _)| f)
        };
        let margin_top = hu(body_top).max(0);
        let margin_bottom =
            (height - hu(flowing().map(|f| f.bottom).fold(f32::MIN, f32::max))).max(0);
        let mut flow_bottoms = allocation
            .try_collect(run.iter().map(|page| {
                allocation.collect(page.frames.iter().map(|frame| hu(frame.bottom)))
            }))?;
        let mut tail_bands = Vec::new();
        // The ordinary reflow witness also infers a tail after its last row.
        // Reconcile that tail with the next observed frame, preserving both
        // accepted line boxes and the confirmed body paragraph owners.
        for (page_index, (page, owners)) in run.iter().zip(&mut placed).enumerate() {
            for column in 0..count {
                let mut order = allocation
                    .collect((0..page.frames.len()).filter(|&i| owners[i] == Some(column)))?;
                allocation.sort_by(&mut order, |&a, &b| {
                    page.frames[a].top.total_cmp(&page.frames[b].top)
                })?;
                for pair in order.windows(2) {
                    let index = pair[0];
                    let next_top = hu(page.frames[pair[1]].top);
                    let bottom = &mut flow_bottoms[page_index][index];
                    if next_top >= *bottom {
                        continue;
                    }
                    let last = old[page.section - base].paragraphs[0]
                        .controls
                        .iter_mut()
                        .find_map(|control| match control {
                            Control::Shape(shape) => match &mut **shape {
                                ShapeObject::Rectangle(rect)
                                    if rect.drawing.inst_id == page.frames[index].inst_id =>
                                {
                                    rect.drawing.text_box.as_mut()?.paragraphs.last_mut()
                                }
                                _ => None,
                            },
                            _ => None,
                        });
                    if let Some(paragraph) = last {
                        let blank_row = paragraph.line_segs.len() == 1
                            && !paragraph.text.is_empty()
                            && paragraph.text.chars().all(char::is_whitespace);
                        let Some(last) = paragraph.line_segs.last_mut() else {
                            continue;
                        };
                        let content_end = i64::from(*bottom) - i64::from(last.line_spacing);
                        let row_top = content_end - i64::from(last.line_height);
                        // [#8381] 공백만 있는 줄은 잉크가 없어 글자 상자가 점유한 내용이 아니다.
                        // 그 줄은 다음 관측 줄까지의 띠만 차지한다. 저장 줄 높이를 그 띠로 줄이고,
                        // 한/글이 마지막 줄을 다시 짜는 고정 피치도 같은 띠로 둔다(무표기본 13쪽
                        // 지문 상자 맨 위 « » 줄: 글자 11.04pt, 다음 줄까지 6.6pt — 두 엔진이 본문을
                        // 4.4pt 아래에 그렸다).
                        if blank_row
                            && i64::from(next_top) < content_end
                            && i64::from(next_top) > row_top
                        {
                            let band = (i64::from(next_top) - row_top) as i32;
                            let before = last.line_height + last.line_spacing;
                            last.line_height = band;
                            last.text_height = last.text_height.min(band);
                            last.line_spacing = 0;
                            if let Some(shape) = doc
                                .doc_info
                                .para_shapes
                                .get_mut(paragraph.para_shape_id as usize)
                            {
                                if shape.line_spacing_type == LineSpacingType::Fixed {
                                    // Paragraph measures are stored as twice HWPUNIT.
                                    shape.line_spacing = 2 * band;
                                }
                            }
                            *bottom = next_top;
                            allocation.push(&mut tail_bands, request_json!(allocation, {"sourceSection":page.section,"instanceId":page.frames[index].inst_id,"contentEndHu":content_end,"sourceBandEndHu":next_top,"inferredTailHu":before,"acceptedTailHu":band})?)?;
                            continue;
                        }
                        // A paragraph's inferred interline tail is not
                        // observed occupied content. Grant only the available
                        // source band, without cutting any accepted line box.
                        if last.line_spacing > 0 && i64::from(next_top) >= content_end {
                            let before = last.line_spacing;
                            last.line_spacing = (i64::from(next_top) - content_end) as i32;
                            let cut = before - last.line_spacing;
                            // Hancom lays a fixed-pitch paragraph's last row
                            // out at the pitch again; its spacing after gives
                            // the cut back. Stored rows already end at the band.
                            if let Some(shape) = doc
                                .doc_info
                                .para_shapes
                                .get_mut(paragraph.para_shape_id as usize)
                            {
                                if shape.line_spacing_type == LineSpacingType::Fixed {
                                    // Paragraph measures are stored as twice HWPUNIT.
                                    shape.spacing_after -= 2 * cut;
                                }
                            }
                            *bottom = next_top;
                            allocation.push(&mut tail_bands, request_json!(allocation, {"sourceSection":page.section,"instanceId":page.frames[index].inst_id,"contentEndHu":content_end,"sourceBandEndHu":next_top,"inferredTailHu":before,"acceptedTailHu":last.line_spacing})?)?;
                        }
                    }
                }
            }
        }
        let mut section = allocation.clone_section(&old[first])?;
        section.paragraphs.clear();
        {
            let pd = &mut section.section_def.page_def;
            pd.margin_left = margin_left as u32;
            pd.margin_right = margin_right as u32;
            pd.margin_top = margin_top as u32;
            pd.margin_bottom = margin_bottom as u32;
            pd.margin_header = 0;
            pd.margin_footer = 0;
        }
        // An anchor line that reserves almost no height: fixed 1pt spacing.
        // Anchor lines hold no text. A 1pt face on a fixed 1pt line keeps
        // the height they take in the column known: `ANCHOR_HEIGHT`.
        let (anchor_shape_id, anchor_char_id) = if let Some(ids) = anchor_shape {
            ids
        } else {
            let mut shape = allocation.clone_record(&doc.doc_info.para_shapes[0])?;
            shape.raw_data = None;
            shape.line_spacing_type = LineSpacingType::Fixed;
            shape.line_spacing = 2 * ANCHOR_HEIGHT;
            shape.spacing_before = 0;
            shape.spacing_after = 0;
            allocation.push(&mut doc.doc_info.para_shapes, shape)?;
            let mut face = allocation.clone_record(&doc.doc_info.char_shapes[0])?;
            face.raw_data = None;
            face.base_size = ANCHOR_HEIGHT;
            allocation.push(&mut doc.doc_info.char_shapes, face)?;
            let ids = (
                (doc.doc_info.para_shapes.len() - 1) as u16,
                (doc.doc_info.char_shapes.len() - 1) as u32,
            );
            anchor_shape = Some(ids);
            ids
        };
        let def = column_def(&boxes, allocation)?;
        let mut pages_report = Vec::new();
        let mut pages_flow = Vec::new();
        for (page_no, page) in run.iter().enumerate() {
            let committed = allocation.set_from(
                page.frames
                    .iter()
                    .zip(&placed[page_no])
                    .filter(|(_, owner)| owner.is_some())
                    .map(|(frame, _)| frame.inst_id),
            )?;
            let mut anchor = std::mem::take(&mut old[page.section - base].paragraphs[0]);
            if page_no == 0 {
                // The section opens with its definition and column grid as the
                // first two extended controls, as stored HWP sections do. Both
                // take stream slots ahead of the first character; savers write
                // the section definition there even when the model omits it.
                let before = anchor.controls.len();
                anchor
                    .controls
                    .retain(|c| !matches!(c, Control::SectionDef(_) | Control::ColumnDef(_)));
                anchor.char_count -= 8 * (before - anchor.controls.len()) as u32;
                let section_def = allocation.clone_section_def(&section.section_def)?;
                let section_def = allocation.boxed(section_def)?;
                let column = allocation.clone_record(&def)?;
                allocation.reserve(&mut anchor.controls, 2)?;
                anchor.controls.insert(0, Control::SectionDef(section_def));
                anchor.controls.insert(1, Control::ColumnDef(column));
                anchor.char_count += 16;
            } else {
                // One section definition and one column grid open the section.
                let before = anchor.controls.len();
                anchor
                    .controls
                    .retain(|c| !matches!(c, Control::SectionDef(_) | Control::ColumnDef(_)));
                let removed = (before - anchor.controls.len()) as u32;
                anchor.char_count = anchor.char_count.saturating_sub(8 * removed);
                anchor.column_type = ColumnBreakType::Page;
            }
            // Positioned content rides on the page's first column-0 paragraph.
            // A separate anchor line is kept only when column 0 has none.
            let keep_anchor = !placed[page_no].contains(&Some(0));
            anchor.para_shape_id = anchor_shape_id;
            anchor.char_shapes = allocation.collect([crate::model::paragraph::CharShapeRef {
                start_pos: 0,
                char_shape_id: anchor_char_id,
            }])?;
            for seg in &mut anchor.line_segs {
                seg.vertical_pos = 0;
                seg.line_height = ANCHOR_HEIGHT;
                seg.text_height = ANCHOR_HEIGHT;
                seg.baseline_distance = ANCHOR_HEIGHT * 85 / 100;
                seg.line_spacing = 0;
                seg.column_start = 0;
                seg.segment_width = column_width_of(0);
            }
            let mut body = Vec::new();
            let mut moved = 0;
            let mut current_column = 0;
            for g in 0..count {
                let mut members = allocation
                    .collect((0..page.frames.len()).filter(|&i| placed[page_no][i] == Some(g)))?;
                allocation.sort_by(&mut members, |&a, &b| {
                    page.frames[a].top.total_cmp(&page.frames[b].top)
                })?;
                // The anchor line occupies the top of the first column.
                // Anchor lines (the section opener, a page anchor) occupy the
                // top of the first column.
                let anchors = i32::from(page_no == 0) + i32::from(keep_anchor);
                let mut previous_bottom =
                    margin_top + if g == 0 { ANCHOR_HEIGHT * anchors } else { 0 };
                let col_left = column_left(g);
                let mut first_in_column = true;
                for &i in &members {
                    let frame = &page.frames[i];
                    let Some(owner_left) = anchor.controls.iter().find_map(|c| match c {
                        Control::Shape(s) => match &**s {
                            ShapeObject::Rectangle(r) if r.drawing.inst_id == frame.inst_id => {
                                Some(r.common.horizontal_offset as i32)
                            }
                            _ => None,
                        },
                        _ => None,
                    }) else {
                        continue;
                    };
                    let Some(mut paragraphs) = take_frame(&mut anchor, frame.inst_id) else {
                        continue;
                    };
                    let top = hu(frame.top);
                    if first_in_column {
                        if let Some(first) = paragraphs.first_mut() {
                            if let Some(prefix) = take_positioned_prefix(
                                &mut anchor,
                                &committed,
                                boxes[g],
                                margin_top,
                                top,
                                allocation,
                            )? {
                                attach_leading_controls(first, prefix, allocation)?;
                            }
                            first_in_column = false;
                        }
                    }
                    let shift_x = owner_left - col_left;
                    let paragraphs_len = paragraphs.len();
                    for (pi, p) in paragraphs.iter_mut().enumerate() {
                        let shape = &mut doc.doc_info.para_shapes[p.para_shape_id as usize];
                        // Paragraph measures are stored as twice HWPUNIT.
                        shape.margin_left = (shape.margin_left + 2 * shift_x).max(0);
                        // A paragraph's rows end at its widest source line,
                        // not at the column edge: Hancom pulls the next row's
                        // characters into any slack as wide as one of them.
                        // A negative right margin never widens a Hancom row,
                        // so the measure stops at the column edge.
                        let right = frame
                            .paragraph_rights
                            .get(pi)
                            .copied()
                            .filter(|_| frame.paragraph_rights.len() == paragraphs_len)
                            .unwrap_or(frame.right);
                        let inset = (boxes[g].1 - hu(right) - ROW_END_SLACK).max(0);
                        shape.margin_right = 2 * (inset - inset.rem_euclid(4));
                        if pi == 0 {
                            shape.spacing_before = 2 * (top - previous_bottom).max(0);
                        }
                        // Body rows reproduce the frame the renderer derives
                        // from the column and the paragraph shape: every row
                        // starts at the left margin (the indent is applied
                        // inside the row) and ends at the right margin, from
                        // the column's right edge snapped down to 4 HWPUNIT.
                        // Rows that miss this key are broken again with
                        // substitute font metrics.
                        let start = shape.margin_left / 2;
                        let end = column_width_of(g)
                            - column_width_of(g).rem_euclid(4)
                            - shape.margin_right / 2;
                        for seg in &mut p.line_segs {
                            seg.vertical_pos += top - margin_top;
                            seg.column_start = start;
                            seg.segment_width = (end - start).max(0);
                        }
                    }
                    if g > current_column {
                        // Each skipped grid column needs its own column break.
                        for _ in current_column + 1..g {
                            let mut empty = Paragraph::new_empty();
                            empty.column_type = ColumnBreakType::Column;
                            allocation.push(&mut body, empty)?;
                        }
                        paragraphs[0].column_type = ColumnBreakType::Column;
                        current_column = g;
                    }
                    // [#8355] 다음 글상자까지의 앞 간격은 이 글상자의 흐름 끝에서 잰다 — 마지막
                    // 줄의 위치 + 줄 높이 + 꼬리 줄간격(고정 줄간격 문단은 마지막 줄도 고정
                    // 피치를 차지한다). 글상자 아래 변은 테두리 여백을 포함할 수 있어 흐름 끝이
                    // 아니다(시험지 «보기» 상자 뒤 선택지가 한/글에서 11px 위).
                    previous_bottom = paragraphs.last().and_then(|p| p.line_segs.last()).map_or(
                        flow_bottoms[page_no][i],
                        |seg| {
                            margin_top
                                + seg.vertical_pos
                                + seg.line_height
                                + seg.line_spacing.max(0)
                        },
                    );
                    moved += paragraphs.len();
                    allocation.extend(&mut body, paragraphs)?;
                }
            }
            let positioned =
                page.frames.len() - placed[page_no].iter().filter(|g| g.is_some()).count();
            allocation.push(&mut pages_report, request_json!(allocation, {"sourceSection":page.section,"columns":count,"bodyParagraphs":moved,"positionedFrames":positioned})?)?;
            restack_columns(doc, &mut body);
            allocation.push(&mut pages_flow, (anchor, body, keep_anchor))?;
        }
        let joined = assemble(doc, &mut section.paragraphs, pages_flow, allocation)?;
        // 이어 붙인 문단은 꼬리 줄간격·피치를 다시 잡으므로 이어 붙인 뒤 한 번 더 쌓는다.
        restack_columns(doc, &mut section.paragraphs);
        // [#8361] 본문 아래 끝은 원본의 본문 아래 끝이어야 한/글도 원본 자리에서 단·쪽을 넘긴다.
        // 글상자 아래 변(관측 글자 범위)은 줄 상자보다 낮아 본문이 약 한 줄간격 길어졌고, 원본에서
        // 다음 줄이 들어가지 않아 다음 단으로 이어진 문단을 한/글은 다시 짜며 앞 단에 한 줄 더
        // 채웠다(4쪽 왼쪽 단). 원본 아래 끝은 [들어간 줄 바닥의 최댓값, 넘어간 줄 바닥의 최솟값)
        // 사이에 있다. 한/글 줄 위치는 고정 피치로 다시 짜여 저장 위치보다 조금 낮게 나오므로
        // 위 끝(넘어간 줄 바로 앞)을 쓴다. 넘어간 줄이 없으면 종전 값을 둔다.
        if let Some(bottom) = column_cut_bottom(&section.paragraphs) {
            let fitted = (height - margin_top - bottom).max(0);
            if fitted > margin_bottom {
                section.section_def.page_def.margin_bottom = fitted as u32;
                for paragraph in &mut section.paragraphs {
                    for control in &mut paragraph.controls {
                        if let Control::SectionDef(def) = control {
                            def.page_def.margin_bottom = fitted as u32;
                        }
                    }
                }
            }
        }
        mark_indented_rows(doc, &mut section.paragraphs);
        allocation.push(&mut report, request_json!(allocation, {"pages":pages_report,"columns":count,"columnGap":gap,"joinedParagraphs":joined,"margins":[margin_left,margin_top,margin_right,margin_bottom],"observedTailBands":tail_bands})?)?;
        allocation.push(&mut doc.sections, section)?;
    }
    Ok(request_json!(allocation, {"layout":"editable","sections":report})?)
}