f-office 0.2.2

Renders Office Open XML documents the way Microsoft Office does.
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
//! Layout tests of pages: headers and footers, sections, columns, page breaks, page numbers,
//! page borders and notes.

use std::fmt::Write as _;

use f_office_docx::testing::WordParts as _;
use f_office_paint::{DisplayList, Item};

use super::{
    CARLITO, CARLITO_FONTS, CARLITO_RUN, FontDb, RELATIONSHIPS, SECTION, capacity, carlito,
    carlito_line, compatibility_mode, docx, field, fills, lines, para, placed, points, render,
    testing,
};

/// A document of a landscape section of one page, then a portrait section of one page.
fn two_page_sizes() -> crate::Document {
    let tall = SECTION.replace(r#"w:w="6000" w:h="4000""#, r#"w:w="4000" w:h="6000""#);
    let body = format!(
        r"{}<w:p><w:pPr><w:sectPr>{SECTION}</w:sectPr></w:pPr></w:p>{}<w:sectPr>{tall}</w:sectPr>",
        para("Wide"),
        para("Tall")
    );
    crate::Document::open(&docx(&body, &[], ""), &carlito(), &crate::Options::base())
        .unwrap()
        .value
}

#[test]
fn gives_the_count_and_the_size_of_its_pages_without_drawing_them() {
    let document = two_page_sizes();
    assert_eq!(document.page_count(), 2);
    let [wide, tall] = [0, 1].map(|index| document.page_size(index).unwrap());
    assert!(wide.0 > wide.1, "{wide:?}");
    assert!(tall.0 < tall.1, "{tall:?}");
    assert_eq!(document.page(2), None);
    assert_eq!(document.page_size(2), None);
    assert_ne!(crate::suite::placed_lines(&document), []);
}

#[test]
fn gives_the_pages_of_its_display_list_and_not_a_copy() {
    let document = two_page_sizes();
    assert!(std::ptr::eq(
        document.pages(),
        document.display_list().pages()
    ));
    for (index, page) in document.pages().iter().enumerate() {
        assert!(std::ptr::eq(document.page(index).unwrap(), page));
        assert_eq!(
            document.page_size(index),
            Some((page.width(), page.height()))
        );
    }
}

#[test]
fn places_the_header_at_its_distance_and_the_footer_above_its_distance() {
    let body = format!(
        r#"{}<w:sectPr xmlns:r="{RELATIONSHIPS}"><w:headerReference w:type="default" r:id="h1"/><w:footerReference w:type="default" r:id="f1"/>{SECTION}</w:sectPr>"#,
        para("Body")
    );
    let list = render(&docx(
        &body,
        &[("h1", &para("Head")), ("f1", &para("Foot"))],
        "",
    ));
    let page = &lines(&list)[0];
    let texts: Vec<&str> = page.iter().map(|(_, t)| t.as_str()).collect();
    assert_eq!(texts, ["Head", "Body", "Foot"]);
    // The header starts 12 pt down and the body 36 pt down, so their baselines differ by 24 pt.
    assert!((page[1].0 - page[0].0 - 24.0).abs() < 1e-9, "{page:?}");
    // The footer's line ends 12 pt above the bottom edge of the 200 pt page.
    let (ascent, line) = carlito_line();
    let expected = 188.0 - line + ascent;
    assert!((page[2].0 - expected).abs() <= 0.12, "{page:?} {expected}");
}

#[test]
fn keeps_the_space_after_the_last_paragraph_of_a_footer_above_the_footer_distance() {
    let body = format!(
        r#"{}<w:sectPr xmlns:r="{RELATIONSHIPS}"><w:footerReference w:type="default" r:id="f1"/>{SECTION}</w:sectPr>"#,
        para("Body")
    );
    // A footer paragraph with 10 pt after it.
    let foot = para("Foot").replacen(
        "<w:p>",
        r#"<w:p><w:pPr><w:spacing w:after="200"/></w:pPr>"#,
        1,
    );
    let page = &lines(&render(&docx(&body, &[("f1", &foot)], "")))[0];
    let (ascent, line) = carlito_line();
    let expected = 188.0 - 10.0 - line + ascent;
    let (y, _) = page.iter().find(|(_, t)| t == "Foot").unwrap();
    assert!((y - expected).abs() <= 0.24, "{page:?} {expected}");
}

#[test]
fn puts_the_gutter_in_the_top_margin_when_the_settings_ask() {
    let section = SECTION.replace(r#"w:left="720""#, r#"w:left="720" w:gutter="240""#);
    let body = format!("{}<w:sectPr>{section}</w:sectPr>", para("Body"));
    let first = |settings: &str| placed(&render(&docx(&body, &[], settings)))[0][0].clone();
    let (ascent, _) = carlito_line();
    // The 12 pt gutter adds to the left margin of 36 pt.
    let (x, y, _) = first("");
    assert!((x - 48.0).abs() <= 0.25, "{x}");
    assert!((y - 36.0 - ascent).abs() <= 0.25, "{y}");
    // With `w:gutterAtTop`, it adds to the top margin instead.
    let (x, y, _) = first("<w:gutterAtTop/>");
    assert!((x - 36.0).abs() <= 0.25, "{x}");
    assert!((y - 48.0 - ascent).abs() <= 0.25, "{y}");
}

#[test]
fn starts_the_body_below_a_header_that_runs_into_the_top_margin() {
    let head = format!("{}{}{}", para("One"), para("Two"), para("Three"));
    let section = SECTION.replace(r#"w:top="720""#, r#"w:top="240""#);
    let body = format!(
        r#"{}<w:sectPr xmlns:r="{RELATIONSHIPS}"><w:headerReference w:type="default" r:id="h1"/>{section}</w:sectPr>"#,
        para("Body")
    );
    let page = &lines(&render(&docx(&body, &[("h1", &head)], "")))[0];
    let texts: Vec<&str> = page.iter().map(|(_, t)| t.as_str()).collect();
    assert_eq!(texts, ["One", "Two", "Three", "Body"]);
    let (_, line) = carlito_line();
    let gap = page[3].0 - page[2].0;
    assert!((gap - line).abs() <= 0.25, "{page:?}");
}

#[test]
fn keeps_the_empty_paragraph_that_ends_a_section_on_a_full_page() {
    // The first section fills its page, and its empty last paragraph, which holds the section
    // break and whose 24 pt mark is taller than the room left, does not fit below. The next
    // section starts on page 2.
    let (_, line) = carlito_line();
    let full: String = (0..capacity(line))
        .map(|n| para(&format!("Line {n}")))
        .collect();
    let mark = format!(r#"<w:rPr>{CARLITO_FONTS}<w:sz w:val="48"/></w:rPr>"#);
    let body = format!(
        r"{full}<w:p><w:pPr>{mark}<w:sectPr>{SECTION}</w:sectPr></w:pPr></w:p>{}<w:sectPr>{SECTION}</w:sectPr>",
        para("Next")
    );
    let pages = lines(&render(&docx(&body, &[], "")));
    assert_eq!(pages.len(), 2, "{pages:?}");
    assert_eq!(pages[1][0].1, "Next");
}

#[test]
fn gives_no_room_to_an_empty_paragraph_that_ends_a_section_before_a_continuous_one() {
    let continuous = r#"<w:type w:val="continuous"/>"#;
    let end = format!(
        "<w:p><w:pPr>{CARLITO_RUN}<w:sectPr>{continuous}{SECTION}</w:sectPr></w:pPr></w:p>"
    );
    let last = format!("<w:sectPr>{continuous}{SECTION}</w:sectPr>");
    let gap = |body: &str| {
        let page = &lines(&render(&docx(body, &[], "")))[0];
        let y = |text: &str| page.iter().find(|(_, t)| t == text).unwrap().0;
        y("Beta") - y("Alpha")
    };
    let (_, line) = carlito_line();
    // The empty paragraph after "Alpha" ends the first section and takes no line.
    let after = gap(&format!("{}{end}{}{last}", para("Alpha"), para("Beta")));
    assert!((after - line).abs() <= 0.25, "{after}");
    // An empty paragraph that is a section of its own keeps its line.
    let alpha = para("Alpha").replacen(
        "<w:p>",
        &format!("<w:p><w:pPr><w:sectPr>{continuous}{SECTION}</w:sectPr></w:pPr>"),
        1,
    );
    let alone = gap(&format!("{alpha}{end}{}{last}", para("Beta")));
    assert!((alone - 2.0 * line).abs() <= 0.25, "{alone}");
}

#[test]
fn leaves_out_the_space_before_a_paragraph_that_starts_a_page_after_a_page_break() {
    let spaced = |text: &str| {
        para(text).replacen(
            "<w:p>",
            r#"<w:p><w:pPr><w:spacing w:before="240"/></w:pPr>"#,
            1,
        )
    };
    let body = format!(
        r#"{}<w:p><w:r><w:br w:type="page"/></w:r></w:p>{}{}<w:sectPr>{SECTION}</w:sectPr>"#,
        para("One"),
        spaced("Two"),
        spaced("Three")
    );
    let pages = lines(&render(&docx(&body, &[], "")));
    assert_eq!(pages.len(), 2, "{pages:?}");
    // "Two" starts page 2 at the height of "One" on page 1, without its 12 pt before.
    assert!((pages[1][0].0 - pages[0][0].0).abs() < 1e-9, "{pages:?}");
    // The paragraph after it keeps its space before.
    let (_, line) = carlito_line();
    let gap = pages[1][1].0 - pages[1][0].0;
    assert!((gap - line - 12.0).abs() <= 0.25, "{pages:?}");
}

/// Two columns of 105 pt with 18 pt between them, in the 228 pt wide text area of `SECTION`.
const TWO_COLUMNS: &str = r#"<w:cols w:num="2" w:space="360"/>"#;

#[test]
fn fills_two_columns_before_the_next_page() {
    let (_, line) = carlito_line();
    let count = capacity(line);
    let body: String = (0..=2 * count)
        .map(|i| para(&format!("Line {i}")))
        .collect();
    let xml = format!("{body}<w:sectPr>{SECTION}{TWO_COLUMNS}</w:sectPr>");
    let pages = placed(&render(&docx(&xml, &[], "")));
    assert_eq!(pages.len(), 2);
    let near = |a: f64, b: f64| (a - b).abs() < 0.25;
    let first: Vec<_> = pages[0].iter().filter(|r| near(r.0, 36.0)).collect();
    let second: Vec<_> = pages[0].iter().filter(|r| near(r.0, 159.0)).collect();
    assert_eq!((first.len(), second.len()), (count, count), "{pages:?}");
    // The second column starts at the top, with the line after the first column's last.
    assert!(near(first[0].1, second[0].1), "{pages:?}");
    assert_eq!(second[0].2, format!("Line {count}"));
    assert_eq!(pages[1][0].2, format!("Line {}", 2 * count));
}

#[test]
fn continues_in_the_next_column_after_a_column_break() {
    let body = format!(
        r#"<w:p><w:r>{CARLITO_RUN}<w:t>One</w:t><w:br w:type="column"/><w:t>Two</w:t></w:r></w:p><w:sectPr>{SECTION}{TWO_COLUMNS}</w:sectPr>"#
    );
    let pages = placed(&render(&docx(&body, &[], "")));
    let texts: Vec<(f64, &str)> = pages[0].iter().map(|r| (r.0, r.2.as_str())).collect();
    assert_eq!(texts.len(), 2, "{pages:?}");
    assert!(
        (texts[1].0 - 159.0).abs() < 0.25 && texts[1].1 == "Two",
        "{pages:?}"
    );
    assert!((pages[0][0].1 - pages[0][1].1).abs() < 1e-9);
}

#[test]
fn breaks_the_lines_after_a_column_break_for_the_width_of_the_next_column() {
    // Columns of 60 pt and 150 pt with 18 pt between them: the words after the break need
    // two lines in the first column's width and one line in the second column's.
    let columns = r#"<w:cols w:num="2" w:equalWidth="0"><w:col w:w="1200" w:space="360"/><w:col w:w="3000"/></w:cols>"#;
    let body = format!(
        r#"<w:p><w:r>{CARLITO_RUN}<w:br w:type="column"/><w:t>aaa bbb ccc ddd eee</w:t></w:r></w:p><w:sectPr>{SECTION}{columns}</w:sectPr>"#
    );
    let pages = placed(&render(&docx(&body, &[], "")));
    let texts: Vec<(f64, &str)> = pages[0].iter().map(|r| (r.0, r.2.as_str())).collect();
    assert_eq!(texts.len(), 1, "{pages:?}");
    assert!(
        (texts[0].0 - 114.0).abs() < 0.25 && texts[0].1 == "aaa bbb ccc ddd eee",
        "{pages:?}"
    );
}

#[test]
fn balances_columns_before_a_continuous_section_break() {
    let continuous = r#"<w:type w:val="continuous"/>"#;
    let ending = |text: &str, cols: &str| {
        para(text).replacen(
            "<w:p>",
            &format!("<w:p><w:pPr><w:sectPr>{continuous}{SECTION}{cols}</w:sectPr></w:pPr>"),
            1,
        )
    };
    let items: String = (1..6).map(|i| para(&format!("Item {i}"))).collect();
    let body = format!(
        "{}{items}{}{}<w:sectPr>{continuous}{SECTION}</w:sectPr>",
        ending("Top", ""),
        ending("Item 6", TWO_COLUMNS),
        para("Bottom")
    );
    let pages = placed(&render(&docx(&body, &[], "")));
    assert_eq!(pages.len(), 1, "{pages:?}");
    let page = &pages[0];
    let at = |text: &str| page.iter().find(|r| r.2 == text).unwrap().clone();
    let (_, line) = carlito_line();
    // Three items in each column, the second column level with the first.
    for (left, right) in [
        ("Item 1", "Item 4"),
        ("Item 2", "Item 5"),
        ("Item 3", "Item 6"),
    ] {
        let (left, right) = (at(left), at(right));
        assert!((left.0 - 36.0).abs() < 0.25 && (right.0 - 159.0).abs() < 0.25);
        assert!((left.1 - right.1).abs() < 1e-9, "{page:?}");
    }
    assert!(
        (at("Item 1").1 - at("Top").1 - line).abs() <= 0.25,
        "{page:?}"
    );
    // The next section starts below the longer column.
    assert!(
        (at("Bottom").1 - at("Item 3").1 - line).abs() <= 0.25,
        "{page:?}"
    );
}

/// The placed texts of a page with "Top", a continuous section of two columns that holds
/// `items`, and "Bottom" in a continuous section of one column. `top` is the paragraph
/// properties of "Top".
fn balanced(top: &str, items: &str) -> Vec<(f64, f64, String)> {
    balanced_in(TWO_COLUMNS, top, items)
}

/// The same with the columns that `columns` writes.
fn balanced_in(columns: &str, top: &str, items: &str) -> Vec<(f64, f64, String)> {
    let continuous = r#"<w:type w:val="continuous"/>"#;
    let end = |cols: &str| format!("<w:sectPr>{continuous}{SECTION}{cols}</w:sectPr>");
    let first = para("Top").replacen("<w:p>", &format!("<w:p><w:pPr>{top}{}</w:pPr>", end("")), 1);
    let body = format!(
        "{first}{items}<w:p><w:pPr>{}</w:pPr></w:p>{}<w:sectPr>{continuous}{SECTION}</w:sectPr>",
        end(columns),
        para("Bottom")
    );
    let mut pages = placed(&render(&docx(&body, &[], "")));
    assert_eq!(pages.len(), 1, "{pages:?}");
    pages.remove(0)
}

#[test]
fn starts_the_section_below_balanced_columns_after_the_space_of_its_last_paragraph() {
    // Three lines with 4 pt after stand two and one. An empty paragraph with 12 pt after
    // ends the section, and the next line has 24 pt before: it starts 4 pt and the 12 pt of
    // its space before beyond the empty paragraph's space after below the first column.
    let continuous = r#"<w:type w:val="continuous"/>"#;
    let item = |i: usize| sized(&format!("Item {i}"), 24, r#"<w:spacing w:after="80"/>"#);
    let items: String = (1..4).map(item).collect();
    let end = format!(
        r#"<w:p><w:pPr><w:spacing w:after="240"/><w:sectPr>{continuous}{SECTION}{TWO_COLUMNS}</w:sectPr></w:pPr></w:p>"#
    );
    let body = format!(
        "<w:p><w:pPr><w:sectPr>{continuous}{SECTION}</w:sectPr></w:pPr></w:p>{items}{end}{}<w:sectPr>{continuous}{SECTION}</w:sectPr>",
        sized("Bottom", 24, r#"<w:spacing w:before="480"/>"#)
    );
    let pages = placed(&render(&docx(&body, &[], "")));
    let page = pages.first().unwrap();
    let at = |text: &str| page.iter().find(|r| r.2 == text).unwrap().clone();
    let line = at("Item 2").1 - at("Item 1").1 - 4.0;
    assert!((at("Item 3").0 - 159.0).abs() < 0.25, "{page:?}");
    assert!(
        (at("Bottom").1 - at("Item 2").1 - line - 16.0).abs() <= 0.25,
        "{page:?}"
    );
}

#[test]
fn starts_the_limit_of_columns_of_two_widths_at_the_area_of_the_text() {
    // One paragraph in a narrow column and a wide one. Half of its height in the narrow
    // column would leave most of its lines there; the area of the text over the width of
    // both columns shares the lines, so the wide column ends no higher than the narrow one
    // by more than a line.
    let columns = r#"<w:cols w:num="2" w:equalWidth="0"><w:col w:w="1200" w:space="360"/><w:col w:w="3000"/></w:cols>"#;
    let words: Vec<String> = (1..41).map(|n| format!("w{n:02}")).collect();
    let page = balanced_in(columns, "", &sized(&words.join(" "), 24, ""));
    let lines = |from: f64, to: f64| {
        let column = page.iter().filter(|r| r.0 >= from && r.0 < to);
        column.filter(|r| r.2.starts_with('w')).count()
    };
    let (narrow, wide) = (lines(35.0, 113.0), lines(113.0, 300.0));
    assert!(narrow > 1 && wide > 1, "{page:?}");
    assert!(narrow <= wide + 1, "{page:?}");
}

/// A paragraph of `text` in the test font at `size` half-points, with the paragraph
/// properties `props`.
fn sized(text: &str, size: u32, props: &str) -> String {
    format!(
        r#"<w:p><w:pPr>{props}</w:pPr><w:r><w:rPr>{CARLITO_FONTS}<w:sz w:val="{size}"/></w:rPr><w:t>{text}</w:t></w:r></w:p>"#
    )
}

#[test]
fn starts_balanced_columns_below_the_space_after_of_the_paragraph_before_them() {
    // Three lines after a paragraph with 20 pt after: two in the first column and one in
    // the second, which starts level with the first, below the space.
    let items: String = (1..4).map(|i| para(&format!("Item {i}"))).collect();
    let page = balanced(r#"<w:spacing w:after="400"/>"#, &items);
    let at = |text: &str| page.iter().find(|r| r.2 == text).unwrap().clone();
    let (_, line) = carlito_line();
    assert!(
        (at("Item 1").1 - at("Top").1 - line - 20.0).abs() <= 0.25,
        "{page:?}"
    );
    assert!((at("Item 2").0 - 36.0).abs() < 0.25, "{page:?}");
    assert!((at("Item 3").0 - 159.0).abs() < 0.25, "{page:?}");
    assert!((at("Item 3").1 - at("Item 1").1).abs() < 1e-9, "{page:?}");
}

#[test]
fn keeps_the_space_before_of_a_paragraph_at_the_top_of_a_column() {
    // Four lines, the third with 20 pt before: it starts the second column below its space.
    let spaced = sized("Item 3", 24, r#"<w:spacing w:before="400"/>"#);
    let items = format!(
        "{}{}{spaced}{}",
        sized("Item 1", 24, ""),
        sized("Item 2", 24, ""),
        sized("Item 4", 24, "")
    );
    let page = balanced("", &items);
    let at = |text: &str| page.iter().find(|r| r.2 == text).unwrap().clone();
    assert!((at("Item 2").0 - 36.0).abs() < 0.25, "{page:?}");
    assert!((at("Item 3").0 - 159.0).abs() < 0.25, "{page:?}");
    assert!(
        (at("Item 3").1 - at("Item 1").1 - 20.0).abs() <= 0.25,
        "{page:?}"
    );
}

#[test]
fn ends_balanced_columns_at_a_limit_that_grows_by_the_smallest_line() {
    // Five lines of 12 pt and two of 8 pt. At the mean height, the last small line fits in
    // no column. The limit grows by a small line, rounded up to whole points: the first
    // column still cannot take the fourth line, and the second column holds four lines and
    // ends below the first.
    let mut items: String = (1..6)
        .map(|i| sized(&format!("Item {i}"), 24, ""))
        .collect();
    items.push_str(&sized("Item 6", 16, ""));
    items.push_str(&sized("Item 7", 16, ""));
    let page = balanced("", &items);
    let at = |text: &str| page.iter().find(|r| r.2 == text).unwrap().clone();
    assert!((at("Item 3").0 - 36.0).abs() < 0.25, "{page:?}");
    assert!((at("Item 4").0 - 159.0).abs() < 0.25, "{page:?}");
    assert!((at("Item 4").1 - at("Item 1").1).abs() < 1e-9, "{page:?}");
    assert!(at("Bottom").1 > at("Item 7").1, "{page:?}");
}

#[test]
fn holds_the_space_after_of_the_last_paragraph_in_the_last_balanced_column() {
    // Five lines with 2 pt before and 6 pt after. Without the 6 pt after the fifth line, the
    // second column would take three lines before the first can; with it, the limit grows
    // until the first column takes the third line.
    let spaces = r#"<w:spacing w:before="40" w:after="120"/>"#;
    let item = |i: usize| sized(&format!("Item {i}"), 24, spaces);
    let items: String = (1..6).map(item).collect();
    let page = balanced("", &items);
    let at = |text: &str| page.iter().find(|r| r.2 == text).unwrap().clone();
    assert!((at("Item 3").0 - 36.0).abs() < 0.25, "{page:?}");
    assert!((at("Item 4").0 - 159.0).abs() < 0.25, "{page:?}");
    assert!(at("Bottom").1 > at("Item 3").1, "{page:?}");
}

/// A paragraph of the test font at 12 pt with a column break before or after its text.
fn broken(text: &str, before: bool, props: &str) -> String {
    let br = r#"<w:br w:type="column"/>"#;
    let (first, last) = if before { (br, "") } else { ("", br) };
    let run = format!(r#"<w:rPr>{CARLITO_FONTS}<w:sz w:val="24"/></w:rPr>"#);
    format!("<w:p><w:pPr>{props}{run}</w:pPr><w:r>{run}{first}<w:t>{text}</w:t>{last}</w:r></w:p>")
}

#[test]
fn leaves_an_empty_line_in_the_next_column_after_a_column_break_at_a_paragraph_end() {
    // The second paragraph ends with a column break: the second column starts with the
    // empty rest of that paragraph, and the third paragraph stands on its second line.
    let items = [
        sized("Item 1", 24, ""),
        broken("Item 2", false, ""),
        sized("Item 3", 24, ""),
    ]
    .concat();
    let page = balanced("", &items);
    let at = |text: &str| page.iter().find(|r| r.2 == text).unwrap().clone();
    assert!((at("Item 3").0 - 159.0).abs() < 0.25, "{page:?}");
    assert!((at("Item 3").1 - at("Item 2").1).abs() < 1e-9, "{page:?}");
}

#[test]
fn takes_the_space_before_to_the_next_column_after_a_column_break_at_a_paragraph_start() {
    // The third paragraph starts with a column break and has 10 pt before: its text stands
    // 10 pt below the top of the second column.
    let items = [
        sized("Item 1", 24, ""),
        sized("Item 2", 24, ""),
        broken("Item 3", true, r#"<w:spacing w:before="200"/>"#),
    ]
    .concat();
    let page = balanced("", &items);
    let at = |text: &str| page.iter().find(|r| r.2 == text).unwrap().clone();
    assert!((at("Item 3").0 - 159.0).abs() < 0.25, "{page:?}");
    assert!(
        (at("Item 3").1 - at("Item 1").1 - 10.0).abs() < 0.25,
        "{page:?}"
    );
}

/// An empty paragraph whose mark has the test font.
fn empty() -> String {
    format!("<w:p><w:pPr>{CARLITO_RUN}</w:pPr></w:p>")
}

#[test]
fn ends_a_page_of_empty_paragraphs_at_its_foot() {
    // The empty paragraphs draw nothing and fill the first page; the line after them does
    // not stay below its foot.
    let (ascent, line) = carlito_line();
    let count = capacity(line);
    let body = format!(
        "{}{}<w:sectPr>{SECTION}</w:sectPr>",
        empty().repeat(count + 2),
        para("After")
    );
    let pages = placed(&render(&docx(&body, &[], "")));
    assert_eq!(pages.len(), 2, "{pages:?}");
    assert!(pages[0].is_empty(), "{pages:?}");
    let after = &pages[1][0];
    assert!(
        after.2 == "After" && (after.1 - 36.0 - ascent - 2.0 * line).abs() <= 0.25,
        "{pages:?}"
    );
}

#[test]
fn keeps_a_chain_that_starts_a_page_with_empty_paragraphs() {
    // Two empty paragraphs kept with the next, then kept lines that do not fit below them:
    // the chain has no better page, and nothing leaves a blank page behind.
    let (ascent, line) = carlito_line();
    let count = capacity(line);
    let kept_empty = empty().replacen("<w:pPr>", "<w:pPr><w:keepNext/>", 1);
    let kept = |text: &str| para(text).replacen("<w:p>", "<w:p><w:pPr><w:keepNext/></w:pPr>", 1);
    let lines: String = (0..count).map(|i| kept(&format!("Kept {i}"))).collect();
    let body = format!(
        "{kept_empty}{kept_empty}{lines}{}<w:sectPr>{SECTION}</w:sectPr>",
        para("After")
    );
    let pages = placed(&render(&docx(&body, &[], "")));
    let first = &pages[0][0];
    assert!(
        first.2 == "Kept 0" && (first.1 - 36.0 - ascent - 2.0 * line).abs() <= 0.25,
        "{pages:?}"
    );
}

#[test]
fn balances_empty_paragraphs_at_the_top_of_a_page() {
    // Four empty paragraphs share the two columns of a section before a continuous section
    // break, also when nothing is drawn on the page yet.
    let (ascent, line) = carlito_line();
    let end = format!("<w:p><w:pPr><w:sectPr>{SECTION}{TWO_COLUMNS}</w:sectPr></w:pPr></w:p>");
    let body = format!(
        r#"{}{end}{}<w:sectPr><w:type w:val="continuous"/>{SECTION}</w:sectPr>"#,
        empty().repeat(4),
        para("After")
    );
    let pages = placed(&render(&docx(&body, &[], "")));
    assert_eq!(pages.len(), 1, "{pages:?}");
    let after = &pages[0][0];
    assert!(
        (after.1 - 36.0 - ascent - 2.0 * line).abs() <= 0.25,
        "{pages:?}"
    );
}

#[test]
fn ends_the_body_above_a_footer_that_runs_into_the_bottom_margin() {
    let foot = format!("{}{}{}", para("One"), para("Two"), para("Three"));
    let body: String = (0..20).map(|i| para(&format!("Line {i}"))).collect();
    let lines_on_page_one = |reference: &str| {
        let xml =
            format!(r#"{body}<w:sectPr xmlns:r="{RELATIONSHIPS}">{reference}{SECTION}</w:sectPr>"#);
        let pages = lines(&render(&docx(&xml, &[("f1", &foot)], "")));
        pages[0]
            .iter()
            .filter(|(_, t)| t.starts_with("Line"))
            .count()
    };
    let (_, line) = carlito_line();
    // The footer's three lines end 12 pt above the bottom edge of the 200 pt page, so the
    // footer starts above the bottom margin at 164 pt, and the body ends there.
    let footer_top = 188.0 - 3.0 * line;
    assert!(footer_top < 164.0);
    let fitting = (1..1000)
        .filter(|n: &i32| 36.0 + f64::from(*n) * line <= footer_top)
        .count();
    assert!(fitting < capacity(line));
    assert_eq!(lines_on_page_one(""), capacity(line));
    let reference = r#"<w:footerReference w:type="default" r:id="f1"/>"#;
    assert_eq!(lines_on_page_one(reference), fitting);
}

#[test]
fn chooses_first_even_and_default_headers_and_numbers_pages() {
    let break_after = |text: &str| {
        format!(r#"<w:p><w:r>{CARLITO_RUN}<w:t>{text}</w:t><w:br w:type="page"/></w:r></w:p>"#)
    };
    let body = format!(
        r#"{}{}{}<w:sectPr xmlns:r="{RELATIONSHIPS}"><w:headerReference w:type="default" r:id="h1"/><w:headerReference w:type="first" r:id="h2"/><w:headerReference w:type="even" r:id="h3"/>{SECTION}<w:titlePg/></w:sectPr>"#,
        break_after("A"),
        break_after("B"),
        para("C")
    );
    let numbered = |prefix: &str| {
        format!(
            r#"<w:p><w:r>{CARLITO_RUN}<w:t xml:space="preserve">{prefix} </w:t></w:r>{}<w:r>{CARLITO_RUN}<w:t xml:space="preserve"> of </w:t></w:r>{}</w:p>"#,
            field("PAGE"),
            field("NUMPAGES")
        )
    };
    let stories = [
        ("h1", numbered("Default")),
        ("h2", para("First")),
        ("h3", numbered("Even")),
    ];
    let stories: Vec<(&str, &str)> = stories
        .iter()
        .map(|(id, xml)| (*id, xml.as_str()))
        .collect();
    let pages = lines(&render(&docx(&body, &stories, "<w:evenAndOddHeaders/>")));
    let heads: Vec<String> = pages.iter().map(|p| p[0].1.replace(' ', "")).collect();
    assert_eq!(heads, ["First", "Even2of3", "Default3of3"]);
    // A paragraph that ends with a page break leaves no empty line on the next page.
    let tops: Vec<f64> = pages.iter().map(|p| p[1].0).collect();
    assert!(tops.iter().all(|y| (y - tops[0]).abs() < 1e-9), "{pages:?}");
}

#[test]
fn leaves_a_missing_header_blank() {
    let body = format!(
        r#"{}<w:sectPr xmlns:r="{RELATIONSHIPS}"><w:headerReference w:type="default" r:id="h1"/>{SECTION}<w:titlePg/></w:sectPr>"#,
        para("Body")
    );
    let pages = lines(&render(&docx(&body, &[("h1", &para("Head"))], "")));
    let texts: Vec<&str> = pages[0].iter().map(|(_, t)| t.as_str()).collect();
    assert_eq!(texts, ["Body"]);
}

/// The settings' list of special footnotes that names the separator footnote -1.
const LISTED: &str = r#"<w:footnotePr><w:footnote w:id="-1"/></w:footnotePr>"#;

/// The pages, as the texts of their lines, of eight lines of Carlito on a page that has room
/// for eight lines and 6 pt above its footnote, or for ten lines without one. The first line
/// has the reference of the footnote when `noted`, and the last line "L8" has the paragraph
/// properties `last`.
fn above_notes(noted: bool, last: &str) -> Vec<Vec<String>> {
    above_notes_with(&format!("{LISTED}{}", compatibility_mode(15)), noted, last)
}

/// The pages of [`above_notes`] in a document with the settings `settings`.
fn above_notes_with(settings: &str, noted: bool, last: &str) -> Vec<Vec<String>> {
    let mut body = String::new();
    for number in 1..=8 {
        let reference = if number == 1 && noted {
            format!(r#"<w:r>{CARLITO_RUN}<w:footnoteReference w:id="1"/></w:r>"#)
        } else {
            String::new()
        };
        let props = if number == 8 { last } else { "" };
        write!(
            body,
            "<w:p><w:pPr>{props}</w:pPr><w:r>{CARLITO_RUN}<w:t>L{number}</w:t></w:r>{reference}</w:p>"
        )
        .unwrap();
    }
    write!(body, "<w:sectPr>{SECTION}</w:sectPr>").unwrap();
    pages_with_note(&body, settings)
}

/// The pages, as the texts of their lines, of the body `body` in a document with the
/// settings `settings` and the footnote 1, " Note" in Carlito, below a written separator.
fn pages_with_note(body: &str, settings: &str) -> Vec<Vec<String>> {
    pages_with_note_of(body, settings, ("", &[" Note"]))
}

/// The pages of [`pages_with_note`] with a footnote 1 of one paragraph with the properties
/// `properties`, whose lines `texts` end with line breaks.
fn pages_with_note_of(
    body: &str,
    settings: &str,
    (properties, texts): (&str, &[&str]),
) -> Vec<Vec<String>> {
    let text = texts.join("</w:t><w:br/><w:t xml:space=\"preserve\">");
    let part = format!(
        r#"<w:footnote w:type="separator" w:id="-1"><w:p><w:r>{CARLITO_RUN}<w:separator/></w:r></w:p></w:footnote><w:footnote w:id="1"><w:p><w:pPr>{properties}</w:pPr><w:r>{CARLITO_RUN}<w:footnoteRef/></w:r><w:r>{CARLITO_RUN}<w:t xml:space="preserve">{text}</w:t></w:r></w:p></w:footnote>"#
    );
    lines(&render(&docx(body, &[("n1", &part)], settings)))
        .iter()
        .map(|page| page.iter().map(|(_, text)| text.clone()).collect())
        .collect()
}

#[test]
fn keeps_a_line_above_footnotes_only_with_its_whole_height() {
    // The text of a last line with double spacing fits above the footnote, and its whole
    // height does not.
    let double = r#"<w:spacing w:line="480" w:lineRule="auto"/>"#;
    let noted = above_notes(true, double);
    assert_eq!(noted.len(), 2, "{noted:?}");
    assert_eq!(noted[1], ["L8"]);
    // With single spacing it stays, and so does the line with double spacing on a page
    // without footnotes, where only its text must fit.
    assert_eq!(above_notes(true, "").len(), 1);
    assert_eq!(above_notes(false, double).len(), 1);
}

#[test]
fn keeps_a_last_line_above_footnotes_only_with_its_space_after() {
    // 8 pt after do not fit into the 6 pt above the footnote, and 5 pt do.
    let noted = above_notes(true, r#"<w:spacing w:after="160"/>"#);
    assert_eq!(noted.len(), 2, "{noted:?}");
    assert_eq!(noted[1], ["L8"]);
    assert_eq!(above_notes(true, r#"<w:spacing w:after="100"/>"#).len(), 1);
    assert_eq!(above_notes(false, r#"<w:spacing w:after="160"/>"#).len(), 1);
}

#[test]
fn counts_the_footnotes_of_a_paragraph_s_lines_for_widow_control() {
    // The page of `above_notes`: room for ten lines, or for eight above a footnote. After
    // `lead` plain lines comes one paragraph of `count` lines "A1", "A2" and so on, with
    // widow control, whose first line has the footnote.
    let pages = |lead: usize, count: usize| -> Vec<Vec<String>> {
        let mode = compatibility_mode(15);
        let mut body = String::new();
        for number in 1..=lead {
            write!(
                body,
                "<w:p><w:r>{CARLITO_RUN}<w:t>L{number}</w:t></w:r></w:p>"
            )
            .unwrap();
        }
        body.push_str("<w:p>");
        for number in 1..=count {
            write!(body, "<w:r>{CARLITO_RUN}<w:t>A{number}</w:t></w:r>").unwrap();
            if number == 1 {
                write!(
                    body,
                    r#"<w:r>{CARLITO_RUN}<w:footnoteReference w:id="1"/></w:r>"#
                )
                .unwrap();
            }
            if number < count {
                write!(body, "<w:r>{CARLITO_RUN}<w:br/></w:r>").unwrap();
            }
        }
        write!(body, "</w:p><w:sectPr>{SECTION}</w:sectPr>").unwrap();
        pages_with_note(&body, &format!("{LISTED}{mode}"))
    };
    // Without the footnote, eight of the nine lines have room below two plain lines. With
    // it, six have, and the three others fill the next page from its top: no break comes
    // before the second last line there.
    let early = pages(2, 9);
    assert_eq!(early.len(), 2, "{early:?}");
    assert_eq!(early[1], ["A7", "A8", "A9"]);
    // The footnote takes the room of the last line only, and widow control moves two lines.
    let widow = pages(5, 4);
    assert_eq!(widow.len(), 2, "{widow:?}");
    assert_eq!(widow[1], ["A3", "A4"]);
}

/// The pages of a document on the page of `above_notes`, in mode 15: `lead` plain lines,
/// the line "R" with the reference of the footnote, and the line "Z". The footnote has five
/// lines " N1" to " N5" in a paragraph with the properties `properties`.
fn pages_with_long_note(lead: usize, properties: &str) -> Vec<Vec<String>> {
    let settings = format!("{LISTED}{}", compatibility_mode(15));
    pages_with_long_note_in(&settings, lead, ("", properties))
}

/// The pages of `pages_with_long_note` with the settings `settings`, the paragraph
/// properties `line` of the line "R" and `note` of the footnote.
fn pages_with_long_note_in(
    settings: &str,
    lead: usize,
    (line, note): (&str, &str),
) -> Vec<Vec<String>> {
    let run = |text: &str| format!("<w:r>{CARLITO_RUN}{text}</w:r>");
    let plain = (1..=lead)
        .map(|number| format!("<w:p>{}</w:p>", run(&format!("<w:t>L{number}</w:t>"))))
        .collect::<Vec<_>>()
        .concat();
    let body = format!(
        "{plain}<w:p><w:pPr>{line}</w:pPr>{}{}</w:p><w:p>{}</w:p><w:sectPr>{SECTION}</w:sectPr>",
        run("<w:t>R</w:t>"),
        run(r#"<w:footnoteReference w:id="1"/>"#),
        run("<w:t>Z</w:t>"),
    );
    let texts = [" N1", " N2", " N3", " N4", " N5"];
    pages_with_note_of(&body, settings, (note, &texts))
}

#[test]
fn puts_the_part_of_a_footnote_below_the_whole_line_in_every_mode() {
    // Without a compatibility mode a line above whole footnotes needs the room of its text
    // only. Three lines of the footnote have room below the text of the line with double
    // spacing, and two below its whole height: two stay.
    let double = r#"<w:spacing w:line="480" w:lineRule="auto"/>"#;
    let split = pages_with_long_note_in(LISTED, 5, (double, ""));
    assert_eq!(split.len(), 2, "{split:?}");
    assert_eq!(split[0][5..], ["R1", "1 N1", "N2"]);
    assert_eq!(split[1], ["Z", "N3", "N4", "N5"]);
}

#[test]
fn splits_a_footnote_without_room_at_an_allowed_break() {
    // Three lines of the footnote stay with the line of the reference, and two go on at the
    // foot of the next page. The body of the first page ends at that line.
    let split = pages_with_long_note(4, "");
    assert_eq!(split.len(), 2, "{split:?}");
    assert_eq!(split[0][4..], ["R1", "1 N1", "N2", "N3"]);
    assert_eq!(split[1], ["Z", "N4", "N5"]);
}

#[test]
fn breaks_a_footnote_with_the_widow_control_of_its_paragraph() {
    // With room for one line of the footnote, widow control of the footnote's paragraph
    // allows no break, and the line of the reference goes to the next page.
    let short = pages_with_long_note(7, "");
    assert_eq!(short.len(), 2, "{short:?}");
    assert_eq!(short[0].last().map(String::as_str), Some("L7"));
    assert_eq!(short[1][..3], ["R1", "Z", "1 N1"]);
    // Without widow control the footnote breaks after its first line.
    let free = pages_with_long_note(7, r#"<w:widowControl w:val="0"/>"#);
    assert_eq!(free.len(), 2, "{free:?}");
    assert_eq!(free[0][7..], ["R1", "1 N1"]);
    assert_eq!(free[1], ["Z", "N2", "N3", "N4", "N5"]);
}

#[test]
fn keeps_a_line_above_footnotes_with_its_text_before_mode_15() {
    // Without a compatibility mode the line needs only the room of its text, and the last
    // line no space after.
    let double = r#"<w:spacing w:line="480" w:lineRule="auto"/>"#;
    assert_eq!(above_notes_with(LISTED, true, double).len(), 1);
    let after = r#"<w:spacing w:after="160"/>"#;
    assert_eq!(above_notes_with(LISTED, true, after).len(), 1);
}

#[test]
fn draws_the_written_separator_only_when_the_settings_list_it() {
    let large = format!(r#"<w:rPr>{CARLITO_FONTS}<w:sz w:val="60"/></w:rPr>"#);
    let body = format!(
        r#"<w:p><w:r>{CARLITO_RUN}<w:t>Body</w:t></w:r><w:r>{CARLITO_RUN}<w:footnoteReference w:id="1"/></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#
    );
    let notes = format!(
        r#"<w:footnote w:type="separator" w:id="-1"><w:p><w:r>{large}<w:separator/></w:r></w:p></w:footnote><w:footnote w:id="1"><w:p><w:r>{CARLITO_RUN}<w:footnoteRef/></w:r><w:r>{CARLITO_RUN}<w:t xml:space="preserve"> Note</w:t></w:r></w:p></w:footnote>"#
    );
    // The thickest rule of the page, in points: the rule of 30 pt is three times as thick as
    // one of 10 pt.
    let thickest = |settings: &str| {
        render(&docx(&body, &[("n1", &notes)], settings)).pages()[0]
            .items()
            .iter()
            .filter_map(|item| match item {
                Item::Rect(r) => Some(points(r.height.units())),
                _ => None,
            })
            .fold(0.0, f64::max)
    };
    let listed = thickest(LISTED);
    let unlisted = thickest("");
    assert!(listed > 1.0, "{listed}");
    assert!(unlisted < listed / 2.0, "{unlisted} {listed}");
}

/// The baselines of two footnotes of one line on a page, in points, whose paragraphs have the
/// spaces after `afters` in twips.
fn note_baselines(afters: [u32; 2]) -> [f64; 2] {
    note_baselines_with(afters, "")
}

/// The baselines of [`note_baselines`] with the paragraph properties `extra` in both
/// footnotes.
fn note_baselines_with(afters: [u32; 2], extra: &str) -> [f64; 2] {
    let reference =
        |id: u32| format!(r#"<w:r>{CARLITO_RUN}<w:footnoteReference w:id="{id}"/></w:r>"#);
    let body = format!(
        "<w:p><w:r>{CARLITO_RUN}<w:t>Body</w:t></w:r>{}{}</w:p><w:sectPr>{SECTION}</w:sectPr>",
        reference(1),
        reference(2)
    );
    let note = |id: u32, after: u32| {
        format!(
            r#"<w:footnote w:id="{id}"><w:p><w:pPr>{extra}<w:spacing w:after="{after}"/></w:pPr><w:r>{CARLITO_RUN}<w:footnoteRef/></w:r><w:r>{CARLITO_RUN}<w:t xml:space="preserve"> Note</w:t></w:r></w:p></w:footnote>"#
        )
    };
    let notes = format!(
        r#"<w:footnote w:type="separator" w:id="-1"><w:p><w:r>{CARLITO_RUN}<w:separator/></w:r></w:p></w:footnote>{}{}"#,
        note(1, afters[0]),
        note(2, afters[1])
    );
    let list = render(&docx(&body, &[("n1", &notes)], LISTED));
    let page = &lines(&list)[0];
    [page[1].0, page[2].0]
}

#[test]
fn keeps_the_space_after_a_footnote() {
    let plain = note_baselines([0, 0]);
    // 8 pt after the first footnote lie between the two.
    let between = note_baselines([160, 0]);
    assert!((plain[0] - between[0] - 8.0).abs() <= 0.12, "{between:?}");
    assert!((plain[1] - between[1]).abs() <= 0.12, "{between:?}");
    // 8 pt after the last footnote lie above the bottom margin.
    let below = note_baselines([0, 160]);
    assert!((plain[0] - below[0] - 8.0).abs() <= 0.12, "{below:?}");
    assert!((plain[1] - below[1] - 8.0).abs() <= 0.12, "{below:?}");
    // Contextual spacing removes the space between two footnotes of one style, and not the
    // space below the last one.
    let same = note_baselines_with([160, 160], "<w:contextualSpacing/>");
    assert!((plain[0] - same[0] - 8.0).abs() <= 0.12, "{same:?}");
    assert!((plain[1] - same[1] - 8.0).abs() <= 0.12, "{same:?}");
}

#[test]
fn places_footnotes_at_the_bottom_of_their_page() {
    let reference =
        |id: &str| format!(r#"<w:r>{CARLITO_RUN}<w:footnoteReference w:id="{id}"/></w:r>"#);
    let body = format!(
        "<w:p><w:r>{CARLITO_RUN}<w:t>Body</w:t></w:r>{}<w:r>{CARLITO_RUN}<w:t>.</w:t></w:r>{}</w:p><w:sectPr>{SECTION}</w:sectPr>",
        reference("7"),
        reference("3")
    );
    let note = |id: &str, text: &str| {
        format!(
            r#"<w:footnote w:id="{id}"><w:p><w:r>{CARLITO_RUN}<w:footnoteRef/></w:r><w:r>{CARLITO_RUN}<w:t xml:space="preserve"> {text}</w:t></w:r></w:p></w:footnote>"#
        )
    };
    let notes = format!(
        r#"<w:footnote w:type="separator" w:id="-1"><w:p><w:r>{CARLITO_RUN}<w:separator/></w:r></w:p></w:footnote>{}{}"#,
        note("3", "Second"),
        note("7", "First")
    );
    let list = render(&docx(&body, &[("n1", &notes)], LISTED));
    let page = &lines(&list)[0];
    let texts: Vec<&str> = page.iter().map(|(_, t)| t.as_str()).collect();
    // The references take the numbers 1 and 2 in their order in the text.
    assert_eq!(texts, ["Body1.2", "1 First", "2 Second"], "{page:?}");
    // The last footnote line ends at the bottom margin of the 200 pt page.
    let (ascent, line) = carlito_line();
    let expected = 164.0 - line + ascent;
    assert!((page[2].0 - expected).abs() <= 0.12, "{page:?} {expected}");
    // The separator is a 2 inch rule at the margin, with Carlito's strikeout thickness, one
    // line above the first footnote, at the strikeout position above the separator's baseline.
    let rules: Vec<[f64; 4]> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Rect(r) => Some([r.x, r.y, r.width, r.height].map(|l| points(l.units()))),
            _ => None,
        })
        .collect();
    let mut fonts = FontDb::new();
    let id = fonts.add_font(CARLITO.to_vec()).unwrap()[0];
    let strikeout = fonts.metrics(id).unwrap().os2.unwrap().strikeout;
    let em = f64::from(fonts.metrics(id).unwrap().units_per_em);
    let thickness = f64::from(strikeout.thickness) / em * 10.0;
    let separator_baseline = page[1].0 - line;
    let top = separator_baseline - f64::from(strikeout.position) / em * 10.0;
    assert_eq!(rules.len(), 1, "{rules:?}");
    let [x, y, width, height] = rules[0];
    assert_eq!((x, width), (36.0, 144.0));
    assert!((height - thickness).abs() <= 0.25, "{rules:?} {thickness}");
    // Three positions round to the 0.24 pt grid on the way: the footnote's baseline, the
    // separator's baseline and the top of the rule.
    assert!((y - top).abs() <= 0.36, "{rules:?} {top}");
}

/// A footer paragraph that shows the page number (the field `PAGE`) in Carlito.
fn page_number_footer() -> String {
    format!(
        r#"<w:p><w:r>{CARLITO_RUN}<w:fldChar w:fldCharType="begin"/></w:r><w:r>{CARLITO_RUN}<w:instrText>PAGE</w:instrText></w:r><w:r>{CARLITO_RUN}<w:fldChar w:fldCharType="end"/></w:r></w:p>"#
    )
}

/// A paragraph "A" that ends a section with the footer `f1` and the page numbering
/// `numbering` (a `w:pgNumType`).
fn section_with_page_numbers(numbering: &str) -> String {
    format!(
        r#"<w:p><w:pPr><w:sectPr xmlns:r="{RELATIONSHIPS}"><w:footerReference w:type="default" r:id="f1"/>{SECTION}{numbering}</w:sectPr></w:pPr><w:r>{CARLITO_RUN}<w:t>A</w:t></w:r></w:p>"#
    )
}

/// The texts of the lines of each page.
fn page_texts(list: &DisplayList) -> Vec<Vec<String>> {
    lines(list)
        .iter()
        .map(|page| page.iter().map(|(_, t)| t.clone()).collect())
        .collect()
}

#[test]
fn starts_sections_on_new_pages_with_their_own_settings() {
    let footer = page_number_footer();
    let first = section_with_page_numbers(r#"<w:pgNumType w:start="5"/>"#);
    let tall = SECTION.replace(r#"w:w="6000" w:h="4000""#, r#"w:w="4000" w:h="6000""#);
    let pages_for = |start: &str| {
        let body = format!("{first}{}<w:sectPr>{start}{tall}</w:sectPr>", para("B"));
        render(&docx(&body, &[("f1", &footer)], ""))
    };
    let list = pages_for("");
    let sizes: Vec<(f64, f64)> = list
        .pages()
        .iter()
        .map(|p| (points(p.width().units()), points(p.height().units())))
        .collect();
    assert_eq!(sizes, [(300.0, 199.92), (199.92, 300.0)]);
    // The second section keeps the first one's footer, and its pages count on.
    assert_eq!(page_texts(&list), [["A", "5"], ["B", "6"]]);
    // An odd-page section after page 5 leaves page 6 blank, without its footer.
    let odd = pages_for(r#"<w:type w:val="oddPage"/>"#);
    assert_eq!(page_texts(&odd), [vec!["A", "5"], vec![], vec!["B", "7"]]);
}

#[test]
fn writes_the_largest_page_number_start_in_digits_and_keeps_it() {
    // A start that the letter format would write with 3.5 x 10^17 letters, and whose next page
    // would pass the largest number of 64 bits.
    let first = section_with_page_numbers(&format!(
        r#"<w:pgNumType w:start="{}" w:fmt="lowerLetter"/>"#,
        i64::MAX
    ));
    let body = format!("{first}{}<w:sectPr>{SECTION}</w:sectPr>", para("B"));
    let list = render(&docx(&body, &[("f1", &page_number_footer())], ""));
    let largest = i64::MAX.to_string();
    assert_eq!(page_texts(&list), [["A", &largest], ["B", &largest]]);
}

#[test]
fn leaves_the_space_after_a_page_break_on_its_page() {
    let spaced = r#"<w:pPr><w:spacing w:after="400"/></w:pPr>"#;
    let next = format!(r"<w:p>{spaced}<w:r>{CARLITO_RUN}<w:t>B</w:t></w:r></w:p>");
    let tops = |breaker: &str| {
        let body = format!("{breaker}{next}<w:sectPr>{SECTION}</w:sectPr>");
        lines(&render(&docx(&body, &[], "")))
            .iter()
            .map(|page| page.first().map(|(y, _)| *y))
            .collect::<Vec<_>>()
    };
    let first = tops(&next)[0];
    // A paragraph that ends with a page break, and a section that starts a new page.
    let page_break =
        format!(r#"<w:p>{spaced}<w:r>{CARLITO_RUN}<w:t>A</w:t><w:br w:type="page"/></w:r></w:p>"#);
    let section = format!(
        r#"<w:p><w:pPr><w:spacing w:after="400"/><w:sectPr>{SECTION}</w:sectPr></w:pPr><w:r>{CARLITO_RUN}<w:t>A</w:t></w:r></w:p>"#
    );
    for breaker in [page_break, section] {
        assert_eq!(tops(&breaker)[1], first, "{breaker}");
    }
}

#[test]
fn starts_a_section_with_the_space_before_that_exceeds_the_space_after_on_the_old_page() {
    let para = |ppr: &str, text: &str| {
        format!(r"<w:p><w:pPr>{ppr}</w:pPr><w:r>{CARLITO_RUN}<w:t>{text}</w:t></w:r></w:p>")
    };
    // The second page's first line, after a section break whose paragraph has `after`
    // twips after, before a paragraph with 480 twips before.
    let second_top = |after: u32| {
        let breaker = para(
            &format!(r#"<w:spacing w:after="{after}"/><w:sectPr>{SECTION}</w:sectPr>"#),
            "A",
        );
        let body = format!(
            "{breaker}{}<w:sectPr>{SECTION}</w:sectPr>",
            para(r#"<w:spacing w:before="480"/>"#, "B")
        );
        lines(&render(&docx(&body, &[], "")))[1][0].0
    };
    let full = second_top(0);
    // 10 pt after leave 14 of the 24 pt before, and 30 pt after leave none.
    assert!((full - second_top(200) - 10.0).abs() < 0.3);
    assert!((full - second_top(600) - 24.0).abs() < 0.3);
}

#[test]
fn starts_a_page_before_a_paragraph_that_asks_for_it() {
    let para = |ppr: &str, text: &str| {
        format!(r"<w:p><w:pPr>{ppr}</w:pPr><w:r>{CARLITO_RUN}<w:t>{text}</w:t></w:r></w:p>")
    };
    let breaking = r#"<w:pageBreakBefore/><w:spacing w:before="400"/>"#;
    let body = format!(
        "{}{}{}<w:sectPr>{SECTION}</w:sectPr>",
        para(breaking, "A"),
        para("", "B"),
        para(breaking, "C")
    );
    let pages = lines(&render(&docx(&body, &[], &compatibility_mode(15))));
    let texts: Vec<Vec<&str>> = pages
        .iter()
        .map(|page| page.iter().map(|(_, t)| t.as_str()).collect())
        .collect();
    // The first paragraph already starts a page, so it keeps its space above.
    assert_eq!(texts, [vec!["A", "B"], vec!["C"]]);
    let (ascent, _) = carlito_line();
    assert!((pages[1][0].0 - (36.0 + ascent)).abs() <= 0.25, "{pages:?}");
    assert!(pages[0][0].0 > 36.0 + ascent + 19.0, "{pages:?}");
    // Before Word 2013, the paragraph after the break keeps its 20 pt above.
    let older = lines(&render(&docx(&body, &[], "")));
    assert!(
        (older[1][0].0 - (36.0 + ascent + 20.0)).abs() <= 0.25,
        "{older:?}"
    );
}

#[test]
fn puts_endnotes_after_the_text_with_roman_numbers() {
    let note = |id: &str, text: &str| {
        format!(
            r#"<w:endnote w:id="{id}"><w:p><w:r>{CARLITO_RUN}<w:endnoteRef/><w:t xml:space="preserve"> {text}</w:t></w:r></w:p></w:endnote>"#
        )
    };
    let notes = format!(
        r#"<w:endnote w:id="0" w:type="separator"><w:p><w:r><w:separator/></w:r></w:p></w:endnote>{}{}"#,
        note("7", "Second"),
        note("3", "First")
    );
    let reference =
        |id: &str| format!(r#"<w:r>{CARLITO_RUN}<w:endnoteReference w:id="{id}"/></w:r>"#);
    let body = format!(
        r"<w:p><w:r>{CARLITO_RUN}<w:t>Text</w:t></w:r>{}{}</w:p><w:sectPr>{SECTION}</w:sectPr>",
        reference("3"),
        reference("7")
    );
    let list = render(&docx(&body, &[("e1", &notes)], ""));
    let texts: Vec<String> = lines(&list)[0].iter().map(|(_, t)| t.clone()).collect();
    // The numbers follow the order of the references, and the separator takes a line.
    assert_eq!(texts, ["Textiii", "i First", "ii Second"], "{texts:?}");
}

#[test]
fn centers_or_lowers_the_body_of_a_page_for_its_section() {
    let page = |align: &str| {
        let body = format!(
            r#"<w:p><w:pPr><w:spacing w:after="0"/></w:pPr><w:r>{CARLITO_RUN}<w:t>Text</w:t></w:r></w:p><w:sectPr>{SECTION}<w:vAlign w:val="{align}"/></w:sectPr>"#
        );
        lines(&render(&docx(&body, &[], "")))[0][0].0
    };
    let (ascent, line) = carlito_line();
    // The page is 200 pt tall with margins of 36 pt, so the body has 128 pt of room.
    let top = page("top");
    assert!((top - (36.0 + ascent)).abs() <= 0.12, "{top}");
    let center = page("center");
    assert!(
        (center - (top + (128.0 - line) / 2.0)).abs() <= 0.25,
        "{center}"
    );
    let bottom = page("bottom");
    assert!((bottom - (top + 128.0 - line)).abs() <= 0.25, "{bottom}");
}

#[test]
fn draws_page_borders_from_the_page_edge_or_around_the_text() {
    let page = |borders: &str| {
        let body = format!(
            r#"<w:p><w:r><w:t>Text</w:t></w:r></w:p><w:sectPr>{SECTION}<w:pgBorders {borders}><w:top w:val="single" w:sz="16" w:space="10" w:color="FF0000"/><w:left w:val="double" w:sz="8" w:space="4"/></w:pgBorders></w:sectPr>"#
        );
        fills(&render(&docx(&body, &[], "")))
    };
    // From the page edge: the top line's outer edge lies 10 pt down, and it is 2 pt thick, each
    // on the nearest device dot of 0.24 pt: 10.08 pt and 1.92 pt.
    let rects = page(r#"w:offsetFrom="page""#);
    let red = rects.iter().find(|r| r.4 == [255, 0, 0]).unwrap();
    assert_eq!((red.0, red.1, red.3), (4.08, 10.08, 1.92), "{rects:?}");
    let black = rects.iter().find(|r| r.4 == [0, 0, 0]).unwrap();
    assert_eq!(
        (black.0, black.1, black.2),
        (4.08, 10.08, 0.96),
        "{rects:?}"
    );
    // From the text: the lines lie outside the margins of 36 pt by their space and width. The
    // double left border is two lines of 1 pt with a gap of 1 pt, 3 pt in all (3.12 pt on the
    // device), and its outer edge 28.88 pt goes to 28.8 pt.
    let rects = page("");
    let red = rects.iter().find(|r| r.4 == [255, 0, 0]).unwrap();
    assert_eq!((red.0, red.1), (28.8, 24.0), "{rects:?}");
    let left: Vec<f64> = rects
        .iter()
        .filter(|r| r.4 == [0, 0, 0])
        .map(|r| r.0)
        .collect();
    assert_eq!(left, [28.8, 30.72], "{rects:?}");
}

#[test]
fn leaves_a_blank_page_without_a_footer_before_a_restarted_section_on_the_wrong_side() {
    let first = format!(
        r#"<w:p><w:pPr><w:sectPr xmlns:r="{RELATIONSHIPS}"><w:footerReference w:type="even" r:id="f2"/>{SECTION}</w:sectPr></w:pPr><w:r>{CARLITO_RUN}<w:t>One</w:t></w:r></w:p>"#
    );
    let body = format!(
        r#"{first}{}<w:sectPr><w:pgNumType w:start="1"/>{SECTION}</w:sectPr>"#,
        para("Two")
    );
    let pages = lines(&render(&docx(
        &body,
        &[("f2", &para("Even"))],
        "<w:evenAndOddHeaders/>",
    )));
    let texts: Vec<Vec<&str>> = pages
        .iter()
        .map(|page| page.iter().map(|(_, t)| t.as_str()).collect())
        .collect();
    // Page 1 of the second section goes on the third page, a right-hand one.
    assert_eq!(texts, [vec!["One"], vec![], vec!["Two"]]);
}

#[test]
fn starts_a_section_after_a_page_break_on_the_page_that_the_break_began() {
    let body = format!(
        r#"{}<w:p><w:r><w:br w:type="page"/></w:r></w:p><w:p><w:pPr><w:sectPr>{SECTION}</w:sectPr></w:pPr></w:p>{}<w:sectPr>{SECTION}</w:sectPr>"#,
        para("One"),
        para("Two")
    );
    let pages = lines(&render(&docx(&body, &[], "")));
    let texts: Vec<Vec<&str>> = pages
        .iter()
        .map(|page| page.iter().map(|(_, t)| t.as_str()).collect())
        .collect();
    assert_eq!(texts, [vec!["One"], vec!["Two"]]);
}

#[test]
fn keeps_a_page_break_that_starts_a_paragraph_of_text_on_a_full_page() {
    // Eight lines of exact 16 pt fill the body of 128 pt.
    let line = format!(
        r#"<w:p><w:pPr><w:spacing w:line="320" w:lineRule="exact"/></w:pPr><w:r>{CARLITO_RUN}<w:t>A</w:t></w:r></w:p>"#
    );
    let full = line.repeat(8);
    let counts = |rest: &str| {
        let body = format!("{full}{rest}<w:sectPr>{SECTION}</w:sectPr>");
        lines(&render(&docx(&body, &[], "")))
            .iter()
            .map(Vec::len)
            .collect::<Vec<_>>()
    };
    // The break stays on the full page, and the text after it starts the next page.
    let starts = format!(r#"<w:p><w:r>{CARLITO_RUN}<w:br w:type="page"/><w:t>B</w:t></w:r></w:p>"#);
    assert_eq!(counts(&starts), [8, 1]);
    // A paragraph of a page break only moves to the next page and breaks there.
    let only = format!(
        r#"<w:p><w:pPr>{CARLITO_RUN}</w:pPr><w:r>{CARLITO_RUN}<w:br w:type="page"/></w:r></w:p>{}"#,
        para("B")
    );
    assert_eq!(counts(&only), [8, 0, 1]);
}

#[test]
fn ends_table_rows_above_the_footnotes_of_their_page() {
    let mut rows = String::new();
    for i in 0..12 {
        write!(
            rows,
            r#"<w:tr><w:tc><w:tcPr><w:tcW w:w="3000" w:type="dxa"/></w:tcPr>{}</w:tc></w:tr>"#,
            para(&format!("row{i}"))
        )
        .unwrap();
    }
    let body = format!(
        r#"<w:p><w:r>{CARLITO_RUN}<w:t>Body</w:t></w:r><w:r>{CARLITO_RUN}<w:footnoteReference w:id="1"/></w:r></w:p><w:tbl><w:tblGrid><w:gridCol w:w="3000"/></w:tblGrid>{rows}</w:tbl><w:sectPr>{SECTION}</w:sectPr>"#
    );
    let notes = format!(
        r#"<w:footnote w:type="separator" w:id="-1"><w:p><w:r>{CARLITO_RUN}<w:separator/></w:r></w:p></w:footnote><w:footnote w:id="1"><w:p><w:r>{CARLITO_RUN}<w:footnoteRef/></w:r><w:r>{CARLITO_RUN}<w:t xml:space="preserve"> Note</w:t></w:r></w:p></w:footnote>"#
    );
    let list = render(&docx(&body, &[("n1", &notes)], LISTED));
    let rule = list.pages()[0]
        .items()
        .iter()
        .find_map(|item| match item {
            Item::Rect(r) => Some(points(r.y.units())),
            _ => None,
        })
        .unwrap();
    let (ascent, line) = carlito_line();
    let descent = line - ascent;
    let page = &lines(&list)[0];
    let rows: Vec<f64> = page
        .iter()
        .filter(|(_, t)| t.starts_with("row"))
        .map(|(y, _)| *y)
        .collect();
    assert!(!rows.is_empty(), "{page:?}");
    // Every row on the first page ends above the footnote separator.
    for y in rows {
        assert!(y + descent <= rule, "{page:?} {rule}");
    }
}

#[test]
fn puts_the_change_bar_of_an_odd_page_right_of_the_text_with_odd_and_even_headers() {
    // Margins of 120.2 pt, which lie on the device grid of 0.24 pt at 120.24 pt.
    let section = SECTION
        .replace(r#"w:right="720""#, r#"w:right="2404""#)
        .replace(r#"w:left="720""#, r#"w:left="2404""#);
    let inserted = |props: &str| {
        format!(
            r#"<w:p><w:pPr>{props}</w:pPr><w:ins w:author="A"><w:r>{CARLITO_RUN}<w:t>new</w:t></w:r></w:ins></w:p>"#
        )
    };
    let body = format!(
        "{}{}<w:sectPr>{section}</w:sectPr>",
        inserted(""),
        inserted("<w:pageBreakBefore/>")
    );
    let bars = |settings: &str| -> Vec<Vec<f64>> {
        render(&docx(&body, &[], settings))
            .pages()
            .iter()
            .map(|page| {
                page.items()
                    .iter()
                    .filter_map(|item| match item {
                        Item::Rect(r) if (points(r.width.units()) - 0.72).abs() < 1e-9 => {
                            Some((points(r.x.units()) * 100.0).round() / 100.0)
                        }
                        _ => None,
                    })
                    .collect()
            })
            .collect()
    };
    // The bar sits 36 pt left of the margin on the device grid on both pages: at 84.24 pt.
    assert_eq!(bars(""), [[84.24], [84.24]]);
    // With odd and even headers, the bar of page 1 sits 36 pt right of the right margin of
    // the 300 pt page, at 215.8 pt rounded down to 215.76 pt; page 2 keeps its bar on the left.
    assert_eq!(bars("<w:evenAndOddHeaders/>"), [[215.76], [84.24]]);
}

#[test]
fn fills_every_page_with_the_page_color_under_its_text() {
    // A navy page color on two pages, which the settings do not ask to show: the first item of
    // each page covers the whole page, automatic text is white on it, and black on a paragraph
    // filled white.
    let white = format!(
        r#"<w:p><w:pPr><w:shd w:val="clear" w:color="auto" w:fill="FFFFFF"/></w:pPr><w:r>{CARLITO_RUN}<w:t>b</w:t></w:r></w:p>"#
    );
    let body = format!(
        r#"{}<w:p><w:r><w:br w:type="page"/></w:r></w:p>{white}<w:sectPr>{SECTION}</w:sectPr>"#,
        para("a")
    );
    let document = testing::word(
        "document",
        &format!(r#"<w:background w:color="1F3864"/><w:body>{body}</w:body>"#),
    );
    let list = render(
        &testing::package(document)
            .word_part("s", "settings", "settings.xml", "settings", "")
            .plain_styles()
            .zip()
            .unwrap(),
    );
    let navy = f_office_paint::Rgb {
        r: 0x1F,
        g: 0x38,
        b: 0x64,
    };
    let text = |page: &f_office_paint::Page| -> Vec<[u8; 3]> {
        page.items()
            .iter()
            .filter_map(|item| match item {
                Item::Glyphs(run) => Some([run.color.r, run.color.g, run.color.b]),
                _ => None,
            })
            .collect()
    };
    assert_eq!(list.pages().len(), 2);
    for page in list.pages() {
        let Some(Item::Rect(first)) = page.items().first() else {
            panic!("{:?}", page.items().first());
        };
        assert_eq!(
            (first.x, first.y, first.color),
            (
                f_office_units::Length::ZERO,
                f_office_units::Length::ZERO,
                navy
            )
        );
        assert!(
            first.width >= page.width() && first.height >= page.height(),
            "{first:?}"
        );
    }
    assert_eq!(text(&list.pages()[0]), [[255; 3]]);
    assert_eq!(text(&list.pages()[1]), [[0; 3]]);
}