f-office-docx 0.2.2

DOCX model and Word's layout rules.
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
//! Rows and lines that move to the next page or split between pages.

use f_office_paint::DisplayList;

use crate::layout::testing::{
    NORMAL, SINGLE, at, base, du, filler, find, find_all, lay_out, lay_out_with_header, marked,
    on_base_with, p, pass_with, rects, table,
};
use crate::numbering::Numbering;
use crate::quirks::RowBelowHeaders;

#[test]
fn moves_a_row_that_does_not_fit_with_its_bottom_border() {
    let rows: &[(&str, &[&str])] = &[
        (r#"<w:trHeight w:val="150" w:hRule="exact"/>"#, &[&p("a")]),
        ("", &[&p("b")]),
    ];
    // 64 lines end at 14240 twips, and a 150 twip row fits above 14400.
    let plain = filler(64) + &table("", &[2000], rows);
    assert_eq!(find(&lay_out(&plain, NORMAL, None), 'a').0, 0);
    // With the table's 20 twip bottom line below the row, the line of its outer edge at the
    // page's foot, it no longer fits.
    let border = r#"<w:tblBorders><w:bottom w:val="single" w:sz="8"/><w:insideH w:val="single" w:sz="8"/></w:tblBorders>"#;
    let bordered = filler(64) + &table(border, &[2000], rows);
    let list = lay_out(&bordered, NORMAL, None);
    assert_eq!(find(&list, 'a'), (1, 1440 * 1270, base(1440)));
    // The second row comes below the 20 twip line between the rows.
    assert_eq!(find(&list, 'b').2, base(1590 + 20));
}

#[test]
fn starts_a_page_at_a_page_break_before_the_table_s_first_paragraph() {
    let first = r"<w:p><w:pPr><w:pageBreakBefore/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>";
    let flat = table("", &[2000], &[("", &[first])]);
    let nested = table("", &[3000], &[("", &[&(flat.clone() + &p("x"))])]);
    for (body, mode) in [(&flat, None), (&flat, Some(15)), (&nested, Some(15))] {
        let list = lay_out(&(p("z") + body + &p("b")), NORMAL, mode);
        let (page, _, baseline) = find(&list, 'a');
        assert_eq!((page, baseline), (1, base(1440)));
        assert_eq!(find(&list, 'z').0, 0);
    }
    // At the top of a page, the table stays there.
    assert_eq!(find(&lay_out(&flat, NORMAL, None), 'a').0, 0);
    // A break before a later paragraph of the cell starts no page.
    let later = table("", &[2000], &[("", &[&(p("c") + first)])]);
    assert_eq!(find(&lay_out(&(p("z") + &later), NORMAL, None), 'a').0, 0);
}

#[test]
fn needs_no_room_at_the_foot_for_a_line_between_rows() {
    let rows: &[(&str, &[&str])] = &[
        (r#"<w:trHeight w:val="150" w:hRule="exact"/>"#, &[&p("a")]),
        ("", &[&p("b")]),
    ];
    // The table's `w:insideH` goes with the next row, and the table has no bottom line, so the
    // first row fits. The second row starts the next page without a top line.
    let border = r#"<w:tblBorders><w:insideH w:val="single" w:sz="8"/></w:tblBorders>"#;
    let list = lay_out(&(filler(64) + &table(border, &[2000], rows)), NORMAL, None);
    assert_eq!(find(&list, 'a').0, 0);
    assert_eq!(find(&list, 'b'), (1, 1440 * 1270, base(1440)));
    assert!(rects(&list, 0).is_empty(), "{:?}", rects(&list, 0));
    assert!(rects(&list, 1).is_empty(), "{:?}", rects(&list, 1));
}

#[test]
fn ends_a_page_with_the_bottom_border_of_the_row_above_a_moved_row() {
    let rows: &[(&str, &[&str])] = &[
        (r#"<w:trHeight w:val="160" w:hRule="exact"/>"#, &[&p("a")]),
        ("", &[&p("b")]),
    ];
    // The first row starts at 14040 twips with the table's 10 twip top line and ends at 14200,
    // with room for the table's 10 twip bottom line below. The second row needs the line
    // between the rows and a line of 200 twips, and goes to the next page.
    let border = format!(
        "<w:tblBorders><w:top {SINGLE}/><w:bottom {SINGLE}/><w:insideH {SINGLE}/></w:tblBorders>"
    );
    let list = lay_out(&(filler(63) + &table(&border, &[2000], rows)), NORMAL, None);
    assert_eq!(find(&list, 'a').0, 0);
    assert_eq!(find(&list, 'b').0, 1);
    // The first row, now the last on its page, draws the table's bottom line below it.
    let foot = rects(&list, 0);
    assert!(
        foot.contains(&(du(1332), du(14200), du(2000), 2)),
        "{foot:?}"
    );
    // The second row starts the next page with the table's top line as its top border.
    assert!(rects(&list, 1).contains(&(du(1332), du(1440), du(2000), 2)));
}

#[test]
fn starts_a_page_with_the_top_line_of_a_cell_that_goes_on_with_a_merge() {
    // The second row goes on with the merge of the first column and sets no top line in its
    // second cell. It goes to the next page, where the merged cell draws its own top line and
    // the row takes the line's room.
    let line = format!("<w:tcBorders><w:top {SINGLE}/></w:tcBorders>");
    let start = format!(
        r#"<w:tcPr><w:vMerge w:val="restart"/>{line}</w:tcPr>{}"#,
        p("a")
    );
    let on = format!("<w:tcPr><w:vMerge/>{line}</w:tcPr><w:p/>");
    let none = format!(
        r#"<w:tcPr><w:tcBorders><w:top w:val="nil"/></w:tcBorders></w:tcPr>{}"#,
        p("d")
    );
    let rows: &[(&str, &[&str])] = &[("", &[&start, &p("b")]), ("", &[&on, &none])];
    // The first row runs from 14040 to 14250 twips, and the second does not fit below it.
    let list = lay_out(
        &(filler(63) + &table("", &[2000, 2000], rows)),
        NORMAL,
        None,
    );
    assert_eq!(find(&list, 'b').0, 0);
    let (page, _, y) = find(&list, 'd');
    assert_eq!((page, y), (1, base(1440 + 10)));
    let top = rects(&list, 1);
    assert!(
        top.iter().any(|&(_, y, _, h)| y == du(1440) && h == 2),
        "{top:?}"
    );
    // With an exact height of 160 twips, the first row ends at the page's foot and holds only
    // part of the merged cell's line, so the region carries its content onto the next page.
    // The carried line and the second row's line take the same top border there.
    let exact = r#"<w:trHeight w:val="160" w:hRule="exact"/>"#;
    let rows: &[(&str, &[&str])] = &[(exact, &[&start, &p("b")]), ("", &[&on, &none])];
    let list = lay_out(
        &(filler(64) + &table("", &[2000, 2000], rows)),
        NORMAL,
        None,
    );
    assert_eq!(find(&list, 'b').0, 0);
    assert_eq!((find(&list, 'a').0, find(&list, 'd').0), (1, 1));
    assert_eq!(find(&list, 'a').2, find(&list, 'd').2);
    assert_eq!(find(&list, 'd').2, base(1440 + 10));
}

#[test]
fn takes_the_lines_between_rows_in_a_table_above_the_top_margin() {
    // A floating table starts 630 twips above the top margin. Its rows below the first stand
    // above the margin too, but below a row of the table, so they take the 10 twip line between
    // rows and not the table's 60 twip top line.
    let props = format!(
        r#"<w:tblpPr w:tblpY="-630"/><w:tblBorders><w:top w:val="single" w:sz="24"/><w:insideH {SINGLE}/></w:tblBorders>"#
    );
    let rows: &[(&str, &[&str])] = &[("", &[&p("a")]), ("", &[&p("b")]), ("", &[&p("c")])];
    let list = lay_out(&table(&props, &[2000], rows), NORMAL, None);
    let (a, b, c) = (at(&list, 'a').1, at(&list, 'b').1, at(&list, 'c').1);
    assert!(b < base(1440), "{b}");
    // A row of 200 twips and a line of 10, within one step of the device grid.
    let row = base(1640 + 10) - base(1440);
    assert!((b - a - row).abs() <= 1, "{a} {b} {row}");
    assert!((c - b - row).abs() <= 1, "{b} {c} {row}");
}

#[test]
fn keeps_a_row_that_cannot_split_whole() {
    let tall = filler(3);
    let rows: &[(&str, &[&str])] = &[("<w:cantSplit/>", &[&format!("{tall}{}", p("z"))])];
    let list = lay_out(&(filler(62) + &table("", &[2000], rows)), NORMAL, None);
    assert_eq!(find(&list, 'z'), (1, 1440 * 1270, base(1440 + 600)));
    // A row at the top of a page that is taller than the page splits there.
    let tall = filler(70);
    let rows: &[(&str, &[&str])] = &[("<w:cantSplit/>", &[&format!("{tall}{}", p("z"))])];
    let list = lay_out(&table("", &[2000], rows), NORMAL, None);
    assert_eq!(find(&list, 'z'), (1, 1440 * 1270, base(1440 + 6 * 200)));
    // Below other lines, such a row moves to the next page and splits there.
    let list = lay_out(&(filler(62) + &table("", &[2000], rows)), NORMAL, None);
    assert_eq!(find(&list, 'z'), (2, 1440 * 1270, base(1440 + 6 * 200)));
}

#[test]
fn goes_on_with_a_row_over_three_pages() {
    // A page holds 64 lines of 200 twips. Of a cell of 150 lines and "z", 64 lines stand on
    // each of the first two pages, and "z" is the 23rd line of the third page.
    let cell = filler(150) + &p("z");
    let rows: &[(&str, &[&str])] = &[("", &[&cell, &p("a")])];
    let list = lay_out(&(table("", &[2000, 2000], rows) + &p("y")), NORMAL, None);
    assert_eq!(list.pages().len(), 3);
    assert_eq!(find(&list, 'a').0, 0);
    assert_eq!(find(&list, 'z'), (2, 1440 * 1270, base(1440 + 22 * 200)));
    // The paragraph after the table follows the row's last part.
    assert_eq!(find(&list, 'y').0, 2);
    assert_eq!(find(&list, 'y').2, base(1440 + 23 * 200));
}

#[test]
fn splits_a_row_of_a_table_in_a_long_row() {
    // The cell's 127 lines fill page 1 and all but one line of page 2. The table in the
    // cell comes next, with two lines in each of its two cells. Its row splits as a row of
    // the body does: the first line of each cell stays on page 2, and the second starts
    // the row's part on page 3.
    let pages_of = |row: &str| {
        let inner_rows: &[(&str, &[&str])] = &[(row, &[&(p("b") + &p("c")), &(p("d") + &p("e"))])];
        let cell = filler(127) + &table("", &[1000, 1000], inner_rows) + &p("z");
        let rows: &[(&str, &[&str])] = &[("", &[&cell, &p("a")])];
        let list = lay_out(&table("", &[2000, 2000], rows), NORMAL, None);
        assert_eq!(list.pages().len(), 3);
        ['b', 'c', 'd', 'e', 'z'].map(|label| find(&list, label).0)
    };
    assert_eq!(pages_of(""), [1, 2, 1, 2, 2]);
    // With `w:cantSplit` the row of the inner table goes to page 3 whole.
    assert_eq!(pages_of("<w:cantSplit/>"), [2, 2, 2, 2, 2]);
}

#[test]
fn breaks_a_table_in_a_cell_between_its_rows_on_each_page() {
    // A page holds 64 lines. The table in the cell has 150 rows of one line: 64 stand on
    // each of the pages 1 and 2, and 22 on page 3, with the line after the table.
    let row = |label: &str| ("", vec![p(label)]);
    let mut inner: Vec<(&str, Vec<String>)> = vec![row("b")];
    inner.extend((0..148).map(|_| row("x")));
    inner.push(row("c"));
    let cells: Vec<Vec<&str>> = inner
        .iter()
        .map(|(_, cells)| cells.iter().map(String::as_str).collect())
        .collect();
    let inner_rows: Vec<(&str, &[&str])> = cells.iter().map(|c| ("", c.as_slice())).collect();
    let cell = table("", &[2000], &inner_rows) + &p("z");
    let rows: &[(&str, &[&str])] = &[("", &[&cell])];
    let list = lay_out(&table("", &[2000], rows), NORMAL, None);
    assert_eq!(list.pages().len(), 3);
    assert_eq!(find(&list, 'b').0, 0);
    assert_eq!(find(&list, 'c').0, 2);
    assert_eq!(find(&list, 'z').0, 2);
    assert_eq!(find(&list, 'c').2, base(1440 + 21 * 200));
}

#[test]
fn moves_a_top_border_to_the_next_page_with_its_first_line() {
    // 64 lines leave less than a line on page 1, where the 0.5 pt line and its 1 pt space
    // alone have room. The border goes to page 2 with the text: page 1 has no line, and
    // the text of page 2 stands below the line, lower than a plain first line.
    let bordered = format!(
        r#"<w:p><w:pPr><w:pBdr><w:top {SINGLE} w:space="1"/></w:pBdr></w:pPr><w:r><w:t>b</w:t></w:r></w:p>"#
    );
    let list = lay_out(&(filler(64) + &bordered), NORMAL, None);
    let plain = lay_out(&(filler(64) + &p("b")), NORMAL, None);
    assert_eq!(find(&list, 'b').0, 1);
    assert_eq!(rects(&list, 0).len(), 0);
    assert_eq!(rects(&list, 1)[0].1, 300);
    assert!(find(&list, 'b').2 > find(&plain, 'b').2);
    // With one line less before it, the paragraph stays on page 1 with its border.
    let fits = lay_out(&(filler(63) + &bordered), NORMAL, None);
    assert_eq!(find(&fits, 'b').0, 0);
    assert_eq!(rects(&fits, 0).len(), 1);
}

#[test]
fn splits_a_row_that_cannot_split_in_a_table_with_a_placement() {
    // The table hangs on the text and is as wide as it, so it stays in the flow. From mode
    // 15 its row with `w:cantSplit` splits: "a" stays below 62 lines, and "z", four lines
    // lower, goes to the next page. In mode 14 the row moves whole.
    let cell = p("a") + &filler(3) + &p("z");
    let rows: &[(&str, &[&str])] = &[("<w:cantSplit/>", &[&cell])];
    let placed = table(
        r#"<w:tblpPr w:vertAnchor="text" w:tblpY="1"/><w:tblW w:w="9360" w:type="dxa"/>"#,
        &[9360],
        rows,
    );
    let body = filler(62) + &placed;
    let list = lay_out(&body, NORMAL, Some(15));
    assert_eq!(find(&list, 'a').0, 0);
    assert_eq!(find(&list, 'z').0, 1);
    let list = lay_out(&body, NORMAL, Some(14));
    assert_eq!(find(&list, 'a').0, 1);
}

#[test]
fn draws_the_bottom_line_of_a_cell_with_no_cell_below_once_above_a_moved_row() {
    // The first row starts at 14040 twips with the table's 10 twip top line and ends at 14200.
    // The second row leaves out the second grid column, so the first row draws the bottom line
    // of its second cell itself, and goes to the next page; the first row, now the last on its
    // page, draws the line of the table's outer edge below both cells again.
    let rows: &[(&str, &[&str])] = &[
        (
            r#"<w:trHeight w:val="160" w:hRule="exact"/>"#,
            &[&p("a"), &p("b")],
        ),
        (r#"<w:gridAfter w:val="1"/>"#, &[&p("c")]),
    ];
    let border = format!(
        "<w:tblBorders><w:top {SINGLE}/><w:bottom {SINGLE}/><w:insideH {SINGLE}/></w:tblBorders>"
    );
    let body = filler(63) + &table(&border, &[2000, 2000], rows);
    let list = lay_out(&body, NORMAL, None);
    assert_eq!(find(&list, 'a').0, 0);
    assert_eq!(find(&list, 'c').0, 1);
    let foot = rects(&list, 0);
    for x in [1332, 3332] {
        let line = (du(x), du(14200), du(2000), 2);
        assert_eq!(foot.iter().filter(|r| **r == line).count(), 1, "{foot:?}");
    }
    assert_eq!(super::doubled_lines(&list, 0), []);
}

#[test]
fn draws_only_the_outer_bottom_line_at_a_page_foot_over_a_column_that_the_next_row_leaves_out() {
    // As above, with a red inside line between the rows: the first row draws the red line
    // below its second cell, which the second row leaves out, before the second row moves to
    // the next page. The first row, now the last on its page, then draws the table's black
    // outer bottom line there, and the red line gives way to it.
    let rows: &[(&str, &[&str])] = &[
        (
            r#"<w:trHeight w:val="160" w:hRule="exact"/>"#,
            &[&p("a"), &p("b")],
        ),
        (r#"<w:gridAfter w:val="1"/>"#, &[&p("c")]),
    ];
    let border = format!(
        r#"<w:tblBorders><w:top {SINGLE}/><w:bottom {SINGLE}/><w:insideH {SINGLE} w:color="FF0000"/></w:tblBorders>"#
    );
    let body = filler(63) + &table(&border, &[2000, 2000], rows);
    let list = lay_out(&body, NORMAL, None);
    assert_eq!(find(&list, 'c').0, 1);
    let foot: Vec<(u8, i64)> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            f_office_paint::Item::Rect(r) if r.y.units() / crate::grid::DOT == du(14200) => {
                Some((r.color.r, r.x.units() / crate::grid::DOT))
            }
            _ => None,
        })
        .collect();
    for x in [1332, 3332] {
        let at: Vec<u8> = foot.iter().filter(|r| r.1 == du(x)).map(|r| r.0).collect();
        assert_eq!(at, [0], "{foot:?}");
    }
}

#[test]
fn draws_the_line_below_a_repeated_header_once_where_its_next_row_leaves_a_column_out() {
    // The header row's next row leaves out the second grid column, so the header row draws
    // the bottom line of its second cell itself. The third row cannot split and goes to the
    // next page, below the repeated header, where its top line lies at the same place.
    let tall = r#"<w:cantSplit/><w:trHeight w:val="3000" w:hRule="exact"/>"#;
    let rows: &[(&str, &[&str])] = &[
        ("<w:tblHeader/>", &[&p("h"), &p("i")]),
        (r#"<w:gridAfter w:val="1"/>"#, &[&p("c")]),
        (tall, &[&p("d"), &p("e")]),
    ];
    let border = format!(
        "<w:tblBorders><w:top {SINGLE}/><w:bottom {SINGLE}/><w:insideH {SINGLE}/></w:tblBorders>"
    );
    let list = lay_out(
        &(filler(55) + &table(&border, &[2000, 2000], rows)),
        NORMAL,
        None,
    );
    assert_eq!(find(&list, 'c').0, 0);
    assert_eq!(find(&list, 'd').0, 1);
    assert_eq!(find_all(&list, 'h').len(), 2);
    // On the next page the header row takes 10 + 200 twips below the top margin, and the line
    // below it runs under both cells once.
    let next = rects(&list, 1);
    for x in [1332, 3332] {
        let line = (du(x), du(1440 + 210), du(2000), 2);
        assert_eq!(next.iter().filter(|r| **r == line).count(), 1, "{next:?}");
    }
    assert_eq!(super::doubled_lines(&list, 1), []);
}

#[test]
fn centers_a_cell_merged_over_two_header_rows_on_the_next_page_as_on_the_first() {
    // The first cell is merged over both header rows and centered, so its text lies below the
    // first row's top by half a row on every page where the header stands.
    let first = r#"<w:tcPr><w:vMerge w:val="restart"/><w:vAlign w:val="center"/></w:tcPr><w:p><w:r><w:t>m</w:t></w:r></w:p>"#;
    let cells = [p("h"), p("i"), p("c"), p("d")];
    let (top, below, body): (&[&str], &[&str], &[&str]) = (
        &[first, &cells[0]],
        &[MERGE_ON, &cells[1]],
        &[&cells[2], &cells[3]],
    );
    let mut rows = vec![("<w:tblHeader/>", top), ("<w:tblHeader/>", below)];
    rows.extend(std::iter::repeat_n(("", body), 90));
    let list = lay_out(&table("", &[2000, 2000], &rows), NORMAL, None);
    let (merged, header) = (find_all(&list, 'm'), find_all(&list, 'h'));
    assert_eq!((merged.len(), header.len(), merged[1].0), (2, 2, 1));
    assert_eq!(merged[0].2 - header[0].2, merged[1].2 - header[1].2);
    assert!(merged[0].2 > header[0].2);
}

/// A header cell whose own bottom line is 3 pt wide (60 twips), above rows that the table's
/// 0.5 pt `w:insideH` (10 twips) separates.
fn wide_header_cell(text: &str) -> String {
    format!(
        r#"<w:tcPr><w:tcBorders><w:bottom w:val="single" w:sz="24"/></w:tcBorders></w:tcPr>{}"#,
        p(text)
    )
}

/// Lays out a body in the compatibility mode `mode` on the base target with the variant
/// `below` of the row below repeated header rows.
fn lay_out_below_headers(body: &str, mode: Option<u32>, below: RowBelowHeaders) -> DisplayList {
    let target = on_base_with(|p| p.with_variant(below));
    pass_with(body, (NORMAL, mode), None, Numbering::default(), target).list
}

/// The variants and modes of the row below repeated header rows, with the room in twips that
/// the row gets there: the header's 60 twip line below mode 15 where the row meets the last
/// header row, else the 10 twip line between it and the row before it.
const BELOW_HEADERS: [(RowBelowHeaders, Option<u32>, i64); 4] = [
    (RowBelowHeaders::LastHeader, Some(14), 60),
    (RowBelowHeaders::LastHeader, None, 60),
    (RowBelowHeaders::LastHeader, Some(15), 10),
    (RowBelowHeaders::RowBefore, Some(14), 10),
];

/// The width of the widest line that starts at `y` twips on `page`: the table's place across
/// the page depends on the mode, by other rules.
fn widest_line(list: &DisplayList, page: usize, y: i64) -> Option<i64> {
    rects(list, page)
        .into_iter()
        .filter(|r| r.1 == du(y))
        .map(|r| r.3)
        .max()
}

/// The places of the rows of the table of
/// `meets_the_bottom_line_of_the_repeated_header_with_a_row_that_moves` in one variant and
/// mode, with `room` twips above the moved row's text below the repeated header.
fn check_the_row_that_moves(list: &DisplayList, room: i64, label: &str) {
    assert_eq!(find(list, 'c').0, 0);
    assert_eq!(find(list, 'd').0, 1);
    // On the first page the header's line takes 60 twips above the second row's text.
    assert_eq!(find(list, 'h').2, base(MOVES_HEADER_TOP));
    assert_eq!(find(list, 'c').2, base(MOVES_SECOND_TOP));
    // On the next page the header row takes 10 + 200 twips below the top margin.
    assert_eq!(find_all(list, 'h')[2].2, base(1440 + 10));
    assert_eq!(find(list, 'd').2, base(1440 + 210 + room), "{label}");
}

/// The tops in twips of the header row's text and of the second row's text on the first page
/// of the table of `meets_the_bottom_line_of_the_repeated_header_with_a_row_that_moves`.
const MOVES_HEADER_TOP: i64 = 11_000 + 1440 + 10;
const MOVES_SECOND_TOP: i64 = MOVES_HEADER_TOP + 200 + 60;

#[test]
fn meets_the_bottom_line_of_the_repeated_header_with_a_row_that_moves() {
    // The third row cannot split and goes to the next page, below the repeated header. Where
    // it meets the last header row, the line drawn above it there is the header's 3 pt
    // bottom line, as above the second row on the first page, and not the 0.5 pt line below
    // the second row on the page before; below mode 15 its text starts below that line.
    let header = wide_header_cell("h");
    let tall = filler(10);
    let rows: &[(&str, &[&str])] = &[
        ("<w:tblHeader/>", &[&header, &header]),
        ("", &[&p("c"), &p("c")]),
        ("<w:cantSplit/>", &[&(p("d") + &tall), &p("d")]),
    ];
    let border = format!(
        "<w:tblBorders><w:top {SINGLE}/><w:bottom {SINGLE}/><w:insideH {SINGLE}/></w:tblBorders>"
    );
    let body = filler(55) + &table(&border, &[2000, 2000], rows);
    for (below, mode, room) in BELOW_HEADERS {
        let list = lay_out_below_headers(&body, mode, below);
        check_the_row_that_moves(&list, room, &format!("{below:?} {mode:?}"));
        let below_header = widest_line(&list, 1, 1440 + 210);
        // Where the row meets the last header row, the line below the repeated header is the
        // header's own, in every mode; else it is the line below the row before.
        let expected = match below {
            RowBelowHeaders::LastHeader => widest_line(&list, 0, MOVES_HEADER_TOP + 200),
            RowBelowHeaders::RowBefore => widest_line(&list, 0, MOVES_SECOND_TOP + 200),
        };
        assert_eq!(below_header, expected, "{below:?} {mode:?}");
    }
    // The header's line is the wider one.
    let list = lay_out_below_headers(&body, Some(14), RowBelowHeaders::LastHeader);
    let (header_line, second_line) = (
        widest_line(&list, 0, MOVES_HEADER_TOP + 200),
        widest_line(&list, 0, MOVES_SECOND_TOP + 200),
    );
    assert!(header_line > second_line, "{header_line:?} {second_line:?}");
}

#[test]
fn meets_the_bottom_line_of_the_repeated_header_with_the_part_of_a_split_row() {
    let header = wide_header_cell("h");
    let lines = filler(69) + &p("z");
    let rows: &[(&str, &[&str])] = &[
        ("<w:tblHeader/>", &[&header, &header]),
        ("", &[&p("b"), &p("b")]),
        ("", &[&lines, &p("y")]),
    ];
    let border = format!("<w:tblBorders><w:insideH {SINGLE}/><w:bottom {SINGLE}/></w:tblBorders>");
    let body = table(&border, &[2000, 2000], rows) + &p("e");
    for (below, mode, room) in BELOW_HEADERS {
        let list = lay_out_below_headers(&body, mode, below);
        // The header takes 200 twips, its line 60 twips above the second row, and the 0.5 pt
        // line 10 twips above the third. Lines of 200 twips fit while they end above 14400
        // twips less the 10 twip border below the row.
        let pages: Vec<usize> = find_all(&list, 'q').iter().map(|g| g.0).collect();
        assert_eq!(pages, [vec![0; 62], vec![1; 7]].concat());
        let (page, _, y) = find(&list, 'b');
        assert_eq!((page, y), (0, base(1440 + 260)));
        // On the next page the part of the row starts below the room of its variant and mode.
        let (page, _, y) = find(&list, 'z');
        assert_eq!(
            (page, y),
            (1, base(1440 + 200 + room + 7 * 200)),
            "{below:?} {mode:?}"
        );
    }
}

#[test]
fn splits_a_row_between_pages_below_the_repeated_header() {
    let lines = filler(69) + &p("z");
    let rows: &[(&str, &[&str])] = &[
        ("<w:tblHeader/>", &[&p("h"), &p("i")]),
        ("", &[&lines, &p("y")]),
    ];
    let border = format!("<w:tblBorders><w:insideH {SINGLE}/><w:bottom {SINGLE}/></w:tblBorders>");
    let list = lay_out(
        &(table(&border, &[2000, 2000], rows) + &p("e")),
        NORMAL,
        None,
    );
    // The header takes 200 twips and the second row starts with a 10 twip border. Lines of
    // 200 twips fit while they end above 14400 twips less the 10 twip border below the row.
    let pages: Vec<usize> = find_all(&list, 'q').iter().map(|g| g.0).collect();
    assert_eq!(pages, [vec![0; 63], vec![1; 6]].concat());
    assert_eq!(find(&list, 'y').0, 0);
    let headers = find_all(&list, 'h');
    assert_eq!(
        headers,
        vec![(0, 1440 * 1270, base(1440)), (1, 1440 * 1270, base(1440))]
    );
    assert_eq!(find(&list, 'z'), (1, 1440 * 1270, base(1650 + 6 * 200)));
    assert_eq!(
        find(&list, 'e'),
        (1, 1440 * 1270, base(1650 + 7 * 200 + 10))
    );
    // On the first page, the part of the row ends with the border below it.
    assert!(rects(&list, 0).contains(&(du(1332), du(1650 + 63 * 200), du(2000), 2)));
    assert!(rects(&list, 1).contains(&(du(1332), du(1650 + 7 * 200), du(2000), 2)));
}

#[test]
fn keeps_the_space_before_of_the_paragraph_that_starts_the_part_of_a_split_row() {
    let lines = filler(63) + &marked(r#"<w:spacing w:before="100"/>"#, "z") + &filler(5);
    let rows: &[(&str, &[&str])] = &[
        ("<w:tblHeader/>", &[&p("h"), &p("i")]),
        ("", &[&lines, &p("y")]),
    ];
    let border = format!("<w:tblBorders><w:insideH {SINGLE}/><w:bottom {SINGLE}/></w:tblBorders>");
    let list = lay_out(
        &(table(&border, &[2000, 2000], rows) + &p("e")),
        NORMAL,
        None,
    );
    // The first page holds 63 lines, as in the table without the space. The part on the next
    // page starts 1650 twips down, below the header, and "z" keeps its space before there.
    let pages: Vec<usize> = find_all(&list, 'q').iter().map(|g| g.0).collect();
    assert_eq!(pages, [vec![0; 63], vec![1; 5]].concat());
    assert_eq!(find(&list, 'z'), (1, 1440 * 1270, base(1650 + 100)));
}

#[test]
fn aligns_a_whole_cell_in_the_part_of_a_split_row_on_the_first_page() {
    let aligned = format!(r#"<w:tcPr><w:vAlign w:val="bottom"/></w:tcPr>{}"#, p("a"));
    let long = p("y").repeat(10);
    let rows: &[(&str, &[&str])] = &[("", &[&aligned, &long])];
    let list = lay_out(
        &(filler(60) + &table("", &[2000, 2000], rows)),
        NORMAL,
        None,
    );
    // The row starts at 13440 twips, and four lines of 200 twips stay on the first page, so
    // its part there ends at 14240. The one line of the aligned cell sits at its bottom.
    let pages: Vec<usize> = find_all(&list, 'y').iter().map(|g| g.0).collect();
    assert_eq!(pages, [vec![0; 4], vec![1; 6]].concat());
    let a = find(&list, 'a');
    assert_eq!((a.0, a.2), (0, base(14040)));
}

#[test]
fn aligns_a_split_cell_in_the_part_of_a_split_row_on_the_first_page_only() {
    // Column 1 has four 200-twip lines on page 0 (800 twips, ending at 14240; 960 twips fit
    // before the 14400 foot) and six on page 1 (1200 twips). Column 0 has a 200-twip line ('a')
    // on page 0 and an 800-twip line ('b') that does not fit in the remaining 760 twips, so
    // column 0 also splits across the page break with 600 twips free on page 0 and 400 twips
    // free on page 1.
    let tall_line = r#"<w:p><w:pPr><w:spacing w:line="800" w:lineRule="exact"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>"#;
    let aligned = format!(
        r#"<w:tcPr><w:vAlign w:val="bottom"/></w:tcPr>{}{tall_line}"#,
        p("a")
    );
    let long = p("y").repeat(10);
    let rows: &[(&str, &[&str])] = &[("", &[&aligned, &long])];
    let list = lay_out(
        &(filler(60) + &table("", &[2000, 2000], rows)),
        NORMAL,
        None,
    );
    // Page 0 part of the split cell aligns to the bottom of page 0's row part (14040 twips).
    let a = find(&list, 'a');
    assert_eq!((a.0, a.2), (0, base(14040)));
    // Page 1 continuation stays top-aligned at the top of page 1 (not shifted to the bottom of
    // page 1's 1200-twip row part).
    let b = find(&list, 'b');
    let top_aligned = {
        let top = format!(
            r#"<w:tcPr><w:vAlign w:val="top"/></w:tcPr>{}{tall_line}"#,
            p("a")
        );
        let top_rows: &[(&str, &[&str])] = &[("", &[&top, &long])];
        let top_list = lay_out(
            &(filler(60) + &table("", &[2000, 2000], top_rows)),
            NORMAL,
            None,
        );
        find(&top_list, 'b')
    };
    assert_eq!(b, top_aligned);
}

#[test]
fn moves_a_row_whose_lines_all_fit_but_whose_height_does_not() {
    let rows: &[(&str, &[&str])] = &[(r#"<w:trHeight w:val="600"/>"#, &[&p("a")])];
    let list = lay_out(&(filler(62) + &table("", &[2000], rows)), NORMAL, None);
    assert_eq!(find(&list, 'a').0, 1);
}

#[test]
fn moves_a_row_whole_when_widow_control_keeps_a_cell_off_the_page() {
    // Glyphs are 100 twips wide, so each word of 15 letters fills a line of the cell.
    let words = "bbbbbbbbbbbbbbb bbbbbbbbbbbbbbb bbbbbbbbbbbbbbb";
    let rows: &[(&str, &[&str])] = &[("", &[&p("a"), &p(words)])];
    let body = filler(62) + &table("", &[2000, 2000], rows);
    // 62 lines end at 13840 twips, so two lines of the row fit above 14400. Before Word 2013,
    // the row splits there and leaves the third line of the paragraph alone. From Word 2013
    // on, widow control keeps the paragraph whole, its cell keeps nothing on the first page,
    // and the whole row moves.
    assert_eq!(find(&lay_out(&body, NORMAL, Some(14)), 'a').0, 0);
    assert_eq!(find(&lay_out(&body, NORMAL, Some(15)), 'a').0, 1);
}

#[test]
fn keeps_widow_control_in_the_later_parts_of_a_split_cell_on_a_target_that_asks() {
    use crate::quirks::LaterPartWidows;
    // Glyphs are 100 twips wide, so each word of 15 letters fills a line of the cell.
    let words = "bbbbbbbbbbbbbbb bbbbbbbbbbbbbbb bbbbbbbbbbbbbbb";
    // 64 lines of 200 twips fit on a page. After 127 single lines, the first line of the
    // paragraph is the last line of the row's second part; after 126, its last line is the
    // first of the third part. Applied, widow control moves the paragraph whole to the third
    // part in both; ignored, the line stays alone.
    for (before, ignored) in [(127, [1, 2, 2]), (126, [1, 1, 2])] {
        let cell = p("q").repeat(before) + &p(words) + &p("z");
        let rows: &[(&str, &[&str])] = &[("", &[&cell])];
        let body = table("", &[2000], rows);
        for (widows, pages) in [
            (LaterPartWidows::Ignored, ignored),
            (LaterPartWidows::Applied, [2, 2, 2]),
        ] {
            let target = on_base_with(|p| p.with_variant(widows));
            let pass = pass_with(
                &body,
                (NORMAL, Some(15)),
                None,
                Numbering::default(),
                target,
            );
            let lines: Vec<usize> = find_all(&pass.list, 'b')
                .iter()
                .step_by(15)
                .map(|glyph| glyph.0)
                .collect();
            assert_eq!(lines, pages, "{widows:?} after {before} lines");
        }
    }
}

#[test]
fn fills_each_part_of_a_split_row_on_a_target_that_asks() {
    use crate::quirks::SplitRowFills;
    // A gray cell of one line beside a cell of 100 lines, of which 64 fit on the first page:
    // the row splits there, and the gray cell's content ends on the first page.
    let gray = r#"<w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/></w:tcPr>"#;
    let first = format!("{gray}{}", p("a"));
    let second = p("q").repeat(100);
    let rows: &[(&str, &[&str])] = &[("", &[&first, &second])];
    let body = table("", &[2000, 2000], rows);
    let gray_fills = |list: &DisplayList, page: usize| -> Vec<(i64, i64)> {
        list.pages()[page]
            .items()
            .iter()
            .filter_map(|item| match item {
                f_office_paint::Item::Rect(r) if r.color.r == 0xD9 => {
                    Some((r.y.units(), r.y.units() + r.height.units()))
                }
                _ => None,
            })
            .collect()
    };
    for fills in [SplitRowFills::Unfilled, SplitRowFills::EachPart] {
        let target = on_base_with(|p| p.with_variant(fills));
        let pass = pass_with(&body, (NORMAL, None), None, Numbering::default(), target);
        let lines: Vec<usize> = find_all(&pass.list, 'q').iter().map(|q| q.0).collect();
        assert_eq!(lines.iter().filter(|page| **page == 1).count(), 36);
        let (first, second) = (gray_fills(&pass.list, 0), gray_fills(&pass.list, 1));
        if fills == SplitRowFills::Unfilled {
            assert_eq!((first.len(), second.len()), (0, 0));
            continue;
        }
        // Each part is filled from the body's top, where the row starts, down to its last line.
        let twips = |twips: i64| twips * f_office_units::Length::UNITS_PER_TWIP;
        assert_eq!(first, [(twips(1440), twips(1440 + 64 * 200))]);
        assert_eq!(second, [(twips(1440), twips(1440 + 36 * 200))]);
    }
}

#[test]
fn keeps_the_later_part_whole_when_a_widow_break_of_the_part_before_comes_too_late() {
    use crate::layout::testing::AnchoredShape;
    use crate::quirks::LaterPartWidows;
    let words = "bbbbbbbbbbbbbbb ".repeat(6);
    // After a line of the body and 58 single lines of the cell, the forecast of widow control
    // keeps five lines of the paragraph on the first page and breaks before its fifth. A band
    // across the page below the paragraph's first line moves its second line past the foot,
    // so the paragraph goes on on the next page before that break: the break no longer
    // applies there, and the four lines stay on that page.
    let band = AnchoredShape {
        across: ("page", 0),
        down: ("page", 673 * 12_700),
        size: (612 * 12_700, 60 * 12_700),
        wrap: "<wp:wrapTopAndBottom/>",
        outline: None,
        text: None,
    }
    .drawing();
    let cell = p("q").repeat(58) + &p(&words) + &p("z");
    let rows: &[(&str, &[&str])] = &[("", &[&cell])];
    let body = format!("<w:p><w:r>{band}<w:t>a</w:t></w:r></w:p>") + &table("", &[2000], rows);
    for widows in [LaterPartWidows::Ignored, LaterPartWidows::Applied] {
        let target = on_base_with(|p| p.with_variant(widows));
        let pass = pass_with(
            &body,
            (NORMAL, Some(15)),
            None,
            Numbering::default(),
            target,
        );
        let lines: Vec<usize> = find_all(&pass.list, 'b')
            .iter()
            .step_by(15)
            .map(|glyph| glyph.0)
            .collect();
        assert_eq!(lines, [0, 1, 1, 1, 1, 1], "{widows:?}");
    }
}

#[test]
fn moves_a_row_whole_when_the_space_after_of_kept_lines_does_not_fit() {
    // Three lines of 200 twips start at 13640 twips and end at 14240, above 14400. With
    // 200 twips after, the last line has no room, `w:keepLines` keeps the paragraph whole,
    // and the row moves. With 100 twips after, the row stays.
    let words = "bbbbbbbbbbbbbbb bbbbbbbbbbbbbbb bbbbbbbbbbbbbbb";
    let kept = |after: u32| {
        let cell = format!(
            r#"<w:p><w:pPr><w:keepLines/><w:spacing w:after="{after}"/></w:pPr><w:r><w:t>{words}</w:t></w:r></w:p>"#
        );
        let rows: &[(&str, &[&str])] = &[("", &[&p("a"), &cell])];
        lay_out(
            &(filler(61) + &table("", &[2000, 2000], rows)),
            NORMAL,
            Some(15),
        )
    };
    assert_eq!(find(&kept(200), 'a').0, 1);
    assert_eq!(find(&kept(100), 'a').0, 0);
}

#[test]
fn splits_a_row_whose_overflow_is_only_empty_paragraphs() {
    // Below 60 lines, the cell's "a" and three empty paragraphs fit above 14400 twips, and
    // three more empty paragraphs go to the next page, above the "z" after the table.
    let cell = p("a") + &"<w:p/>".repeat(6);
    let rows: &[(&str, &[&str])] = &[("", &[&cell])];
    let body = filler(60) + &table("", &[2000], rows) + &p("z");
    let list = lay_out(&body, NORMAL, None);
    assert_eq!(find(&list, 'a').0, 0);
    assert_eq!(find(&list, 'z'), (1, 1440 * 1270, base(1440 + 3 * 200)));
}

#[test]
fn splits_a_row_whose_overflow_is_only_its_last_empty_line() {
    // Below 63 lines, the cell's "a" fits, and only its empty last paragraph does not: it
    // starts the next page, above the "z" after the table.
    let cell = p("a") + "<w:p/>";
    let rows: &[(&str, &[&str])] = &[("", &[&cell])];
    let body = filler(63) + &table("", &[2000], rows) + &p("z");
    let list = lay_out(&body, NORMAL, None);
    assert_eq!(find(&list, 'a').0, 0);
    assert_eq!(find(&list, 'z'), (1, 1440 * 1270, base(1440 + 200)));
}

#[test]
fn splits_a_row_after_an_empty_first_paragraph() {
    // Below 63 lines, only the cell's empty first paragraph fits, and "a" starts the next page.
    let cell = "<w:p/>".to_owned() + &p("a") + "<w:p/>";
    let rows: &[(&str, &[&str])] = &[("", &[&cell])];
    let list = lay_out(&(filler(63) + &table("", &[2000], rows)), NORMAL, None);
    assert_eq!(find(&list, 'a'), (1, 1440 * 1270, base(1440)));
}

#[test]
fn moves_a_row_whose_minimum_height_does_not_fit() {
    // Below 63 lines, one line of the cell fits. A minimum height of 150 twips fits too, and
    // the row splits; one of 600 twips does not, and the row moves whole.
    let cell = p("a") + &p("b");
    let low: &[(&str, &[&str])] = &[(r#"<w:trHeight w:val="150"/>"#, &[&cell])];
    let list = lay_out(&(filler(63) + &table("", &[2000], low)), NORMAL, None);
    assert_eq!((find(&list, 'a').0, find(&list, 'b').0), (0, 1));
    // The part on the next page has the minimum height again: 300 twips, where the one
    // line of 200 twips needs less.
    let three = p("c") + &cell;
    let mid: &[(&str, &[&str])] = &[(r#"<w:trHeight w:val="300"/>"#, &[&three])];
    let body = filler(62) + &table("", &[2000], mid) + &p("z");
    let list = lay_out(&body, NORMAL, None);
    assert_eq!((find(&list, 'a').0, find(&list, 'b').0), (0, 1));
    assert_eq!(find(&list, 'z'), (1, 1440 * 1270, base(1440 + 300)));
    let tall: &[(&str, &[&str])] = &[(r#"<w:trHeight w:val="600"/>"#, &[&cell])];
    let list = lay_out(&(filler(63) + &table("", &[2000], tall)), NORMAL, None);
    assert_eq!(find(&list, 'a'), (1, 1440 * 1270, base(1440)));
}

#[test]
fn moves_a_row_of_which_no_line_fits() {
    let rows: &[(&str, &[&str])] = &[("", &[&(p("a") + &p("b"))])];
    let list = lay_out(&(filler(64) + &table("", &[2000], rows)), NORMAL, None);
    assert_eq!(find(&list, 'a'), (1, 1440 * 1270, base(1440)));
}

/// Lays out 60 lines and a row of one cell with the paragraphs "a", "z" and "y", which each
/// have `after` twips after. The row starts at 13440 twips.
fn spaced_row(after: u32) -> DisplayList {
    let spaced = |ch: &str| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:after="{after}"/></w:pPr><w:r><w:t>{ch}</w:t></w:r></w:p>"#
        )
    };
    let cell = spaced("a") + &spaced("z") + &spaced("y");
    let rows: &[(&str, &[&str])] = &[("", &[&cell])];
    lay_out(&(filler(60) + &table("", &[2000], rows)), NORMAL, None)
}

#[test]
fn keeps_a_last_line_in_a_split_row_only_with_its_space_after() {
    // With 300 twips after, the line "z" ends at 14140 twips and its space after at 14440,
    // below the bottom margin at 14400.
    let list = spaced_row(300);
    assert_eq!(find(&list, 'a').0, 0);
    assert_eq!(find(&list, 'z').0, 1);
    // With 250 twips after, the space after ends at 14340, and "z" stays.
    let list = spaced_row(250);
    assert_eq!(find(&list, 'z').0, 0);
    assert_eq!(find(&list, 'y').0, 1);
}

/// A cell that starts a merged cell, with one paragraph for each character of `lines`.
fn merge_start(lines: &str) -> String {
    let content: String = lines.chars().map(|ch| p(&ch.to_string())).collect();
    format!(r#"<w:tcPr><w:vMerge w:val="restart"/></w:tcPr>{content}"#)
}

/// A cell that goes on with the merged cell above it.
const MERGE_ON: &str = "<w:tcPr><w:vMerge/></w:tcPr><w:p/>";

/// The page and the baseline of the first glyph of a character.
fn place(list: &DisplayList, ch: char) -> (usize, i64) {
    let (page, _, baseline) = find(list, ch);
    (page, baseline)
}

#[test]
fn carries_the_lines_of_a_merged_cell_on_to_the_next_page() {
    let merged = merge_start("abcd");
    let rows: &[(&str, &[&str])] = &[
        ("", &[&p("e"), &merged]),
        ("", &[&p("g"), MERGE_ON]),
        ("", &[&p("h"), &p("i")]),
    ];
    let list = lay_out(
        &(filler(62) + &table("", &[2000, 2000], rows)),
        NORMAL,
        None,
    );
    // The table starts at 13840 twips, and two lines of 200 twips fit above 14400. The
    // merged cell's other two lines start the next page.
    assert_eq!(place(&list, 'b'), (0, base(14040)));
    assert_eq!(place(&list, 'g'), (0, base(14040)));
    assert_eq!(place(&list, 'c'), (1, base(1440)));
    assert_eq!(place(&list, 'd'), (1, base(1640)));
    // The merged cell's last row splits to hold them, although its own cell fits, and the
    // next row stands below them.
    assert_eq!(place(&list, 'h'), (1, base(1840)));
}

/// The page and the exact baseline of each glyph of a character.
fn baselines(list: &DisplayList, ch: char) -> Vec<(usize, f_office_units::Length)> {
    let mut out = Vec::new();
    let pages = list.pages().iter().map(f_office_paint::Page::painted);
    for (page, painted) in pages.enumerate() {
        for item in painted {
            let f_office_paint::Painted::Glyphs(run) = item else {
                continue;
            };
            for glyph in &run.glyphs {
                if run
                    .glyph_text(glyph)
                    .is_some_and(|text| text.starts_with(ch))
                {
                    out.push((page, glyph.y));
                }
            }
        }
    }
    out
}

#[test]
fn moves_the_lines_that_a_merged_cell_carries_to_a_dot_on_a_target_that_does() {
    use crate::quirks::CarriedMergeMove;
    // The table starts at 13840 twips; the merged cell's first two rows fit above 14400 with
    // its lines `a` and `b`, and its last row moves to the next page, where the merged cell
    // carries its lines `c` and `d`. The table's borders, of a few eighths of a point, are no
    // whole number of dots, and the row that starts the next page stands below its top border
    // there.
    let merged = merge_start("abcd");
    let rows: &[(&str, &[&str])] = &[
        ("", &[&p("e"), &merged]),
        ("", &[&p("g"), MERGE_ON]),
        ("", &[&p("h"), MERGE_ON]),
        ("", &[&p("i"), &p("j")]),
    ];
    let mut checked = 0;
    for target in crate::Target::all() {
        let profile = crate::profile::Profile::of(target).expect("the profile reads");
        let device = profile.device();
        let quirks = profile.quirks();
        if quirks.carried_merge_move != CarriedMergeMove::ToDot {
            continue;
        }
        checked += 1;
        let carried = |eighths: u32, rule| {
            let line = format!(r#"w:val="single" w:sz="{eighths}""#);
            let borders = format!(
                "<w:tblBorders><w:top {line}/><w:bottom {line}/><w:insideH {line}/></w:tblBorders>"
            );
            let body = filler(62) + &table(&borders, &[2000, 2000], rows);
            let carried = profile.with_variant(rule);
            let target = (carried.device(), carried.quirks());
            let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
            [baselines(&list, 'c')[0], baselines(&list, 'd')[0]]
        };
        let mut off = 0;
        for eighths in [2, 3, 4, 6] {
            for (page, baseline) in carried(eighths, CarriedMergeMove::ToDot) {
                assert_eq!((page, device.snap(baseline)), (1, baseline), "{eighths}");
            }
            let exact = carried(eighths, CarriedMergeMove::Exact);
            off += exact.iter().filter(|(_, y)| device.snap(*y) != *y).count();
        }
        // Moved by the exact distance, the carried lines lie off the dots with some borders.
        assert!(off > 0);
    }
    assert!(checked > 0);
}

#[test]
fn turns_the_text_of_a_merged_cell_over_its_part_before_a_page_break() {
    let merged = merge_start("ab").replace(
        r#"<w:vMerge w:val="restart"/>"#,
        r#"<w:vMerge w:val="restart"/><w:textDirection w:val="btLr"/>"#,
    );
    let rows: &[(&str, &[&str])] = &[
        ("", &[&p("e"), &merged]),
        ("", &[&p("g"), MERGE_ON]),
        ("", &[&p("h"), MERGE_ON]),
    ];
    let list = lay_out(
        &(filler(63) + &table("", &[2000, 2000], rows)),
        NORMAL,
        None,
    );
    // The table starts at 14040 twips, and its second row moves to the next page.
    assert_eq!(place(&list, 'e'), (0, base(14040)));
    assert_eq!(place(&list, 'g'), (1, base(1440)));
    // The region's text turns over its part on the first page: two lines side by side, the
    // first one left of the second, each reading up from the part's bottom.
    let ((a_page, ax, ay), (b_page, bx, by)) = (find(&list, 'a'), find(&list, 'b'));
    assert_eq!((a_page, b_page), (0, 0));
    assert!(ax < bx);
    assert_eq!(ay, by);
    assert!(ay > base(14040));
    assert!(super::run_of(&list, 'a').turn.is_some());
}

#[test]
fn grows_only_the_last_row_of_a_merged_cell_that_a_page_ends_in() {
    let merged = merge_start("abcd");
    let rows: &[(&str, &[&str])] = &[
        ("", &[&p("e"), &merged]),
        ("", &[&p("g"), MERGE_ON]),
        ("", &[&p("h"), MERGE_ON]),
        ("", &[&p("i"), &p("j")]),
    ];
    let list = lay_out(
        &(filler(63) + &table("", &[2000, 2000], rows)),
        NORMAL,
        None,
    );
    // The table starts at 14040 twips, where one line fits. The second row moves to the next
    // page, and the merged cell's other three lines go on at its top.
    assert_eq!(place(&list, 'a'), (0, base(14040)));
    assert_eq!(place(&list, 'b'), (1, base(1440)));
    assert_eq!(place(&list, 'd'), (1, base(1840)));
    // The rows beside them keep the heights of their own cells, and only the merged cell's
    // last row grows.
    assert_eq!(place(&list, 'g'), (1, base(1440)));
    assert_eq!(place(&list, 'h'), (1, base(1640)));
    assert_eq!(place(&list, 'i'), (1, base(2040)));
}

#[test]
fn leaves_a_merged_cell_out_of_the_height_of_a_split_row_on_the_next_page() {
    let merged = merge_start("abcde");
    let split: String = ["k", "l", "m"].map(p).concat();
    let rows: &[(&str, &[&str])] = &[
        ("", &[&merged, &split]),
        ("", &[MERGE_ON, &p("g")]),
        ("", &[MERGE_ON, &p("h")]),
        ("", &[&p("i"), &p("j")]),
    ];
    let list = lay_out(
        &(filler(62) + &table("", &[2000, 2000], rows)),
        NORMAL,
        None,
    );
    // The first row splits with two lines of each cell on the first page.
    assert_eq!(place(&list, 'l'), (0, base(14040)));
    assert_eq!(place(&list, 'm'), (1, base(1440)));
    assert_eq!(place(&list, 'c'), (1, base(1440)));
    assert_eq!(place(&list, 'e'), (1, base(1840)));
    // Its part on the next page is as tall as the cell that ends in it, and the next rows
    // stand beside the merged cell's lines.
    assert_eq!(place(&list, 'g'), (1, base(1640)));
    assert_eq!(place(&list, 'h'), (1, base(1840)));
    assert_eq!(place(&list, 'i'), (1, base(2040)));
}

/// The pages of the filler lines in a laid out document.
fn filler_pages(list: &DisplayList) -> Vec<usize> {
    find_all(list, 'q').iter().map(|g| g.0).collect()
}

#[test]
fn keeps_room_for_the_border_below_a_split_row() {
    let border = r#"<w:tblBorders><w:insideH w:val="single" w:sz="40"/><w:bottom w:val="single" w:sz="40"/></w:tblBorders>"#;
    let rows: &[(&str, &[&str])] = &[("", &[&p("h")]), ("", &[&filler(70)])];
    let list = lay_out(&table(border, &[2000], rows), NORMAL, None);
    // The lines start at 1640 + 100 twips and must end above 14400 - 100 twips.
    assert_eq!(filler_pages(&list), [vec![0; 62], vec![1; 8]].concat());
}

#[test]
fn keeps_room_for_the_bottom_margin_of_a_split_cell() {
    let margins = r#"<w:tblCellMar><w:bottom w:w="150" w:type="dxa"/></w:tblCellMar>"#;
    let rows: &[(&str, &[&str])] = &[("", &[&p("h")]), ("", &[&filler(70)])];
    let list = lay_out(&table(margins, &[2000], rows), NORMAL, None);
    // The lines start at 1440 + 350 twips and must end above 14400 - 150 twips.
    assert_eq!(filler_pages(&list), [vec![0; 62], vec![1; 8]].concat());
}

#[test]
fn gives_a_cell_without_lines_on_the_next_page_its_margins_there() {
    let wide = r#"<w:tcPr><w:tcMar><w:top w:w="300" w:type="dxa"/><w:bottom w:w="300" w:type="dxa"/></w:tcMar></w:tcPr><w:p/>"#;
    let rows: &[(&str, &[&str])] = &[("", &[&p("h"), &p("i")]), ("", &[&filler(64), wide])];
    let list = lay_out(&(table("", &[2000, 2000], rows) + &p("e")), NORMAL, None);
    // Both cells have the row's largest margins, 300 twips above and below. Four lines go to
    // the next page, where the other cell still has its 600 twips of margins.
    assert_eq!(filler_pages(&list), [vec![0; 60], vec![1; 4]].concat());
    assert_eq!(find(&list, 'e'), (1, 1440 * 1270, base(1440 + 600 + 800)));
}

#[test]
fn splits_rows_with_cell_margins() {
    let margins = r#"<w:tblCellMar><w:top w:w="20" w:type="dxa"/><w:bottom w:w="40" w:type="dxa"/></w:tblCellMar><w:tblBorders><w:insideH w:val="single" w:sz="8"/><w:bottom w:val="single" w:sz="8"/></w:tblBorders>"#;
    let left = filler(69) + &p("y");
    let right = filler(68) + &p("z");
    let rows: &[(&str, &[&str])] = &[("", &[&p("h"), &p("i")]), ("", &[&left, &right])];
    let list = lay_out(&table(margins, &[2000, 2000], rows), NORMAL, None);
    // The second row starts at 1440 + 260 twips with a 20 twip border and a 20 twip margin.
    // Lines fit while they end above 14400 less the 20 twip border and the 40 twip margin.
    let pages: Vec<usize> = find_all(&list, 'q').iter().map(|g| g.0).collect();
    assert_eq!(pages, [vec![0; 126], vec![1; 11]].concat());
    // On page 1, the border below the row comes after the bottom margin of the cells.
    let end = 1740 + 63 * 200 + 40;
    assert!(rects(&list, 0).contains(&(du(1332), du(end), du(2000), 4)));
    // On page 2, the row starts as a row that starts a page: without a line, since the table
    // has no top line, and the cells with their top margin.
    assert_eq!(at(&list, 'y').1, base(1440 + 20 + 6 * 200));
    assert_eq!(at(&list, 'z').1, base(1440 + 20 + 5 * 200));
    let bottom = 1460 + 7 * 200 + 40;
    assert!(rects(&list, 1).contains(&(du(1332), du(bottom), du(2000), 4)));
}

#[test]
fn lays_out_tables_in_headers_and_splits_rows_below_them() {
    // A header table of five lines from the 720 twip header distance ends at 1720 twips, so
    // the body starts there on every page.
    let lines: String = ["h", "i", "j", "k", "l"].map(p).concat();
    let header = table("", &[2000], &[("", &[&lines])]);
    let rows: &[(&str, &[&str])] = &[("", &[&filler(70)])];
    let list = lay_out_with_header(&table("", &[2000], rows), NORMAL, None, Some(&header));
    assert_eq!(find_all(&list, 'h').len(), 2);
    assert_eq!(at(&list, 'i').1, base(720 + 200));
    // Lines from 1720 twips fit while they end above 14400 twips: 63 on the first page.
    assert_eq!(filler_pages(&list), [vec![0; 63], vec![1; 7]].concat());
    let second: Vec<i64> = find_all(&list, 'q')
        .iter()
        .filter(|g| g.0 == 1)
        .map(|g| g.2)
        .collect();
    assert_eq!(second[0], base(1720));
}

#[test]
fn keeps_the_body_at_a_fixed_top_margin_below_a_deeper_header() {
    // The header table of five lines ends at 1720 twips. A top margin of 1440 twips pushes
    // the body below it, and the same margin written as a negative number keeps it at 1440.
    let lines: String = ["h", "i", "j", "k", "l"].map(p).concat();
    let header = table("", &[2000], &[("", &[&lines])]);
    let first = |top: i64| {
        let body = p("b") + &format!(r#"<w:sectPr><w:pgMar w:top="{top}"/></w:sectPr>"#);
        let list = lay_out_with_header(&body, NORMAL, None, Some(&header));
        at(&list, 'b').1
    };
    assert_eq!((first(1440), first(-1440)), (base(1720), base(1440)));
}

#[test]
fn continues_a_split_row_at_the_top_of_the_next_page() {
    // The first page has no header, and the header of the other pages pushes their body down
    // to 1720 twips.
    let lines: String = ["h", "i", "j", "k", "l"].map(p).concat();
    let header = table("", &[2000], &[("", &[&lines])]);
    let rows: &[(&str, &[&str])] = &[("", &[&filler(70)])];
    let body = table("", &[2000], rows) + "<w:sectPr><w:titlePg/></w:sectPr>";
    let list = lay_out_with_header(&body, NORMAL, None, Some(&header));
    assert_eq!(find_all(&list, 'h').len(), 1);
    assert_eq!(filler_pages(&list), [vec![0; 64], vec![1; 6]].concat());
    let second = find_all(&list, 'q')[64];
    assert_eq!((second.0, second.2), (1, base(1720)));
}

#[test]
fn lays_out_a_header_off_the_line_grid_of_its_section() {
    // On a grid of 18 pt, the body's line of 10 pt fills one step with its text in the middle,
    // 4 pt below the top margin, and the ascent of 8 pt (33 device dots) below that. The
    // header's line keeps its own height from the header distance.
    let grid = r#"<w:sectPr><w:docGrid w:type="lines" w:linePitch="360"/></w:sectPr>"#;
    let list = lay_out_with_header(&(p("b") + grid), NORMAL, None, Some(&p("h")));
    assert_eq!(at(&list, 'h').1, base(720));
    assert_eq!(at(&list, 'b').1, du(1440 + 80) + 33);
}

#[test]
fn shows_a_continued_merge_cell_without_a_merged_cell_above() {
    let cell = |merge: &str, text: &str| {
        format!(
            r#"<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/>{merge}</w:tcPr><w:p><w:r><w:t>{text}</w:t></w:r></w:p></w:tc>"#
        )
    };
    let table = |above: &str| {
        format!(
            r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr>{}</w:tr><w:tr>{}</w:tr></w:tbl>"#,
            cell(above, "A"),
            cell("<w:vMerge/>", "X")
        )
    };
    let shows_x = |above: &str| !find_all(&lay_out(&table(above), NORMAL, None), 'X').is_empty();
    // Below a cell that starts a merge, the continued cell shows nothing of its own.
    assert!(!shows_x(r#"<w:vMerge w:val="restart"/>"#));
    // Below a cell that merges nothing, it stands on its own.
    assert!(shows_x(""));
}

#[test]
fn lays_out_a_continued_merge_cell_below_a_plain_cell_in_its_own_row() {
    // A cell of two lines that merges nothing, above a cell that goes on with a merge: the
    // second cell stands on its own, so the first cell's row takes both of its lines and the
    // second cell's line lies a line or more below them, on the device's grid, not over the
    // first cell's second line.
    let cell = |merge: &str, paragraphs: &str| {
        format!(
            r#"<w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/>{merge}</w:tcPr>{paragraphs}</w:tc>"#
        )
    };
    let paragraph = |text: &str| format!("<w:p><w:r><w:t>{text}</w:t></w:r></w:p>");
    let table = format!(
        r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr>{}</w:tr><w:tr>{}</w:tr></w:tbl>"#,
        cell("", &(paragraph("A") + &paragraph("B"))),
        cell("<w:vMerge/>", &paragraph("X"))
    );
    let list = lay_out(&table, NORMAL, None);
    let (a, b, x) = (find(&list, 'A'), find(&list, 'B'), find(&list, 'X'));
    assert!(b.2 > a.2);
    assert!(x.2 - b.2 >= b.2 - a.2, "{a:?} {b:?} {x:?}");
}

#[test]
fn keeps_page_breaks_of_paragraphs_out_of_cells() {
    // Paragraphs kept with the next one, and a paragraph whose last line would stand alone,
    // split with their row where the lines stop fitting. The first paragraph of the cell is
    // not kept, so the row is not kept either.
    let kept = p("q") + &"<w:p><w:pPr><w:keepNext/></w:pPr><w:r><w:t>q</w:t></w:r></w:p>".repeat(2);
    let list = lay_out(
        &(filler(62) + &table("", &[2000], &[("", &[&kept])])),
        NORMAL,
        None,
    );
    assert_eq!(filler_pages(&list), [vec![0; 64], vec![1; 1]].concat());
    let lines = "<w:p><w:r><w:t>q</w:t><w:br/><w:t>q</w:t><w:br/><w:t>q</w:t></w:r></w:p>";
    let list = lay_out(
        &(filler(62) + &table("", &[2000], &[("", &[lines])])),
        NORMAL,
        None,
    );
    assert_eq!(filler_pages(&list), [vec![0; 64], vec![1; 1]].concat());
}

#[test]
fn aligns_a_merged_cell_that_a_page_break_splits_in_its_part_on_the_page() {
    use crate::quirks::SplitMergeAlign;
    let centered = r#"<w:vAlign w:val="center"/>"#;
    let start = format!(
        r#"<w:tcPr><w:vMerge w:val="restart"/>{centered}</w:tcPr>{}"#,
        p("a")
    );
    let on = format!("<w:tcPr><w:vMerge/>{centered}</w:tcPr><w:p/>");
    let rows: &[(&str, &[&str])] = &[
        ("", &[&p("e"), &start]),
        ("", &[&p("g"), &on]),
        ("", &[&p("h"), &on]),
        ("", &[&p("i"), &p("j")]),
    ];
    let body = filler(62) + &table("", &[2000, 2000], rows);
    // The table starts at 13840 twips, and two rows of 200 twips fit above 14400; the merged
    // cell's third row moves to the next page. Centered in its two rows on the page, its line
    // moves down by 100 twips; centered in its three rows, the third one laid out below the
    // page's end, by 200.
    for (align, down) in [
        (SplitMergeAlign::WholeCell, 200),
        (SplitMergeAlign::PagePart, 100),
    ] {
        let target = on_base_with(|p| p.with_variant(align));
        let pass = pass_with(&body, (NORMAL, None), None, Numbering::default(), target);
        assert_eq!(place(&pass.list, 'a'), (0, base(13840 + down)), "{align:?}");
        assert_eq!(place(&pass.list, 'h'), (1, base(1440)), "{align:?}");
    }
}

#[test]
fn moves_a_nested_row_whole_when_its_minimum_does_not_fit_on_a_target_that_asks() {
    use crate::quirks::NestedRowMinimum;
    // 61 lines end at 13640 twips, and the nested row of `a` ends at 13840: 560 twips are left,
    // room for two of the three lines of the next row and not for a minimum of 700 twips.
    for (height, rule, page) in [
        (700, NestedRowMinimum::Splits, 0),
        (700, NestedRowMinimum::MovesWhole, 1),
        (500, NestedRowMinimum::MovesWhole, 0),
    ] {
        let minimum = format!(r#"<w:trHeight w:val="{height}"/>"#);
        let lines = p("b") + &p("c") + &p("d");
        let rows: &[(&str, &[&str])] = &[("", &[&p("a")]), (&minimum, &[&lines])];
        let cell = table("", &[1800], rows) + "<w:p/>";
        let body = filler(61) + &table("", &[2000], &[("", &[&cell])]);
        let target = on_base_with(|p| p.with_variant(rule));
        let pass = pass_with(&body, (NORMAL, None), None, Numbering::default(), target);
        assert_eq!(
            place(&pass.list, 'a'),
            (0, base(13640)),
            "{height} {rule:?}"
        );
        let b = place(&pass.list, 'b');
        assert_eq!(b.0, page, "{height} {rule:?}");
        if page == 1 {
            assert_eq!(b.1, base(1440), "{height} {rule:?}");
            assert_eq!(place(&pass.list, 'c'), (1, base(1640)), "{height} {rule:?}");
        }
    }
}

#[test]
fn breaks_a_floating_table_of_the_body_at_the_foot_on_a_target_that_asks() {
    use crate::quirks::FloatingTableBreaks;
    let placement = r#"<w:tblpPr w:vertAnchor="page" w:horzAnchor="margin" w:tblpY="1440"/><w:tblW w:w="3000" w:type="dxa"/>"#;
    let (q, a, b) = (p("q"), p("a"), p("b"));
    let cells = [[q.as_str()], [a.as_str()], [b.as_str()]];
    let mut rows: Vec<(&str, &[&str])> = vec![("", &cells[0][..]); 64];
    rows.push(("", &cells[1][..]));
    rows.push(("", &cells[2][..]));
    let body = table(placement, &[3000], &rows) + &p("z");
    // 64 rows end at 14240 twips: the row of `a` starts above the body's end at 14400 and
    // ends below it. Whole, the table runs on past the foot and `z` stands beside its top.
    // Breaking from mode 15, `a` starts the next page; in mode 14 it stays, and `b` starts the
    // next page. Either way `z` goes on on the table's last page, beside its part there.
    for (breaks, mode, a_place, b_place, z_page) in [
        (
            FloatingTableBreaks::Whole,
            15,
            (0, base(14240)),
            (0, base(14440)),
            0,
        ),
        (
            FloatingTableBreaks::AcrossPages,
            15,
            (1, base(1440)),
            (1, base(1640)),
            1,
        ),
        (
            FloatingTableBreaks::AcrossPages,
            14,
            (0, base(14240)),
            (1, base(1440)),
            1,
        ),
    ] {
        let target = on_base_with(|p| p.with_variant(breaks));
        let pass = pass_with(
            &body,
            (NORMAL, Some(mode)),
            None,
            Numbering::default(),
            target,
        );
        let case = format!("{breaks:?} in mode {mode}");
        assert_eq!(place(&pass.list, 'a'), a_place, "{case}");
        assert_eq!(place(&pass.list, 'b'), b_place, "{case}");
        assert_eq!(place(&pass.list, 'z'), (z_page, base(1440)), "{case}");
    }
}

#[test]
fn keeps_a_framed_cell_paragraph_in_the_cell_on_a_target_whose_cells_hold_no_frames() {
    use crate::quirks::CellFrames;
    let framed = r#"<w:p><w:pPr><w:framePr w:wrap="around" w:hAnchor="page" w:vAnchor="page" w:x="6000" w:y="8000"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#;
    let body = table("", &[2000], &[("", &[&(framed.to_owned() + &p("b"))])]);
    // In a frame, `a` leaves the cell, and `b` takes its first line; in the cell's flow, `a`
    // takes the cell's first line and `b` the next one, 200 twips below.
    for (frames, b) in [(CellFrames::Framed, 1440), (CellFrames::InFlow, 1640)] {
        let target = on_base_with(|p| p.with_variant(frames));
        let pass = pass_with(&body, (NORMAL, None), None, Numbering::default(), target);
        assert_eq!(place(&pass.list, 'b'), (0, base(b)), "{frames:?}");
        let in_cell = place(&pass.list, 'a') == (0, base(1440));
        assert_eq!(in_cell, frames == CellFrames::InFlow, "{frames:?}");
    }
}

/// The rectangles of `color` that page `page` of `list` paints, also inside groups, each as
/// its top and bottom in twips.
fn filled(list: &DisplayList, page: usize, color: f_office_paint::Rgb) -> Vec<(i64, i64)> {
    fn walk(items: &[f_office_paint::Item], color: f_office_paint::Rgb, out: &mut Vec<(i64, i64)>) {
        for item in items {
            match item {
                f_office_paint::Item::Rect(r) if r.color == color => {
                    let twips = |length: f_office_units::Length| {
                        length.units() / f_office_units::Length::UNITS_PER_TWIP
                    };
                    out.push((twips(r.y), twips(r.y + r.height)));
                }
                f_office_paint::Item::Group(group) => walk(&group.items, color, out),
                _ => {}
            }
        }
    }
    let mut out = Vec::new();
    walk(list.pages()[page].items(), color, &mut out);
    out
}

#[test]
fn fills_the_merged_column_of_a_table_in_a_cell_on_each_part_of_the_cell() {
    // A table in a cell whose first column is one shaded merged region of ten rows. The row
    // of the outer table starts four lines above the page's end and splits, and the rows of
    // the inner table that do not fit go on in the cell's part on the next page, where the
    // region's cells keep their fill.
    let shade = r#"<w:shd w:val="clear" w:color="auto" w:fill="4472C4"/>"#;
    let start = format!(
        r#"<w:tcPr><w:vMerge w:val="restart"/>{shade}</w:tcPr>{}"#,
        p("a")
    );
    let on = format!(r"<w:tcPr><w:vMerge/>{shade}</w:tcPr><w:p/>");
    let (b, c) = (p("b"), p("c"));
    let mut rows: Vec<(&str, &[&str])> = Vec::new();
    let first = [start.as_str(), b.as_str()];
    let later = [on.as_str(), c.as_str()];
    rows.push(("", &first));
    rows.extend(std::iter::repeat_n(("", &later[..]), 9));
    let inner = table("", &[1000, 1000], &rows) + "<w:p/>";
    let body = filler(60) + &table("", &[2500], &[("", &[&inner])]);
    let list = lay_out(&body, NORMAL, None);
    let pages: Vec<usize> = find_all(&list, 'c').iter().map(|glyph| glyph.0).collect();
    assert!(pages.contains(&0) && pages.contains(&1), "{pages:?}");
    let blue = f_office_paint::Rgb {
        r: 0x44,
        g: 0x72,
        b: 0xC4,
    };
    let shaded: Vec<bool> = (0..2)
        .map(|page| !filled(&list, page, blue).is_empty())
        .collect();
    assert_eq!(shaded, [true, true]);
}

#[test]
fn fills_a_shaded_paragraph_that_a_split_row_moves_to_the_next_page_around_its_line() {
    // A cell of four lines and a shaded paragraph after them. The row starts four lines above
    // the page's end, so the shaded paragraph's line does not fit, and it goes on in the row's
    // part on the next page. Its fill lies there, around its line, and nothing of its color
    // stays on the first page.
    let shaded = r#"<w:p><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="FFFF00"/></w:pPr><w:r><w:t>s</w:t></w:r></w:p>"#;
    let cell = p("a") + &p("b") + &p("c") + &p("d") + shaded;
    let body = filler(60) + &table("", &[2000], &[("", &[&cell])]);
    let list = lay_out(&body, NORMAL, None);
    assert_eq!(find(&list, 'd').0, 0);
    let (page, _, baseline) = find(&list, 's');
    assert_eq!(page, 1);
    let yellow = f_office_paint::Rgb {
        r: 0xFF,
        g: 0xFF,
        b: 0,
    };
    assert_eq!(filled(&list, 0, yellow), []);
    let fills = filled(&list, 1, yellow);
    assert_eq!(fills.len(), 1, "{fills:?}");
    let (top, bottom) = fills[0];
    assert!(
        du(top) < baseline && baseline < du(bottom),
        "{fills:?} {baseline}"
    );
}