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
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
//! Tests of the layout of tables, with the layout test harness of `layout/testing.rs`.

use f_office_fonts::{FamilyName, FontId};
use f_office_paint::{DisplayList, FillRule, Item, Page, PathCommand, PathItem, Point, Rgb};
use f_office_units::Length;

use super::{CellFloor, Sides, align, band, heavier, row_height};
use crate::body::Sections;
use crate::grid::DOT;
use crate::layout::testing::{
    Fake, NORMAL, SINGLE, at, base, base_context, du, find, find_all, indented, lay_out,
    on_base_with, p, pass_on, pass_with, pass_with_header, rects, table, x_du,
};
use crate::layout::{EarlierPass, Layout, SectionLayout};
use crate::numbering::Numbering;
use crate::props::{Border, BorderParts, Color};
use crate::quirks::{ExactRowMargin, RightToLeftEdge};
use crate::styles::{FontTable, Settings, Styles, Theme};
use crate::table::{HeightRule, Region, VerticalAlign};
use crate::tests::{HEADER_REFERENCE, package};
use crate::text::{Shaper, ShaperSettings};
use crate::{ChosenFace, Fonts};

mod cell_drawings;
mod cell_room;
mod clips;
mod dashes;
mod floating_lefts;
mod floating_tables;
mod floating_tops;
mod keeps;
mod pages;
mod spaced_breaks;
mod top_dots;
mod top_room;
mod trials;
mod turned;

/// Lays out a body on a device of 600 dots per inch whose table lines are centered on their
/// grid lines (`TableLines::RoundsCenters`).
fn lay_out_centered_lines(body: &str, styles: &str, mode: Option<u32>) -> DisplayList {
    let target = crate::layout::testing::target_at(600, |p| {
        p.with_variant(crate::quirks::TableLines::RoundsCenters)
    });
    pass_with(body, (styles, mode), None, Numbering::default(), target).list
}

fn font_of(list: &DisplayList, ch: char) -> FontId {
    run_of(list, ch).font
}

fn run_of(list: &DisplayList, ch: char) -> &f_office_paint::GlyphRun {
    list.pages()
        .iter()
        .flat_map(Page::items)
        .find_map(|item| match item {
            Item::Glyphs(run) if run.text.contains(ch) => Some(run),
            _ => None,
        })
        .unwrap()
}

#[test]
fn takes_the_cell_margins_and_borders_of_a_row_s_exceptions() {
    // The table has 108 twip cell margins, a top border and lines between its rows. The first
    // row has no top border for itself (`w:tblPrEx`), and the second row a left cell margin
    // of 400 twips.
    let first = r#"<w:tblPrEx><w:tblBorders><w:top w:val="none"/></w:tblBorders></w:tblPrEx>"#;
    let second =
        r#"<w:tblPrEx><w:tblCellMar><w:left w:w="400" w:type="dxa"/></w:tblCellMar></w:tblPrEx>"#;
    let body = format!(
        r#"<w:tbl><w:tblPr><w:tblBorders><w:top {SINGLE}/><w:insideH {SINGLE}/></w:tblBorders></w:tblPr><w:tblGrid><w:gridCol w:w="2000"/></w:tblGrid><w:tr>{first}<w:tc>{}</w:tc></w:tr><w:tr>{second}<w:tc>{}</w:tc></w:tr><w:tr><w:tc>{}</w:tc></w:tr></w:tbl>"#,
        p("a"),
        p("b"),
        p("c")
    );
    let list = lay_out(&body, NORMAL, None);
    let x = |ch| x_du(find(&list, ch).1);
    assert_eq!(x('b') - x('a'), du(400 - 108));
    assert_eq!(x('c'), x('a'));
    // The first row starts at the 1440 twip margin without a line, and its text right there.
    assert!(rects(&list, 0).iter().all(|r| r.1 != du(1440)));
    assert_eq!(find(&list, 'a').2, base(1440));
    // The lines between the rows stay.
    assert_eq!(rects(&list, 0).len(), 2);
}

#[test]
fn hangs_the_first_cell_margin_into_the_margin_before_mode_15() {
    let list = lay_out(
        &(table("", &[2000, 3000], &[("", &[&p("a"), &p("b")])]) + &p("c")),
        NORMAL,
        Some(14),
    );
    // The text of the first cell sits at the 1440 twip margin, and the second cell starts at
    // 1440 - 108 + 2000 twips.
    assert_eq!(find(&list, 'a'), (0, 1440 * 1270, base(1440)));
    let (_, x, y) = find(&list, 'b');
    assert_eq!((x_du(x), y), (du(3440), base(1440)));
    // The paragraph after the table starts below the 200 twip row.
    assert_eq!(find(&list, 'c').2, base(1640));
    assert_eq!(rects(&list, 0), Vec::new());
}

#[test]
fn takes_the_widths_of_grid_columns_without_a_width_from_the_cells() {
    // A table across the 9,360 twip text width, whose first cell asks for 25%.
    let row = |first: &str| {
        format!(
            "<w:tr><w:tc><w:tcPr>{first}</w:tcPr>{}</w:tc><w:tc>{}</w:tc></w:tr>",
            p("a"),
            p("b")
        )
    };
    let whole = r#"<w:tblPr><w:tblW w:w="5000" w:type="pct"/></w:tblPr>"#;
    let quarter = row(r#"<w:tcW w:w="1250" w:type="pct"/>"#);
    let at = |body: &str| {
        let list = lay_out(&(body.to_owned() + &p("c")), NORMAL, Some(15));
        (find(&list, 'a'), find(&list, 'b'))
    };
    let written = |grid: &[i64]| table("", grid, &[("", &[&p("a"), &p("b")])]);
    // An empty grid takes the 25% and the rest.
    let empty =
        format!("<w:tbl>{whole}<w:tblGrid><w:gridCol/><w:gridCol/></w:tblGrid>{quarter}</w:tbl>");
    assert_eq!(at(&empty), at(&written(&[2340, 7020])));
    // Without a grid and without cell widths, the columns share the table's width.
    let shared = format!("<w:tbl>{whole}{}</w:tbl>", row(""));
    assert_eq!(at(&shared), at(&written(&[4680, 4680])));
}

/// A table of two cells with single borders on all sides, followed by a paragraph.
fn bordered() -> String {
    let borders = format!(
        "<w:tblBorders><w:top {SINGLE}/><w:left {SINGLE}/><w:bottom {SINGLE}/><w:right {SINGLE}/><w:insideV {SINGLE}/></w:tblBorders>"
    );
    table(&borders, &[2000, 3000], &[("", &[&p("a"), &p("b")])]) + &p("c")
}

#[test]
fn puts_the_outer_edge_of_the_left_border_at_the_indent_from_mode_15() {
    let list = lay_out(&bordered(), NORMAL, Some(15));
    // Half the 10 twip border, then the 108 twip margin. The top border comes above the text.
    let (_, x, y) = find(&list, 'a');
    assert_eq!((x_du(x), y), (du(1440 + 5 + 108), base(1440 + 10)));
    let (_, x, _) = find(&list, 'b');
    assert_eq!(x_du(x), du(1445 + 2000 + 108));
    // The bottom border comes below the last row.
    assert_eq!(find(&list, 'c').2, base(1440 + 10 + 200 + 10));
    let old = lay_out(&bordered(), NORMAL, None);
    let (_, x, _) = find(&old, 'a');
    assert_eq!(x_du(x), 300);
}

#[test]
fn puts_a_nested_table_at_the_outer_edge_of_its_left_border_in_every_mode() {
    let borders = format!("<w:tblBorders><w:left {SINGLE}/></w:tblBorders>");
    let inner = table(&borders, &[2000], &[("", &[&p("a")])]);
    let cell = inner + &p("b");
    let outer = table("", &[4000], &[("", &[&cell])]) + &p("c");
    let list = lay_out(&outer, NORMAL, Some(14));
    // Before mode 15, the outer table's text sits at the margin, but the nested table puts the
    // outer edge of its 10 twip border there and its text after half that and the margin.
    assert_eq!(x_du(find(&list, 'b').1), du(1440));
    assert_eq!(x_du(find(&list, 'a').1), du(1440 + 5 + 108));
}

#[test]
fn starts_the_text_after_the_left_border_without_a_left_margin() {
    // No style sets cell margins, so the text of each cell starts after its 10 twip border.
    let list = lay_out(&bordered(), "", Some(12));
    assert_eq!(x_du(find(&list, 'a').1), du(1440 + 10));
    assert_eq!(x_du(find(&list, 'b').1), du(1440 + 2000 + 10));
    // A left margin of 0 that the table sets keeps the text on the grid line.
    let zero = bordered().replace(
        "<w:tblBorders>",
        r#"<w:tblCellMar><w:left w:w="0" w:type="dxa"/></w:tblCellMar><w:tblBorders>"#,
    );
    let list = lay_out(&zero, "", Some(12));
    assert_eq!(x_du(find(&list, 'a').1), du(1440));
}

#[test]
fn draws_borders_around_the_cells() {
    let list = lay_out(&bordered(), NORMAL, Some(15));
    let rects = rects(&list, 0);
    // The lines run between the junctions, and each junction is a square of its own: two at
    // a corner of the table, where two lines end, and one where a line runs on.
    let square = |x: i64, y: i64| rects.iter().filter(|r| **r == (x, y, 2, 2)).count();
    let (bottom, middle, right) = (du(1650), du(1440 + 2000), du(1440 + 5000));
    assert_eq!(
        [square(300, 300), square(middle, 300), square(right, 300)],
        [2, 1, 2]
    );
    assert_eq!(
        [
            square(300, bottom),
            square(middle, bottom),
            square(right, bottom)
        ],
        [2, 1, 2]
    );
    // The left border, two device dots wide, runs from below the top line to the bottom one.
    assert!(rects.contains(&(300, 302, 2, bottom - 302)));
    // The top line runs from the left line to the line between the cells, and on from there.
    assert!(rects.contains(&(302, 300, middle - 302, 2)));
    assert!(rects.contains(&(middle + 2, 300, right - middle - 2, 2)));
    assert_eq!(rects.len(), 17);
}

#[test]
fn leaves_out_a_hidden_row_that_shows_nothing_with_its_lines() {
    let borders = format!(
        "<w:tblBorders><w:top {SINGLE}/><w:left {SINGLE}/><w:bottom {SINGLE}/><w:right {SINGLE}/><w:insideH {SINGLE}/></w:tblBorders>"
    );
    let hidden_mark = r"<w:p><w:pPr><w:rPr><w:vanish/></w:rPr></w:pPr></w:p>";
    let hidden_text = r"<w:p><w:pPr><w:rPr><w:vanish/></w:rPr></w:pPr><w:r><w:rPr><w:vanish/></w:rPr><w:t>h</w:t></w:r></w:p>";
    let laid = |body: &str| lay_out(body, NORMAL, Some(15));
    // A table of one hidden row that shows nothing is not there: the paragraph after it stands
    // where it stands without the table, and no line is drawn.
    let alone = p("a") + &table(&borders, &[2000], &[("<w:hidden/>", &[hidden_mark])]) + &p("c");
    let list = laid(&alone);
    assert_eq!(find(&list, 'c'), find(&laid(&(p("a") + &p("c"))), 'c'));
    assert_eq!(rects(&list, 0), [] as [(i64, i64, i64, i64); 0]);
    // Above a row that shows, the table is that row alone, with its top line.
    let one = laid(&(table(&borders, &[2000], &[("", &[&p("b")])]) + &p("c")));
    let b = p("b");
    let rows = [("<w:hidden/>", &[hidden_text][..]), ("", &[b.as_str()][..])];
    let above = laid(&(table(&borders, &[2000], &rows) + &p("c")));
    assert_eq!(rects(&above, 0), rects(&one, 0));
    assert_eq!(find(&above, 'c'), find(&one, 'c'));
    // A hidden row whose text shows stays, and so does a row that shows its row-end mark.
    let shown = laid(&(table(&borders, &[2000], &[("<w:hidden/>", &[&p("b")])]) + &p("c")));
    assert_eq!(rects(&shown, 0), rects(&one, 0));
    let mark_shown = laid(&(table(&borders, &[2000], &[("", &[hidden_mark])]) + &p("c")));
    assert_ne!(rects(&mark_shown, 0), [] as [(i64, i64, i64, i64); 0]);
}

/// The rectangles of page `page` that are drawn more than once and are not junction squares,
/// which Word draws once for each line that ends there: the lines drawn twice.
fn doubled_lines(list: &DisplayList, page: usize) -> Vec<(i64, i64, i64, i64)> {
    let rects = rects(list, page);
    let mut doubled: Vec<_> = rects
        .iter()
        .filter(|r| r.2 != r.3 && rects.iter().filter(|s| s == r).count() > 1)
        .copied()
        .collect();
    doubled.sort_unstable();
    doubled.dedup();
    doubled
}

#[test]
fn draws_the_line_that_two_cells_or_two_rows_share_once() {
    // Two rows of two cells, with every border: the line between the cells is the right
    // border of the first cell and the left border of the second, and the line between the
    // rows the top border of the second row, which takes the bottom border of the first.
    let borders = format!(
        "<w:tblBorders><w:top {SINGLE}/><w:left {SINGLE}/><w:bottom {SINGLE}/><w:right {SINGLE}/><w:insideH {SINGLE}/><w:insideV {SINGLE}/></w:tblBorders>"
    );
    let rows: [(&str, &[&str]); 2] = [("", &[&p("a"), &p("b")]), ("", &[&p("c"), &p("d")])];
    let list = lay_out(&table(&borders, &[2000, 3000], &rows), NORMAL, Some(15));
    assert_eq!(doubled_lines(&list, 0), []);
    // The line between the cells runs down each row once, between the squares.
    let middle = du(1440 + 2000);
    let between: Vec<_> = rects(&list, 0)
        .into_iter()
        .filter(|r| r.0 == middle && r.2 == 2 && r.3 > 2)
        .collect();
    assert_eq!(between.len(), 2, "{between:?}");
}

#[test]
fn draws_the_line_between_two_cells_of_the_last_row_once_when_one_has_no_bottom() {
    // One row of two cells with every border, but the second cell takes away its bottom: the
    // line between the cells is the first cell's right border, which ends with its bottom
    // line, and the second cell's left border, which ends at the row's bottom.
    let borders = format!(
        "<w:tblBorders><w:top {SINGLE}/><w:left {SINGLE}/><w:bottom {SINGLE}/><w:right {SINGLE}/><w:insideV {SINGLE}/></w:tblBorders>"
    );
    let open = format!(
        r#"<w:tcPr><w:tcBorders><w:bottom w:val="nil"/></w:tcBorders></w:tcPr>{}"#,
        p("b")
    );
    let rows: [(&str, &[&str]); 1] = [("", &[&p("a"), &open])];
    let list = lay_out(&table(&borders, &[2000, 3000], &rows), NORMAL, Some(15));
    assert_eq!(doubled_lines(&list, 0), []);
    // The line between the cells runs once from the square at the top to the square of the
    // first cell's bottom line.
    let middle = du(1440 + 2000);
    let between: Vec<_> = rects(&list, 0)
        .into_iter()
        .filter(|r| r.0 == middle && r.2 == 2 && r.3 > 2)
        .collect();
    assert_eq!(between, [(middle, 302, 2, du(1650) - 302)]);
}

#[test]
fn lays_the_cells_of_a_right_to_left_table_out_from_the_right() {
    let rows: [(&str, &[&str]); 1] = [("", &[&p("a"), &p("b"), &p("c")])];
    let ltr = lay_out(&table("", &[2000, 3000, 4000], &rows), NORMAL, Some(15));
    let rtl = lay_out(
        &table("<w:bidiVisual/>", &[2000, 3000, 4000], &rows),
        NORMAL,
        Some(15),
    );
    // Left to right, "a" comes first; right to left, "c" comes first and "a" last.
    let x = |list: &DisplayList, ch| find(list, ch).1;
    assert!(x(&ltr, 'a') < x(&ltr, 'b') && x(&ltr, 'b') < x(&ltr, 'c'));
    assert!(x(&rtl, 'c') < x(&rtl, 'b') && x(&rtl, 'b') < x(&rtl, 'a'));
    // The column of the margins holds the 9,000 twip table at its right: the first cell's
    // grid line on the right is at the right margin of 12,240 - 1,440 twips, so "a" starts a
    // cell margin right of the cell's left grid line, 2,000 twips further left.
    assert_eq!(x_du(x(&rtl, 'a')), du(12_240 - 1_440 - 2_000 + 108));
}

#[test]
fn draws_the_outer_lines_of_a_right_to_left_table_around_its_cells() {
    let borders = format!(
        "<w:bidiVisual/><w:tblBorders><w:top {SINGLE}/><w:left {SINGLE}/><w:bottom {SINGLE}/><w:right {SINGLE}/><w:insideV {SINGLE}/></w:tblBorders>"
    );
    let rows: [(&str, &[&str]); 1] = [("", &[&p("a"), &p("b")])];
    let list = lay_out(&table(&borders, &[2000, 3000], &rows), NORMAL, Some(15));
    let rects = rects(&list, 0);
    assert!(rects.iter().all(|r| r.2 > 0 && r.3 > 0), "{rects:?}");
    // The lines at the table's top run from the outer edge of its left line to the outer edge
    // of its right line, as in a table from left to right.
    let left = rects.iter().map(|r| r.0).min();
    let right = rects.iter().map(|r| r.0 + r.2).max();
    let top = rects.iter().map(|r| r.1).min();
    let at_top: Vec<_> = rects.iter().filter(|r| Some(r.1) == top).collect();
    assert_eq!(at_top.iter().map(|r| r.0).min(), left, "{rects:?}");
    assert_eq!(at_top.iter().map(|r| r.0 + r.2).max(), right, "{rects:?}");
}

#[test]
fn starts_a_right_to_left_table_wider_than_the_text_at_the_left_margin() {
    let rows: [(&str, &[&str]); 1] = [("", &[&p("a"), &p("b")])];
    let wide = |properties: &str, section: &str, mode: u32| {
        let body = table(properties, &[3000, 7000], &rows) + section;
        lay_out(&body, NORMAL, Some(mode))
    };
    let x = |list: &DisplayList, ch| x_du(find(list, ch).1);
    // In a left-to-right section the table of 10,000 twips goes over the left margin: its
    // right grid line is at the right margin.
    let list = wide("<w:bidiVisual/>", "", 15);
    assert_eq!(x(&list, 'a'), du(12_240 - 1_440 - 3_000 + 108));
    // So it does in a right-to-left section in mode 14, where the grid lies a cell margin
    // further out.
    let section = "<w:sectPr><w:bidi/></w:sectPr>";
    let list = wide("<w:bidiVisual/>", section, 14);
    assert_eq!(x(&list, 'a'), du(12_240 - 1_440 - 3_000 + 2 * 108));
    // In a right-to-left section from mode 15 its left grid line stays at the left margin,
    // also with an indent that moves its leading edge to the right, and when centered.
    for properties in [
        "<w:bidiVisual/>",
        r#"<w:bidiVisual/><w:tblInd w:w="-226" w:type="dxa"/>"#,
        r#"<w:bidiVisual/><w:jc w:val="center"/>"#,
    ] {
        let list = wide(properties, section, 15);
        assert_eq!(x(&list, 'b'), du(1_440 + 108));
        assert_eq!(x(&list, 'a'), du(1_440 + 7_000 + 108));
    }
}

#[test]
fn moves_a_right_to_left_table_in_by_the_lines_of_its_first_and_last_cell_where_the_quirk_says() {
    let line = |side: &str, eighths: u32| {
        if eighths == 0 {
            format!(r#"<w:{side} w:val="nil"/>"#)
        } else {
            format!(r#"<w:{side} w:val="single" w:sz="{eighths}"/>"#)
        }
    };
    let cell = |own: &str, text: &str| {
        format!(
            "<w:tcPr><w:tcBorders>{own}</w:tcBorders></w:tcPr>{}",
            p(text)
        )
    };
    // The place of "c", in the last cell at the table's left end beside its 1 pt line that the
    // file calls right, in a right-to-left table of mode 15 whose line that the file calls left
    // is `left` and whose lines between cells are `inside` eighths of a point wide, with the
    // own lines `second` of the second cell and `last` of the last.
    let x = |edge: RightToLeftEdge, (left, inside): (u32, u32), (second, last): (&str, &str)| {
        let props = format!(
            "<w:bidiVisual/><w:tblBorders><w:top {SINGLE}/>{}<w:bottom {SINGLE}/>{}{}</w:tblBorders>",
            line("left", left),
            line("right", 8),
            line("insideV", inside)
        );
        let cells = [p("a"), cell(second, "b"), cell(last, "c")];
        let rows: [(&str, &[&str]); 1] = [("", &[&cells[0], &cells[1], &cells[2]])];
        let body = table(&props, &[2000, 3000, 4000], &rows);
        let target = crate::layout::testing::target_at(600, |configuration| {
            configuration.with_variant(edge)
        });
        let pass = pass_with(
            &body,
            (NORMAL, Some(15)),
            None,
            Numbering::default(),
            target,
        );
        x_du(find(&pass.list, 'c').1)
    };
    // A 3 pt line at the leading edge and nil lines between cells: the line between the first
    // two cells moves nothing, and the leading line moves the table half its width, 30 twips.
    let (between, leading) = (
        RightToLeftEdge::BetweenCells,
        RightToLeftEdge::LeadingAndInside,
    );
    assert_eq!(
        x(between, (24, 0), ("", "")) - x(leading, (24, 0), ("", "")),
        du(30)
    );
    // With lines of 3 pt between cells, the second cell's own nil line toward the first moves
    // nothing, and the last cell's own nil line that the file calls left takes their half, 30
    // twips, away.
    let (own_nil, plain) = (line("left", 0), x(leading, (8, 24), ("", "")));
    assert_eq!(x(leading, (8, 24), (&own_nil, "")), plain);
    assert_eq!(x(leading, (8, 24), ("", &own_nil)) - plain, du(30));
}

#[test]
fn moves_a_floating_right_to_left_table_left_by_the_line_of_its_last_cell_where_the_quirk_says() {
    let line = |side: &str, eighths: u32| {
        if eighths == 0 {
            format!(r#"<w:{side} w:val="nil"/>"#)
        } else {
            format!(r#"<w:{side} w:val="single" w:sz="{eighths}"/>"#)
        }
    };
    // The place of "c", in the last cell at the table's left end, in a right-to-left table of
    // mode 15 that floats 720 twips right of the margin, whose line that the file calls left is
    // `left` and whose lines between cells are `inside` eighths of a point wide, with the own
    // lines `last` of the last cell.
    let x = |edge: RightToLeftEdge, (left, inside): (u32, u32), last: &str| {
        let props = format!(
            r#"<w:tblpPr w:vertAnchor="text" w:horzAnchor="margin" w:tblpX="720" w:tblpY="1"/><w:bidiVisual/><w:tblBorders><w:top {SINGLE}/>{}<w:bottom {SINGLE}/>{}{}</w:tblBorders>"#,
            line("left", left),
            line("right", 8),
            line("insideV", inside)
        );
        let own = format!(
            "<w:tcPr><w:tcBorders>{last}</w:tcBorders></w:tcPr>{}",
            p("c")
        );
        let cells = [p("a"), p("b"), own];
        let rows: [(&str, &[&str]); 1] = [("", &[&cells[0], &cells[1], &cells[2]])];
        let body = table(&props, &[2000, 3000, 4000], &rows) + &p("after");
        let target = crate::layout::testing::target_at(600, |configuration| {
            configuration.with_variant(edge)
        });
        let pass = pass_with(
            &body,
            (NORMAL, Some(15)),
            None,
            Numbering::default(),
            target,
        );
        x_du(find(&pass.list, 'c').1)
    };
    let (between, leading) = (
        RightToLeftEdge::BetweenCells,
        RightToLeftEdge::LeadingAndInside,
    );
    // With lines of 3 pt between cells, the earlier rule moves the table right by half the line
    // between its first two cells, 30 twips, and the quirk moves it left by half the last
    // cell's line toward the cell before it, 30 twips.
    assert_eq!(x(between, (8, 24), "") - x(leading, (8, 24), ""), du(60));
    // The line at the leading edge moves nothing.
    assert_eq!(x(leading, (24, 8), ""), x(leading, (8, 8), ""));
    // The last cell's own nil line takes the half of the lines between cells away.
    let own_nil = line("left", 0);
    assert_eq!(
        x(leading, (8, 24), &own_nil) - x(leading, (8, 24), ""),
        du(30)
    );
}

#[test]
fn draws_the_bottom_of_a_cell_with_no_cell_below_it() {
    let borders = format!(
        "<w:tblBorders><w:top {SINGLE}/><w:left {SINGLE}/><w:bottom {SINGLE}/><w:right {SINGLE}/><w:insideH {SINGLE}/><w:insideV {SINGLE}/></w:tblBorders>"
    );
    let rows: [(&str, &[&str]); 3] = [
        ("", &[&p("a"), &p("b")]),
        // The second row leaves out the second grid column.
        (r#"<w:gridAfter w:val="1"/>"#, &[&p("c")]),
        ("", &[&p("d"), &p("e")]),
    ];
    let body = table(&borders, &[2000, 3000], &rows) + &p("f");
    let list = lay_out(&body, NORMAL, Some(15));
    let rects = rects(&list, 0);
    // Below "b", where the second row has no cell, a line runs from the line between the cells
    // to the right edge of the table, at the top of the second row.
    let second_row = du(1440 + 10 + 200);
    let line = |r: &&(i64, i64, i64, i64)| r.3 == 2 && r.2 > du(2900) && r.2 < du(3100);
    let lines: Vec<i64> = rects.iter().filter(line).map(|r| r.1).collect();
    // One line above "b", one below it, one above "e" and one below it.
    assert_eq!(lines.len(), 4);
    assert!(lines.contains(&second_row));
}

/// The colors of the vertical lines of the first page of `body` with the quirk `ends`, as
/// their red and green channels and their left edge in dots, from left to right and from the
/// top down.
fn vertical_colors(body: &str, ends: crate::quirks::RowEndBorders) -> Vec<(u8, u8, i64, i64)> {
    let target = on_base_with(|p| p.with_variant(ends));
    vertical_lines(body, NORMAL, &target)
}

/// The colors of the vertical lines of the first page of `body` with the styles `styles` on
/// `target`, as their red and green channels and their left edge in dots, from left to right
/// and from the top down.
fn vertical_lines(
    body: &str,
    styles: &str,
    target: &(crate::grid::Device, crate::quirks::Quirks),
) -> Vec<(u8, u8, i64, i64)> {
    let list = pass_with(body, (styles, None), None, Numbering::default(), *target).list;
    let mut lines: Vec<(u8, u8, i64, i64)> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Rect(r) if r.height.units() > 4 * r.width.units() => {
                Some((r.color.r, r.color.g, r.x.units() / DOT, r.y.units() / DOT))
            }
            _ => None,
        })
        .collect();
    lines.sort_by_key(|line| (line.2, line.3));
    lines
}

#[test]
fn gives_a_rows_last_cell_the_outer_right_border_on_a_target_that_does() {
    // Three rows of two grid columns; the second row leaves out the second column. The table's
    // outer right border is red and its inside vertical border green. Under `RowEnds`, the
    // second row's one cell takes the red line on its right, where the grid's columns meet;
    // under `GridEdges`, the green one, as between two cells.
    let borders = format!(
        r#"<w:tblBorders><w:right {SINGLE} w:color="FF0000"/><w:insideV {SINGLE} w:color="00FF00"/></w:tblBorders>"#
    );
    let rows: [(&str, &[&str]); 3] = [
        ("", &[&p("a"), &p("b")]),
        (r#"<w:gridAfter w:val="1"/>"#, &[&p("c")]),
        ("", &[&p("d"), &p("e")]),
    ];
    let body = table(&borders, &[2000, 3000], &rows);
    let red = |lines: &[(u8, u8, i64, i64)]| lines.iter().filter(|l| l.0 == 0xFF).count();
    let green = |lines: &[(u8, u8, i64, i64)]| lines.iter().filter(|l| l.1 == 0xFF).count();
    let ends = vertical_colors(&body, crate::quirks::RowEndBorders::RowEnds);
    assert_eq!((red(&ends), green(&ends)), (3, 2), "{ends:?}");
    // The red line of the second row stands where the green lines of the other rows stand.
    let middle: Vec<_> = ends.iter().filter(|l| l.2 == ends[0].2).collect();
    assert_eq!(middle.len(), 3, "{ends:?}");
    assert_eq!(middle[1].0, 0xFF, "{ends:?}");
    let edges = vertical_colors(&body, crate::quirks::RowEndBorders::GridEdges);
    assert_eq!((red(&edges), green(&edges)), (2, 3), "{edges:?}");
}

#[test]
fn gives_the_side_lines_of_a_style_region_to_its_outer_cells_only_on_a_target_that_does() {
    // The header row's region sets red left and right lines and no line between its cells
    // (`w:insideV` nil), and the table no lines of its own. Under `Blocks`, the header row draws
    // red lines only at the table's left and right; under `EachCell`, each of its three cells
    // takes both red lines, which stand at all four grid lines. The second row draws none.
    let style = format!(
        r#"{NORMAL}<w:style w:type="table" w:styleId="Head"><w:basedOn w:val="TableNormal"/>
        <w:tblStylePr w:type="firstRow"><w:tcPr><w:tcBorders><w:left {SINGLE} w:color="FF0000"/>
        <w:right {SINGLE} w:color="FF0000"/><w:insideV w:val="nil"/></w:tcBorders></w:tcPr></w:tblStylePr></w:style>"#
    );
    let look = r#"<w:tblStyle w:val="Head"/><w:tblLook w:firstRow="1"/>"#;
    let rows: [(&str, &[&str]); 2] = [
        ("", &[&p("a"), &p("b"), &p("c")]),
        ("", &[&p("d"), &p("e"), &p("f")]),
    ];
    let body = table(look, &[2000, 2000, 2000], &rows);
    let lines = |regions| {
        let target = on_base_with(|p| p.with_variant(regions));
        vertical_lines(&body, &style, &target)
    };
    let blocks = lines(crate::quirks::StyleRegionBorders::Blocks);
    assert_eq!(blocks.len(), 2, "{blocks:?}");
    assert!(blocks.iter().all(|line| line.0 == 0xFF), "{blocks:?}");
    let each = lines(crate::quirks::StyleRegionBorders::EachCell);
    assert_eq!(each.len(), 4, "{each:?}");
}

#[test]
fn gives_a_rows_first_cell_after_grid_before_the_outer_left_border_on_a_target_that_does() {
    // The second row starts after the first grid column. The table's outer left border is
    // red and its inside vertical border green; the second row's one cell takes the red line
    // on its left under `RowEnds`, and the green one under `GridEdges`.
    let borders = format!(
        r#"<w:tblBorders><w:left {SINGLE} w:color="FF0000"/><w:insideV {SINGLE} w:color="00FF00"/></w:tblBorders>"#
    );
    let rows: [(&str, &[&str]); 3] = [
        ("", &[&p("a"), &p("b")]),
        (r#"<w:gridBefore w:val="1"/>"#, &[&p("c")]),
        ("", &[&p("d"), &p("e")]),
    ];
    let body = table(&borders, &[2000, 3000], &rows);
    let count = |lines: &[(u8, u8, i64, i64)]| {
        (
            lines.iter().filter(|l| l.0 == 0xFF).count(),
            lines.iter().filter(|l| l.1 == 0xFF).count(),
        )
    };
    assert_eq!(
        count(&vertical_colors(
            &body,
            crate::quirks::RowEndBorders::RowEnds
        )),
        (3, 2)
    );
    assert_eq!(
        count(&vertical_colors(
            &body,
            crate::quirks::RowEndBorders::GridEdges
        )),
        (2, 3)
    );
}

#[test]
fn applies_the_row_height_rules() {
    let margins = r#"<w:tblCellMar><w:top w:w="20" w:type="dxa"/><w:bottom w:w="40" w:type="dxa"/></w:tblCellMar>"#;
    let rows: &[(&str, &[&str])] = &[
        (r#"<w:trHeight w:val="600"/>"#, &[&p("a")]),
        (r#"<w:trHeight w:val="400" w:hRule="exact"/>"#, &[&p("b")]),
        (r#"<w:trHeight w:val="900" w:hRule="auto"/>"#, &[&p("c")]),
        (r#"<w:trHeight w:val="100" w:hRule="atLeast"/>"#, &[&p("d")]),
    ];
    let list = lay_out(&(table(margins, &[2000], rows) + &p("e")), NORMAL, None);
    // At least 600 twips without the margins, exactly 400 twips with the top margin, and the
    // content with its margins.
    assert_eq!(find(&list, 'a').2, base(1440 + 20));
    assert_eq!(find(&list, 'b').2, base(2100 + 20));
    assert_eq!(find(&list, 'c').2, base(2520 + 20));
    assert_eq!(find(&list, 'd').2, base(2780 + 20));
    assert_eq!(find(&list, 'e').2, base(3040));
}

#[test]
fn aligns_cell_content_vertically() {
    let cell = |align: &str, text: &str| {
        format!(r#"<w:tcPr><w:vAlign w:val="{align}"/></w:tcPr>{}"#, p(text))
    };
    let rows: &[(&str, &[&str])] = &[(
        r#"<w:trHeight w:val="1000"/>"#,
        &[
            &cell("bottom", "a"),
            &cell("center", "b"),
            &cell("top", "c"),
        ],
    )];
    let list = lay_out(&table("", &[2000, 2000, 2000], rows), NORMAL, None);
    assert_eq!(find(&list, 'a').2, base(1440 + 800));
    assert_eq!(find(&list, 'b').2, base(1440 + 400));
    assert_eq!(find(&list, 'c').2, base(1440));
}

#[test]
fn aligns_cells_as_their_table_style_says() {
    // The style centers its cells and puts those of the first row at the bottom; a cell's own
    // `w:vAlign` wins over both.
    let style = format!(
        r#"{NORMAL}<w:style w:type="table" w:styleId="Mid"><w:basedOn w:val="TableNormal"/>
        <w:tcPr><w:vAlign w:val="center"/></w:tcPr>
        <w:tblStylePr w:type="firstRow"><w:tcPr><w:vAlign w:val="bottom"/></w:tcPr></w:tblStylePr></w:style>"#
    );
    let look = r#"<w:tblStyle w:val="Mid"/><w:tblLook w:firstRow="1"/>"#;
    let top = format!(r#"<w:tcPr><w:vAlign w:val="top"/></w:tcPr>{}"#, p("b"));
    let rows: &[(&str, &[&str])] = &[
        (r#"<w:trHeight w:val="1000"/>"#, &[&p("a"), &top]),
        (r#"<w:trHeight w:val="1000"/>"#, &[&p("c"), &p("d")]),
    ];
    let list = lay_out(&table(look, &[2000, 2000], rows), &style, None);
    assert_eq!(find(&list, 'a').2, base(1440 + 800));
    assert_eq!(find(&list, 'b').2, base(1440));
    assert_eq!(find(&list, 'c').2, base(2440 + 400));
    assert_eq!(find(&list, 'd').2, base(2440 + 400));
}

#[test]
fn grows_the_last_row_of_a_merged_region() {
    let restart = format!(
        r#"<w:tcPr><w:vMerge w:val="restart"/></w:tcPr>{}{}{}"#,
        p("a"),
        p("b"),
        p("c")
    );
    let rows: &[(&str, &[&str])] = &[
        ("", &[&restart, &p("d")]),
        (
            "",
            &[&format!("<w:tcPr><w:vMerge/></w:tcPr>{}", p("x")), &p("e")],
        ),
    ];
    let list = lay_out(&(table("", &[2000, 2000], rows) + &p("f")), NORMAL, None);
    assert_eq!(find(&list, 'c').2, base(1440 + 400));
    assert_eq!(find(&list, 'e').2, base(1640));
    // The second row grows so that the merged cell fits, and the continuing cell shows
    // nothing.
    assert_eq!(find(&list, 'f').2, base(2040));
    assert_eq!(find_all(&list, 'x'), Vec::new());
}

#[test]
fn centers_a_merged_cell_over_its_region() {
    let restart = format!(
        r#"<w:tcPr><w:vMerge w:val="restart"/><w:vAlign w:val="center"/></w:tcPr>{}"#,
        p("a")
    );
    let rows: &[(&str, &[&str])] = &[
        ("", &[&restart, &p("b")]),
        ("", &["<w:tcPr><w:vMerge/></w:tcPr><w:p/>", &p("c")]),
        ("", &["<w:tcPr><w:vMerge/></w:tcPr><w:p/>", &p("d")]),
    ];
    let list = lay_out(&table("", &[2000, 2000], rows), NORMAL, None);
    // The region is 600 twips tall and the cell 200, so the cell moves down 200 twips. The
    // move is rounded on its own.
    assert_eq!(find(&list, 'a').2, base(1440) + du(200));
    assert_eq!(find(&list, 'd').2, base(1840));
}

#[test]
fn applies_the_regions_of_the_table_style() {
    let style = format!(
        r#"{NORMAL}<w:style w:type="table" w:styleId="Fancy"><w:basedOn w:val="TableNormal"/>
        <w:tblPr><w:tblStyleRowBandSize w:val="1"/></w:tblPr>
        <w:tblStylePr w:type="firstRow"><w:rPr><w:b/></w:rPr></w:tblStylePr>
        <w:tblStylePr w:type="nwCell"><w:rPr><w:i/></w:rPr></w:tblStylePr>
        <w:tblStylePr w:type="band1Horz"><w:tcPr><w:tcBorders><w:top w:val="single" w:sz="8"/></w:tcBorders></w:tcPr></w:tblStylePr>
        <w:tblStylePr w:type="lastCol"><w:rPr><w:i/></w:rPr></w:tblStylePr></w:style>"#
    );
    let look = r#"<w:tblStyle w:val="Fancy"/><w:tblLook w:firstRow="1" w:firstColumn="1" w:lastColumn="0" w:noVBand="1"/>"#;
    let rows: &[(&str, &[&str])] = &[
        ("", &[&p("a"), &p("b")]),
        ("", &[&p("c"), &p("d")]),
        ("", &[&p("e"), &p("f")]),
        ("", &[&p("g"), &p("h")]),
    ];
    let list = lay_out(&table(look, &[2000, 2000], rows), &style, None);
    assert_eq!(font_of(&list, 'a'), FontId::from_index(3));
    assert_eq!(font_of(&list, 'b'), FontId::from_index(1));
    assert_eq!(font_of(&list, 'd'), FontId::from_index(0));
    // The bands start below the first row: the second and the fourth rows get a top border.
    assert_eq!(find(&list, 'c').2, base(1640 + 20));
    assert_eq!(find(&list, 'e').2, base(1860));
    assert_eq!(find(&list, 'g').2, base(2060 + 20));
}

#[test]
fn draws_a_line_where_one_of_two_cells_has_one() {
    let above = format!(
        r#"<w:tcPr><w:tcBorders><w:bottom w:val="single" w:sz="8"/></w:tcBorders></w:tcPr>{}"#,
        p("a")
    );
    let below = format!(
        r#"<w:tcPr><w:tcBorders><w:top w:val="nil"/></w:tcBorders></w:tcPr>{}"#,
        p("b")
    );
    let rows: &[(&str, &[&str])] = &[("", &[&above]), ("", &[&below])];
    let list = lay_out(&table("", &[2000], rows), NORMAL, None);
    assert_eq!(find(&list, 'b').2, base(1640 + 20));
    assert_eq!(rects(&list, 0).len(), 1);
}

#[test]
fn places_nested_tables_in_their_cell() {
    let inner = table(
        r#"<w:tblInd w:w="200" w:type="dxa"/>"#,
        &[1000],
        &[("", &[&p("n")])],
    );
    let rows: &[(&str, &[&str])] = &[("", &[&(inner + &p("o"))])];
    let list = lay_out(&table("", &[3000], rows), NORMAL, None);
    // The nested table does not hang its 108 twip margin out of its indent.
    let (_, x, y) = find(&list, 'n');
    assert_eq!((x_du(x), y), (du(1440 + 200 + 108), base(1440)));
    assert_eq!(find(&list, 'o').2, base(1640));
}

#[test]
fn aligns_tables_between_the_margins() {
    let center = table(r#"<w:jc w:val="center"/>"#, &[2000], &[("", &[&p("a")])]);
    let end = table(r#"<w:jc w:val="right"/>"#, &[2000], &[("", &[&p("b")])]);
    let list = lay_out(&(center + &end), NORMAL, None);
    let (_, x, _) = find(&list, 'a');
    assert_eq!(x_du(x), du(1440 + 3680 + 108));
    // Before mode 15, a right-aligned table extends its trailing cell margin past the right column
    // edge so the last cell's text lines up with the column margin.
    let (_, x, _) = find(&list, 'b');
    assert_eq!(x_du(x), du(1440 + 7360 + 108 + 108));
}

#[test]
fn takes_columns_from_the_cells_without_a_grid_and_skips_grid_columns() {
    let no_grid = r#"<w:tbl><w:tr><w:tc><w:tcPr><w:tcW w:w="1000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>a</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>b</w:t></w:r></w:p></w:tc></w:tr></w:tbl>"#;
    let list = lay_out(no_grid, NORMAL, None);
    let (_, x, _) = find(&list, 'b');
    assert_eq!(x_du(x), du(1332 + 1000 + 108));
    let skipped = table(
        "",
        &[1000, 2000],
        &[
            (r#"<w:gridBefore w:val="1"/>"#, &[&p("c")]),
            ("", &[&p("d"), &p("e")]),
        ],
    );
    let list = lay_out(&skipped, NORMAL, None);
    let (_, x, _) = find(&list, 'c');
    assert_eq!(x_du(x), du(1332 + 1000 + 108));
    // A missing grid line falls back to the last one.
    let short = table("", &[1000], &[("", &[&p("f"), &p("g")])]);
    let list = lay_out(&short, NORMAL, None);
    let (_, x, _) = find(&list, 'g');
    assert_eq!(x_du(x), du(1332 + 1000 + 108));
}

#[test]
fn picks_the_wider_line() {
    let line = |eighths| {
        Some(Border::new(
            BorderParts::single(Length::from_eighth_points(eighths).unwrap()),
            Length::ZERO,
            Color::Auto,
        ))
    };
    assert_eq!(heavier(line(4), line(8)), line(8));
    assert_eq!(heavier(line(8), line(4)), line(8));
    let red = line(4).map(|b| Border {
        color: Color::Rgb([255, 0, 0]),
        ..b
    });
    assert_eq!(heavier(line(4), red), line(4));
    assert_eq!(heavier(None, line(4)), line(4));
    assert_eq!(heavier(line(4), None), line(4));
    assert_eq!(heavier(None, None), None);
}

#[test]
fn moves_content_down_for_its_alignment() {
    let shifts = [
        (Some(VerticalAlign::Center), 9),
        (Some(VerticalAlign::Bottom), 9),
        (Some(VerticalAlign::Bottom), -9),
        (Some(VerticalAlign::Center), -9),
        (Some(VerticalAlign::Top), 9),
        (None, 9),
    ]
    .map(|(a, free)| align(a, Length::from_units(free)).units());
    assert_eq!(shifts, [4, 9, 0, 0, 0, 0]);
    let bands = [0, 1, 3].map(|i| band(i, Region::Band1Horz, Region::Band2Horz));
    assert_eq!(
        bands,
        [Region::Band1Horz, Region::Band2Horz, Region::Band2Horz]
    );
}

#[test]
fn computes_row_heights() {
    let at = Length::from_units;
    let margins = Sides {
        top: at(2),
        left: Length::ZERO,
        bottom: at(3),
        right: Length::ZERO,
    };
    let cells = [(at(10), margins), (at(20), Sides::default())];
    let height = |h: i64, rule| Some((at(h), rule));
    let quirks = with_margin(ExactRowMargin::AddsTopMargin);
    let row = |rule| row_height(at(1), &cells, rule, &quirks).units();
    assert_eq!(row(None), 21);
    assert_eq!(row(height(30, HeightRule::Auto)), 21);
    assert_eq!(row(height(30, HeightRule::AtLeast)), 36);
    assert_eq!(row(height(5, HeightRule::AtLeast)), 21);
    assert_eq!(row(height(5, HeightRule::Exact)), 7);
    let none = row_height(at(1), &[], None, &quirks);
    assert_eq!(none, at(1));
}

#[test]
fn a_row_of_exact_height_adds_the_cell_margin_that_the_target_asks_for() {
    // A cell with a top margin of 2 and a bottom margin of 3 under an exact height of 5: the
    // row adds its top margin on one target and its bottom margin on another, and a row of
    // minimum height adds both on each.
    let at = Length::from_units;
    let margins = Sides {
        top: at(2),
        left: Length::ZERO,
        bottom: at(3),
        right: Length::ZERO,
    };
    let cells = [(at(4), margins)];
    let row =
        |rule, margin| row_height(at(1), &cells, Some((at(5), rule)), &with_margin(margin)).units();
    assert_eq!(row(HeightRule::Exact, ExactRowMargin::AddsTopMargin), 7);
    assert_eq!(row(HeightRule::Exact, ExactRowMargin::AddsBottomMargin), 8);
    assert_eq!(row(HeightRule::AtLeast, ExactRowMargin::AddsTopMargin), 11);
    assert_eq!(
        row(HeightRule::AtLeast, ExactRowMargin::AddsBottomMargin),
        11
    );
}

/// The quirks of the base target with `margin` as the rule for a row of exact height.
fn with_margin(margin: ExactRowMargin) -> crate::quirks::Quirks {
    crate::layout::testing::on_base_with(|p| p.with_variant(margin)).1
}

/// A table style that marks each region in its own way: the column bands indent, the row bands
/// add space before, the first and last columns are bold and italic, the first row is in
/// capitals, and the last row and the corner cells have their own sizes.
const REGIONS: &str = r#"<w:style w:type="table" w:styleId="Regions"><w:basedOn w:val="TableNormal"/>
    <w:pPr><w:jc w:val="left"/></w:pPr>
    <w:tblPr><w:tblStyleRowBandSize w:val="2"/><w:tblStyleColBandSize w:val="2"/></w:tblPr>
    <w:tblStylePr w:type="band1Vert"><w:pPr><w:ind w:left="100"/></w:pPr></w:tblStylePr>
    <w:tblStylePr w:type="band2Vert"><w:pPr><w:ind w:left="200"/></w:pPr></w:tblStylePr>
    <w:tblStylePr w:type="band1Horz"><w:pPr><w:spacing w:before="20"/></w:pPr></w:tblStylePr>
    <w:tblStylePr w:type="band2Horz"><w:pPr><w:spacing w:before="40"/></w:pPr></w:tblStylePr>
    <w:tblStylePr w:type="firstCol"><w:rPr><w:b/></w:rPr></w:tblStylePr>
    <w:tblStylePr w:type="lastCol"><w:rPr><w:i/></w:rPr></w:tblStylePr>
    <w:tblStylePr w:type="firstRow"><w:rPr><w:caps/></w:rPr></w:tblStylePr>
    <w:tblStylePr w:type="lastRow"><w:rPr><w:sz w:val="30"/></w:rPr></w:tblStylePr>
    <w:tblStylePr w:type="nwCell"><w:rPr><w:sz w:val="24"/></w:rPr></w:tblStylePr>
    <w:tblStylePr w:type="neCell"><w:rPr><w:sz w:val="26"/></w:rPr></w:tblStylePr>
    <w:tblStylePr w:type="swCell"><w:rPr><w:sz w:val="28"/></w:rPr></w:tblStylePr>
    <w:tblStylePr w:type="seCell"><w:rPr><w:sz w:val="32"/></w:rPr></w:tblStylePr></w:style>"#;

/// A table of six rows and six columns of 1000 twips in the regions style, with one letter in
/// each cell, row by row.
fn regions() -> DisplayList {
    let letters: Vec<String> = ('a'..='z')
        .chain('0'..='9')
        .map(|c| p(&c.to_string()))
        .collect();
    let rows: Vec<Vec<&str>> = letters
        .chunks(6)
        .map(|row| row.iter().map(String::as_str).collect())
        .collect();
    let rows: Vec<(&str, &[&str])> = rows.iter().map(|r| ("", r.as_slice())).collect();
    let look = r#"<w:tblStyle w:val="Regions"/><w:tblLook w:firstRow="1" w:lastRow="1" w:firstColumn="1" w:lastColumn="1" w:noHBand="0" w:noVBand="0"/>"#;
    let style = format!("{NORMAL}{REGIONS}");
    lay_out(&table(look, &[1000; 6], &rows), &style, None)
}

/// The text start of a cell in the regions table: its grid line, its margin and an indent.
fn column(index: i64, indent: i64) -> i64 {
    indented(1332 + 1000 * index + 108, indent)
}

#[test]
fn bands_columns_and_rows_in_groups() {
    let list = regions();
    // Row 1 holds g to l, row 3 holds s to x. Column bands of two start after column 0. The
    // first and last columns are in no column band, and the last row in no row band.
    let row1 = base(1700 + 20);
    let found = ['g', 'h', 'i', 'j', 'l', 't', '6'].map(|ch| at(&list, ch));
    let expected = [
        (column(0, 0), row1),
        (column(1, 100), row1),
        (column(2, 100), row1),
        (column(3, 200), row1),
        (column(5, 0), row1),
        (column(1, 100), base(2140 + 40)),
        // At 15 pt the single line of 62.5 device dots rounds up, so the baseline sits the
        // descent of 12.5 units, rounded to 13, above its bottom.
        (
            column(2, 100),
            f_office_units::div_round(
                2620 * Length::UNITS_PER_TWIP + 300 * Length::UNITS_PER_TWIP - 13 * DOT,
                DOT,
            ),
        ),
    ];
    assert_eq!(found, expected);
    assert_eq!(at(&list, 'n').1, base(1920 + 20));
    assert_eq!(at(&list, 'z').1, base(2380 + 40));
}

#[test]
fn formats_the_first_and_last_rows_columns_and_corners() {
    let list = regions();
    let size = |ch| run_of(&list, ch).size;
    let points =
        |half: i64| crate::grid::base_device().snap(Length::from_half_points(half).unwrap());
    // The first row is in capitals, the first column bold and the last column italic.
    assert_eq!(font_of(&list, 'A'), FontId::from_index(1));
    assert_eq!(
        (font_of(&list, 'C'), size('C')),
        (FontId::from_index(0), points(20))
    );
    assert_eq!(font_of(&list, 'F'), FontId::from_index(2));
    assert_eq!(
        (font_of(&list, 'm'), size('m')),
        (FontId::from_index(1), points(20))
    );
    assert_eq!(
        (font_of(&list, 'r'), size('r')),
        (FontId::from_index(2), points(20))
    );
    // The corner cells win over the last row.
    assert_eq!(
        [size('A'), size('F'), size('4'), size('9'), size('6')],
        [24, 26, 28, 32, 30].map(points)
    );
}

#[test]
fn region_alignment_overrides_direct_start_without_style_jc() {
    let styles = format!(
        r#"{NORMAL}
        <w:style w:type="paragraph" w:styleId="ParaLeft"><w:pPr><w:jc w:val="left"/></w:pPr></w:style>
        <w:style w:type="paragraph" w:styleId="ParaCenter"><w:pPr><w:jc w:val="center"/></w:pPr></w:style>
        <w:style w:type="table" w:styleId="FirstColRight"><w:basedOn w:val="TableNormal"/>
          <w:tblStylePr w:type="firstCol"><w:pPr><w:jc w:val="right"/></w:pPr></w:tblStylePr></w:style>
        <w:style w:type="table" w:styleId="WholeRight"><w:basedOn w:val="TableNormal"/>
          <w:pPr><w:jc w:val="right"/></w:pPr></w:style>"#
    );
    let cell_x = |tbl_style: &str, ppr: &str| {
        let look = format!(r#"<w:tblStyle w:val="{tbl_style}"/><w:tblLook w:firstColumn="1"/>"#);
        let cell = format!("<w:p><w:pPr>{ppr}</w:pPr><w:r><w:t>a</w:t></w:r></w:p>");
        let body = table(&look, &[3000, 1000], &[("", &[&cell, &p("b")])]);
        find(&lay_out(&body, &styles, None), 'a').1
    };
    let right = cell_x("FirstColRight", "");
    let left = cell_x("WholeRight", r#"<w:jc w:val="left"/>"#);
    let center = cell_x("FirstColRight", r#"<w:jc w:val="center"/>"#);
    assert!(left < center && center < right, "{left} {center} {right}");
    // Direct `left` / `start` yields to conditional `firstCol` alignment when the style sets no
    // `w:jc`, but wins over whole-table `w:jc`, paragraph-style `w:jc`, and non-default direct
    // alignments.
    for (tbl_style, ppr, want) in [
        ("FirstColRight", r#"<w:jc w:val="left"/>"#, right),
        ("FirstColRight", r#"<w:jc w:val="start"/>"#, right),
        ("FirstColRight", r#"<w:pStyle w:val="ParaLeft"/>"#, left),
        ("FirstColRight", r#"<w:pStyle w:val="ParaCenter"/>"#, center),
        (
            "FirstColRight",
            r#"<w:pStyle w:val="ParaCenter"/><w:jc w:val="left"/>"#,
            left,
        ),
        ("WholeRight", "", right),
        ("WholeRight", r#"<w:jc w:val="left"/>"#, left),
    ] {
        assert_eq!(cell_x(tbl_style, ppr), want, "{tbl_style} {ppr}");
    }
    // Under `w:bidi`, direct `jc="left"` (logical start) yields to `firstCol`'s `jc="right"`
    // (logical end = physical left).
    assert_eq!(
        cell_x("FirstColRight", r#"<w:bidi/><w:jc w:val="left"/>"#),
        cell_x("FirstColRight", r#"<w:bidi/><w:jc w:val="right"/>"#),
    );
}

#[test]
fn leaves_out_the_hidden_end_of_cell_mark() {
    // A cell of "a" and an empty paragraph: with `w:hideMark`, the paragraph after the table
    // lies where it lies after a cell of "a" alone; without it, a line lower.
    let after = |cell: &str| {
        let body = table("", &[2000], &[("", &[cell])]) + &p("z");
        find(&lay_out(&body, NORMAL, None), 'z').2
    };
    let alone = after(&p("a"));
    let hidden = after(&format!("<w:tcPr><w:hideMark/></w:tcPr>{}<w:p/>", p("a")));
    let shown = after(&format!("{}<w:p/>", p("a")));
    assert_eq!(hidden, alone);
    assert!(shown > alone, "{shown} {alone}");
    // A last paragraph with text keeps its line.
    let two = after(&format!(
        "<w:tcPr><w:hideMark/></w:tcPr>{}{}",
        p("a"),
        p("b")
    ));
    assert_eq!(two, shown);
}

#[test]
fn leaves_out_the_empty_paragraph_after_a_nested_table() {
    // A cell of a nested table and an empty paragraph: the paragraph after the outer table
    // lies where it lies after a cell that is one empty paragraph shorter.
    let nested = table("", &[1000], &[("", &[&p("n")])]);
    let after = |cell: &str| {
        let body = table("", &[2000], &[("", &[cell])]) + &p("z");
        find(&lay_out(&body, NORMAL, None), 'z').2
    };
    let ends = after(&format!("{nested}<w:p/>"));
    let text = after(&format!("{nested}{}", p("a")));
    assert!(text > ends, "{text} {ends}");
    // Of two empty paragraphs after the nested table, both keep their lines.
    let two = after(&format!("{nested}<w:p/><w:p/>"));
    assert_eq!(two - text, text - ends);
    // An empty paragraph before the nested table keeps its line too.
    let before = after(&format!("<w:p/>{nested}<w:p/>"));
    assert_eq!(before, after(&format!("{}{nested}<w:p/>", p("a"))));
    assert!(before > ends, "{before} {ends}");
}

#[test]
fn gives_cell_paragraphs_the_table_style() {
    let style = format!(
        r#"{NORMAL}<w:style w:type="table" w:styleId="Big"><w:basedOn w:val="TableNormal"/><w:pPr><w:ind w:left="300"/></w:pPr><w:rPr><w:b/></w:rPr></w:style>"#
    );
    let body = table(r#"<w:tblStyle w:val="Big"/>"#, &[2000], &[("", &[&p("a")])]);
    let list = lay_out(&body, &style, None);
    assert_eq!(font_of(&list, 'a'), FontId::from_index(1));
    assert_eq!(at(&list, 'a').0, indented(1440, 300));
}

#[test]
fn keeps_a_continuing_cell_in_the_first_row() {
    let rows: &[(&str, &[&str])] = &[("", &[&format!("<w:tcPr><w:vMerge/></w:tcPr>{}", p("a"))])];
    let list = lay_out(&table("", &[2000], rows), NORMAL, None);
    assert_eq!(at(&list, 'a').1, base(1440));
}

#[test]
fn takes_the_wider_line_from_the_neighbor() {
    let left = format!(
        "<w:tcPr><w:tcBorders><w:right {SINGLE}/></w:tcBorders></w:tcPr>{}",
        p("a")
    );
    let right = format!(
        r#"<w:tcPr><w:tcBorders><w:left w:val="single" w:sz="24"/></w:tcBorders></w:tcPr>{}"#,
        p("b")
    );
    let list = lay_out(
        &table("", &[2000, 2000], &[("", &[&left, &right])]),
        NORMAL,
        None,
    );
    // Both cells take the 3 pt line, centered on the grid line between them, and it is drawn
    // once. It is 13 device dots wide, and the odd unit lies left of the grid line.
    let wide = (du(3332) - 7, 300, du(60), du(200));
    assert_eq!(rects(&list, 0), vec![wide]);
}

#[test]
fn uses_the_outer_borders_at_the_edges() {
    let borders = r#"<w:tblBorders><w:top w:val="single" w:sz="16"/><w:right w:val="single" w:sz="24"/><w:insideH w:val="single" w:sz="8"/><w:insideV w:val="single" w:sz="4"/></w:tblBorders>"#;
    let rows: &[(&str, &[&str])] = &[("", &[&p("a"), &p("b")]), ("", &[&p("c"), &p("d")])];
    let list = lay_out(&table(borders, &[2000, 2000], rows), NORMAL, None);
    // A 2 pt top border above the first row, a 1 pt one above the second.
    assert_eq!(at(&list, 'a').1, base(1440 + 40));
    assert_eq!(at(&list, 'c').1, base(1640 + 40 + 20));
    let rects = rects(&list, 0);
    // The line between the cells is 0.5 pt, and the right edge 3 pt, with its odd device
    // unit left of the grid line. Both run from below the top line.
    let top = du(1440) + du(40);
    assert!(rects.contains(&(du(3332) - 1, top, 2, du(240) - du(40))));
    assert!(rects.contains(&(du(5332) - 7, top, du(60), du(240) - du(40))));
}

#[test]
fn starts_a_table_below_the_space_after_the_paragraph_before_it() {
    let before = r#"<w:p><w:pPr><w:spacing w:after="100"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#;
    let list = lay_out(
        &(before.to_owned() + &table("", &[2000], &[("", &[&p("b")])])),
        NORMAL,
        None,
    );
    assert_eq!(at(&list, 'b').1, base(1640 + 100));
}

#[test]
fn counts_the_space_after_the_last_paragraph_of_a_cell() {
    let cell = r#"<w:p><w:pPr><w:spacing w:after="300"/></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#;
    let list = lay_out(
        &(table("", &[2000], &[("", &[cell])]) + &p("b")),
        NORMAL,
        None,
    );
    assert_eq!(at(&list, 'b').1, base(1440 + 200 + 300));
}

/// The table style of [`NORMAL`], the default paragraph style `Normal` and the style `Other`.
const WITH_OTHER: &str = r#"<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/></w:style><w:style w:type="paragraph" w:styleId="Other"><w:name w:val="Other"/><w:basedOn w:val="Normal"/></w:style>"#;

#[test]
fn leaves_out_the_space_at_a_cells_edges_of_a_contextual_default_paragraph() {
    let cell = |props: &str| format!("<w:p><w:pPr>{props}</w:pPr><w:r><w:t>a</w:t></w:r></w:p>");
    let styles = format!("{NORMAL}{WITH_OTHER}");
    let places = |props: &str| {
        let list = lay_out(
            &(table("", &[2000], &[("", &[&cell(props)])]) + &p("b")),
            &styles,
            None,
        );
        (at(&list, 'a').1, at(&list, 'b').1)
    };
    let spaced = r#"<w:spacing w:before="100" w:after="300"/>"#;
    let contextual = format!("{spaced}<w:contextualSpacing/>");
    // A paragraph of the default style with contextual spacing lies as one without space
    // before, and the cell ends as one without space after.
    let after_only = places(r#"<w:spacing w:after="300"/>"#);
    assert_eq!(places(&contextual), (after_only.0, places("").1));
    // A paragraph of another style keeps both spaces.
    assert_eq!(
        places(&format!(r#"<w:pStyle w:val="Other"/>{contextual}"#)),
        places(spaced)
    );
    assert_ne!(places(spaced), places(""));
}

#[test]
fn compares_cell_edge_contextual_spacing_against_backing_stream_neighbors() {
    let styles = format!("{NORMAL}{WITH_OTHER}");
    let para = |style: Option<&str>, props: &str, text: &str| {
        let style_xml = style.map_or_else(String::new, |s| format!(r#"<w:pStyle w:val="{s}"/>"#));
        format!("<w:p><w:pPr>{style_xml}{props}</w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>")
    };
    let row_step = |c1: &str, c2: &str| {
        let body = table(
            "",
            &[2000, 2000],
            &[("", &[c1, c2]), ("", &[&p("r"), &p("s")])],
        );
        let list = lay_out(&body, &styles, None);
        at(&list, 'r').1 - at(&list, 'a').1
    };
    let after = r#"<w:spacing w:after="240"/><w:contextualSpacing/>"#;
    let zero_after = r#"<w:spacing w:after="0"/>"#;
    let before = r#"<w:spacing w:before="240"/><w:contextualSpacing/>"#;
    // Non-last cell drops space after when the next cell starts with the same style, and keeps it
    // before a different style (even for Normal).
    let dropped_after = row_step(
        &para(Some("Other"), after, "a"),
        &para(Some("Other"), zero_after, "b"),
    );
    let kept_after = row_step(
        &para(Some("Other"), after, "a"),
        &para(None, zero_after, "b"),
    );
    assert_eq!(kept_after - dropped_after, du(240));
    let normal_before_other = row_step(
        &para(None, after, "a"),
        &para(Some("Other"), zero_after, "b"),
    );
    assert_eq!(normal_before_other, kept_after);
    // Non-first cell drops space before when the previous cell ends with the same style, and keeps
    // it after a different style (even for Normal).
    let sibling_gap = |c1: &str, c2: &str| {
        let body = table("", &[2000, 2000], &[("", &[c1, c2])]);
        let list = lay_out(&body, &styles, None);
        at(&list, 'b').1 - at(&list, 'a').1
    };
    assert_eq!(
        sibling_gap(
            &para(Some("Other"), "", "a"),
            &para(Some("Other"), before, "b")
        ),
        0
    );
    assert_eq!(
        sibling_gap(&para(None, "", "a"), &para(Some("Other"), before, "b")),
        du(240)
    );
    assert_eq!(
        sibling_gap(&para(Some("Other"), "", "a"), &para(None, before, "b")),
        du(240)
    );
    // Row 0 cell 0 compares space before against the paragraph immediately preceding the table.
    let top_gap = |r1c1: &str| {
        let body = para(Some("Other"), "", "x")
            + &table("", &[2000, 2000], &[("", &[r1c1, &para(None, "", "b")])]);
        let list = lay_out(&body, &styles, None);
        at(&list, 'a').1 - at(&list, 'b').1
    };
    assert_eq!(top_gap(&para(Some("Other"), before, "a")), 0);
    assert_eq!(top_gap(&para(None, before, "a")), du(240));
}

#[test]
fn lays_out_a_merged_cell_s_lines_from_its_aligned_top_on_a_target_that_does() {
    use crate::quirks::MergedCellLines;
    // A centered merged cell over two rows of exact heights holds two lines, and a single row
    // of the summed height holds the same lines. Each twip that the second row grows moves the
    // centering shift by a fortieth of a point, across the dots of 0.12 pt.
    let centered = r#"<w:vAlign w:val="center"/>"#;
    let lines = p("a") + &p("b");
    let starts = format!(r#"<w:tcPr><w:vMerge w:val="restart"/>{centered}</w:tcPr>{lines}"#);
    let goes_on = format!("<w:tcPr><w:vMerge/>{centered}</w:tcPr><w:p/>");
    let alone = format!("<w:tcPr>{centered}</w:tcPr>{lines}");
    let exact = |twips: u32| format!(r#"<w:trHeight w:val="{twips}" w:hRule="exact"/>"#);
    let places = |body: &str, rule| {
        let target = crate::layout::testing::target_at(600, |p| p.with_variant(rule));
        let list = pass_with(body, (NORMAL, None), None, Numbering::default(), target).list;
        (find(&list, 'a').2, find(&list, 'b').2)
    };
    let mut apart = 0;
    for step in 0..6 {
        let (first, second) = (exact(300), exact(600 + step));
        let merged = table("", &[2000], &[(&first, &[&starts]), (&second, &[&goes_on])]);
        let single = table("", &[2000], &[(&exact(900 + step), &[&alone])]);
        let wanted = places(&single, MergedCellLines::FromAlignedTop);
        let from_top = places(&merged, MergedCellLines::FromAlignedTop);
        assert_eq!(from_top, wanted, "step {step}");
        apart += usize::from(places(&merged, MergedCellLines::MovedAsBlock) != wanted);
    }
    // Moved as one block by the rounded shift, the lines lie a dot off at some steps.
    assert!(apart > 0);
}

/// How far up the page the baseline of the first 'b' of `body`, below `header` on every page,
/// lies at 600 dots per inch with whole twips held as the nearest 1/4,096 pt, against held
/// exactly.
fn held_one_dot_up(header: Option<&str>, body: &str) -> i64 {
    held_one_dot_up_on(&Fake, header, body)
}

/// [`held_one_dot_up`] with the faces of `fonts`.
fn held_one_dot_up_on(fonts: &dyn Fonts, header: Option<&str>, body: &str) -> i64 {
    use crate::quirks::TwipLengthUnit;
    let baseline = |unit| {
        let (device, quirks) = crate::layout::testing::target_at(600, |p| p.with_variant(unit));
        let list = pass_on(
            body,
            (NORMAL, None),
            header,
            Numbering::default(),
            (device, quirks, EarlierPass::default()),
            &(fonts, ShaperSettings::base()),
        );
        run_of(&list.list, 'b').glyphs.first().unwrap().y.units()
    };
    baseline(TwipLengthUnit::HalfEmus) - baseline(TwipLengthUnit::Nearest4096ths)
}

/// The fake faces with a single line of 1.111 of the size, 900 of the em's 1,000 units above
/// the baseline and 211 below: at 10 pt a line of 222.2 twips, which is not whole twips.
struct Tall;

impl Fonts for Tall {
    fn face(&self, family: &FamilyName, bold: bool, italic: bool) -> Option<ChosenFace> {
        Fake.face(family, bold, italic).map(|mut face| {
            face.metrics.hhea_ascender = 900;
            face.metrics.hhea_descender = -211;
            face.metrics.descent = 211;
            face.metrics.line_top = 900;
            face.metrics.script_top = 900;
            face
        })
    }

    fn glyph(&self, font: FontId, ch: char) -> Option<u32> {
        Fake.glyph(font, ch)
    }

    fn advance(&self, font: FontId, glyph: u32) -> Option<u16> {
        Fake.advance(font, glyph)
    }
}

/// A table of one row of at least `height` twips whose cell, aligned to `align`, holds
/// `paragraph`.
fn aligned_row(height: u32, align: &str, paragraph: &str) -> String {
    let row = format!(r#"<w:trHeight w:val="{height}"/>"#);
    let cell = format!(r#"<w:tcPr><w:vAlign w:val="{align}"/></w:tcPr>{paragraph}"#);
    let rows: &[(&str, &[&str])] = &[(&row, &[&cell])];
    table("", &[2000], rows)
}

#[test]
fn starts_the_twips_rest_of_a_cell_s_text_at_its_top() {
    // Below a first row of exactly 318 twips at the top margin of 1,440 twips, the second row's
    // text top lies 1,758 twips from the page's top, 87.9 pt, exactly on half a dot of 600 dots
    // per inch (732.5 dots). Held as the nearest 1/4,096 pt, that length lies above the half,
    // so the cell's exact line goes up the page; held exactly, the half goes down.
    let first = r#"<w:trHeight w:val="318" w:hRule="exact"/>"#;
    let line = r#"<w:p><w:pPr><w:spacing w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>"#;
    let body = table("", &[2000], &[(first, &[&p("a")]), ("", &[line])]);
    assert_eq!(held_one_dot_up(None, &body), Length::UNITS_PER_INCH / 600);
}

#[test]
fn carries_the_twips_rest_through_the_rows_of_a_table() {
    // Two rows of exactly 243 twips at the top margin of 1,440 twips put the third row's text
    // top 1,926 twips from the page's top, 96.3 pt, exactly on half a dot of 600 dots per inch
    // (802.5 dots). Entered one by one, each row lies 0.4 of a 1/4,096 pt short, so the sum
    // lies 0.8 of one short and the cell's exact line goes up the page. Held as one length,
    // 1,926 twips lie 0.2 of one past, and held exactly the half goes down.
    let exact = r#"<w:trHeight w:val="243" w:hRule="exact"/>"#;
    let line = r#"<w:p><w:pPr><w:spacing w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>"#;
    let rows: &[(&str, &[&str])] = &[(exact, &[&p("a")]), (exact, &[&p("a")]), ("", &[line])];
    let body = table("", &[2000], rows);
    assert_eq!(held_one_dot_up(None, &body), Length::UNITS_PER_INCH / 600);
}

#[test]
fn carries_the_rests_that_the_cells_of_a_row_start() {
    // Below a header that ends 1,500 twips from the page's top, the body's top has no twips
    // rest, so neither has the first row's top. Its cell starts the rest at its text top as one
    // length (0 at 1,500 twips), and its exact line of 243 twips enters 0.4 of a 1/4,096 pt
    // short. The second row carries the rest at the first row's end and adds its own line, so
    // the third row's text top, 1,986 twips from the page's top, exactly on half a dot of 600
    // dots per inch (827.5 dots), lies 0.8 of one short and the cell's exact line goes up the
    // page. Started anew there as one length, 1,986 twips lie 0.2 past, and held exactly the
    // half goes down.
    let exact = |text| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:line="{}" w:lineRule="exact"/></w:pPr><w:r><w:t>{}</w:t></w:r></w:p>"#,
            if text == "b" { 240 } else { 243 },
            text
        )
    };
    let (a, b) = (exact("a"), exact("b"));
    let rows: &[(&str, &[&str])] = &[("", &[&a]), ("", &[&a]), ("", &[&b])];
    let body = table("", &[2000], rows);
    let header = r#"<w:p><w:pPr><w:spacing w:line="780" w:lineRule="exact"/></w:pPr><w:r><w:t>h</w:t></w:r></w:p>"#;
    assert_eq!(
        held_one_dot_up(Some(header), &body),
        Length::UNITS_PER_INCH / 600
    );
}

#[test]
fn rounds_a_single_top_with_the_rest_that_its_row_carries() {
    // As in `carries_the_twips_rest_through_the_rows_of_a_table`, the third row's text top lies
    // 1,926 twips from the page's top, on half a dot, with a carried rest 0.8 of a 1/4,096 pt
    // short. The box of the single line there takes that rest and goes up the page. As one
    // length 1,926 twips lie 0.2 past, and held exactly the half goes down.
    let exact = r#"<w:trHeight w:val="243" w:hRule="exact"/>"#;
    let rows: &[(&str, &[&str])] = &[(exact, &[&p("a")]), (exact, &[&p("a")]), ("", &[&p("b")])];
    let body = table("", &[2000], rows);
    assert_eq!(held_one_dot_up(None, &body), Length::UNITS_PER_INCH / 600);
}

#[test]
fn rounds_a_single_top_above_its_space_before() {
    // A row of exactly 330 twips at the top margin puts the second row's text top 1,770 twips
    // from the page's top, on half a dot, with a carried rest of 0, so the place as one length
    // decides it, down the page. The single line there has 43 twips of space before, which
    // enter 0.4 of a 1/4,096 pt short, but its box holds that space, so its top keeps the rest
    // above it and goes down too, as held exactly.
    let exact = r#"<w:trHeight w:val="330" w:hRule="exact"/>"#;
    let spaced = r#"<w:p><w:pPr><w:spacing w:before="43"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>"#;
    let rows: &[(&str, &[&str])] = &[(exact, &[&p("a")]), ("", &[spaced])];
    let body = table("", &[2000], rows);
    assert_eq!(held_one_dot_up(None, &body), 0);
}

#[test]
fn moves_every_cell_of_a_bottom_aligned_row() {
    let cell = |text| format!(r#"<w:tcPr><w:vAlign w:val="bottom"/></w:tcPr>{}"#, p(text));
    let rows: &[(&str, &[&str])] = &[(r#"<w:trHeight w:val="600"/>"#, &[&cell("a"), &cell("b")])];
    let list = lay_out(&table("", &[2000, 2000], rows), NORMAL, None);
    assert_eq!(at(&list, 'a').1, base(1440 + 400));
    assert_eq!(at(&list, 'b').1, base(1440 + 400));
}

#[test]
fn moves_the_underline_of_a_centered_merged_cell() {
    let restart = r#"<w:tcPr><w:vMerge w:val="restart"/><w:vAlign w:val="center"/></w:tcPr><w:p><w:r><w:rPr><w:u w:val="single"/></w:rPr><w:t>a</w:t></w:r></w:p>"#;
    let rows: &[(&str, &[&str])] = &[
        ("", &[restart, &p("b")]),
        ("", &["<w:tcPr><w:vMerge/></w:tcPr><w:p/>", &p("c")]),
    ];
    let centered = lay_out(&table("", &[2000, 2000], rows), NORMAL, None);
    let top = restart.replace(r#"<w:vAlign w:val="center"/>"#, "");
    let rows: &[(&str, &[&str])] = &[
        ("", &[&top, &p("b")]),
        ("", &["<w:tcPr><w:vMerge/></w:tcPr><w:p/>", &p("c")]),
    ];
    let plain = lay_out(&table("", &[2000, 2000], rows), NORMAL, None);
    // The underline moves down 100 twips with the text.
    assert_eq!(rects(&centered, 0)[0].1, rects(&plain, 0)[0].1 + du(100));
}

#[test]
fn gives_a_continuing_cell_the_height_of_its_margins() {
    let margins = r#"<w:tblCellMar><w:top w:w="300" w:type="dxa"/><w:bottom w:w="300" w:type="dxa"/></w:tblCellMar>"#;
    let rows: &[(&str, &[&str])] = &[
        (
            "",
            &[&format!(
                r#"<w:tcPr><w:vMerge w:val="restart"/></w:tcPr>{}"#,
                p("a")
            )],
        ),
        ("", &["<w:tcPr><w:vMerge/></w:tcPr><w:p/>"]),
    ];
    let list = lay_out(&(table(margins, &[2000], rows) + &p("b")), NORMAL, None);
    // Each row is as tall as the 600 twips of an empty cell's margins.
    assert_eq!(at(&list, 'b').1, base(1440 + 1200));
}

#[test]
fn draws_hairline_borders_one_device_dot_wide() {
    let borders = r#"<w:tblBorders><w:top w:val="single" w:sz="0"/><w:left w:val="single" w:sz="0"/></w:tblBorders>"#;
    let list = lay_out(&table(borders, &[2000], &[("", &[&p("a")])]), NORMAL, None);
    // The top line ends at the right grid line, rounded to the device grid. It starts right of
    // the left line, which starts below it, and where both end the corner is a square, drawn
    // once for each of them.
    assert_eq!(
        rects(&list, 0),
        vec![
            (du(1332) + 1, 300, du(3332) - du(1332) - 1, 1),
            (du(1332), 301, 1, du(200) - 1),
            (du(1332), 300, 1, 1),
            (du(1332), 300, 1, 1)
        ]
    );
}

#[test]
fn draws_paragraph_borders_and_leaders_in_cells() {
    let cell = r#"<w:p><w:pPr><w:ind w:left="100" w:right="200"/><w:pBdr><w:top w:val="single" w:sz="4"/></w:pBdr><w:tabs><w:tab w:val="right" w:leader="dot" w:pos="1000"/></w:tabs></w:pPr><w:r><w:tab/><w:t>a</w:t></w:r></w:p>"#;
    let list = lay_out(&table("", &[3000], &[("", &[cell])]), NORMAL, None);
    // The border runs between the indents inside the cell's text column, from 6 device dots
    // before the left one to 6 after the right one, with its ends on the device grid.
    let border = rects(&list, 0)[0];
    let (left, right) = (du(1540) - 6, du(1540 + 2484) + 6);
    assert_eq!((border.0, border.2), (left, right - left));
    // Dots of 100 twips fill the tab up to the right-aligned text before the stop, on a grid
    // from the page's left edge. The tab starts at the indent, 1540 twips, so the first whole
    // cell starts at 1600 twips.
    let dots: Vec<i64> = find_all(&list, '.').iter().map(|g| g.1).collect();
    let grid: Vec<i64> = (16..23).map(|k| 100 * k * 1270).collect();
    assert_eq!(dots, grid);
}

#[test]
fn starts_the_border_of_a_hanging_paragraph_at_its_first_line() {
    let cell = r#"<w:p><w:pPr><w:ind w:left="400" w:hanging="300"/><w:pBdr><w:top w:val="single" w:sz="4"/></w:pBdr></w:pPr><w:r><w:t>a</w:t></w:r></w:p>"#;
    let list = lay_out(&table("", &[3000], &[("", &[cell])]), NORMAL, None);
    // The first line starts 100 twips into the cell's text column, which starts at 1440 twips
    // and ends at 4224, and the line starts 6 device dots before it.
    let border = rects(&list, 0)[0];
    let (left, right) = (du(1540) - 6, du(4224) + 6);
    assert_eq!((border.0, border.2), (left, right - left));
}

#[test]
fn indents_and_aligns_lines_in_cells() {
    let cell = r#"<w:p><w:pPr><w:ind w:left="100"/><w:jc w:val="right"/></w:pPr><w:r><w:t>ab</w:t></w:r></w:p>"#;
    let list = lay_out(&table("", &[3000], &[("", &[cell])]), NORMAL, None);
    // The line ends at the right margin of the cell: 1332 + 3000 - 108 twips.
    assert_eq!(at(&list, 'a').0, du(4224 - 200));
}

#[test]
fn lays_out_a_package_with_tables_in_the_body_and_the_header() {
    let header = table("", &[2000], &[("", &[&p("h")])]);
    let body = table("", &[2000], &[("", &[&p("b")])]);
    let bytes = package(&body, &header, HEADER_REFERENCE);
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let list = crate::layout(
        &package,
        (&Fake, &crate::ArtPictures::new()),
        &crate::Options::base(),
    )
    .unwrap()
    .value;
    assert_eq!(list.pages().len(), 1);
    assert_eq!(at(&list, 'h').1, base(720));
    assert_eq!(at(&list, 'b').1, base(1440));
}

#[test]
fn moves_paths_with_the_rest_of_a_cell() {
    let styles = Styles::default();
    let settings = Settings::default();
    let (theme, fonts) = (Theme::default(), FontTable::default());
    let context = base_context(&styles, &settings);
    let stories = context.for_stories();
    let sections = Sections::one(SectionLayout::plain(&crate::body::Section::default(), 0));
    let mut layout = Layout::new(
        (&context, &stories),
        &sections,
        Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
    );
    let point = |y: i64| Point {
        x: Length::ZERO,
        y: Length::from_units(y),
    };
    let commands = vec![
        PathCommand::MoveTo(point(1)),
        PathCommand::LineTo(point(2)),
        PathCommand::QuadTo(point(3), point(4)),
        PathCommand::CubicTo(point(5), point(6), point(7)),
        PathCommand::Close,
    ];
    layout.items.push(Item::Path(PathItem {
        commands,
        color: Rgb::BLACK,
        fill_rule: FillRule::default(),
    }));
    layout.shift(0..1, Length::from_units(10));
    let items = layout.items.to_vec();
    let Item::Path(path) = &items[0] else {
        panic!("not a path");
    };
    let ys: Vec<i64> = path
        .commands
        .iter()
        .flat_map(|c| match c {
            PathCommand::MoveTo(a) | PathCommand::LineTo(a) => vec![a.y],
            PathCommand::QuadTo(a, b) => vec![a.y, b.y],
            PathCommand::CubicTo(a, b, c) => vec![a.y, b.y, c.y],
            PathCommand::Close => Vec::new(),
        })
        .map(Length::units)
        .collect();
    assert_eq!(ys, (11..=17).collect::<Vec<_>>());
}

/// A table of two rows and two columns with 1 pt borders and the cell spacing `spacing` in
/// twips, or none.
fn spaced(spacing: Option<i64>) -> DisplayList {
    let spacing = spacing.map_or(String::new(), |w| {
        format!(r#"<w:tblCellSpacing w:w="{w}" w:type="dxa"/>"#)
    });
    let line = r#"w:val="single" w:sz="8""#;
    let borders = format!(
        "{spacing}<w:tblBorders><w:top {line}/><w:left {line}/><w:bottom {line}/><w:right {line}/><w:insideH {line}/><w:insideV {line}/></w:tblBorders>"
    );
    let rows: &[(&str, &[&str])] = &[("", &[&p("a"), &p("b")]), ("", &[&p("c"), &p("d")])];
    lay_out(&table(&borders, &[2000, 2000], rows), NORMAL, None)
}

#[test]
fn keeps_the_cells_of_a_table_with_cell_spacing_apart() {
    let (plain, spaced) = (spaced(None), spaced(Some(40)));
    // The first cell's box starts twice the spacing (80 twips) inside the grid line, the
    // second one the spacing inside it, and the text starts half a line (10 twips) after the
    // box's edge.
    assert_eq!(at(&plain, 'a').0, du(1440));
    assert_eq!(at(&spaced, 'a').0, du(1440 + 90));
    assert_eq!(at(&spaced, 'b').0, du(3440 + 50));
    // Below the table's 1 pt top line come twice the spacing and the cell's 1 pt top line.
    assert_eq!(find(&spaced, 'a').2, base(1440 + 20 + 80 + 20));
    // The first row holds its cells' bottom lines and the spacing below them, and the second
    // row's boxes start the spacing below that.
    assert_eq!(find(&spaced, 'c').2, base(1560 + 200 + 20 + 40 + 40 + 20));
}

#[test]
fn draws_a_box_for_each_cell_of_a_table_with_cell_spacing() {
    let rects = rects(&spaced(Some(40)), 0);
    // The table's own top line spans the table, the first cell's box lies inside it with its
    // edges on the device grid toward the inside, and no line runs between the boxes.
    assert!(
        rects.contains(&(du(1332 - 10), 300, du(4020), 4)),
        "{rects:?}"
    );
    assert!(rects.contains(&(295, 321, 685 - 295, 4)), "{rects:?}");
    assert!(!rects.iter().any(|r| r.0 == du(3332 - 10)), "{rects:?}");
}

#[test]
fn takes_a_cell_spacing_below_zero_as_none() {
    assert_eq!(spaced(Some(-20)), spaced(None));
}

#[test]
fn draws_the_lines_inside_a_table_from_the_column_edge_on_the_device_grid() {
    // A left margin of 851 twips (42.55 pt) lies off the device grid of 0.24 pt. In mode 15,
    // the left border's outer edge is at the margin, rounded to 42.48 pt (177 units). The
    // lines inside take the grid lines from the margin rounded to the device grid: 42.48 pt
    // plus the half border and 5,382 twips is 311.83 pt, which rounds to 1,299 units, and the
    // 0.48 pt line starts one unit to its left. Taken from the exact margin, the grid line
    // would round to 1,300 units.
    let section = r#"<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="851" w:bottom="1440" w:left="851"/></w:sectPr>"#;
    let borders = r#"<w:tblBorders><w:left w:val="single" w:sz="4"/><w:right w:val="single" w:sz="4"/><w:insideV w:val="single" w:sz="4"/></w:tblBorders>"#;
    let body = table(borders, &[5382, 3398], &[("", &[&p("a"), &p("b")])]) + section;
    let list = lay_out(&body, NORMAL, Some(15));
    let mut starts: Vec<i64> = rects(&list, 0).iter().map(|r| r.0).collect();
    starts.sort_unstable();
    starts.dedup();
    assert_eq!(starts, [177, 1298, 2006]);
}

/// The rectangles of the first page in dots of 1/600 inch: x, y, width and height.
fn rects_600(list: &DisplayList) -> Vec<(i64, i64, i64, i64)> {
    let unit = DOT / 2;
    list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Rect(r) => Some([r.x, r.y, r.width, r.height].map(|v| {
                assert_eq!(v.units() % unit, 0, "{r:?}");
                v.units() / unit
            })),
            Item::Glyphs(_)
            | Item::Path(_)
            | Item::Gradient(_)
            | Item::Image(_)
            | Item::Group(_) => None,
        })
        .map(Into::into)
        .collect()
}

#[test]
fn centers_vertical_lines_on_their_grid_lines_from_the_column_edge_a_half_down() {
    // A left margin of 1134 twips is 472.5 dots of 1/600 inch, which the column's edge takes a
    // half down, as 472. In mode 15 the grid lies half the 0.75 pt border, 7.5 twips, right of the margin;
    // rounded up to 8 twips, the grid lines move 635 half-EMUs right. The 0.75 pt lines are
    // 6.25 dots, so 6 dots wide, and each is centered on its grid line rounded: 475.33, 1308.67
    // and 2558.67 dots, so they start at 472, 1306 and 2556.
    let section = r#"<w:sectPr><w:pgSz w:w="11906" w:h="16838"/><w:pgMar w:top="1440" w:right="1134" w:bottom="1440" w:left="1134"/></w:sectPr>"#;
    let borders = r#"<w:tblBorders><w:left w:val="single" w:sz="6"/><w:right w:val="single" w:sz="6"/><w:insideV w:val="single" w:sz="6"/></w:tblBorders>"#;
    let body = table(borders, &[2000, 3000], &[("", &[&p("a"), &p("b")])]) + section;
    let list = lay_out_centered_lines(&body, NORMAL, Some(15));
    let mut lines: Vec<(i64, i64)> = rects_600(&list).iter().map(|r| (r.0, r.2)).collect();
    lines.sort_unstable();
    lines.dedup();
    assert_eq!(lines, [(472, 6), (1306, 6), (2556, 6)]);
}

/// The start and the width, in dots of 1/600 inch, of each vertical line of a table of mode 15
/// centered in a text column of 9,360 twips from a margin of 1,440, with a grid of `grid` twips
/// and lines of 0.75 pt, laid out on `device`.
fn centered_line_starts(
    target: &(crate::grid::Device, crate::quirks::Quirks),
    grid: [i64; 2],
) -> Vec<(i64, i64)> {
    let section = r#"<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr>"#;
    let borders = r#"<w:jc w:val="center"/><w:tblLayout w:type="fixed"/><w:tblBorders><w:left w:val="single" w:sz="6"/><w:right w:val="single" w:sz="6"/><w:insideV w:val="single" w:sz="6"/></w:tblBorders>"#;
    let body = table(borders, &grid, &[("", &[&p("a"), &p("b")])]) + section;
    let list = pass_with(
        &body,
        (NORMAL, Some(15)),
        None,
        Numbering::default(),
        *target,
    )
    .list;
    let mut lines: Vec<(i64, i64)> = rects_600(&list).iter().map(|r| (r.0, r.2)).collect();
    lines.sort_unstable();
    lines.dedup();
    lines
}

#[test]
fn draws_a_centered_tables_lines_from_its_outer_edge_on_the_device_grid() {
    // Centered in a text column of 9,360 twips from a margin of 1,440 (600 dots), with lines
    // of 0.75 pt (6 dots, 7.5 twips for half of one), a table's lines are drawn from the outer
    // edge of its left border rounded to the nearest dot, and the half border rounded up to 8
    // twips. A grid of 2,002 and 3,000 twips leaves 4,358 twips: the outer edge lies at
    // 1,504.79 dots, so 1,505, and the centers at 1,508.33, 2,342.5 and 3,592.5 dots, where
    // the exact grid lines give 2,341.67 and 3,591.67 for the two on the right. A grid of
    // 5,000 and 4,403 twips, wider than the column, puts the edge at 587.92 dots, so 588, and
    // the centers at 591.33, 2,674.67 and 4,509.25, where the exact lines give 591.04, 2,674.38
    // and 4,508.96. Grids of 2,012 and 3,001 twips and of 5,000 and 4,405 put the edge on
    // exactly half a dot, 1,502.5 and 587.5, and the lines stay at their exact places.
    let target = crate::layout::testing::target_at(600, |p| {
        p.with_variant(crate::quirks::TableLines::RoundsCenters)
            .with_variant(crate::quirks::CenteredTableLines::FromOuterEdge)
    });
    for (grid, starts) in [
        ([2002, 3000], [1505, 2340, 3590]),
        ([5000, 4403], [588, 2672, 4506]),
        ([2012, 3001], [1503, 2341, 3591]),
        ([5000, 4405], [588, 2671, 4506]),
    ] {
        assert_eq!(
            centered_line_starts(&target, grid),
            starts.map(|x| (x, 6)),
            "{grid:?}"
        );
    }
}

#[test]
fn draws_a_centered_tables_lines_from_its_outer_edge_in_fixed_point_on_a_half_dot() {
    // The grids of 2,012 and 3,001 twips and of 5,000 and 4,405 of the test above put the
    // outer edge on exactly half a dot, 1,502.5 and 587.5. In fixed-point points, the margin
    // plus half of the column's width less the grid's width less the 0.75 pt border lies above
    // the half for the first and on it for the second, so both edges take the dot above, 1,503
    // and 588, and the centers lie 8 twips and the grid lines' distance right of it: 1,506.33,
    // 2,344.67 and 3,595.08 dots, and 591.33, 2,674.67 and 4,510.08.
    let target = crate::layout::testing::target_at(600, |p| {
        p.with_variant(crate::quirks::TableLines::RoundsCenters)
            .with_variant(crate::quirks::CenteredTableLines::FromOuterEdge)
            .with_variant(crate::quirks::CenteredTablePlace::FixedPointHalf)
            .with_variant(crate::quirks::LineStartHalves::FixedPoint)
    });
    for (grid, starts) in [
        ([2002, 3000], [1505, 2340, 3590]),
        ([2012, 3001], [1503, 2342, 3592]),
        ([5000, 4405], [588, 2672, 4507]),
    ] {
        assert_eq!(
            centered_line_starts(&target, grid),
            starts.map(|x| (x, 6)),
            "{grid:?}"
        );
    }
}

#[test]
fn draws_a_centered_tables_lines_from_the_column_edge_before_mode_15() {
    // In mode 14, with a left margin of 1,443 twips (601.25 dots, so 601) and a text column of
    // 9,357 twips, a centered table's lines of 0.75 pt (6 dots) are drawn from the margin's
    // dot, each center at its grid line's distance from the margin, the half twip of an odd
    // free width dropped. A grid of 2,001 and 3,000 twips leaves 4,356: the centers lie 2,178,
    // 4,179 and 7,179 twips right of the margin, 907.5, 1,741.25 and 2,991.25 dots, so at
    // 1,509, 2,342 and 3,592, where the exact grid lines give 2,342.5 and 3,592.5 for the two
    // on the right. A grid of 5,000 and 4,368 twips leaves -11: the first center lies 6 twips,
    // 2.5 dots, left of the margin's dot and takes the dot further left, 598, where the exact
    // grid line gives 598.96. With a left margin of 1,446 twips, exactly 602.5 dots, the lines
    // of a grid of 2,001 and 3,000 twips stay at their exact places: 1,509.38, 2,343.13 and
    // 3,593.13, where the margin's dot above would give 1,510.
    let (device, quirks) = crate::layout::testing::target_at(600, |p| {
        p.with_variant(crate::quirks::TableLines::RoundsCenters)
            .with_variant(crate::quirks::CenteredTableLinesBefore15::FromColumnEdge)
    });
    let borders = r#"<w:jc w:val="center"/><w:tblLayout w:type="fixed"/><w:tblBorders><w:left w:val="single" w:sz="6"/><w:right w:val="single" w:sz="6"/><w:insideV w:val="single" w:sz="6"/></w:tblBorders>"#;
    for (margin, grid, starts) in [
        (1443, [2001, 3000], [1506, 2339, 3589]),
        (1443, [5000, 4368], [595, 2679, 4499]),
        (1446, [2001, 3000], [1506, 2340, 3590]),
    ] {
        let section = format!(
            r#"<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="{margin}"/></w:sectPr>"#
        );
        let body = table(borders, &grid, &[("", &[&p("a"), &p("b")])]) + &section;
        let target = (device, quirks);
        let list = pass_with(
            &body,
            (NORMAL, Some(14)),
            None,
            Numbering::default(),
            target,
        )
        .list;
        let mut lines: Vec<(i64, i64)> = rects_600(&list).iter().map(|r| (r.0, r.2)).collect();
        lines.sort_unstable();
        lines.dedup();
        assert_eq!(lines, starts.map(|x| (x, 6)), "{grid:?}");
    }
}

#[test]
fn starts_a_centered_tables_text_on_a_whole_twip_before_mode_15() {
    // A centered cell of 5,013 twips in a text column of 9,360 twips from a margin of 1,440
    // leaves 4,347 twips: the table starts 2,173.5 twips right of the margin, and its text
    // 108 twips further, at 3,721.5 twips or 1,550.63 dots, on the dot 1,551. Before mode 15,
    // with the half twip dropped, the text starts at 3,721 twips, 1,550.42 dots, on the dot
    // 1,550. Mode 15 keeps the exact place, and so does a table of an even free width.
    let (device, quirks) = crate::layout::testing::target_at(600, |p| {
        p.with_variant(crate::quirks::CenteredTableTextBefore15::WholeTwip)
    });
    let dot = 3048;
    let start = |width: i64, mode: u32| {
        let body = table(r#"<w:jc w:val="center"/>"#, &[width], &[("", &[&p("a")])]);
        let target = (device, quirks);
        let list = pass_with(
            &body,
            (NORMAL, Some(mode)),
            None,
            Numbering::default(),
            target,
        )
        .list;
        find(&list, 'a').1
    };
    assert_eq!(start(5013, 14), 1550 * dot);
    assert_eq!(start(5013, 15), 1551 * dot);
    // 4,346 twips leave the table at 2,173 twips, its text at 3,721 twips in both modes.
    assert_eq!(start(5014, 14), 1550 * dot);
    assert_eq!(start(5014, 15), 1550 * dot);
}

#[test]
fn starts_the_text_from_the_half_border_on_whole_twips_from_mode_15() {
    // A left line of 6 eighths is 15 twips wide, and half of it is 7.5 twips. A centered cell
    // of 5,000 twips in a text column of 9,360 twips from a margin of 1,440 starts 2,180 twips
    // right of the margin, and its text 108 twips further, at 3,728 twips or 1,553.33 dots, on
    // the dot 1,553. With half the border rounded up to 8 twips, the text starts at 3,728.5
    // twips, 1,553.54 dots, on the dot 1,554. A left-aligned table indented 3 twips puts its
    // text at 1,558.5 twips, 649.38 dots, or at 1,559 twips, 649.58 dots. Mode 14 keeps the
    // exact place.
    let (device, quirks) = crate::layout::testing::target_at(600, |p| {
        p.with_variant(crate::quirks::EdgeTableText::WholeTwipBorder)
    });
    let dot = 3048;
    let border = r#"<w:tblBorders><w:left w:val="single" w:sz="6"/><w:right w:val="single" w:sz="6"/></w:tblBorders>"#;
    let start = |place: &str, mode: u32| {
        let props = format!("{place}{border}");
        let body = table(&props, &[5000], &[("", &[&p("a")])]);
        let target = (device, quirks);
        let list = pass_with(
            &body,
            (NORMAL, Some(mode)),
            None,
            Numbering::default(),
            target,
        )
        .list;
        find(&list, 'a').1
    };
    let center = r#"<w:jc w:val="center"/>"#;
    let indent = r#"<w:tblInd w:w="3" w:type="dxa"/>"#;
    assert_eq!(start(center, 15), 1554 * dot);
    assert_eq!(start(center, 14), 1553 * dot);
    assert_eq!(start(indent, 15), 650 * dot);
}

#[test]
fn keeps_the_exact_place_for_a_cell_margin_less_than_half_the_left_line() {
    // The centered cell of the test above with a left margin of 0, less than half its left
    // line of 15 twips: the text starts half the line, 7.5 twips, right of the exact grid line
    // at 3,620 twips, at 3,627.5 twips or 1,511.46 dots, on the dot 1,511. From the grid line
    // with half the border rounded up to 8 twips it would start at 3,628 twips, on the dot
    // 1,512.
    let (device, quirks) = crate::layout::testing::target_at(600, |p| {
        p.with_variant(crate::quirks::EdgeTableText::WholeTwipBorder)
            .with_variant(crate::quirks::CellTextRoom::CombinedBorderMinimum)
    });
    let props = concat!(
        r#"<w:jc w:val="center"/><w:tblBorders><w:left w:val="single" w:sz="6"/><w:right w:val="single" w:sz="6"/></w:tblBorders>"#,
        r#"<w:tblCellMar><w:left w:w="0" w:type="dxa"/></w:tblCellMar>"#
    );
    let body = table(props, &[5000], &[("", &[&p("a")])]);
    let target = (device, quirks);
    let list = pass_with(
        &body,
        (NORMAL, Some(15)),
        None,
        Numbering::default(),
        target,
    )
    .list;
    assert_eq!(find(&list, 'a').1, 1511 * 3048);
}

#[test]
fn starts_a_spaced_cells_text_after_its_whole_left_line_under_inside_lines() {
    // A table with a cell spacing of 40 twips and lines of 1.5 pt, 30 twips: the cell's box
    // starts twice the spacing inside the grid line. Its text starts after half the box's left
    // line under `LineMiddles` and after the whole line under `InsideLines`, 15 twips further
    // right: 6.25 dots of 1/600 inch, which the text's place on the device takes as 6 dots.
    let props = concat!(
        r#"<w:tblCellSpacing w:w="40" w:type="dxa"/>"#,
        r#"<w:tblBorders><w:left w:val="single" w:sz="12"/></w:tblBorders>"#
    );
    let body = table(props, &[5000], &[("", &[&p("a")])]);
    let start = |text: crate::quirks::SpacedCellText| {
        let target = on_base_with(|p| p.with_variant(text));
        find(
            &pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list,
            'a',
        )
        .1
    };
    let middles = start(crate::quirks::SpacedCellText::LineMiddles);
    let inside = start(crate::quirks::SpacedCellText::InsideLines);
    assert_eq!(inside - middles, 6 * 3048);
}

#[test]
fn rounds_line_widths_down_and_centers_the_bottom_line_below_the_row() {
    // A 1.5 pt line is 12.5 dots of 1/600 inch, drawn 12 dots wide. The top line starts
    // at the row's top, 600 dots. The row's bottom is 404 twips lower, at 768.33 dots, and the
    // bottom line is centered 0.75 pt, 6.25 dots, below it: at 774.58, rounded to 775, so it
    // starts at 769, not at the bottom rounded, 768. The side lines end where it starts, and
    // the corners fill it.
    let borders = r#"<w:tblBorders><w:top w:val="single" w:sz="12"/><w:left w:val="single" w:sz="12"/><w:bottom w:val="single" w:sz="12"/><w:right w:val="single" w:sz="12"/></w:tblBorders>"#;
    let height = r#"<w:trHeight w:val="404" w:hRule="exact"/>"#;
    let body = table(borders, &[2000], &[(height, &[&p("a")])]);
    let list = lay_out_centered_lines(&body, NORMAL, Some(15));
    let rects = rects_600(&list);
    assert!(rects.iter().all(|r| r.2.min(r.3) == 12), "{rects:?}");
    for line in [
        (612, 600, 822, 12),
        (612, 769, 822, 12),
        (600, 612, 12, 157),
    ] {
        assert!(rects.contains(&line), "{line:?} in {rects:?}");
    }
    assert!(rects.contains(&(600, 769, 12, 12)), "{rects:?}");
}

#[test]
fn fills_a_continued_merged_cell_under_the_text_of_the_region() {
    // A gray cell merged over two rows with lines between the rows. The second row's cell
    // continues the region: its fill starts at the top of its row, where no line is drawn,
    // and it lies under the text of the region, which the first cell holds.
    let gray = r#"<w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/>"#;
    let borders = r#"<w:tblBorders><w:insideH w:val="single" w:sz="8"/></w:tblBorders>"#;
    let first = format!(
        r#"<w:tcPr><w:vMerge w:val="restart"/>{gray}</w:tcPr>{}"#,
        p("a")
    );
    let next = format!("<w:tcPr><w:vMerge/>{gray}</w:tcPr><w:p/>");
    let list = lay_out(
        &table(borders, &[2000], &[("", &[&first]), ("", &[&next])]),
        NORMAL,
        None,
    );
    let items = list.pages()[0].items();
    let gray_fills: Vec<(usize, i64, i64)> = items
        .iter()
        .enumerate()
        .filter_map(|(index, item)| match item {
            Item::Rect(r) if r.color.r == 0xD9 => Some((
                index,
                r.y.units() / DOT,
                (r.y.units() + r.height.units()) / DOT,
            )),
            _ => None,
        })
        .collect();
    assert_eq!(gray_fills.len(), 2, "{gray_fills:?}");
    // The second fill starts where the first ends.
    assert_eq!(gray_fills[1].1, gray_fills[0].2);
    // Both fills come before the text.
    let text = items
        .iter()
        .position(|item| matches!(item, Item::Glyphs(run) if run.text == "a"))
        .unwrap();
    assert!(gray_fills.iter().all(|(index, _, _)| *index < text));
}

/// The fills of the first page of `body` with the merged cells' fill `fill`, as their red
/// channel and their top and bottom in dots, from the top down; black lines left out.
fn merged_fills(body: &str, fill: crate::quirks::MergedCellFill) -> Vec<(u8, i64, i64)> {
    let target = on_base_with(|p| p.with_variant(fill));
    let list = pass_with(body, (NORMAL, None), None, Numbering::default(), target).list;
    let mut fills: Vec<(u8, i64, i64)> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Rect(r) if r.color.r != 0 => Some((
                r.color.r,
                r.y.units() / DOT,
                (r.y.units() + r.height.units()) / DOT,
            )),
            _ => None,
        })
        .collect();
    fills.sort_by_key(|fill| fill.1);
    fills
}

/// Spans across the page: each a left and a right x in layout units.
type Spans = Vec<(i64, i64)>;

/// The gray fills and the black vertical lines of the first page of `list`, each as its left and
/// right x in layout units, from left to right; a line drawn twice counts once.
fn fills_and_lines(list: &DisplayList) -> (Spans, Spans) {
    let mut fills = Vec::new();
    let mut lines = Vec::new();
    for item in list.pages()[0].items() {
        if let Item::Rect(r) = item {
            let x = (r.x.units(), r.x.units() + r.width.units());
            if r.color.r == 0xD9 {
                fills.push(x);
            } else if r.color.r == 0 && r.height > r.width {
                lines.push(x);
            }
        }
    }
    fills.sort_unstable();
    lines.sort_unstable();
    lines.dedup();
    (fills, lines)
}

/// The gray fills and the black vertical lines of the first page of `body` with the cells'
/// fill sides `sides`, each as its left and right x in layout units, from left to right.
fn fill_sides(body: &str, sides: crate::quirks::CellFillSides) -> (Spans, Spans) {
    let target = on_base_with(|p| p.with_variant(sides));
    let list = pass_with(body, (NORMAL, None), None, Numbering::default(), target).list;
    fills_and_lines(&list)
}

#[test]
fn fills_a_cell_from_grid_line_to_grid_line_under_half_of_each_line() {
    // Two gray cells with 1 pt lines on every side and between them. With `GridLines`, each
    // fill runs from grid line to grid line, under half of each line.
    let body = own_lines_table(8, &[2000, 2000]);
    let (grid, lines) = fill_sides(&body, crate::quirks::CellFillSides::GridLines);
    let under = |x: i64, line: (i64, i64)| line.0 < x && x < line.1;
    assert_eq!((grid.len(), lines.len()), (2, 3), "{grid:?} {lines:?}");
    assert!(under(grid[0].0, lines[0]), "{grid:?} {lines:?}");
    assert!(under(grid[0].1, lines[1]), "{grid:?} {lines:?}");
    assert_eq!(grid[0].1, grid[1].0);
    assert!(under(grid[1].1, lines[2]), "{grid:?} {lines:?}");
}

/// The gray fills and the black vertical lines of the first page of `body`, each as its left
/// and right x in layout units from left to right, on a Letter page with margins of 1 inch in
/// mode 15, on a device of 600 dots per inch whose table lines are centered on their places
/// (`TableLines::RoundsCenters`), with the cells' fills between their side lines
/// (`CellFillSides::InsideLines`).
fn dot_fill_sides(body: &str) -> (Spans, Spans) {
    let (device, quirks) = crate::layout::testing::target_at(600, |p| {
        p.with_variant(crate::quirks::TableLines::RoundsCenters)
            .with_variant(crate::quirks::CellFillSides::InsideLines)
    });
    let section = r#"<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr>"#;
    let body = format!("{body}{section}");
    let list = pass_with(
        &body,
        (NORMAL, Some(15)),
        None,
        Numbering::default(),
        (device, quirks),
    )
    .list;
    fills_and_lines(&list)
}

/// Asserts that [`dot_fill_sides`] of `body` gives the black vertical lines `lines` and the gray
/// fills `fills`, each given in dots of 1/600 inch, half of [`DOT`].
fn assert_dot_spans(body: &str, lines: &[(i64, i64)], fills: &[(i64, i64)]) {
    let dot = DOT / 2;
    let in_dots = |spans: &[(i64, i64)]| -> Spans {
        spans.iter().map(|&(a, b)| (a * dot, b * dot)).collect()
    };
    let (found_fills, found_lines) = dot_fill_sides(body);
    assert_eq!(found_lines, in_dots(lines), "{found_lines:?}");
    assert_eq!(found_fills, in_dots(fills), "{found_fills:?}");
}

/// A table of fixed layout with the columns `grid` in twips and one row of two gray cells,
/// with single lines of `eighths` on every side of the table and between the cells.
fn own_lines_table(eighths: u32, grid: &[i64]) -> String {
    let gray = r#"<w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/></w:tcPr>"#;
    let line = format!(r#"w:val="single" w:sz="{eighths}""#);
    let borders = format!(
        "<w:tblLayout w:type=\"fixed\"/><w:tblBorders><w:top {line}/><w:left {line}/><w:bottom {line}/><w:right {line}/><w:insideV {line}/></w:tblBorders>"
    );
    let cell = format!("{gray}{}", p("a"));
    table(&borders, grid, &[("", &[&cell, &cell])])
}

#[test]
fn fills_a_cell_on_whole_dots_half_its_own_line_inside_the_lines_place() {
    // Lines of 1 pt (20 twips) on every side: the grid starts half the table's left line,
    // 10 twips, right of the margin's 1,440 twips, so the lines' places are 1,450, 2,051 and
    // 2,652 twips, 604.17, 854.58 and 1,105 dots, and the lines of 8 dots are drawn from 600,
    // 851 and 1,101. Each fill lies 10 twips inside the places, rounded to the dot: from
    // 1,460 (608.33, so 608) to 2,041 (850.42, so 850), one dot before the line between the
    // cells, and from 2,061 (858.75, so 859) to 2,642 (1,100.83, so 1,101).
    assert_dot_spans(
        &own_lines_table(8, &[601, 601]),
        &[(600, 608), (851, 859), (1101, 1109)],
        &[(608, 850), (859, 1101)],
    );
}

/// The top and bottom of each gray fill of the first page of `body`, in layout units, on a
/// device of 600 dots per inch in mode 15, with the cells' fill rows `rows`.
fn fill_rows(body: &str, rows: crate::quirks::CellFillRows) -> Vec<(i64, i64)> {
    let target = crate::layout::testing::target_at(600, |p| p.with_variant(rows));
    let list = pass_with(body, (NORMAL, Some(15)), None, Numbering::default(), target).list;
    list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Rect(r) if r.color.r == 0xD9 => Some((r.y.units(), (r.y + r.height).units())),
            _ => None,
        })
        .collect()
}

/// The gray rectangles and the black ones of the first page of `body` in their order, as
/// (index, top, bottom, gray) in layout units, on a device of 600 dots per inch in mode 15,
/// with the cells' top bands `band` and lines whose width the device rounds down.
fn band_rects(body: &str, band: crate::quirks::CellTopBand) -> Vec<(usize, i64, i64, bool)> {
    let target = crate::layout::testing::target_at(600, |p| {
        p.with_variant(band)
            .with_variant(crate::quirks::TableLines::RoundsCenters)
    });
    let list = pass_with(body, (NORMAL, Some(15)), None, Numbering::default(), target).list;
    list.pages()[0]
        .items()
        .iter()
        .enumerate()
        .filter_map(|(i, item)| match item {
            Item::Rect(r) if r.color.r == 0xD9 || r.color.r == 0 => {
                Some((i, r.y.units(), (r.y + r.height).units(), r.color.r == 0xD9))
            }
            _ => None,
        })
        .collect()
}

#[test]
fn paints_the_dot_that_a_top_line_loses_in_the_fills_color_after_it_on_a_target_that_does() {
    // Two gray cells without a top margin under a line of 1.5 pt, 12.5 dots of 1/600 inch,
    // which the device draws 12 dots tall where it rounds a line's width down. With `FromLineEdge`, a gray band follows the line
    // in the items, from the line's drawn lower edge down to its top plus 12.5 dots, a half up:
    // one dot under each cell. With `BelowMargin`, a cell without a top margin has no band.
    use crate::quirks::CellTopBand::{BelowMargin, FromLineEdge};
    let body = own_lines_table(12, &[2000, 2000]);
    let dot = DOT / 2;
    let gray = |rects: &[(usize, i64, i64, bool)]| rects.iter().filter(|r| r.3).count();
    let plain = band_rects(&body, BelowMargin);
    assert_eq!(gray(&plain), 2, "{plain:?}");
    let banded = band_rects(&body, FromLineEdge);
    assert_eq!(gray(&banded), 4, "{banded:?}");
    let top_line = banded.iter().filter(|r| !r.3).min_by_key(|r| r.1).copied();
    let Some((line_at, line_top, line_end, _)) = top_line else {
        panic!("no line: {banded:?}");
    };
    assert_eq!(line_end - line_top, 12 * dot, "{banded:?}");
    let bands: Vec<_> = banded
        .iter()
        .filter(|r| r.3 && r.1 == line_end && r.2 - r.1 == dot)
        .collect();
    assert_eq!(bands.len(), 2, "{banded:?}");
    assert!(bands.iter().all(|r| r.0 > line_at), "{banded:?}");
}

#[test]
fn puts_a_cells_fill_top_and_bottom_on_the_nearest_dots_on_a_target_that_does() {
    // Two gray cells under a line of 0.5 pt: each fill starts 0.5 pt below the row's top,
    // between two dots of 1/600 inch. With `WholeDots`, its top and bottom move to the nearest
    // dots, each by half a dot or less; with `Exact`, its top lies between them.
    use crate::quirks::CellFillRows::{Exact, WholeDots};
    let body = own_lines_table(4, &[2000, 2000]);
    let dot = DOT / 2;
    let on_dot = |y: i64| y % dot == 0;
    let (exact, dots) = (fill_rows(&body, Exact), fill_rows(&body, WholeDots));
    assert_eq!((exact.len(), dots.len()), (2, 2), "{exact:?} {dots:?}");
    assert!(exact.iter().all(|&(top, _)| !on_dot(top)), "{exact:?}");
    assert!(
        dots.iter()
            .all(|&(top, bottom)| on_dot(top) && on_dot(bottom)),
        "{dots:?}"
    );
    let near = |a: i64, b: i64| 2 * (a - b).abs() <= dot;
    for (&(top, bottom), &(dot_top, dot_bottom)) in exact.iter().zip(&dots) {
        assert!(
            near(top, dot_top) && near(bottom, dot_bottom),
            "{exact:?} {dots:?}"
        );
    }
}

#[test]
fn fills_a_cell_half_its_own_line_inside_in_whole_twips_rounded_down() {
    // Lines of 0.25 pt (5 twips) on every side: the grid starts half the table's left line,
    // 2.5 twips, rounded up to 3 twips right of the margin, so the line between the cells of
    // 3,005 and 601 twips lies at 4,448 twips (1,853.33 dots) and is drawn from 1,852 to
    // 1,854. Half the line is 2 twips in whole twips, rounded down: the left cell's fill ends
    // at 4,446 twips, exactly 1,852.5 dots, so 1,853, one dot under the line, and the right
    // cell's fill starts at 4,450 twips (1,854.17, so 1,854). The table's own lines at 1,443
    // and 5,049 twips give the fill's outer ends: 1,445 (602.08, so 602) and 5,047 (2,102.92,
    // so 2,103).
    assert_dot_spans(
        &own_lines_table(2, &[3005, 601]),
        &[(600, 602), (1852, 1854), (2103, 2105)],
        &[(602, 1853), (1854, 2103)],
    );
}

#[test]
fn fills_a_cell_to_the_lines_place_on_a_side_without_its_own_line() {
    // Two gray cells of 601 twips without table lines, and one line of 0.5 pt (10 twips)
    // between them, the left cell's own right line; the right cell's own left border is nil.
    // The line's place lies 2,041 twips from the page's edge, 850.42 dots, so the line of 4
    // dots is drawn from 848. The left cell's fill ends half its own line inside the place,
    // at 2,036 twips (848.33, so 848); the right cell's fill starts at the place itself, 850,
    // under the line. The outer sides have no line: the fills end at the places, 600 and
    // 1,101 (2,642 twips, 1,100.83 dots).
    let line = r#"w:val="single" w:sz="4""#;
    let shading = r#"<w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/>"#;
    let left = format!(
        "<w:tcPr><w:tcBorders><w:right {line}/></w:tcBorders>{shading}</w:tcPr>{}",
        p("a")
    );
    let right = format!(
        r#"<w:tcPr><w:tcBorders><w:left w:val="nil"/></w:tcBorders>{shading}</w:tcPr>{}"#,
        p("b")
    );
    let props = r#"<w:tblLayout w:type="fixed"/>"#;
    let body = table(props, &[601, 601], &[("", &[&left, &right])]);
    assert_dot_spans(&body, &[(848, 852)], &[(600, 848), (850, 1101)]);
}

#[test]
fn fills_a_merged_cell_with_its_first_cells_shading_on_a_target_that_does() {
    // A merged cell over three rows: an orange first cell, a blue second cell and a third cell
    // without a shading. With `FirstCell`, each row of the merged cell is orange, from the
    // first row's fill down without a gap; with `EachRow`, the first row is orange, the second
    // blue and the third has no fill.
    let orange = r#"<w:shd w:val="clear" w:color="auto" w:fill="FBE4D5"/>"#;
    let blue = r#"<w:shd w:val="clear" w:color="auto" w:fill="D2EAF1"/>"#;
    let borders = r#"<w:tblBorders><w:insideH w:val="single" w:sz="8"/></w:tblBorders>"#;
    let first = format!(
        r#"<w:tcPr><w:vMerge w:val="restart"/>{orange}</w:tcPr>{}"#,
        p("a")
    );
    let second = format!("<w:tcPr><w:vMerge/>{blue}</w:tcPr><w:p/>");
    let third = "<w:tcPr><w:vMerge/></w:tcPr><w:p/>";
    let rows: [(&str, &[&str]); 3] = [("", &[&first]), ("", &[&second]), ("", &[third])];
    let body = table(borders, &[2000], &rows);
    let whole = merged_fills(&body, crate::quirks::MergedCellFill::FirstCell);
    assert_eq!(whole.len(), 3, "{whole:?}");
    assert!(whole.iter().all(|fill| fill.0 == 0xFB), "{whole:?}");
    assert!(
        whole.windows(2).all(|pair| pair[1].1 == pair[0].2),
        "{whole:?}"
    );
    let each = merged_fills(&body, crate::quirks::MergedCellFill::EachRow);
    let colors: Vec<u8> = each.iter().map(|fill| fill.0).collect();
    assert_eq!(colors, [0xFB, 0xD2], "{each:?}");
}

#[test]
fn takes_back_the_fill_under_a_merged_cell_when_its_next_row_moves_on() {
    // A centred merged cell, orange in its first row, whose second row does not fit on the
    // small page and moves to the next page whole. The trial of the second row puts the first
    // cell's fill under the merged cell's content in the first row; going back takes it out,
    // so that the first page is the one of a merged cell without that fill: every item of the
    // first row stays, and no fill reaches below it.
    let orange = r#"<w:shd w:val="clear" w:color="auto" w:fill="FBE4D5"/>"#;
    let section = r#"<w:sectPr><w:pgSz w:w="4000" w:h="2400"/><w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="720"/></w:sectPr>"#;
    let first = format!(
        r#"<w:tcPr><w:vMerge w:val="restart"/>{orange}<w:vAlign w:val="center"/></w:tcPr>{}"#,
        p("a")
    );
    let tall: String = ["b", "c", "d", "e"].into_iter().map(p).collect();
    let rest = "<w:tcPr><w:vMerge/></w:tcPr><w:p/>";
    let rows: [(&str, &[&str]); 2] = [("", &[&first, &p("x")]), ("<w:cantSplit/>", &[rest, &tall])];
    let body = table("", &[1200, 1200], &rows) + section;
    let first_page = |fill| {
        let target = on_base_with(|p| p.with_variant(fill));
        let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
        assert!(list.pages().len() > 1, "the second row moves on");
        list.pages()[0].items().to_vec()
    };
    assert_eq!(
        first_page(crate::quirks::MergedCellFill::FirstCell),
        first_page(crate::quirks::MergedCellFill::EachRow)
    );
}

#[test]
fn paints_the_top_margin_of_a_filled_cell_again_after_the_lines() {
    // A gray cell with a top margin of 72 twips (3.6 pt, 15 dots) below a 1 pt top line: after
    // the line comes a gray band from the line's bottom down by the margin.
    let gray = r#"<w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/>"#;
    let borders = r#"<w:tblBorders><w:top w:val="single" w:sz="8"/></w:tblBorders>"#;
    let margin = r#"<w:tcMar><w:top w:w="72" w:type="dxa"/></w:tcMar>"#;
    let cell = format!("<w:tcPr>{margin}{gray}</w:tcPr>{}", p("a"));
    let list = lay_out(&table(borders, &[2000], &[("", &[&cell])]), NORMAL, None);
    let rects: Vec<(u8, i64, i64)> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Rect(r) => Some((
                r.color.r,
                r.y.units() / DOT,
                (r.y.units() + r.height.units()) / DOT,
            )),
            _ => None,
        })
        .collect();
    // The fill, the line, then the band from the line's bottom.
    assert_eq!(rects.len(), 3, "{rects:?}");
    let (line, band) = (rects[1], rects[2]);
    assert_eq!((rects[0].0, line.0, band.0), (0xD9, 0, 0xD9));
    assert_eq!((band.1, band.2 - band.1), (line.2, 15));
}

#[test]
fn paints_a_white_band_and_then_the_right_line_beside_it() {
    // A white cell with a top margin of 72 twips, a top line and a right line: its white fill
    // under the lines, a white band after the top line, and the right line's piece beside the
    // band after it.
    let white = r#"<w:shd w:val="clear" w:color="auto" w:fill="FFFFFF"/>"#;
    let borders = r#"<w:tblBorders><w:top w:val="single" w:sz="8"/><w:right w:val="single" w:sz="8"/></w:tblBorders>"#;
    let margin = r#"<w:tcMar><w:top w:w="72" w:type="dxa"/></w:tcMar>"#;
    let cell = format!("<w:tcPr>{margin}{white}</w:tcPr>{}", p("a"));
    let list = lay_out(&table(borders, &[2000], &[("", &[&cell])]), NORMAL, None);
    let rects: Vec<(u8, i64, i64, i64)> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Rect(r) => Some((
                r.color.r,
                r.x.units(),
                r.y.units(),
                r.y.units() + r.height.units(),
            )),
            _ => None,
        })
        .collect();
    let band = rects
        .iter()
        .rposition(|r| r.0 == 0xFF)
        .expect("a white band");
    let (_, band_x, top, bottom) = rects[band];
    // The cell's fill is the first item, white, from inside the band down past its bottom.
    let fill = rects[0];
    assert!(
        fill.0 == 0xFF && (top..bottom).contains(&fill.2) && fill.3 > bottom,
        "{rects:?}"
    );
    let after: Vec<_> = rects.iter().skip(band + 1).collect();
    // The right line's piece beside the band comes after it, and the rest of the line before.
    assert_eq!(after.len(), 1, "{rects:?}");
    assert!(
        after[0].1 > band_x && (after[0].2, after[0].3) == (top, bottom),
        "{rects:?}"
    );
    assert!(
        rects
            .iter()
            .take(band)
            .any(|r| r.1 == after[0].1 && r.2 == bottom),
        "{rects:?}"
    );
}

#[test]
fn draws_automatic_text_white_on_a_dark_fill() {
    // Text of the automatic color is white on a dark cell fill and black on a light one, and a
    // dark highlight does not change it.
    let color = |fill: &str, run: &str| {
        let cell = format!(
            r#"<w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="{fill}"/></w:tcPr><w:p><w:r>{run}<w:t>a</w:t></w:r></w:p>"#
        );
        let list = lay_out(&table("", &[2000], &[("", &[&cell])]), NORMAL, None);
        list.pages()[0]
            .items()
            .iter()
            .find_map(|item| match item {
                Item::Glyphs(run) => Some([run.color.r, run.color.g, run.color.b]),
                _ => None,
            })
            .unwrap()
    };
    assert_eq!(color("002060", ""), [255, 255, 255]);
    assert_eq!(color("D9D9D9", ""), [0, 0, 0]);
    assert_eq!(color("C00000", ""), [255, 255, 255]);
    assert_eq!(color("365F91", ""), [0, 0, 0]);
    // A color of the run's own stays.
    assert_eq!(
        color("002060", r#"<w:rPr><w:color w:val="000000"/></w:rPr>"#),
        [0, 0, 0]
    );
    // On a white cell, a dark highlight keeps the text black.
    assert_eq!(
        color(
            "FFFFFF",
            r#"<w:rPr><w:highlight w:val="darkBlue"/></w:rPr>"#
        ),
        [0, 0, 0]
    );
}

#[test]
fn draws_a_white_run_fill_over_a_dark_cell_with_black_text() {
    // A run shaded white in a dark cell: the cell's fill, then the run's white fill over it,
    // and text of the automatic color stays black on the run's own white.
    let cell = r#"<w:tcPr><w:shd w:val="clear" w:color="auto" w:fill="002060"/></w:tcPr><w:p><w:r><w:rPr><w:shd w:val="clear" w:color="auto" w:fill="FFFFFF"/></w:rPr><w:t>a</w:t></w:r></w:p>"#;
    let list = lay_out(&table("", &[2000], &[("", &[cell])]), NORMAL, None);
    let painted: Vec<[u8; 3]> = list.pages()[0]
        .items()
        .iter()
        .filter_map(|item| match item {
            Item::Rect(r) => Some([r.color.r, r.color.g, r.color.b]),
            Item::Glyphs(run) => Some([run.color.r, run.color.g, run.color.b]),
            _ => None,
        })
        .collect();
    assert_eq!(
        painted,
        [[0x00, 0x20, 0x60], [255, 255, 255], [0, 0, 0]],
        "the cell's fill, the run's fill and the glyphs, in this order"
    );
}

#[test]
fn keeps_the_cell_of_each_line_record() {
    // Two tables with a paragraph between them. The second table's first cell holds two
    // paragraphs and spans both grid columns of its row, and a nested table lies in its
    // second row; the nested table takes the next number. The empty paragraph after the
    // nested table ends the cell and has no line.
    let nested = table("", &[1000], &[("", &[&p("n")])]);
    let second_row = format!("{}{nested}<w:p/>", p("d"));
    let span = format!(
        r#"<w:tcPr><w:gridSpan w:val="2"/></w:tcPr>{}{}"#,
        p("b"),
        p("c")
    );
    let body = table("", &[2000, 2000], &[("", &[&p("a"), &p("x")])])
        + &p("o")
        + &table(
            "",
            &[2000, 2000],
            &[("", &[&span]), ("", &[&second_row, &p("e")])],
        );
    let pass = pass_with_header(&body, NORMAL, None, None);
    let cells: Vec<_> = pass
        .lines
        .iter()
        .map(|line| {
            let cell = line.cell.map(|c| (c.table, c.row, c.column));
            (cell, line.index)
        })
        .collect();
    assert_eq!(
        cells,
        [
            (Some((1, 1, 1)), 0),
            (Some((1, 1, 2)), 0),
            (None, 0),
            (Some((2, 1, 1)), 0),
            (Some((2, 1, 1)), 0),
            (Some((2, 2, 1)), 0),
            (Some((3, 1, 1)), 0),
            (Some((2, 2, 2)), 0),
        ],
        "{cells:?}"
    );
}

#[test]
fn numbers_the_lines_of_a_paragraph() {
    // Ten "q" of 5 pt each and spaces do not fit in a cell 1000 twips (50 pt) wide less its
    // margins, so the paragraph takes more than one line.
    let text = ["q"; 10].join(" ");
    let body = table("", &[1000], &[("", &[&p(&text)])]);
    let pass = pass_with_header(&body, NORMAL, None, None);
    let indexes: Vec<usize> = pass.lines.iter().map(|line| line.index).collect();
    assert!(indexes.len() > 1, "{indexes:?}");
    assert!(indexes.iter().copied().eq(0..indexes.len()), "{indexes:?}");
}

/// The cell floor gives the lowest bottom of the wrapping drawings, or of all drawings, with
/// `i64::MIN` for no drawing, on many orders of wrapping and other drawings.
#[test]
fn cell_floor_reaches_the_lowest_bottom_of_its_drawings() {
    let mut seed: u64 = 0x2545_f491_4f6c_dd1d;
    let mut next = |range: u64| {
        seed = seed
            .wrapping_mul(6_364_136_223_846_793_005)
            .wrapping_add(1_442_695_040_888_963_407);
        (seed >> 33) % range
    };
    for _ in 0..2_000 {
        let mut floor = CellFloor::Clear;
        let (mut wrapping, mut every) = (i64::MIN, i64::MIN);
        for _ in 0..next(6) {
            let bottom = i64::try_from(next(2_000)).unwrap() - 500;
            let wraps = next(2) == 1;
            floor = floor.lowered(Length::from_units(bottom), wraps);
            if wraps {
                wrapping = wrapping.max(bottom);
            }
            every = every.max(bottom);
        }
        let content = i64::try_from(next(2_000)).unwrap() - 500;
        for (all, pair) in [(false, wrapping), (true, every)] {
            let reached = floor
                .reach(all)
                .map_or(content, |floor| content.max(floor.units()));
            assert_eq!(reached, content.max(pair), "{floor:?} {all}");
        }
    }
}

#[test]
fn wrap_none_in_centered_cell_aligns_without_growing_row_height() {
    let drawing = |pos_pt: i64, h_pt: i64, wrap: &str| {
        let pos = pos_pt * 12_700;
        let cy = h_pt * 12_700;
        format!(
            r#"<w:r><w:drawing><wp:anchor distT="0" distB="0" distL="0" distR="0" simplePos="0" relativeHeight="1" behindDoc="1" locked="0" layoutInCell="1" allowOverlap="1" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wp:simplePos x="0" y="0"/><wp:positionH relativeFrom="column"><wp:posOffset>0</wp:posOffset></wp:positionH><wp:positionV relativeFrom="paragraph"><wp:posOffset>{pos}</wp:posOffset></wp:positionV><wp:extent cx="635000" cy="{cy}"/><wp:effectExtent l="0" t="0" r="0" b="0"/>{wrap}<wp:docPr id="1" name="s"/><a:graphic><a:graphicData uri="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wps:wsp><wps:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="635000" cy="{cy}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></wps:spPr><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>"#
        )
    };
    let cell = |va: &str, d: &str| {
        format!(r#"<w:tcPr><w:vAlign w:val="{va}"/></w:tcPr><w:p>{d}<w:r><w:t>a</w:t></w:r></w:p>"#)
    };
    // Auto-height centered row: 100 pt wrapNone does not grow row height, while 100 pt wrapSquare
    // does.
    let auto_none = table(
        "",
        &[2000],
        &[
            ("", &[&cell("center", &drawing(0, 100, "<wp:wrapNone/>"))]),
            ("", &[&p("b")]),
        ],
    );
    let auto_plain = table(
        "",
        &[2000],
        &[("", &[&cell("center", "")]), ("", &[&p("b")])],
    );
    let auto_sq = table(
        "",
        &[2000],
        &[
            (
                "",
                &[&cell(
                    "center",
                    &drawing(0, 100, r#"<wp:wrapSquare wrapText="bothSides"/>"#),
                )],
            ),
            ("", &[&p("b")]),
        ],
    );
    let none_list = lay_out(&auto_none, NORMAL, Some(15));
    let plain_list = lay_out(&auto_plain, NORMAL, Some(15));
    let sq_list = lay_out(&auto_sq, NORMAL, Some(15));
    assert_eq!(at(&none_list, 'b').1, at(&plain_list, 'b').1);
    assert!(at(&sq_list, 'b').1 > at(&none_list, 'b').1 + du(1500));
    // Minimum-height 120 pt centered row: 60 pt wrapNone at +20 pt (bottom 80 pt < 120 pt) shifts
    // "a" down by (120 - 80)/2 = 20 pt, less than the (120 - 10)/2 = 55 pt of text alone.
    let min_tr = r#"<w:trHeight w:val="2400" w:hRule="atLeast"/>"#;
    let min_none = table(
        "",
        &[2000],
        &[
            (
                min_tr,
                &[&cell("center", &drawing(20, 60, "<wp:wrapNone/>"))],
            ),
            ("", &[&p("b")]),
        ],
    );
    let min_plain = table(
        "",
        &[2000],
        &[(min_tr, &[&cell("center", "")]), ("", &[&p("b")])],
    );
    let min_none_list = lay_out(&min_none, NORMAL, Some(15));
    let min_plain_list = lay_out(&min_plain, NORMAL, Some(15));
    assert_eq!(at(&min_none_list, 'b').1, at(&min_plain_list, 'b').1);
    assert_eq!(at(&min_none_list, 'a').1 - base(1440), du(400));
    assert!(at(&min_plain_list, 'a').1 > at(&min_none_list, 'a').1 + du(500));
}

#[test]
fn puts_the_row_end_s_rest_at_the_bottom_of_a_cell_aligned_to_the_bottom() {
    // A row of at least 318 twips at the top margin of 1,440 twips ends 1,758 twips from the
    // page's top, exactly on half a dot of 600 dots per inch (732.5 dots), and its height
    // enters 0.4 of a 1/4,096 pt short. Its cell, aligned to the bottom, holds a single line
    // of 222.2 twips, which is not whole twips, so its moved text top starts no rest. The
    // line's box rounds up, so its bottom, at the row's end, places it. The cell takes the
    // row end's rest there, and the line goes up the page; held exactly, the half goes down.
    let body = aligned_row(318, "bottom", &p("b"));
    assert_eq!(
        held_one_dot_up_on(&Tall, None, &body),
        Length::UNITS_PER_INCH / 600
    );
}

#[test]
fn moves_a_centered_cell_by_half_of_the_rests_of_its_free_room() {
    // A row of at least 289 twips at the top margin of 1,440 twips, whose height enters 0.2
    // of a 1/4,096 pt short, holds a centered single line of 222.2 twips. Moved by half of the
    // free room, the line's bottom lies exactly on half a dot (884.5 dots), and its moved
    // text top, which is not whole twips, takes half of the row end's rest: 0.1 of a 1/4,096
    // pt short, so the line goes up the page; held exactly, the half goes down.
    let body = aligned_row(289, "center", &p("b"));
    assert_eq!(
        held_one_dot_up_on(&Tall, None, &body),
        Length::UNITS_PER_INCH / 600
    );
}

#[test]
fn starts_the_rest_of_a_moved_text_top_of_whole_twips_as_one_length() {
    // A row of at least 276 twips at the top margin of 1,440 twips holds a centered exact line
    // of 240 twips. Its free room of 36 twips moves the cell's text top to 1,458 twips from
    // the page's top, whole twips, exactly on half a dot (607.5 dots). That top starts its
    // rest as one length, 0.4 of a 1/4,096 pt short, so the line goes up the page. Half of the
    // free room's rests would put it 0.1 past, and held exactly the half goes down.
    let line = r#"<w:p><w:pPr><w:spacing w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>b</w:t></w:r></w:p>"#;
    let body = aligned_row(276, "center", line);
    assert_eq!(held_one_dot_up(None, &body), Length::UNITS_PER_INCH / 600);
}

#[test]
fn gives_the_rests_of_a_cell_s_move_for_its_alignment() {
    use super::rows::moved_rest;
    let half_emu = Length::from_units(1);
    assert_eq!(
        moved_rest(Some(VerticalAlign::Bottom), -1270, half_emu),
        Some(-1270)
    );
    assert_eq!(
        moved_rest(Some(VerticalAlign::Center), -1270, Length::ZERO),
        Some(-635)
    );
    assert_eq!(
        moved_rest(Some(VerticalAlign::Center), 1270, half_emu),
        Some(891)
    );
    assert_eq!(moved_rest(Some(VerticalAlign::Top), 1270, half_emu), None);
    assert_eq!(moved_rest(None, 1270, half_emu), None);
}

#[test]
fn starts_the_twips_rest_at_the_top_of_a_split_cell_s_part() {
    // On pages 3,000 twips high with a top margin of 1,134 twips and a bottom margin of 1,000
    // twips, a cell's fourth exact line of 240 twips ends below the page's foot, so the row
    // splits and that line goes on at the next page's top margin. The line ends 1,374 twips
    // from that page's top, exactly on half a dot (114.5 dots). Its part's text top, 1,134
    // twips, held as the nearest 1/4,096 pt, lies above its exact place, so the line goes up
    // the page; held exactly, the half goes down.
    let exact = |text| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>{text}</w:t></w:r></w:p>"#
        )
    };
    let cell = [exact("a"), exact("a"), exact("a"), exact("b")].concat();
    let section = r#"<w:sectPr><w:pgSz w:w="12240" w:h="3000"/><w:pgMar w:top="1134" w:right="1440" w:bottom="1000" w:left="1440"/></w:sectPr>"#;
    let body = table("", &[2000], &[("", &[&cell])]) + section;
    assert_eq!(held_one_dot_up(None, &body), Length::UNITS_PER_INCH / 600);
}

/// The step from the text of the first to the text of the second of two cells of 2,000 twips on
/// a grid of the same widths, in a table with a cell spacing of 40 twips and the properties
/// `props`, under the quirk `columns`.
fn spaced_column_step(props: &str, columns: crate::quirks::SpacedColumns) -> i64 {
    let props = format!(r#"<w:tblCellSpacing w:w="40" w:type="dxa"/>{props}"#);
    let cell = |text: &str| {
        format!(
            r#"<w:tcPr><w:tcW w:w="2000" w:type="dxa"/></w:tcPr>{}"#,
            p(text)
        )
    };
    let (a, b) = (cell("a"), cell("b"));
    let body = table(&props, &[2000, 2000], &[("", &[&a, &b])]);
    let target = on_base_with(|p| p.with_variant(columns));
    let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
    find(&list, 'b').1 - find(&list, 'a').1
}

#[test]
fn widens_a_spaced_column_to_its_cells_width_and_spacing_under_cell_widths() {
    // Under `Grid` the second cell's text starts 2,000 twips less the spacing after the
    // first's; under `CellWidths`, in a table of fixed layout, the first column is the cell's
    // width plus three spacings, and the second text starts 120 twips, 50 dots, further right.
    let fixed = r#"<w:tblLayout w:type="fixed"/>"#;
    let grid = spaced_column_step(fixed, crate::quirks::SpacedColumns::Grid);
    let widths = spaced_column_step(fixed, crate::quirks::SpacedColumns::CellWidths);
    assert_eq!(widths - grid, 50 * 3048);
}

#[test]
fn keeps_the_grid_columns_of_a_spaced_table_of_automatic_layout_under_cell_widths() {
    // Without a fixed layout the columns fit their content in Word, and `CellWidths` keeps the
    // grid.
    let grid = spaced_column_step("", crate::quirks::SpacedColumns::Grid);
    let widths = spaced_column_step("", crate::quirks::SpacedColumns::CellWidths);
    assert_eq!(widths, grid);
}

/// The step from the text of the first to the text of the second of two cells of 3,000 twips,
/// on the saved grid `grid`, in a table with the properties `props`, under the quirk `columns`.
fn autofit_column_step(props: &str, grid: &[i64], columns: crate::quirks::AutofitGrid) -> i64 {
    autofit_step_after("a", props, grid, columns)
}

/// [`autofit_column_step`] with the first cell's text `first`, which starts with "a".
fn autofit_step_after(
    first: &str,
    props: &str,
    grid: &[i64],
    columns: crate::quirks::AutofitGrid,
) -> i64 {
    let cell = |text: &str| {
        format!(
            r#"<w:tcPr><w:tcW w:w="3000" w:type="dxa"/></w:tcPr>{}"#,
            p(text)
        )
    };
    let (a, b) = (cell(first), cell("b"));
    let body = table(props, grid, &[("", &[&a, &b])]);
    let target = on_base_with(|p| p.with_variant(columns));
    let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
    find(&list, 'b').1 - find(&list, 'a').1
}

#[test]
fn takes_the_cells_widths_of_an_autofit_table_whose_grid_disagrees_under_fitting_cells() {
    // The grid of 1,500 twips a column disagrees with the cells of 3,000, which fit the text
    // column: under `FittingCells` the second text starts 1,500 twips, 625 dots, further right,
    // within the one dot of the device grid.
    use crate::quirks::AutofitGrid::{FittingCells, Saved};
    let saved = autofit_column_step("", &[1500, 1500], Saved);
    let cells = autofit_column_step("", &[1500, 1500], FittingCells);
    assert!((cells - saved - 625 * 3048).abs() <= 3048);
}

#[test]
fn keeps_the_saved_grid_of_a_fixed_wide_or_unfitting_table_under_fitting_cells() {
    // A fixed layout, a preferred width, and an indent that leaves the cells no room keep the
    // grid.
    use crate::quirks::AutofitGrid::{FittingCells, Saved};
    let fixed = r#"<w:tblLayout w:type="fixed"/>"#;
    let width = r#"<w:tblW w:w="5000" w:type="dxa"/>"#;
    let indent = r#"<w:tblInd w:w="4000" w:type="dxa"/>"#;
    for props in [fixed, width, indent] {
        let saved = autofit_column_step(props, &[1500, 1500], Saved);
        assert_eq!(
            autofit_column_step(props, &[1500, 1500], FittingCells),
            saved
        );
    }
}

#[test]
fn keeps_the_saved_grid_where_a_word_is_wider_than_its_cell_under_fitting_cells() {
    // A word of 60 letters, wider than the first cell of 3,000 twips, is a least width that the
    // cell does not hold: Word widened that column for it, so the saved grid stays.
    use crate::quirks::AutofitGrid::{FittingCells, Saved};
    let word = "a".repeat(60);
    let saved = autofit_step_after(&word, "", &[1500, 1500], Saved);
    assert_eq!(
        autofit_step_after(&word, "", &[1500, 1500], FittingCells),
        saved
    );
}

#[test]
fn keeps_the_saved_grid_where_a_cell_over_both_columns_holds_a_wider_word_under_fitting_cells() {
    // A word of 140 letters in a cell over both columns is wider than the two cells of 3,000
    // twips together, so the saved grid stays; a short word there lets the cells' widths in.
    use crate::quirks::AutofitGrid::{FittingCells, Saved};
    let step = |letters: usize, columns| {
        let cell = |text: &str| {
            format!(
                r#"<w:tcPr><w:tcW w:w="3000" w:type="dxa"/></w:tcPr>{}"#,
                p(text)
            )
        };
        let spanned = format!(
            r#"<w:tcPr><w:tcW w:w="6000" w:type="dxa"/><w:gridSpan w:val="2"/></w:tcPr>{}"#,
            p(&"x".repeat(letters))
        );
        let (a, b) = (cell("a"), cell("b"));
        let body = table("", &[1500, 1500], &[("", &[&spanned]), ("", &[&a, &b])]);
        let target = on_base_with(|p| p.with_variant(columns));
        let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
        find(&list, 'b').1 - find(&list, 'a').1
    };
    assert_eq!(step(140, FittingCells), step(140, Saved));
    assert_ne!(step(4, FittingCells), step(4, Saved));
}

#[test]
fn starts_a_spaced_tables_text_at_its_indent_before_mode_15_under_spaced_text_start() {
    // In mode 12, a table with a cell spacing of 45 twips, a left line of 30 twips, left cell
    // margins of 100 twips and an indent of 300 twips. Under `ExplicitTextStart` the first grid
    // line lies one margin left of the indent; under `SpacedTextStart` it lies the margin, twice
    // the spacing and the whole line left of it, so that the text starts at the indent: 120
    // twips, 50 dots, further left.
    let props = concat!(
        r#"<w:tblCellSpacing w:w="45" w:type="dxa"/><w:tblInd w:w="300" w:type="dxa"/>"#,
        r#"<w:tblBorders><w:left w:val="single" w:sz="12"/></w:tblBorders>"#,
        r#"<w:tblCellMar><w:left w:w="100" w:type="dxa"/></w:tblCellMar>"#
    );
    let body = table(props, &[3000], &[("", &[&p("a")])]);
    let start = |indent: crate::quirks::TableIndent| {
        let target = on_base_with(|p| {
            p.with_variant(indent)
                .with_variant(crate::quirks::SpacedCellText::InsideLines)
        });
        find(
            &pass_with(
                &body,
                (NORMAL, Some(12)),
                None,
                Numbering::default(),
                target,
            )
            .list,
            'a',
        )
        .1
    };
    let margin = start(crate::quirks::TableIndent::ExplicitTextStart);
    let text = start(crate::quirks::TableIndent::SpacedTextStart);
    assert_eq!(margin - text, 50 * 3048);
}

#[test]
fn keeps_only_the_text_of_a_table_of_zero_cell_spacing_between_the_line_middles() {
    // A cell spacing of zero, in mode 12, with an indent of 300 twips, left cell margins of 100
    // twips, a left line of 6 pt (120 twips, 50 dots) and cells of 2,040 twips on a grid of
    // 1,800. The text keeps the room of half the line, but the first grid line lies the margin
    // and the whole line left of the indent, 120 twips further left than one margin, and the
    // first column is the cell's width, 240 twips (100 dots) wider than the grid's.
    let props = concat!(
        r#"<w:tblCellSpacing w:w="0" w:type="dxa"/><w:tblInd w:w="300" w:type="dxa"/>"#,
        r#"<w:tblBorders><w:left w:val="single" w:sz="48"/></w:tblBorders>"#,
        r#"<w:tblLayout w:type="fixed"/>"#,
        r#"<w:tblCellMar><w:left w:w="100" w:type="dxa"/></w:tblCellMar>"#
    );
    let a = format!(
        r#"<w:tcPr><w:tcW w:w="2040" w:type="dxa"/></w:tcPr>{}"#,
        p("a")
    );
    let b = format!(
        r#"<w:tcPr><w:tcW w:w="2040" w:type="dxa"/></w:tcPr>{}"#,
        p("b")
    );
    let body = table(props, &[1800, 1800], &[("", &[&a, &b])]);
    let places = |rules: bool| {
        let target = on_base_with(|p| {
            if rules {
                p.with_variant(crate::quirks::SpacedCellText::InsideLines)
                    .with_variant(crate::quirks::SpacedColumns::CellWidths)
                    .with_variant(crate::quirks::TableIndent::SpacedTextStart)
            } else {
                p.with_variant(crate::quirks::SpacedCellText::LineMiddles)
                    .with_variant(crate::quirks::SpacedColumns::Grid)
                    .with_variant(crate::quirks::TableIndent::ExplicitTextStart)
            }
        });
        let list = pass_with(
            &body,
            (NORMAL, Some(12)),
            None,
            Numbering::default(),
            target,
        )
        .list;
        (find(&list, 'a').1, find(&list, 'b').1)
    };
    let (rules, earlier) = (places(true), places(false));
    assert_eq!(earlier.0 - rules.0, 50 * 3048);
    assert_eq!((rules.1 - rules.0) - (earlier.1 - earlier.0), 100 * 3048);
}

/// The page and the baseline in dots of `x` and of `y` in a cell whose paragraph holds `x`, a
/// break of the kind `kind` and `y`, with the quirk `breaks`.
fn cell_break_places(kind: &str, breaks: crate::quirks::CellBreak) -> ((usize, i64), (usize, i64)) {
    let cell = format!(r#"<w:p><w:r><w:t>x</w:t><w:br w:type="{kind}"/><w:t>y</w:t></w:r></w:p>"#);
    let body = table("", &[4000], &[("", &[cell.as_str()])]);
    let target = on_base_with(|p| p.with_variant(breaks));
    let list = pass_with(&body, (NORMAL, None), None, Numbering::default(), target).list;
    let (x_page, _, x) = find(&list, 'x');
    let (y_page, _, y) = find(&list, 'y');
    ((x_page, x), (y_page, y))
}

#[test]
fn keeps_the_text_around_a_break_in_a_cell_on_one_line_on_a_target_that_ignores_it() {
    use crate::quirks::CellBreak;
    for kind in ["page", "column"] {
        let (x, y) = cell_break_places(kind, CellBreak::Ignored);
        assert_eq!(x, y, "{kind}");
        let (x, y) = cell_break_places(kind, CellBreak::EndsLine);
        assert_eq!(x.0, y.0, "{kind}");
        assert!(y.1 > x.1, "{kind}");
    }
}

#[test]
fn drops_space_before_on_leading_cell_break_in_mode_15_only() {
    use crate::quirks::CellBreak;
    let delta = |mode: u32, valign: &str, c1: &str, c2: &str| {
        let va = if valign.is_empty() {
            String::new()
        } else {
            format!(r#"<w:tcPr><w:vAlign w:val="{valign}"/></w:tcPr>"#)
        };
        let body = format!(
            r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid><w:tr><w:tc>{va}{c1}</w:tc><w:tc>{va}{c2}</w:tc></w:tr></w:tbl>"#
        );
        let target = on_base_with(|p| p.with_variant(CellBreak::Ignored));
        let list = pass_with(
            &body,
            (NORMAL, Some(mode)),
            None,
            Numbering::default(),
            target,
        )
        .list;
        find(&list, 'B').2 - find(&list, 'A').2
    };
    let p_ref = r#"<w:p><w:pPr><w:spacing w:before="240"/></w:pPr><w:r><w:t>B</w:t></w:r></w:p>"#;
    let p_lead_pg = r#"<w:p><w:pPr><w:spacing w:before="240"/></w:pPr><w:r><w:br w:type="page"/><w:t>A</w:t></w:r></w:p>"#;
    let p_lead_col = r#"<w:p><w:pPr><w:spacing w:before="240"/></w:pPr><w:r><w:br w:type="column"/><w:t>A</w:t></w:r></w:p>"#;
    let p_mid_pg = r#"<w:p><w:pPr><w:spacing w:before="240"/></w:pPr><w:r><w:t>X</w:t><w:br w:type="page"/><w:t>A</w:t></w:r></w:p>"#;
    let p2_c1 = format!(
        r#"<w:p><w:pPr><w:spacing w:after="120"/></w:pPr><w:r><w:t>P</w:t></w:r></w:p>{p_lead_pg}"#
    );
    let p2_c2 = format!(
        r#"<w:p><w:pPr><w:spacing w:after="120"/></w:pPr><w:r><w:t>Q</w:t></w:r></w:p>{p_ref}"#
    );
    let cases = [
        (15, "", p_lead_pg, p_ref, du(240)),
        (15, "center", p_lead_pg, p_ref, du(120)),
        (15, "", p_lead_col, p_ref, du(240)),
        (15, "", p2_c1.as_str(), p2_c2.as_str(), du(120)),
        (15, "", p_mid_pg, p_ref, 0),
        (14, "", p_lead_pg, p_ref, 0),
        (12, "", p_lead_pg, p_ref, 0),
    ];
    for (mode, valign, c1, c2, expected) in cases {
        assert_eq!(delta(mode, valign, c1, c2), expected);
    }
}

#[test]
fn shifts_aligned_inline_and_floating_tables_by_border_in_mode_15_and_margin_before() {
    let dot = 3048;
    let target = crate::layout::testing::target_at(600, |p| {
        p.with_variant(crate::quirks::RightToLeftEdge::LeadingAndInside)
    });
    let pad = r#"<w:tblCellMar><w:left w:w="200" w:type="dxa"/><w:right w:w="200" w:type="dxa"/></w:tblCellMar>"#;
    let x_of = |props: &str, mode: u32| {
        let body = table(props, &[2000, 2000], &[("", &[&p("a"), &p("b")])]);
        find(
            &pass_with(
                &body,
                (NORMAL, Some(mode)),
                None,
                Numbering::default(),
                target,
            )
            .list,
            'a',
        )
        .1
    };
    let l12 = format!(r#"{pad}<w:tblBorders><w:left w:val="single" w:sz="96"/></w:tblBorders>"#);
    let r12 = format!(r#"{pad}<w:tblBorders><w:right w:val="single" w:sz="96"/></w:tblBorders>"#);
    let i12 = format!(r#"{pad}<w:tblBorders><w:insideV w:val="single" w:sz="96"/></w:tblBorders>"#);

    let ic = r#"<w:jc w:val="center"/>"#;
    let ir = r#"<w:jc w:val="right"/>"#;
    let fl = r#"<w:tblpPr w:horzAnchor="margin" w:tblpXSpec="left" w:vertAnchor="margin" w:tblpY="200"/>"#;
    let fc = r#"<w:tblpPr w:horzAnchor="margin" w:tblpXSpec="center" w:vertAnchor="margin" w:tblpY="200"/>"#;
    let fr = r#"<w:tblpPr w:horzAnchor="margin" w:tblpXSpec="right" w:vertAnchor="margin" w:tblpY="200"/>"#;
    let rtl = "<w:bidiVisual/>";
    let rtl_cases = [
        format!("{rtl}{ic}"),
        format!("{rtl}{fl}"),
        format!("{rtl}{fc}"),
        format!("{rtl}{fr}"),
    ];
    let mode_15_cases: [(&str, [i64; 3]); 9] = [
        (ic, [25, -25, 0]),
        (ir, [0, -50, 0]),
        (fl, [50, 0, 0]),
        (fc, [25, -25, 0]),
        (fr, [0, -50, 0]),
        (&rtl_cases[0], [-25, 0, -25]),
        (&rtl_cases[1], [0, 0, -50]),
        (&rtl_cases[2], [-25, 0, -50]),
        (&rtl_cases[3], [-50, 0, -50]),
    ];
    for (prefix, [dl, dr, di]) in mode_15_cases {
        let base = x_of(&format!("{prefix}{pad}"), 15);
        assert_eq!(x_of(&format!("{prefix}{l12}"), 15) - base, dl * dot);
        assert_eq!(x_of(&format!("{prefix}{r12}"), 15) - base, dr * dot);
        assert_eq!(x_of(&format!("{prefix}{i12}"), 15) - base, di * dot);
    }

    let m0 = r#"<w:tblCellMar><w:left w:w="0" w:type="dxa"/><w:right w:w="0" w:type="dxa"/></w:tblCellMar>"#;
    let m108 = r#"<w:tblCellMar><w:left w:w="108" w:type="dxa"/><w:right w:w="108" w:type="dxa"/></w:tblCellMar>"#;
    for (prefix, delta) in [(ir, 90), (fl, 0), (rtl_cases[3].as_str(), 90)] {
        assert_eq!(
            x_of(&format!("{prefix}{m108}"), 14) - x_of(&format!("{prefix}{m0}"), 14),
            delta * dot
        );
    }
}

#[test]
fn split_row_first_part_enforces_at_least_minimum_height_for_vertical_alignment() {
    // On a 6,000-twip page with 720-twip top/bottom margins (4,560-twip body) and a 3,720-twip
    // exact spacer, 840 twips remain on page 1. A row with trHeight="720" (36 pt atLeast)
    // splits across pages 1 and 2 when cell 2's 720-twip second paragraph overflows page 1; cell 1
    // (vAlign="center") centers inside the 720-twip minimum height rather than cell 2's shorter
    // 240-twip page-1 paragraph alone.
    let spacer = r#"<w:p><w:pPr><w:spacing w:after="0" w:line="3720" w:lineRule="exact"/></w:pPr><w:r><w:t>S</w:t></w:r></w:p>"#;
    let c1 = r#"<w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:vAlign w:val="center"/></w:tcPr><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>A</w:t></w:r></w:p>"#;
    let c2 = concat!(
        r#"<w:tcPr><w:tcW w:w="2000" w:type="dxa"/></w:tcPr>"#,
        r#"<w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="exact"/></w:pPr><w:r><w:t>B</w:t></w:r></w:p>"#,
        r#"<w:p><w:pPr><w:spacing w:after="0" w:line="720" w:lineRule="exact"/></w:pPr><w:r><w:t>C</w:t></w:r></w:p>"#,
    );
    let section = r#"<w:sectPr><w:pgSz w:w="12240" w:h="6000"/><w:pgMar w:top="720" w:right="720" w:bottom="720" w:left="720"/></w:sectPr>"#;
    let y_of = |row_props: &str| {
        let body = format!(
            "{spacer}{}{section}",
            table("", &[2000, 2000], &[(row_props, &[c1, c2])])
        );
        let list = lay_out(&body, NORMAL, None);
        assert_eq!(list.pages().len(), 2);
        assert_eq!(find(&list, 'A').0, 0);
        assert_eq!(find(&list, 'C').0, 1);
        find(&list, 'A').2
    };
    let auto_y = y_of("");
    let min_y = y_of(r#"<w:trHeight w:val="720"/>"#);
    // Minimum 720 twips vs 240-twip page-1 content adds 480 twips free room -> +240 twips (+12 pt = +50 dots at 300 dpi) for center alignment.
    assert_eq!(min_y - auto_y, 50);
}

#[test]
fn realigns_inline_table_across_mirrored_pages_and_columns() {
    // 2-column section: page 12240, margins 1440, space 720 -> col 1 left=1440, col 2 left=6480
    // (+5040 twips). A table with 4 tall rows overflows column 1 into column 2, shifting row 4
    // right by 5040 twips.
    let tall = r#"<w:trHeight w:val="4000" w:hRule="atLeast"/>"#;
    let body_cols = format!(
        r#"{}<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/><w:cols w:num="2" w:space="720"/></w:sectPr>"#,
        table(
            "",
            &[3600],
            &[
                (tall, &[&p("A")]),
                (tall, &[&p("B")]),
                (tall, &[&p("C")]),
                (tall, &[&p("D")]),
            ]
        )
    );
    let list_cols = lay_out(&body_cols, NORMAL, Some(15));
    let (pa, xa, _) = find(&list_cols, 'A');
    let (pd, xd, _) = find(&list_cols, 'D');
    assert_eq!((pa, pd), (0, 0));
    assert_eq!((xd - xa) / Length::UNITS_PER_TWIP, 5040);

    // Mirrored margins: left=720, right=1440 (diff +720 twips on even page 2). Both a whole-row
    // break and a split-row break shift page 2's cells right by 720 twips.
    let settings = Settings {
        side_margins: crate::styles::SideMargins::Mirrored,
        ..Settings::default()
    };
    let paras = |ch: &str| {
        format!(
            r#"<w:p><w:pPr><w:spacing w:after="0" w:line="4000" w:lineRule="exact"/></w:pPr><w:r><w:t>{ch}</w:t></w:r></w:p>"#
        )
    };
    let cell = format!("{}{}{}{}", paras("W"), paras("X"), paras("Y"), paras("Z"));
    let body_mirror = format!(
        r#"{}<w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="720"/></w:sectPr>"#,
        table("", &[3600], &[("", &[cell.as_str()])])
    );
    let doc = crate::layout::testing::parse(&format!(
        r#"<w:body xmlns:w="{}">{body_mirror}</w:body>"#,
        crate::ns::W
    ));
    let body = crate::body::Body::read(
        &mut crate::reader::PartReader::new(&doc),
        doc.root().unwrap(),
        (
            crate::reader::settings::ReaderSettings::base(),
            settings.mode_rules,
        ),
    );
    let styles = Styles::default();
    let (theme, fonts) = (Theme::default(), FontTable::default());
    let context = base_context(&styles, &settings);
    let stories = context.for_stories();
    let sections = crate::layout::testing::sections_of(&body, &crate::layout::Stories::default());
    let list_mirror = Layout::new(
        (&context, &stories),
        &sections,
        Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
    )
    .run_with_wraps(&body)
    .list;
    let (pw, xw, _) = find(&list_mirror, 'W');
    let (pz, xz, _) = find(&list_mirror, 'Z');
    assert_eq!((pw, pz), (0, 1));
    assert_eq!((xz - xw) / Length::UNITS_PER_TWIP, 720);
}