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
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
use super::*;
use crate::model::page::{ColumnDef, PageDef};
use crate::model::paragraph::{LineSeg, Paragraph};

fn a4_page_def() -> PageDef {
    PageDef {
        width: 59528,
        height: 84188,
        margin_left: 8504,
        margin_right: 8504,
        margin_top: 5669,
        margin_bottom: 4252,
        margin_header: 4252,
        margin_footer: 4252,
        margin_gutter: 0,
        ..Default::default()
    }
}

fn make_paragraph_with_height(line_height: i32) -> Paragraph {
    Paragraph {
        line_segs: vec![LineSeg {
            line_height,
            ..Default::default()
        }],
        ..Default::default()
    }
}

fn missing_lineseg_fragment_boundary_is_identical_in_both_paginators() {
    let para = Paragraph {
        text: "visible converted paragraph".to_string(),
        ..Default::default()
    };
    // 실물 문서의 픽셀 좌표 대신 줄 단위로 가용 공간을 구성한다.
    let line_count = 6;
    let line_unit = 1.0;
    let available = line_count as f64 * line_unit * 8.0;
    let operands = (line_count, available * 4.0 / 5.0, available, line_unit);
    let typeset = crate::renderer::typeset::missing_lineseg_trailing_line_break(
        &para, operands.0, operands.1, operands.2, operands.3, true, true,
    );
    let fallback = super::engine::missing_lineseg_trailing_line_break(
        &para, operands.0, operands.1, operands.2, operands.3, true, true,
    );
    assert_eq!(
        typeset, None,
        "저장 줄 부재와 변환 계보는 문단의 절반을 다음 쪽 소유로 바꾸는 근거가 아니다"
    );
    assert_eq!(fallback, typeset);

    let hwpx_typeset = crate::renderer::typeset::missing_lineseg_trailing_line_break(
        &para, operands.0, operands.1, operands.2, operands.3, true, false,
    );
    let hwpx_fallback = super::engine::missing_lineseg_trailing_line_break(
        &para, operands.0, operands.1, operands.2, operands.3, true, false,
    );
    assert_eq!(
        hwpx_typeset,
        Some(line_count - 1),
        "명시된 inline field reset은 마지막 줄의 경계 소유를 보존한다"
    );
    assert_eq!(hwpx_fallback, hwpx_typeset);

    assert_eq!(
        crate::renderer::typeset::missing_lineseg_trailing_line_break(
            &para, operands.0, operands.1, operands.2, operands.3, false, true,
        ),
        None
    );
    assert_eq!(
        super::engine::missing_lineseg_trailing_line_break(
            &para, operands.0, operands.1, operands.2, operands.3, false, true,
        ),
        None
    );
    assert_eq!(
        crate::renderer::typeset::missing_lineseg_trailing_line_break(
            &para, operands.0, operands.1, operands.2, operands.3, false, false,
        ),
        None
    );
    assert_eq!(
        super::engine::missing_lineseg_trailing_line_break(
            &para, operands.0, operands.1, operands.2, operands.3, false, false,
        ),
        None
    );
}

#[test]
fn tac_picture_and_shape_require_partial_paragraph_page_routing() {
    missing_lineseg_fragment_boundary_is_identical_in_both_paginators();
    use crate::model::control::Control;
    use crate::model::image::Picture;
    use crate::model::page::ColumnDef;
    use crate::model::shape::ShapeObject;
    use crate::renderer::page_layout::PageLayoutInfo;

    let mut picture = Picture::default();
    picture.common.treat_as_char = true;
    assert!(is_routable_treat_as_char_picture_or_shape(
        &Control::Picture(Box::new(picture))
    ));

    let shape = ShapeObject::Rectangle(Default::default());
    let mut shape = shape;
    shape.common_mut().treat_as_char = true;
    assert!(is_routable_treat_as_char_picture_or_shape(&Control::Shape(
        Box::new(shape)
    )));

    let mut floating_picture = Picture::default();
    floating_picture.common.treat_as_char = false;
    assert!(
        !is_routable_treat_as_char_picture_or_shape(&Control::Picture(Box::new(floating_picture))),
        "비-TAC 그림은 기존 floating 개체 경로를 유지해야 한다"
    );

    let tac_picture = || {
        let mut picture = Picture::default();
        picture.common.treat_as_char = true;
        Control::Picture(Box::new(picture))
    };
    let para = Paragraph {
        line_segs: (0..3)
            .map(|line| LineSeg {
                text_start: line * 8,
                ..Default::default()
            })
            .collect(),
        controls: vec![tac_picture(), tac_picture(), tac_picture()],
        ..Default::default()
    };
    let layout = PageLayoutInfo::from_page_def(&a4_page_def(), &ColumnDef::default(), 96.0);
    let page = |page_index, start_line, end_line| PageContent {
        page_index,
        page_number: page_index + 1,
        page_number_restarted: false,
        section_index: 0,
        layout: layout.clone(),
        column_contents: vec![ColumnContent {
            paragraph_origins: Default::default(),
            computed_paragraphs: Default::default(),
            column_index: 0,
            start_height: 0.0,
            endnote_flow: false,
            items: vec![PageItem::PartialParagraph {
                para_index: 0,
                start_line,
                end_line,
            }],
            zone_layout: None,
            zone_y_offset: 0.0,
            wrap_around_paras: Vec::new(),
            used_height: 0.0,
            wrap_anchors: Default::default(),
            overlay_continuations: Vec::new(),
            overlay_cuts: Vec::new(),
            inline_placements: Default::default(),
            inline_flow_plans: Default::default(),
            stored_paragraph_flow_ends: Default::default(),
            host_compositions: Default::default(),
            stored_column_top_spacings: Default::default(),
            paragraph_float_placements: Default::default(),
            float_pushed_line_spacings: Default::default(),
            page_band_flow_starts: Default::default(),
        }],
        active_header: None,
        active_footer: None,
        page_number_pos: None,
        page_hide: None,
        footnotes: Vec::new(),
        active_master_page: None,
        extra_master_pages: Vec::new(),
        ladder_band_tables: Vec::new(),
    };
    let pages = vec![page(0, 0, 1), page(1, 1, 2)];
    let current_items = vec![PageItem::PartialParagraph {
        para_index: 0,
        start_line: 2,
        end_line: 3,
    }];
    assert_eq!(
        find_inline_control_target_page(&pages, &current_items, 0, 0, &para),
        Some((0, 0)),
        "첫 TAC 그림은 첫 번째 저장 줄의 쪽으로 라우팅해야 한다"
    );
    assert_eq!(
        find_inline_control_target_page(&pages, &current_items, 0, 1, &para),
        Some((1, 0)),
        "두 번째 TAC 그림은 두 번째 저장 줄의 쪽으로 라우팅해야 한다"
    );
    assert_eq!(
        find_inline_control_target_page(&pages, &current_items, 0, 2, &para),
        None,
        "마지막 TAC 그림은 현재 쪽에 남아야 한다"
    );
}

#[test]
fn page_bottom_text_box_fit_keeps_line_even_when_advance_overflows() {
    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();
    let page_def = a4_page_def();
    let body_height_hu = page_def
        .height
        .saturating_sub(page_def.margin_top)
        .saturating_sub(page_def.margin_bottom)
        .saturating_sub(page_def.margin_header)
        .saturating_sub(page_def.margin_footer) as i32;

    let lead_advance = body_height_hu - 580;
    let lead = Paragraph {
        line_segs: vec![LineSeg {
            vertical_pos: 0,
            line_height: lead_advance,
            text_height: body_height_hu - 2500,
            line_spacing: 0,
            ..Default::default()
        }],
        ..Default::default()
    };
    let bottom_line = Paragraph {
        line_segs: vec![LineSeg {
            vertical_pos: body_height_hu - 1200,
            line_height: 1200,
            text_height: 1200,
            line_spacing: 840,
            ..Default::default()
        }],
        ..Default::default()
    };
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &[lead, bottom_line],
        &composed,
        &styles,
        &page_def,
        &ColumnDef::default(),
        0,
    );

    assert_eq!(result.pages.len(), 1);
    let items = &result.pages[0].column_contents[0].items;
    assert!(matches!(
        items.as_slice(),
        [
            PageItem::FullParagraph { para_index: 0 },
            PageItem::FullParagraph { para_index: 1 }
        ]
    ));
}

#[test]
fn page_bottom_empty_paragraph_before_vpos_reset_does_not_create_blank_page() {
    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();
    let page_def = a4_page_def();
    let body_height_hu = page_def
        .height
        .saturating_sub(page_def.margin_top)
        .saturating_sub(page_def.margin_bottom)
        .saturating_sub(page_def.margin_header)
        .saturating_sub(page_def.margin_footer) as i32;

    let lead = Paragraph {
        text: "앞쪽 본문".to_string(),
        line_segs: vec![LineSeg {
            vertical_pos: 0,
            line_height: body_height_hu - 100,
            text_height: body_height_hu - 100,
            line_spacing: 0,
            ..Default::default()
        }],
        ..Default::default()
    };
    let bottom_empty = Paragraph {
        line_segs: vec![LineSeg {
            vertical_pos: body_height_hu - 1200,
            line_height: 1000,
            text_height: 1000,
            line_spacing: 400,
            ..Default::default()
        }],
        ..Default::default()
    };
    let reset_next = Paragraph {
        text: "다음 쪽 본문".to_string(),
        line_segs: vec![LineSeg {
            vertical_pos: 0,
            line_height: 1000,
            text_height: 1000,
            line_spacing: 400,
            ..Default::default()
        }],
        ..Default::default()
    };

    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &[lead, bottom_empty, reset_next],
        &composed,
        &styles,
        &page_def,
        &ColumnDef::default(),
        0,
    );

    assert_eq!(result.pages.len(), 2);
    assert!(result.hidden_empty_paras.contains(&1));
    assert!(matches!(
        result.pages[0].column_contents[0].items.as_slice(),
        [PageItem::FullParagraph { para_index: 0 }]
    ));
    assert!(matches!(
        result.pages[1].column_contents[0].items.as_slice(),
        [PageItem::FullParagraph { para_index: 2 }]
    ));
}

#[test]
fn test_empty_paragraphs() {
    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &[],
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );
    // 빈 문서도 최소 1페이지
    assert_eq!(result.pages.len(), 1);
}

#[test]
fn test_single_paragraph() {
    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();
    let paras = vec![make_paragraph_with_height(400)];
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );
    assert_eq!(result.pages.len(), 1);
}

#[test]
fn test_page_overflow() {
    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();
    // 본문 영역 높이를 넘는 많은 문단 생성
    let paras: Vec<Paragraph> = (0..100)
        .map(|_| make_paragraph_with_height(2000)) // 각 문단 약 26.7px
        .collect();
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );
    // 여러 페이지로 분할되어야 함
    assert!(!result.pages.is_empty());
}

#[test]
fn test_paginator_dpi() {
    let paginator = Paginator::new(72.0);
    assert!((paginator.dpi - 72.0).abs() < 0.01);
}

#[test]
fn test_table_page_split() {
    // 표가 페이지를 초과할 때 PartialTable로 분할되는지 테스트
    use crate::model::control::Control;
    use crate::model::table::{Cell, Table};

    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();

    // 짧은 텍스트 문단 + 큰 표 (4행, 각 행 높이 30000 HWPUNIT = ~400px → 총 ~1600px)
    let text_para = make_paragraph_with_height(1000);
    let mut table_para = Paragraph::default();
    table_para.controls.push(Control::Table(Box::new(Table {
        row_count: 4,
        col_count: 2,
        cells: vec![
            Cell {
                row: 0,
                col: 0,
                row_span: 1,
                col_span: 1,
                height: 30000,
                width: 5000,
                ..Default::default()
            },
            Cell {
                row: 0,
                col: 1,
                row_span: 1,
                col_span: 1,
                height: 30000,
                width: 5000,
                ..Default::default()
            },
            Cell {
                row: 1,
                col: 0,
                row_span: 1,
                col_span: 1,
                height: 30000,
                width: 5000,
                ..Default::default()
            },
            Cell {
                row: 1,
                col: 1,
                row_span: 1,
                col_span: 1,
                height: 30000,
                width: 5000,
                ..Default::default()
            },
            Cell {
                row: 2,
                col: 0,
                row_span: 1,
                col_span: 1,
                height: 30000,
                width: 5000,
                ..Default::default()
            },
            Cell {
                row: 2,
                col: 1,
                row_span: 1,
                col_span: 1,
                height: 30000,
                width: 5000,
                ..Default::default()
            },
            Cell {
                row: 3,
                col: 0,
                row_span: 1,
                col_span: 1,
                height: 30000,
                width: 5000,
                ..Default::default()
            },
            Cell {
                row: 3,
                col: 1,
                row_span: 1,
                col_span: 1,
                height: 30000,
                width: 5000,
                ..Default::default()
            },
        ],
        ..Default::default()
    })));

    let paras = vec![text_para, table_para];
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    // 표가 1페이지에 안 맞으므로 2페이지 이상이어야 함
    assert!(
        result.pages.len() >= 2,
        "표가 페이지를 넘어 분할되어야 함, pages={}",
        result.pages.len()
    );

    // PartialTable 항목이 존재하는지 확인
    let mut has_partial_table = false;
    for page in &result.pages {
        for col in &page.column_contents {
            for item in &col.items {
                if matches!(item, PageItem::PartialTable { .. }) {
                    has_partial_table = true;
                }
            }
        }
    }
    assert!(has_partial_table, "PartialTable 항목이 존재해야 함");
}

#[test]
fn test_table_fits_single_page() {
    // 표가 페이지에 들어가면 Table로 배치 (분할 안 됨)
    use crate::model::control::Control;
    use crate::model::table::{Cell, Table};

    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();

    let mut table_para = Paragraph::default();
    table_para.controls.push(Control::Table(Box::new(Table {
        row_count: 2,
        col_count: 2,
        cells: vec![
            Cell {
                row: 0,
                col: 0,
                row_span: 1,
                col_span: 1,
                height: 2000,
                width: 5000,
                ..Default::default()
            },
            Cell {
                row: 0,
                col: 1,
                row_span: 1,
                col_span: 1,
                height: 2000,
                width: 5000,
                ..Default::default()
            },
            Cell {
                row: 1,
                col: 0,
                row_span: 1,
                col_span: 1,
                height: 2000,
                width: 5000,
                ..Default::default()
            },
            Cell {
                row: 1,
                col: 1,
                row_span: 1,
                col_span: 1,
                height: 2000,
                width: 5000,
                ..Default::default()
            },
        ],
        ..Default::default()
    })));

    let paras = vec![table_para];
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    // 1페이지에 들어가야 함
    assert_eq!(result.pages.len(), 1);
    // Table 항목이어야 함 (PartialTable 아님)
    let items = &result.pages[0].column_contents[0].items;
    assert!(
        matches!(items[0], PageItem::Table { .. }),
        "작은 표는 Table로 배치되어야 함"
    );
}

#[test]
fn test_table_split_with_repeat_header() {
    // repeat_header=true인 표가 분할될 때 is_continuation 확인
    use crate::model::control::Control;
    use crate::model::table::{Cell, Table};

    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();

    let mut table_para = Paragraph::default();
    table_para.controls.push(Control::Table(Box::new(Table {
        row_count: 4,
        col_count: 1,
        repeat_header: true,
        cells: vec![
            Cell {
                row: 0,
                col: 0,
                row_span: 1,
                col_span: 1,
                height: 5000,
                width: 10000,
                is_header: true,
                ..Default::default()
            },
            Cell {
                row: 1,
                col: 0,
                row_span: 1,
                col_span: 1,
                height: 40000,
                width: 10000,
                ..Default::default()
            },
            Cell {
                row: 2,
                col: 0,
                row_span: 1,
                col_span: 1,
                height: 40000,
                width: 10000,
                ..Default::default()
            },
            Cell {
                row: 3,
                col: 0,
                row_span: 1,
                col_span: 1,
                height: 40000,
                width: 10000,
                ..Default::default()
            },
        ],
        ..Default::default()
    })));

    let paras = vec![table_para];
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    // 2페이지 이상으로 분할
    assert!(result.pages.len() >= 2, "큰 표가 분할되어야 함");

    // 두 번째 페이지의 PartialTable에 is_continuation=true 확인
    let mut found_continuation = false;
    for page in result.pages.iter().skip(1) {
        for col in &page.column_contents {
            for item in &col.items {
                if let PageItem::PartialTable {
                    is_continuation, ..
                } = item
                {
                    if *is_continuation {
                        found_continuation = true;
                    }
                }
            }
        }
    }
    assert!(
        found_continuation,
        "연속 페이지에 is_continuation=true인 PartialTable이 있어야 함"
    );
}

/// 여러 줄로 구성된 문단 생성 (줄 수, 줄당 높이 HWPUNIT)
fn make_multiline_paragraph(line_count: usize, line_height: i32) -> Paragraph {
    let line_segs: Vec<LineSeg> = (0..line_count)
        .map(|_| LineSeg {
            line_height,
            ..Default::default()
        })
        .collect();
    Paragraph {
        line_segs,
        ..Default::default()
    }
}

#[test]
fn test_partial_paragraph_split() {
    // 10줄 문단 (줄당 ~133px) → A4 본문 영역(~826px)에 ~6줄만 들어감
    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();
    let paras = vec![make_multiline_paragraph(10, 10000)]; // 10줄 x 10000 HWPUNIT
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    // 2페이지 이상으로 분할되어야 함
    assert!(
        result.pages.len() >= 2,
        "긴 문단이 2페이지 이상으로 분할되어야 함, pages={}",
        result.pages.len()
    );

    // PartialParagraph 항목이 존재하는지 확인
    let mut has_partial = false;
    let mut partial_ranges: Vec<(usize, usize)> = Vec::new();
    for page in &result.pages {
        for col in &page.column_contents {
            for item in &col.items {
                if let PageItem::PartialParagraph {
                    start_line,
                    end_line,
                    ..
                } = item
                {
                    has_partial = true;
                    partial_ranges.push((*start_line, *end_line));
                }
            }
        }
    }
    assert!(has_partial, "PartialParagraph 항목이 존재해야 함");

    // 첫 파트는 start_line=0이어야 함
    assert_eq!(partial_ranges[0].0, 0, "첫 파트 start_line은 0이어야 함");

    // 파트가 연속적이어야 함 (이전 end_line == 다음 start_line)
    for i in 1..partial_ranges.len() {
        assert_eq!(
            partial_ranges[i - 1].1,
            partial_ranges[i].0,
            "파트 {}의 end_line({})이 파트 {}의 start_line({})과 일치해야 함",
            i - 1,
            partial_ranges[i - 1].1,
            i,
            partial_ranges[i].0,
        );
    }

    // 마지막 파트의 end_line은 전체 줄 수(10)여야 함
    assert_eq!(
        partial_ranges.last().unwrap().1,
        10,
        "마지막 파트 end_line은 전체 줄 수(10)여야 함"
    );
}

#[test]
fn test_short_paragraph_no_split() {
    // 1줄 짧은 문단은 FullParagraph로 유지
    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();
    let paras = vec![make_paragraph_with_height(400)];
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    assert_eq!(result.pages.len(), 1);
    let items = &result.pages[0].column_contents[0].items;
    assert!(
        matches!(items[0], PageItem::FullParagraph { .. }),
        "짧은 문단은 FullParagraph여야 함"
    );
}

#[test]
fn test_partial_paragraph_multi_page_span() {
    // 30줄 문단이 3페이지 이상에 걸치는지 확인
    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();
    let paras = vec![make_multiline_paragraph(30, 10000)]; // 30줄 x ~133px
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    assert!(
        result.pages.len() >= 3,
        "30줄 문단이 3페이지 이상이어야 함, pages={}",
        result.pages.len()
    );
}

#[test]
fn test_partial_paragraph_after_content() {
    // 기존 콘텐츠 뒤에 긴 문단이 올 때 올바르게 분할
    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();
    let paras = vec![
        make_multiline_paragraph(3, 10000), // 짧은 문단 (3줄 x ~133px = ~400px)
        make_multiline_paragraph(10, 10000), // 긴 문단 (10줄 x ~133px)
    ];
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    // 2페이지 이상
    assert!(result.pages.len() >= 2, "긴 문단이 페이지를 넘어야 함");

    // 첫 페이지에 첫 문단 FullParagraph + 두번째 문단 PartialParagraph
    let page1_items = &result.pages[0].column_contents[0].items;
    assert!(
        matches!(page1_items[0], PageItem::FullParagraph { para_index: 0 }),
        "첫 문단은 FullParagraph여야 함"
    );

    let has_partial_on_page1 = page1_items
        .iter()
        .any(|item| matches!(item, PageItem::PartialParagraph { para_index: 1, .. }));
    assert!(
        has_partial_on_page1,
        "첫 페이지에 두번째 문단의 PartialParagraph가 있어야 함"
    );
}

/// 셀 내용이 포함된 CellBreak 표 생성 헬퍼
fn make_cellbreak_table(
    row_count: u16,
    col_count: u16,
    cell_height: u32,
) -> crate::model::table::Table {
    use crate::model::paragraph::LineSeg;
    use crate::model::table::{Cell, Table, TablePageBreak};

    let mut cells = Vec::new();
    for r in 0..row_count {
        for c in 0..col_count {
            // 각 셀에 여러 줄의 문단을 넣어 높이를 키움
            let line_count = (cell_height / 1000) as usize;
            let line_segs: Vec<LineSeg> = (0..line_count.max(1))
                .map(|_| LineSeg {
                    line_height: 1000,
                    ..Default::default()
                })
                .collect();
            let para = Paragraph {
                line_segs,
                ..Default::default()
            };
            cells.push(Cell {
                row: r,
                col: c,
                row_span: 1,
                col_span: 1,
                height: cell_height,
                width: 5000,
                paragraphs: vec![para],
                ..Default::default()
            });
        }
    }
    Table {
        row_count,
        col_count,
        cells,
        page_break: TablePageBreak::CellBreak,
        ..Default::default()
    }
}

#[test]
#[ignore = "Task #993: 레거시 Paginator(engine.rs)는 분할 표 컷을 생산하지 않음 — TypesetEngine 컷 모델로 대체. advance_row_cut 단위 테스트(table_layout.rs row_cut_tests)가 인트라-로우 분할을 검증."]
fn test_table_cell_break_intra_row_split() {
    // CellBreak 표: 행이 페이지보다 크면 인트라-로우 분할 발생
    use crate::model::control::Control;

    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();

    // 1행 2열, 셀 높이 80000 HWPUNIT (>> A4 본문 ~60000 HWPUNIT)
    let table = make_cellbreak_table(1, 2, 80000);
    let mut table_para = Paragraph::default();
    table_para.controls.push(Control::Table(Box::new(table)));

    let paras = vec![table_para];
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    // 2페이지 이상이어야 함
    assert!(
        result.pages.len() >= 2,
        "CellBreak 큰 행이 분할되어야 함, pages={}",
        result.pages.len()
    );

    // split_start_content_offset 또는 split_end_content_limit > 0인 PartialTable 존재 확인
    let mut has_intra_split = false;
    for page in &result.pages {
        for col in &page.column_contents {
            for item in &col.items {
                if let PageItem::PartialTable {
                    start_cut, end_cut, ..
                } = item
                {
                    if !start_cut.is_empty() || !end_cut.is_empty() {
                        has_intra_split = true;
                    }
                }
            }
        }
    }
    assert!(
        has_intra_split,
        "CellBreak 표에 인트라-로우 분할이 발생해야 함"
    );
}

#[test]
#[ignore = "Task #993: 레거시 Paginator(engine.rs)는 분할 표 컷을 생산하지 않음 — TypesetEngine 컷 모델로 대체. advance_row_cut 단위 테스트(table_layout.rs row_cut_tests)가 인트라-로우 분할을 검증."]
fn test_table_none_also_intra_row_split() {
    // page_break=None 표도 인트라-로우 분할 적용 (모든 표에 적용)
    use crate::model::control::Control;
    use crate::model::table::TablePageBreak;

    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();

    // 1행 2열, 셀 높이 80000 HWPUNIT (>> A4 본문)
    let mut table = make_cellbreak_table(1, 2, 80000);
    table.page_break = TablePageBreak::None;

    let mut table_para = Paragraph::default();
    table_para.controls.push(Control::Table(Box::new(table)));

    let paras = vec![table_para];
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    // 2페이지 이상이어야 함
    assert!(
        result.pages.len() >= 2,
        "None 표도 큰 행이 분할되어야 함, pages={}",
        result.pages.len()
    );

    // 인트라-로우 분할이 발생해야 함
    let mut has_intra_split = false;
    for page in &result.pages {
        for col in &page.column_contents {
            for item in &col.items {
                if let PageItem::PartialTable {
                    start_cut, end_cut, ..
                } = item
                {
                    if !start_cut.is_empty() || !end_cut.is_empty() {
                        has_intra_split = true;
                    }
                }
            }
        }
    }
    assert!(
        has_intra_split,
        "None 표에도 인트라-로우 분할이 발생해야 함"
    );
}

#[test]
#[ignore = "Task #993: 레거시 Paginator(engine.rs)는 분할 표 컷을 생산하지 않음 — TypesetEngine 컷 모델로 대체. advance_row_cut 단위 테스트(table_layout.rs row_cut_tests)가 인트라-로우 분할을 검증."]
fn test_table_cell_break_multi_page_row() {
    // CellBreak: 하나의 행이 3페이지 이상에 걸치는 경우
    use crate::model::control::Control;

    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();

    // 1행 1열, 셀 높이 200000 HWPUNIT (~3페이지 분량)
    let table = make_cellbreak_table(1, 1, 200000);
    let mut table_para = Paragraph::default();
    table_para.controls.push(Control::Table(Box::new(table)));

    let paras = vec![table_para];
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    // 3페이지 이상
    assert!(
        result.pages.len() >= 3,
        "200000 HWPUNIT 행이 3+페이지에 걸쳐야 함, pages={}",
        result.pages.len()
    );

    // [Task #993] 시작 컷이 단조 전진하는지 확인 — 컷 합(셀별 소비 유닛 수의 합)
    // 을 진행도 지표로 사용. 첫 페이지=0(빈 컷), 이후 증가.
    let mut progress: Vec<usize> = Vec::new();
    for page in &result.pages {
        for col in &page.column_contents {
            for item in &col.items {
                if let PageItem::PartialTable { start_cut, .. } = item {
                    progress.push(start_cut.iter().sum());
                }
            }
        }
    }

    // 첫 페이지: 컷 합=0, 이후 페이지: 컷 합 > 0 증가
    if progress.len() >= 2 {
        assert_eq!(progress[0], 0, "첫 페이지 시작 컷은 비어 있어야 함");
        for i in 1..progress.len() {
            assert!(
                progress[i] > 0,
                "{}번째 페이지 시작 컷은 0보다 커야 함: {}",
                i + 1,
                progress[i]
            );
            if i >= 2 {
                assert!(
                    progress[i] > progress[i - 1],
                    "시작 컷이 증가해야 함: {} > {}",
                    progress[i],
                    progress[i - 1]
                );
            }
        }
    }
}

// ─── 타스크 198: 표 페이지 경계 분할 검증 테스트 ───

/// 10행 표가 페이지 하단에서 시작 → 행 단위 분리 검증 (S1)
#[test]
fn test_table_split_10rows_at_page_bottom() {
    use crate::model::control::Control;
    use crate::model::table::{Cell, Table};

    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();

    // 본문 영역 절반 이상을 채우는 텍스트 문단 (본문 ~826px, 500px 점유)
    let filler = make_multiline_paragraph(5, 7500); // 5줄 x ~100px = ~500px

    // 10행 표 (각 행 6000 HWPUNIT ≈ 80px → 총 ~800px, 남은 ~326px에 안 맞음)
    let mut cells = Vec::new();
    for r in 0..10u16 {
        for c in 0..2u16 {
            cells.push(Cell {
                row: r,
                col: c,
                row_span: 1,
                col_span: 1,
                height: 6000,
                width: 5000,
                ..Default::default()
            });
        }
    }
    let mut table_para = Paragraph::default();
    table_para.controls.push(Control::Table(Box::new(Table {
        row_count: 10,
        col_count: 2,
        cells,
        ..Default::default()
    })));

    let paras = vec![filler, table_para];
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    // 2페이지 이상으로 분할되어야 함
    assert!(
        result.pages.len() >= 2,
        "10행 표가 페이지 하단에서 분할되어야 함, pages={}",
        result.pages.len()
    );

    // PartialTable들의 행 범위를 수집
    let mut partials: Vec<(usize, usize)> = Vec::new();
    for page in &result.pages {
        for col in &page.column_contents {
            for item in &col.items {
                if let PageItem::PartialTable {
                    start_row, end_row, ..
                } = item
                {
                    partials.push((*start_row, *end_row));
                }
            }
        }
    }
    assert!(!partials.is_empty(), "PartialTable이 존재해야 함");

    // 첫 파트 start_row=0
    assert_eq!(partials[0].0, 0, "첫 파트 start_row은 0이어야 함");

    // 파트가 연속적이어야 함 (이전 end_row == 다음 start_row)
    for i in 1..partials.len() {
        assert_eq!(
            partials[i - 1].1,
            partials[i].0,
            "행 범위가 연속적이어야 함: 파트{} end_row={} ≠ 파트{} start_row={}",
            i - 1,
            partials[i - 1].1,
            i,
            partials[i].0
        );
    }

    // 마지막 파트 end_row=10
    assert_eq!(
        partials.last().unwrap().1,
        10,
        "마지막 파트 end_row은 전체 행 수(10)여야 함"
    );
}

/// 50행 대형 표 → 여러 페이지 분할 검증 (S2)
#[test]
fn test_table_split_50rows_multi_page() {
    use crate::model::control::Control;
    use crate::model::table::{Cell, Table};

    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();

    // 50행 표 (각 행 4000 HWPUNIT ≈ 53px → 총 ~2667px, 약 3~4페이지 필요)
    let mut cells = Vec::new();
    for r in 0..50u16 {
        cells.push(Cell {
            row: r,
            col: 0,
            row_span: 1,
            col_span: 1,
            height: 4000,
            width: 10000,
            ..Default::default()
        });
    }
    let mut table_para = Paragraph::default();
    table_para.controls.push(Control::Table(Box::new(Table {
        row_count: 50,
        col_count: 1,
        cells,
        ..Default::default()
    })));

    let paras = vec![table_para];
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    // 3페이지 이상
    assert!(
        result.pages.len() >= 3,
        "50행 대형 표가 3+페이지에 걸쳐야 함, pages={}",
        result.pages.len()
    );

    // 모든 PartialTable의 행 범위 수집
    let mut partials: Vec<(usize, usize)> = Vec::new();
    for page in &result.pages {
        for col in &page.column_contents {
            for item in &col.items {
                if let PageItem::PartialTable {
                    start_row, end_row, ..
                } = item
                {
                    partials.push((*start_row, *end_row));
                }
            }
        }
    }

    // 전체 50행이 빠짐없이 커버되어야 함
    assert_eq!(partials[0].0, 0, "첫 파트 start_row=0");
    for i in 1..partials.len() {
        assert_eq!(
            partials[i - 1].1,
            partials[i].0,
            "행 범위 연속: 파트{} end={}  ≠ 파트{} start={}",
            i - 1,
            partials[i - 1].1,
            i,
            partials[i].0
        );
    }
    assert_eq!(partials.last().unwrap().1, 50, "마지막 파트 end_row=50");

    // 각 파트의 행 범위가 비어있지 않아야 함
    for (i, (s, e)) in partials.iter().enumerate() {
        assert!(e > s, "파트{}: start_row={} >= end_row={}", i, s, e);
    }
}

/// 셀 내 중첩 표가 있는 행의 분할 검증 (S3)
#[test]
fn test_table_split_with_nested_table() {
    use crate::model::control::Control;
    use crate::model::paragraph::LineSeg;
    use crate::model::table::{Cell, Table};

    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();

    // 중첩 표: 10행, 각 행 높이 8000 HWPUNIT → ~1067px (본문 영역 826px 초과)
    let mut nested_cells = Vec::new();
    for r in 0..10u16 {
        nested_cells.push(Cell {
            row: r,
            col: 0,
            row_span: 1,
            col_span: 1,
            height: 8000,
            width: 5000,
            paragraphs: vec![Paragraph {
                line_segs: vec![LineSeg {
                    line_height: 8000,
                    ..Default::default()
                }],
                ..Default::default()
            }],
            ..Default::default()
        });
    }
    let nested_table = Table {
        row_count: 10,
        col_count: 1,
        cells: nested_cells,
        ..Default::default()
    };

    // 외부 표: 2행, 첫 행에 중첩 표 포함
    // 셀 높이를 중첩 표 전체 높이(~1067px)로 설정 → 본문 영역 초과 → 분할 필수
    let nested_h: i32 = 8000 * 10; // 80000 HWPUNIT
    let outer_cell_0 = Cell {
        row: 0,
        col: 0,
        row_span: 1,
        col_span: 1,
        height: nested_h as u32,
        width: 10000,
        paragraphs: vec![Paragraph {
            line_segs: vec![LineSeg {
                line_height: nested_h,
                ..Default::default()
            }],
            controls: vec![Control::Table(Box::new(nested_table))],
            ..Default::default()
        }],
        ..Default::default()
    };
    let outer_cell_1 = Cell {
        row: 1,
        col: 0,
        row_span: 1,
        col_span: 1,
        height: 5000,
        width: 10000,
        paragraphs: vec![Paragraph {
            line_segs: vec![LineSeg {
                line_height: 5000,
                ..Default::default()
            }],
            ..Default::default()
        }],
        ..Default::default()
    };

    let mut table_para = Paragraph::default();
    table_para.controls.push(Control::Table(Box::new(Table {
        row_count: 2,
        col_count: 1,
        cells: vec![outer_cell_0, outer_cell_1],
        ..Default::default()
    })));

    // 필러: 페이지의 절반을 채움
    let filler = make_multiline_paragraph(4, 7500);
    let paras = vec![filler, table_para];
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    // 페이지가 분할되어야 함
    assert!(
        result.pages.len() >= 2,
        "중첩 표가 있는 외부 표가 분할되어야 함, pages={}",
        result.pages.len()
    );

    // PartialTable 존재 확인
    let has_partial = result.pages.iter().any(|p| {
        p.column_contents.iter().any(|c| {
            c.items
                .iter()
                .any(|i| matches!(i, PageItem::PartialTable { .. }))
        })
    });
    assert!(
        has_partial,
        "중첩 표 포함 외부 표에 PartialTable이 존재해야 함"
    );
}

/// B-011 재현: 표 높이가 body area를 초과하지 않는지 검증 (S4)
#[test]
fn test_table_height_within_body_area() {
    use crate::model::control::Control;
    use crate::model::table::{Cell, Table};

    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();
    let page_def = a4_page_def();

    // A4 본문 영역 높이 계산 (HWPUNIT → px)
    let body_h_hwpunit = page_def.height as i32
        - page_def.margin_top as i32
        - page_def.margin_bottom as i32
        - page_def.margin_header as i32
        - page_def.margin_footer as i32;
    let body_h_px = crate::renderer::hwpunit_to_px(body_h_hwpunit, 96.0);

    // 여러 표를 순서대로 배치 (각 5행, 높이 10000 HWPUNIT)
    let mut paras = Vec::new();
    for _ in 0..5 {
        let mut cells = Vec::new();
        for r in 0..5u16 {
            for c in 0..2u16 {
                cells.push(Cell {
                    row: r,
                    col: c,
                    row_span: 1,
                    col_span: 1,
                    height: 10000,
                    width: 5000,
                    ..Default::default()
                });
            }
        }
        let mut table_para = Paragraph::default();
        table_para.controls.push(Control::Table(Box::new(Table {
            row_count: 5,
            col_count: 2,
            cells,
            ..Default::default()
        })));
        paras.push(table_para);
    }

    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &page_def,
        &ColumnDef::default(),
        0,
    );

    // 각 페이지의 콘텐츠 높이 합이 body area를 초과하지 않는지 확인
    for (page_idx, page) in result.pages.iter().enumerate() {
        for col in &page.column_contents {
            let mut height_sum = 0.0_f64;
            for item in &col.items {
                match item {
                    PageItem::FullParagraph { para_index } => {
                        let mp = measured.get_measured_paragraph(*para_index);
                        if let Some(m) = mp {
                            height_sum += m.total_height;
                        }
                    }
                    PageItem::Table { para_index, .. } => {
                        let mt = measured.get_measured_table(*para_index, 0);
                        if let Some(m) = mt {
                            height_sum += m.total_height;
                        }
                    }
                    PageItem::PartialTable {
                        para_index,
                        start_row,
                        end_row,
                        ..
                    } => {
                        let mt = measured.get_measured_table(*para_index, 0);
                        if let Some(m) = mt {
                            // cumulative_heights로 부분 높이 계산
                            let start_h = if *start_row > 0 {
                                m.cumulative_heights
                                    .get(*start_row - 1)
                                    .copied()
                                    .unwrap_or(0.0)
                            } else {
                                0.0
                            };
                            let end_h = m
                                .cumulative_heights
                                .get(*end_row - 1)
                                .copied()
                                .unwrap_or(m.total_height);
                            height_sum += end_h - start_h;
                        }
                    }
                    _ => {}
                }
            }
            // body area를 초과하면 안 됨 (약간의 여유 허용)
            assert!(
                height_sum <= body_h_px + 2.0,
                "page {} 콘텐츠 높이({:.1}px)가 body area({:.1}px)를 초과함",
                page_idx,
                height_sum,
                body_h_px
            );
        }
    }
}

/// [#2699] Bottom 캡션 예약이 호스트 문단의 음수 line_spacing 때문에 과소 계산되면
/// 마지막 표 행 + 캡션이 다음 페이지로 넘어가지 않고 본문 하단을 넘어 그려진다.
///
/// 음수 line_spacing 은 고정값 줄간격 TAC 표 마커(Task #9)로 실제 사용되는 값이며
/// (`engine.rs:977`, `layout.rs:5276`), 캡션 예약 계산은 같은 `line_segs.first()` 를 읽는다.
/// 클램프가 없으면 `caption_overhead` 가 |ls| 만큼 작아져
/// `end_row = end_row.saturating_sub(1)` 이 발동하지 않는다.
#[test]
fn bottom_caption_reserve_ignores_negative_host_line_spacing_issue2699() {
    use crate::model::control::Control;
    use crate::model::shape::{Caption, CaptionDirection};
    use crate::model::table::{Cell, Table};

    let paginator = Paginator::with_default_dpi();
    let styles = ResolvedStyleSet::default();

    // 본문 영역 ≈ 876.8px (a4_page_def 기준, 96 DPI).
    // 표 본체 높이는 피트 판단에서 캡션을 제외하므로(engine.rs:1861-1874) 캡션 예약은
    // 연속(continuation) 페이지에서 판정된다. 따라서 2페이지에 걸치는 표로 구성한다.
    //
    // 표: 20행 x 6000HU(=80px) = 1600px → 분할됨
    //   1페이지: 행 0..10 = 800px (11행이면 880px > 876.8px 이므로 10행)
    //   2페이지: 남은 행 10..20 = 800px → 행만으로는 들어감 (여유 76.8px)
    // 캡션: 10275HU(=137px) → 800 + 137 = 937px > 876.8px (60px 초과)
    //   → 마지막 행(19)을 3페이지로 넘기고 캡션도 함께 이동해야 한다.
    // 호스트 ls = -9000HU(=-120px): 클램프가 없으면 캡션 예약이 137-120=17px 로 줄어
    //   800 + 17 = 817px <= 876.8px (60px 여유) 가 되어 행 넘김이 발동하지 않고,
    //   행 19 + 캡션이 2페이지 본문 하단을 넘어 그려진다.
    let mut cells = Vec::new();
    for r in 0..20u16 {
        for c in 0..2u16 {
            cells.push(Cell {
                row: r,
                col: c,
                row_span: 1,
                col_span: 1,
                height: 6000,
                width: 5000,
                ..Default::default()
            });
        }
    }

    let caption_para = Paragraph {
        line_segs: vec![LineSeg {
            line_height: 10275,
            ..Default::default()
        }],
        ..Default::default()
    };

    let mut table_para = Paragraph {
        // 고정값 줄간격 TAC 표 마커와 동일한 형태의 음수 line_spacing
        line_segs: vec![LineSeg {
            line_height: 1000,
            line_spacing: -9000,
            ..Default::default()
        }],
        ..Default::default()
    };
    table_para.controls.push(Control::Table(Box::new(Table {
        row_count: 20,
        col_count: 2,
        cells,
        caption: Some(Caption {
            direction: CaptionDirection::Bottom,
            paragraphs: vec![caption_para],
            ..Default::default()
        }),
        ..Default::default()
    })));

    let paras = vec![table_para];
    let composed: Vec<ComposedParagraph> = Vec::new();
    let (result, _measured) = paginator.paginate(
        &paras,
        &composed,
        &styles,
        &a4_page_def(),
        &ColumnDef::default(),
        0,
    );

    let mut partials: Vec<(usize, usize)> = Vec::new();
    for page in &result.pages {
        for col in &page.column_contents {
            for item in &col.items {
                if let PageItem::PartialTable {
                    start_row, end_row, ..
                } = item
                {
                    partials.push((*start_row, *end_row));
                }
            }
        }
    }

    assert!(
        !partials.is_empty(),
        "표가 분할되어 PartialTable이 존재해야 함, pages={}",
        result.pages.len()
    );
    // 연속 페이지에서 남은 행(10..20)이 모두 들어가더라도 Bottom 캡션 예약분 때문에
    // 마지막 행은 다음 페이지로 넘어가야 한다. 음수 ls가 예약분을 깎으면 이 분할이 사라진다.
    assert_eq!(
        partials.len(),
        3,
        "캡션 예약으로 3개 파트(0..10, 10..19, 19..20)여야 함, partials={:?} pages={}",
        partials,
        result.pages.len()
    );
    assert_eq!(
        partials[1].1, 19,
        "연속 페이지 파트는 캡션 예약분 때문에 마지막 행(19)을 넘겨 end_row=19여야 함, partials={:?}",
        partials
    );
    assert_eq!(
        partials.last().unwrap().1,
        20,
        "마지막 파트 end_row은 전체 행 수(20)여야 함, partials={:?}",
        partials
    );
}