f-office-docx 0.2.4

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
//! The height of a line and where its baseline goes.

use f_office_units::scale::LINE;
use f_office_units::{Length, div_round, div_round_i128, saturated};

use super::face_of;
use crate::grid::{Device, LowBaseline, Rounding};
use crate::layout::decisions;
use crate::layout::{BaselineForm, Layout, Within};
use crate::lines::{Line, LineEnd, Piece, Placed};
use crate::params;
use crate::props::{LineSpacing, ParaProps};
use crate::text::{Face, FaceIndex, MathRoom};

/// The size of a line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) struct LineBox {
    /// How far its text goes above the baseline.
    pub(in crate::layout) ascent: Length,
    /// How far its text goes below the baseline.
    pub(in crate::layout) descent: Length,
    /// The height that the next line starts below its top.
    pub(in crate::layout) height: Length,
    /// The height of its text line, without what hangs below it: with multiple spacing, its
    /// single line scaled by the spacing (see [`multiple_baseline`]).
    pub(in crate::layout) text_height: Length,
    /// The offset of the baseline from its top.
    pub(in crate::layout) baseline: Length,
    /// How far below its top the text reaches, which must fit above the end of the body.
    pub(in crate::layout) text_bottom: Length,
    /// Whether the rules of single spacing place its baseline, which then depend on the
    /// paragraph's own space before on the first line (see [`rested_boxed_baseline`]).
    pub(in crate::layout) single: bool,
    /// Whether the page places its baseline up from its bottom, and for which kind of line.
    pub(in crate::layout) from_bottom: FromBottom,
    /// Whether multiple spacing places its baseline (see [`multiple_baseline`]). Below the
    /// paragraph's own space before, the page rounds that space on its own, or holds it in the
    /// line's box where the descent goes above the extra spacing (see [`placed_baseline`]).
    pub(in crate::layout) multiple: bool,
    /// The paragraph's space after that its box holds below the extra spacing, on the last
    /// line of a paragraph of automatic spacing at or above single spacing outside table cells
    /// whose space after follows it, which the next paragraph does not remove, under
    /// `MultipleBaseline::DescentAboveExtra`, and on such a line whose at-least minimum sets its
    /// height under `AtLeastSpaceAfter::Held`; otherwise 0 (see [`placed_baseline`]).
    pub(in crate::layout) after: Length,
    /// The room of the paragraph's top border that its box holds above it, as part of the
    /// space before, on the paragraph's first line where the box holds that room; otherwise 0.
    pub(in crate::layout) top_room: Length,
    /// The height rest: the part of a half-EMU, in 1/[`REST_PARTS`] of one, by which the
    /// line's exact height in whole 1/4096 pt lies past `height`, under
    /// `LineHeightUnit::Whole4096ths`; otherwise 0. The cursor carries it down the page.
    pub(in crate::layout) rest: i64,
    /// The twips rest of `height` ([`twips_rest`]) when it is a length of whole twips without a
    /// height rest, such as the height of an exact line; 0 for a line whose height is whole
    /// 1/4096 pt under `LineHeightUnit::Whole4096ths`, which adds no error of its own; otherwise
    /// `None`.
    pub(in crate::layout) twips: Option<i64>,
    /// The face of a centered line of multiple spacing whose middle the page rounds, which then
    /// places its baseline (`CenteredMultiple::MiddleRounded`); otherwise `None`.
    pub(in crate::layout) centered: Option<super::centered::CenteredFace>,
    /// Where the line lies in the steps of a line grid with its ascent and descent rounded
    /// apart (`GridSingleLine::PartsRounded`), how the page rounds the top of its steps from
    /// its exact place, whatever rest the cursor carries: its baseline lies whole dots below
    /// that top. `None` for another line.
    pub(in crate::layout) grid_ties: Option<Rounding>,
}

/// The parts of a half-EMU in which a height of whole `params::HEIGHT_PARTS_PER_POINT` parts
/// of a point is exact: those parts over their greatest common divisor with the half-EMUs of a
/// point, 4,096 / 8 = 512. The parts of a point are a power of two, so that divisor is the
/// twos that both numbers hold ([`SHARED_TWOS`]). One part of a point is [`REST_PER_PART`] of
/// them.
pub(in crate::layout) const REST_PARTS: i64 = params::HEIGHT_PARTS_PER_POINT >> SHARED_TWOS;

/// The parts of a half-EMU ([`REST_PARTS`]) in one part of a point: 25,400 / 8 = 3,175.
const REST_PER_PART: i64 = Length::UNITS_PER_POINT >> SHARED_TWOS;

/// The factors 2 that the half-EMUs of a point and `params::HEIGHT_PARTS_PER_POINT` share: 3.
const SHARED_TWOS: u32 = {
    let points = Length::UNITS_PER_POINT.trailing_zeros();
    let parts = params::HEIGHT_PARTS_PER_POINT.trailing_zeros();
    if points < parts { points } else { parts }
};

const _: () = assert!(params::HEIGHT_PARTS_PER_POINT.count_ones() == 1);

/// The metrics of a line's text that size its box ([`Layout::line_metrics`]).
struct LineMetrics {
    /// The tallest ascent, a list label's included.
    ascent: Length,
    /// The deepest descent of the text.
    descent: Length,
    /// How far a list label's ascent rises above the text's.
    rise: Length,
    /// The room below the text that parts of fractions need.
    drop: Length,
    /// The single line of the faces that give the ascent and the descent in whole parts of
    /// `params::HEIGHT_PARTS_PER_POINT` of a point ([`crate::text::Face::whole_line`]), a list
    /// label's rise included, when each such face has it and no fraction or operator adds to
    /// the line; otherwise `None`.
    whole_single: Option<i64>,
    /// The part of `whole_single` by which a list label's ascent rises above the text's, in
    /// the same parts; 0 where the line has no `whole_single`.
    whole_rise: i64,
    /// The shift room: how much taller the single line of the line's text is with the shifts
    /// of its runs' `w:position` than without them, list labels and parts of fractions left
    /// out ([`Layout::room_once`]).
    shift_room: Length,
    /// The face room: how much taller the box of the largest ascent and the largest descent of
    /// the line's text is than the largest single line of one of its faces, without the shifts
    /// of raised and lowered runs, as a length and, where the line has `whole_single`, in whole
    /// parts of `params::HEIGHT_PARTS_PER_POINT` of a point ([`Layout::face_room_once`]).
    face_room: (Length, Option<i64>),
    /// The largest font size that the line height of the faces that give the ascent uses.
    size: Length,
}

/// The height of a line of the spacing `n` in 240ths whose single line is `single` whole parts
/// of `params::HEIGHT_PARTS_PER_POINT` of a point, of which the part `once` comes once,
/// unscaled: the product of the rest of the single line rounded to a whole part, a half up,
/// with `once`, as the nearest half-EMU, a half up, and its height rest in 1/[`REST_PARTS`] of
/// a half-EMU. The products count in `i128`: a multiple within `params::MAX_LINE_MULTIPLE` of
/// the single line of a face at a size that the reader takes gives a length.
fn whole_height(single: i64, once: i64, n: i64) -> (Length, i64) {
    let exact = (div_round_i128(i128::from(single - once) * i128::from(n), i128::from(LINE))
        + i128::from(once))
        * i128::from(REST_PER_PART);
    let height = div_round_i128(exact, i128::from(REST_PARTS));
    // The rest lies within half of REST_PARTS of zero.
    let rest = i64::try_from(exact - height * i128::from(REST_PARTS)).unwrap_or(0);
    (Length::from_units(saturated(height)), rest)
}

/// The twips rest of a length of whole twips that the cursor adds down the page: the part of
/// a half-EMU, in 1/[`REST_PARTS`] of one, by which the length in the target's unit
/// (`TwipLengthUnit`) lies past it. Under `Nearest4096ths` that is its nearest whole part of
/// `params::HEIGHT_PARTS_PER_POINT`, a half up, and under `HalfEmus` the length itself, so
/// 0. A length of n twips never lies on half a part, so a length taken back has the opposite
/// rest. `None` for a length that is not whole twips.
pub(in crate::layout) fn twips_rest(device: &Device, length: Length) -> Option<i64> {
    if length.units() % Length::UNITS_PER_TWIP != 0 {
        return None;
    }
    let twips = length.units() / Length::UNITS_PER_TWIP;
    Some(device.twip_parts(twips).map_or(0, |parts| {
        parts * REST_PER_PART - length.units() * REST_PARTS
    }))
}

/// The twips rest of a line of the height `height` and the height rest `rest`: that of its
/// height when it is a length of whole twips without a height rest, such as the height of a
/// line of exact spacing or of at-least spacing whose minimum sets it; otherwise `None`.
fn height_twips(device: &Device, height: Length, rest: i64) -> Option<i64> {
    if rest == 0 {
        twips_rest(device, height)
    } else {
        None
    }
}

/// The rest of the bottom of a line `size` past its top's half-EMUs and its height, from a
/// top whose twips rest is `twips`: the line's own height rest, and its twips rest where the
/// top has one. Below a line whose height is neither whole twips nor whole 1/4096 pt, the
/// bottom has no twips rest, so it takes back the top's.
fn bottom_rest(size: &LineBox, twips: Option<i64>) -> i64 {
    // quirk: TwipLengthUnit::Nearest4096ths (src/quirks.rs)
    size.rest
        + match (twips, size.twips) {
            (Some(_), Some(own)) => own,
            (Some(above), None) => -above,
            (None, _) => 0,
        }
}

/// The spacing in 240ths whose height a line of the spacing `rule` takes in whole parts of
/// [`whole_height`], where its faces give it a single line in those parts: automatic spacing at
/// or above single spacing, and at-least spacing whose minimum is at most the line's single line
/// `single`, which takes single spacing.
fn whole_spacing(rule: LineSpacing, single: Length) -> Option<i64> {
    match rule {
        LineSpacing::Auto(n) if n >= LINE => Some(n),
        LineSpacing::AtLeast(h) if h <= single => Some(LINE),
        _ => None,
    }
}

/// A place down the page: the half-EMUs that hold it and its height rest, the part of a
/// half-EMU in 1/[`REST_PARTS`] of one by which the exact sum of line heights in whole
/// 1/4096 pt lies past them ([`LineBox::rest`]). A place whose half-EMUs lie exactly half a dot
/// past a whole dot is a tie only when its rest is 0; otherwise the rest's sign gives its dot.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ExactPlace {
    at: Length,
    rest: i64,
}

impl ExactPlace {
    /// The place `rest` parts of a half-EMU past `at`, carried into whole half-EMUs so that its
    /// own rest is below half a half-EMU, as the cursor carries it.
    fn carried(at: Length, rest: i64) -> Self {
        let carry = div_round(rest, REST_PARTS);
        Self {
            at: at + Length::from_units(carry),
            rest: rest - carry * REST_PARTS,
        }
    }

    /// The dot of a place with a height rest, which no half decides: the nearest dot, or at
    /// half a dot the one on the rest's side. `None` without a rest, where the rules of ties
    /// decide.
    fn rested_dot(self, device: &Device) -> Option<Length> {
        if self.rest == 0 {
            return None;
        }
        Some(if device.half_dot_side(self.at).is_eq() {
            let below = device.count(self.at, Rounding::Down);
            device.dots(if self.rest > 0 { below + 1 } else { below })
        } else {
            device.snap(self.at)
        })
    }
}

impl std::ops::Add<Length> for ExactPlace {
    type Output = Self;
    fn add(self, length: Length) -> Self {
        Self {
            at: self.at + length,
            rest: self.rest,
        }
    }
}

impl std::ops::Sub<Length> for ExactPlace {
    type Output = Self;
    fn sub(self, length: Length) -> Self {
        Self {
            at: self.at - length,
            rest: self.rest,
        }
    }
}

impl LineBox {
    /// The height of the steps in which the line goes down beside a tight or through wrap that
    /// leaves it no room, under `BlockedLines::LineSteps`: its single line, without the part
    /// that multiple spacing adds, and its height otherwise.
    pub(in crate::layout) fn step(&self) -> Length {
        if self.multiple {
            self.ascent + self.descent
        } else {
            self.height
        }
    }

    /// Whether multiple spacing below single spacing places its baseline: its text line, scaled
    /// by the spacing, is lower than its single line.
    pub(in crate::layout) fn low_multiple(&self) -> bool {
        self.multiple && self.text_height < self.ascent + self.descent
    }

    /// How much taller than its single line a line is whose at-least minimum sets its height.
    /// That part lies above the text, and above the paragraph's top border, which stands on the
    /// text's single line. It is 0 for every other line.
    pub(in crate::layout) fn least_extra(&self) -> Length {
        if matches!(self.from_bottom, FromBottom::AtLeast) {
            self.height - (self.ascent + self.descent)
        } else {
            Length::ZERO
        }
    }

    /// How much taller than its single line a line is whose multiple spacing places its
    /// baseline: the part that a spacing above single spacing adds to it. It is 0 for every
    /// other line and below single spacing.
    pub(in crate::layout) fn multiple_extra(&self) -> Length {
        if self.multiple {
            (self.height - (self.ascent + self.descent)).max(Length::ZERO)
        } else {
            Length::ZERO
        }
    }
}

/// Whether the page places the baseline of a line up from the line's bottom.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) enum FromBottom {
    /// It does not: the rules of the line's spacing place its baseline.
    No,
    /// A line of exact height: the page rounds its exact bottom (see [`exact_baseline`]).
    Exact,
    /// A line of exact height that ends its paragraph outside table cells, with the space
    /// after following it, under `ExactSpacedBottom::PartsRounded`: the page rounds its exact
    /// top and its exact height each on their own, and its bottom lies at their sum (see
    /// [`spaced_exact_baseline`]).
    ExactSpaced,
    /// A line whose at-least minimum, above its single line, sets its height: its box holds
    /// the paragraph's own space before on the first line, as a single line's box does (see
    /// [`placed_baseline`]).
    AtLeast,
}

impl FromBottom {
    /// The kind of a line of the spacing `rule`, with an object `excess` taller than its single
    /// line of height `single`.
    fn of(rule: LineSpacing, excess: Length, single: Length) -> Self {
        match rule {
            LineSpacing::Exact(_) => Self::Exact,
            LineSpacing::AtLeast(h) if excess <= Length::ZERO && h > single => Self::AtLeast,
            _ => Self::No,
        }
    }

    /// Whether the line is of exact height.
    fn exact(self) -> bool {
        matches!(self, Self::Exact | Self::ExactSpaced)
    }
}

/// `length` times the multiple `lines` of single spacing, in 240ths, to the nearest half-EMU,
/// a half up. The product counts in `i128`: a multiple within `params::MAX_LINE_MULTIPLE` of a
/// length that the reader takes, such as a line pitch, or of the single line of a face at a size
/// that the reader takes, gives a length. A product beyond the range of a length gives the nearer
/// end of that range.
fn times_lines(length: Length, lines: i64) -> Length {
    let product = i128::from(length.units()) * i128::from(lines);
    Length::from_units(saturated(div_round_i128(product, i128::from(LINE))))
}

impl Layout<'_> {
    /// The space after that the box of a line of a paragraph with the properties `props` holds,
    /// with the bottom border's room `border` that the box holds, on a line that the space
    /// after follows and that no object makes taller (`spaced`): the box of a line of exact
    /// spacing, or of automatic spacing below single spacing, holds the border's room alone.
    fn box_after(&self, props: &ParaProps, border: Length, spaced: bool) -> Length {
        let rule = props.line.unwrap_or(LineSpacing::Auto(LINE));
        if matches!(rule, LineSpacing::Exact(_)) || matches!(rule, LineSpacing::Auto(n) if n < LINE)
        {
            border
        } else {
            self.device.held_after(
                props.space_after() + border,
                rule,
                spaced && self.grid_pitch.is_none(),
                self.column.cell.is_some(),
            )
        }
    }

    /// The size of a line of a paragraph with the properties `props`. `mark` is the face of the
    /// paragraph mark and whether the line is the paragraph's last one, which holds it, and
    /// which the paragraph's space after follows unless the next paragraph removes it
    /// ([`Layout::kept_after`]).
    pub(in crate::layout) fn line_box_of(
        &self,
        line: &Line,
        mark: (Option<FaceIndex>, bool),
        props: &ParaProps,
    ) -> LineBox {
        let rule = props.line.unwrap_or(LineSpacing::Auto(LINE));
        // A last line takes the rules of a line with space after only where that space follows
        // it; where the next paragraph removes it, the line takes the rules of a line without.
        // The box of a paragraph's last line can hold the room of its bottom border as space
        // after, which then follows the line.
        let border = self.held_space_after(mark.1);
        let spaced = mark.1 && self.kept_after(props, true) + border > Length::ZERO;
        let LineMetrics {
            ascent,
            descent,
            rise,
            drop,
            whole_single,
            whole_rise,
            shift_room,
            face_room,
            size,
        } = self.line_metrics(line, mark);
        let (ascent, descent, whole_single) =
            self.turned_room((ascent, descent, whole_single), size);
        // On a centered line whose pieces' middles lie on one line, the line ends at the lowest
        // win bottom of its text, which no whole single line gives.
        // quirk: CenteredLine::MiddlesShared (src/quirks.rs)
        let (descent, whole_single) = self
            .centered_line(line, props)
            .and_then(|centered| centered.descent)
            .map_or((descent, whole_single), |descent| (descent, None));
        let (ascent, rise, whole_single, lifted) =
            self.object_rise(line, rule, (ascent, descent), (rise, whole_single));
        let text = ascent + descent;
        let (face_room, whole_face_room) = self.face_room_once(rule, face_room);
        let rise = rise + self.room_once(rule, shift_room) + face_room;
        let excess = self.object_excess(line, rule, ascent, descent);
        let box_parts = (ascent, descent, rise);
        let (mut height, mut baseline) = line_box(&self.device, box_parts, rule, (excess, spaced));
        // A line of SmartArt text with automatic spacing below or above single spacing places its
        // baseline by SmartArt's rule rather than Word's body-paragraph rule.
        let (smartart_base, smartart_tall) =
            self.smartart_baseline(rule, (ascent, descent, height, excess), baseline);
        baseline = smartart_base;
        // A line of automatic spacing at or above single spacing whose faces are of 2,048 units
        // per em takes its height in whole 1/4096 pt, and the rest past its half-EMUs goes
        // down the page with it ([`Layout::whole_box`]).
        let whole = self.whole_box(
            (rule, text, excess),
            (whole_single, whole_face_room, whole_rise),
            height,
        );
        let whole_parts = whole.is_some();
        let rest = whole.map_or(0, |(_, rest)| rest);
        height = whole.map_or(height, |(whole, _)| whole);
        let mut text_height = height;
        height += below_text(rule, excess, drop);
        self.adjust_at_least_drop(
            line,
            rule,
            (ascent, descent, rise, excess, drop, spaced),
            (&mut height, &mut text_height, &mut baseline),
        );
        // Below a taller object on the baseline, the descent of the line's text stays in the
        // line, and the part of a multiple spacing above single spacing comes below it. A line
        // with no text but spaces keeps the object's height.
        if let LineSpacing::Auto(n) = rule
            && excess > Length::ZERO
            && holds_glyph_besides_white_space(line)
        {
            height = height.max(text_below_object(n, (ascent, descent), baseline));
        }
        // A line that holds a tall inline object alone keeps the room that Word reserves below the
        // object: the multiple-spacing room scaled by the object run's line, and an underline's.
        height = self.object_alone_room(line, rule, (descent, excess), (height, baseline));
        // An object of a lowered run reaches its lowering below the baseline, and the line
        // holds it below its text's descent, with the part of a multiple spacing above single
        // spacing below it.
        let depth = object_depth(line, rule);
        height = reaching_below(height, baseline, (depth, above_single(rule, text - lifted)));
        let (height, baseline, grid_ties) = self.on_grid(
            rule,
            (ascent, descent),
            (excess, spaced),
            (height, baseline),
        );
        let (single, multiple, text_bottom, after_ok) = self.line_box_tail(
            line,
            rule,
            (ascent, descent, excess, drop, spaced),
            (baseline, depth, mark.1, smartart_tall),
        );
        LineBox {
            ascent,
            descent,
            height,
            text_height,
            baseline,
            text_bottom,
            single,
            from_bottom: self.bottom_kind(rule, (excess, text + drop), spaced),
            multiple,
            after: self.box_after(props, border, after_ok),
            // quirk: BorderSpace::Held (src/quirks.rs)
            top_room: self.held_borders.top,
            rest,
            // A line whose height is whole 1/4096 pt, which nothing below its text grows, adds
            // that height without an error of its own, so the twips rest of the lengths above
            // it goes on below it.
            twips: height_twips(&self.device, height, rest)
                .or((whole_parts && height == text_height).then_some(0)),
            // quirk: CenteredMultiple::MiddleRounded (src/quirks.rs)
            centered: self.centered_face(line, props, excess),
            // quirk: GridSingleLine::PartsRounded (src/quirks.rs)
            grid_ties,
        }
    }

    /// The height and baseline of a line of the spacing `rule`, with its text's `ascent` and
    /// `descent`, an object `excess` taller than its single line and whether its space after
    /// follows it (`spaced`), on the section's line grid, from its `height` and `baseline`
    /// without the grid; and how the page rounds the top of its steps when its target rounds
    /// its parts apart. Without a grid or with another spacing, the line keeps them.
    ///
    /// On a document grid, a line of automatic spacing fills whole steps of the pitch, with its
    /// text in the middle of them. A multiple m of single spacing fills m times the pitch, or the
    /// steps that its single line needs where those are more, and its single line lies in the
    /// middle of that height.
    fn on_grid(
        &self,
        rule: LineSpacing,
        (ascent, descent): (Length, Length),
        (excess, spaced): (Length, bool),
        (height, baseline): (Length, Length),
    ) -> (Length, Length, Option<Rounding>) {
        let Some(pitch) = self.grid_pitch else {
            return (height, baseline, None);
        };
        match rule {
            LineSpacing::Auto(n) => self.on_grid_auto(
                n,
                pitch,
                (ascent, descent),
                (excess, spaced),
                (height, baseline),
            ),
            LineSpacing::AtLeast(min) => self.on_grid_at_least(
                min,
                pitch,
                (ascent, descent),
                (excess, spaced),
                (height, baseline),
            ),
            LineSpacing::Exact(_) => (height, baseline, None),
        }
    }

    /// Places a line of automatic spacing `n` on a document line grid of `pitch`.
    fn on_grid_auto(
        &self,
        n: i64,
        pitch: Length,
        (ascent, descent): (Length, Length),
        (excess, spaced): (Length, bool),
        (height, baseline): (Length, Length),
    ) -> (Length, Length, Option<Rounding>) {
        // The count of whole pitches that a length fills, rounded up.
        let steps = |length: Length| (length.units() + pitch.units() - 1) / pitch.units();
        let rounded = (n == LINE && excess <= Length::ZERO)
            .then(|| {
                decisions::grid_single_parts(
                    &self.context.quirks,
                    &self.device,
                    (ascent, descent),
                    pitch,
                )
            })
            .flatten();
        if let Some(((above, below), ties)) = rounded {
            // A single line whose target rounds its ascent and descent apart fills the steps
            // that hold its height. Its baseline lies the rounded ascent plus half of what the
            // steps' height, rounded to the device as `ties` says, adds to the rounded parts
            // with the line's extra leading, a half away from zero, below its top: a line whose
            // rounded parts pass that height goes up.
            let parts = height - ascent - descent + above + below;
            let grown = pitch * steps(height).max(1);
            let added = self.device.dots(self.device.count(grown, ties)) - parts;
            let baseline = above + self.device.snap_half_away(added.div_toward_zero(2));
            (grown, baseline, Some(ties))
        } else if n == LINE || excess > Length::ZERO {
            let grown = pitch * steps(height).max(1);
            (grown, baseline + (grown - height).div_toward_zero(2), None)
        } else {
            let text = ascent + descent;
            let multiplied = times_lines(pitch, n);
            let grown = multiplied.max(pitch * steps(text).max(1));
            let baseline = text_baseline(&self.device, (ascent, descent), n, spaced)
                + (grown - text).div_toward_zero(2);
            (grown, baseline, None)
        }
    }

    /// Places a line of at-least spacing `min` on a document line grid of `pitch`: Word pads the
    /// line's natural single height to whole grid steps `grown` (centering the single line inside
    /// `grown`), then enforces `min`, putting any extra `min - grown` above the grid-padded line.
    fn on_grid_at_least(
        &self,
        min: Length,
        pitch: Length,
        (ascent, descent): (Length, Length),
        (excess, spaced): (Length, bool),
        (height, baseline): (Length, Length),
    ) -> (Length, Length, Option<Rounding>) {
        let text = ascent + descent;
        let natural = if excess <= Length::ZERO && min > text && height == min {
            (
                text,
                text_baseline(&self.device, (ascent, descent), LINE, spaced),
            )
        } else {
            (height, baseline)
        };
        let (grown, grid_base, grid_ties) =
            self.on_grid_auto(LINE, pitch, (ascent, descent), (excess, spaced), natural);
        if min <= grown {
            return (grown, grid_base, grid_ties);
        }
        if let Some(ties) = grid_ties {
            let grown_dots = self.device.dots(self.device.count(grown, ties));
            let grid_descent = grown_dots - grid_base;
            (min, self.device.snap(min) - grid_descent, None)
        } else {
            let grid_descent = grown - grid_base;
            (min, min - grid_descent, None)
        }
    }

    /// The kind of a line of the spacing `rule` that the page places up from its bottom
    /// ([`FromBottom::of`]), with an object `excess` taller than its single line `text`: a line
    /// of exact height that ends its paragraph outside table cells with the space after
    /// following it (`spaced`) is [`FromBottom::ExactSpaced`] under
    /// `ExactSpacedBottom::PartsRounded`.
    fn bottom_kind(
        &self,
        rule: LineSpacing,
        (excess, text): (Length, Length),
        spaced: bool,
    ) -> FromBottom {
        match FromBottom::of(rule, excess, text) {
            FromBottom::AtLeast if self.grid_pitch.is_some() => FromBottom::No,
            FromBottom::Exact if spaced && self.column.cell.is_none() => self
                .device
                .spaced_exact_bottom(FromBottom::ExactSpaced)
                .unwrap_or(FromBottom::Exact),
            kind => kind,
        }
    }

    /// The height and the height rest of a line of the spacing `rule` in whole parts of
    /// `params::HEIGHT_PARTS_PER_POINT` of a point, where the target holds heights in them and
    /// nothing but its text sizes it: a line of automatic spacing at or above single spacing,
    /// and one of at-least spacing whose minimum is at most its single line `text`, which takes
    /// the box of single spacing, whose faces give the whole single line `single` with the face
    /// room `once` and a list label's rise `rise` that come once, unscaled ([`whole_height`]).
    /// A line with a rise keeps the box of half-EMUs that its ascent and descent give, `height`,
    /// and its height rest carries the rest to the whole height, so that the box of a single
    /// line stays its ascent and descent. `None` for a line that keeps its half-EMUs.
    fn whole_box(
        &self,
        (rule, text, excess): (LineSpacing, Length, Length),
        (single, once, rise): (Option<i64>, Option<i64>, i64),
        height: Length,
    ) -> Option<(Length, i64)> {
        if excess > Length::ZERO || self.grid_pitch.is_some() {
            return None;
        }
        self.device.whole_line_height(|| {
            let n = whole_spacing(rule, text)?;
            let (whole, whole_rest) = whole_height(single?, once? + rise, n);
            if rise == 0 {
                return Some((whole, whole_rest));
            }
            let exact = i128::from(whole.units()) * i128::from(REST_PARTS) + i128::from(whole_rest);
            let kept = i128::from(height.units()) * i128::from(REST_PARTS);
            Some((height, i64::try_from(exact - kept).unwrap_or(whole_rest)))
        })
    }

    /// The ascent, the descent and the whole single line of a line whose font size is `size`,
    /// grown for a line of a turned frame's text where the target's `TurnedLineRoom` is
    /// `SizeShare`: by the share `params::TURNED_LINE_ROOM` of the size, half added to the
    /// ascent and half to the descent, and to the whole single line where the share is a whole
    /// number of its parts, which a size in half points always gives.
    fn turned_room(
        &self,
        (ascent, descent, whole_single): (Length, Length, Option<i64>),
        size: Length,
    ) -> (Length, Length, Option<i64>) {
        let turned = matches!(self.column.within, Within::TurnedFrame(..));
        let Some((part, whole)) = turned
            .then(|| decisions::turned_line_room(&self.context.quirks))
            .flatten()
        else {
            return (ascent, descent, whole_single);
        };
        let room = size * part;
        let half = room.div_round(whole * 2);
        let parts = room.units() * params::HEIGHT_PARTS_PER_POINT;
        let per_part = whole * Length::UNITS_PER_POINT;
        let whole_room = (parts % per_part == 0).then_some(parts / per_part);
        (
            ascent + half,
            descent + (room.div_round(whole) - half),
            whole_single
                .zip(whole_room)
                .map(|(single, room)| single + room),
        )
    }

    /// The room of the paragraph's bottom border that the box of its last line (`last`) holds
    /// as space after (`HeldBorders`), and 0 on its other lines.
    fn held_space_after(&self, last: bool) -> Length {
        // quirk: BorderSpace::Held (src/quirks.rs)
        if last {
            self.held_borders.bottom
        } else {
            Length::ZERO
        }
    }

    /// The room of the paragraph's bottom border that its last line (`last`) needs below its
    /// text at the foot of a page (`HeldBorders::foot`), and 0 on its other lines.
    fn foot_border_room(&self, last: bool) -> Length {
        // quirk: FootBorderRoom::Fits (src/quirks.rs)
        if last {
            self.held_borders.foot
        } else {
            Length::ZERO
        }
    }

    /// The tallest ascent and descent on a line, and how far a list label's ascent rises above
    /// the ascent of the text. The rise of superscripts and subscripts does not count.
    fn line_metrics(&self, line: &Line, (mark, last): (Option<FaceIndex>, bool)) -> LineMetrics {
        // Spaces and tabs size the line only when it holds nothing else.
        let only_blanks = line.placed.iter().all(is_blank);
        let sizing: Vec<&Placed> = line
            .placed
            .iter()
            .filter(|p| only_blanks || !is_blank(p))
            .collect();
        // A list label, and a part of a fraction, stand apart from the text: the room that
        // they need above it comes on top of the line.
        let apart = |p: &&&Placed| match p.piece {
            Piece::Glyph(g) => {
                g.label
                    || self
                        .shaper
                        .faces()
                        .get(g.face)
                        .is_some_and(|f| f.math.in_fraction)
            }
            _ => false,
        };
        let faces_of = |pieces: &mut dyn Iterator<Item = &&Placed>| -> Vec<FaceIndex> {
            pieces
                .filter_map(|p| face_of(&p.piece))
                .filter(|i| !self.inked(*i))
                .collect()
        };
        let mut faces = faces_of(&mut sizing.iter());
        let mut text = faces_of(&mut sizing.iter().filter(|p| !apart(p)));
        let alone = text.is_empty();
        let object_faces = self.object_run_faces(&sizing);
        self.fill_empty_line_faces(
            line,
            &sizing,
            (mark, alone),
            &object_faces,
            (&mut faces, &mut text),
        );
        let metric = |faces: &[FaceIndex], pick: fn(&Face) -> Length| {
            faces
                .iter()
                .filter_map(|i| self.shaper.faces().get(*i))
                .map(pick)
                .max()
                .unwrap_or(Length::ZERO)
        };
        // A blanks-only line takes its line break's face, or its paragraph mark on the last line.
        if let Some(face) = blank_line_end_face(line.end, mark, last).filter(|_| only_blanks) {
            faces = vec![face];
            text = vec![face];
        }
        // A raised or lowered run takes its ascent and descent with it.
        let ascent = metric(&faces, Face::raised_ascent);
        let rise = (ascent - metric(&text, Face::raised_ascent)).max(Length::ZERO);
        // The faces that give the line its descent: the text's, and a list label's where the
        // target counts it.
        let below = [
            text.clone(),
            self.counted_label_faces(&sizing).unwrap_or_default(),
        ]
        .concat();
        let descent = metric(&below, Face::raised_descent);
        // The shift room counts the text only: a list label or a part of a fraction above the
        // text already comes on top of the line as the rise. The room of a shadow is not a
        // shift: a multiple spacing scales it with the line.
        let shift_room = (metric(&text, Face::shifted_ascent) - metric(&text, Face::ascent)
            + (metric(&text, Face::shifted_descent) - metric(&text, Face::descent)))
        .max(Length::ZERO);
        // The room that a part of a fraction needs below the text comes below the line. The
        // parts of a fraction whose face has the room of its ink reach down as far as the ink
        // of their glyphs, as do those of an inline equation in a font without a `MATH` table;
        // the others reach as far as their font's descent.
        let parts: Vec<FaceIndex> = faces
            .iter()
            .copied()
            .filter(|i| {
                self.shaper
                    .faces()
                    .get(*i)
                    .is_some_and(|f| f.math.in_fraction && f.math.room != MathRoom::InkBelow)
            })
            .collect();
        let depth = metric(&parts, Face::raised_descent).max(self.fraction_ink_depth(&sizing));
        // The ink of a display's n-ary operator and its limits, and of the parts of a fraction
        // whose face has the room of its ink, reaches up, with the math font's `MathLeading` at the equation's size
        // over it, and down; that room comes on top of the line and below it.
        let (top, bottom) = self.operator_ink(&sizing);
        let rise = rise.max(top - (ascent - rise));
        let ascent = ascent.max(top);
        let drop = (depth.max(bottom) - descent).max(Length::ZERO);
        // A list label's rise counts in whole parts too: where nothing but the faces gives the
        // ascent, the rise is that of the label's face above the text's.
        let plain = drop == Length::ZERO && ascent == metric(&faces, Face::raised_ascent);
        let (whole_single, whole_text, whole_rise) =
            self.whole_singles(plain, &faces, (&text, &below));
        let (rise, whole_rise) = self.alone_rise(alone, &sizing, (rise, whole_rise));
        let size = faces
            .iter()
            .filter_map(|i| self.shaper.faces().get(*i))
            .map(|f| f.line_size)
            .max()
            .unwrap_or(Length::ZERO);
        let mut metrics = LineMetrics {
            ascent,
            descent,
            rise,
            drop,
            whole_single,
            whole_rise,
            shift_room,
            face_room: self.face_room(&text, whole_text),
            size,
        };
        if !alone && !object_faces.is_empty() {
            self.apply_object_run_height(&mut metrics, &object_faces);
        }
        metrics
    }

    /// Fills `faces` and `text` on a line without non-label text: from the inline objects' run
    /// faces when present and active (`ObjectLineMultiple::ObjectRun`, mode 15 and later), or else
    /// from the line break or paragraph mark.
    fn fill_empty_line_faces(
        &self,
        line: &Line,
        sizing: &[&Placed],
        (mark, alone): (Option<FaceIndex>, bool),
        object_faces: &[FaceIndex],
        (faces, text): (&mut Vec<FaceIndex>, &mut Vec<FaceIndex>),
    ) {
        if alone && !object_faces.is_empty() {
            faces.extend(object_faces.iter().copied());
            text.extend(object_faces.iter().copied());
            return;
        }
        let broken = match line.end {
            LineEnd::Break(face) => face,
            _ => None,
        };
        let empty = broken.or(mark);
        if faces.is_empty() || (alone && self.label_only_line(sizing)) {
            faces.extend(empty);
        }
        // A list label's descent does not size the line, unless the line holds nothing else.
        if text.is_empty() {
            text.extend(empty);
        }
        if text.is_empty() {
            text.clone_from(faces);
        }
    }

    /// Whether this layout sizes inline object lines and scales multiple spacing below tall
    /// objects alone by the objects' runs (`ObjectLineMultiple::ObjectRun`, compatibility mode 15
    /// and later).
    fn uses_object_run_faces(&self) -> bool {
        self.settings
            .mode_rules
            .scales_object_lines_by_object_runs()
            && decisions::object_line_multiple(&self.context.quirks, || Some(())).is_some()
    }

    /// The unshifted run faces of the inline objects in `sizing`, where the target sizes inline
    /// object lines by the objects' runs (`ObjectLineMultiple::ObjectRun`, compatibility mode 15
    /// and later); empty otherwise.
    fn object_run_faces(&self, sizing: &[&Placed]) -> Vec<FaceIndex> {
        if !self.uses_object_run_faces() {
            return Vec::new();
        }
        sizing
            .iter()
            .filter_map(|p| match p.piece {
                Piece::Object {
                    run_face: Some(face),
                    ..
                } if !self.inked(face) => Some(face),
                _ => None,
            })
            .collect()
    }

    /// Expands a text line's single line to the tallest inline object run's single line when that
    /// run is taller than the text's single line, keeping the text's descent below the baseline.
    fn apply_object_run_height(&self, metrics: &mut LineMetrics, object_faces: &[FaceIndex]) {
        let Some(tallest) = object_faces
            .iter()
            .filter_map(|i| self.shaper.faces().get(*i))
            .max_by_key(|f| f.line_height())
        else {
            return;
        };
        let single = tallest.line_height();
        if single > metrics.ascent + metrics.descent {
            metrics.ascent = single - metrics.descent;
            metrics.rise = Length::ZERO;
            metrics.whole_single = tallest.whole_line().map(|(up, down)| up + down);
            metrics.whole_rise = 0;
            metrics.shift_room = Length::ZERO;
            metrics.face_room = (Length::ZERO, Some(0));
            metrics.size = metrics.size.max(tallest.line_size);
        }
    }

    /// Whether `sizing` holds at least one list label and no fraction part, so an empty list line
    /// includes its paragraph mark (or line break) face when finding the tallest ascent.
    fn label_only_line(&self, sizing: &[&Placed]) -> bool {
        let mut has_label = false;
        for placed in sizing {
            if let Piece::Glyph(g) = placed.piece {
                if g.label {
                    has_label = true;
                } else if self
                    .shaper
                    .faces()
                    .get(g.face)
                    .is_some_and(|f| f.math.in_fraction)
                {
                    return false;
                }
            }
        }
        has_label
    }

    /// The rise of a list label above the text's ascent and its part of the whole single line,
    /// `rise`: none on a line whose pieces `sizing` hold a list label and no text (`alone`),
    /// where the target's multiple spacing scales that rise with the rest of the line, as if
    /// the label were the line's text, and `rise` elsewhere.
    fn alone_rise(&self, alone: bool, sizing: &[&Placed], rise: (Length, i64)) -> (Length, i64) {
        let label = || (sizing.iter()).any(|p| matches!(p.piece, Piece::Glyph(g) if g.label));
        (alone && label())
            .then(|| decisions::scaled_label_rise(&self.context.quirks, || (Length::ZERO, 0)))
            .flatten()
            .unwrap_or(rise)
    }

    /// Whether the face `i` takes the room of its ink below the text, as a display's n-ary
    /// operator and its limits, and the parts of a fraction in a math font whose face has the
    /// room of its ink, do.
    fn inked(&self, i: FaceIndex) -> bool {
        self.shaper
            .faces()
            .get(i)
            .is_some_and(|f| matches!(f.math.room, MathRoom::Ink { .. }))
    }

    /// The faces of the list labels among the pieces `sizing` that take no room of their ink,
    /// where the target counts a label's descent in its line's descent.
    fn counted_label_faces(&self, sizing: &[&Placed]) -> Option<Vec<FaceIndex>> {
        decisions::counted_labels(&self.context.quirks, || {
            (sizing.iter())
                .filter(|p| matches!(p.piece, Piece::Glyph(g) if g.label))
                .filter_map(|p| face_of(&p.piece))
                .filter(|i| !self.inked(*i))
                .collect()
        })
    }

    /// The whole single lines of a line whose faces `faces` give its ascent and `below` its
    /// descent, of the text `text`, where nothing but those faces sizes it (`plain`): the
    /// line's ([`Self::whole_single`]), its text's own with the same descent, and the part by
    /// which a list label's ascent rises above the text's, in the same parts (0 without a whole
    /// single line).
    fn whole_singles(
        &self,
        plain: bool,
        faces: &[FaceIndex],
        (text, below): (&[FaceIndex], &[FaceIndex]),
    ) -> (Option<i64>, Option<i64>, i64) {
        let own = plain.then(|| self.whole_single(text, below)).flatten();
        let all = own.and(self.whole_single(faces, below));
        let rise = all.zip(own).map_or(0, |(all, own)| all - own);
        (all, own, rise)
    }

    /// The single line of the faces `faces`, which give a line its ascent, and `text`, which
    /// give its descent, in whole parts of `params::HEIGHT_PARTS_PER_POINT` of a point: the
    /// largest ascent and the largest descent of [`Face::whole_line`], or `None` when a face has
    /// none.
    fn whole_single(&self, faces: &[FaceIndex], text: &[FaceIndex]) -> Option<i64> {
        let whole = |faces: &[FaceIndex], pick: fn((i64, i64)) -> i64| {
            faces
                .iter()
                .map(|i| {
                    self.shaper
                        .faces()
                        .get(*i)
                        .and_then(Face::whole_line)
                        .map(pick)
                })
                .collect::<Option<Vec<i64>>>()?
                .into_iter()
                .max()
        };
        Some(whole(faces, |(up, _)| up)? + whole(text, |(_, down)| down)?)
    }

    /// The face room of a line whose text is in the faces `text` ([`LineMetrics::face_room`]):
    /// like the shift room, it counts the text only, without the shifts; in whole parts where
    /// its text has the whole single line `whole_single`.
    fn face_room(&self, text: &[FaceIndex], whole_single: Option<i64>) -> (Length, Option<i64>) {
        let largest = |pick: fn(&Face) -> Length| {
            text.iter()
                .filter_map(|i| self.shaper.faces().get(*i))
                .map(pick)
                .max()
                .unwrap_or(Length::ZERO)
        };
        let room = (largest(Face::ascent) + largest(Face::descent) - largest(Face::line_height))
            .max(Length::ZERO);
        let whole = whole_single
            .zip(self.whole_face_line(text))
            .map(|(single, line)| (single - line).max(0));
        (room, whole)
    }

    /// The largest single line of one of the faces `text` in whole parts of
    /// `params::HEIGHT_PARTS_PER_POINT` of a point ([`Face::whole_line`]), or `None` when a face
    /// has none.
    fn whole_face_line(&self, text: &[FaceIndex]) -> Option<i64> {
        text.iter()
            .map(|i| {
                self.shaper
                    .faces()
                    .get(*i)
                    .and_then(Face::whole_line)
                    .map(|(up, down)| up + down)
            })
            .collect::<Option<Vec<i64>>>()?
            .into_iter()
            .max()
    }

    /// The ascent, the rise and the whole single line of a line of spacing `rule` with the
    /// objects of its runs that are lowered or not raised, and how much the objects lift the
    /// line: on a target whose variant is `ObjectAscent::Ascent`, where such an object's part
    /// above the baseline, its height less the lowering, is taller than the line's `ascent` and
    /// no taller than its single line, the ascent and `descent` of its text, it becomes the
    /// ascent, and the difference comes on top of the line unscaled, as a list label's rise does.
    /// A taller part grows the line as an object taller than the single line does
    /// ([`Layout::object_excess`]). Only a line of automatic spacing at or above single spacing
    /// takes the rule, and an object of a run that is not lowered only on a line that holds text:
    /// a line of other spacing, such an object on a line of objects and white space alone, and a
    /// target of `ObjectAscent::SingleLine`, keep theirs.
    fn object_rise(
        &self,
        line: &Line,
        rule: LineSpacing,
        (ascent, descent): (Length, Length),
        (rise, whole_single): (Length, Option<i64>),
    ) -> (Length, Length, Option<i64>, Length) {
        let kept = (ascent, rise, whole_single, Length::ZERO);
        if !matches!(rule, LineSpacing::Auto(n) if n >= LINE) {
            return kept;
        }
        let text = holds_glyph_besides_white_space(line);
        decisions::object_ascent(&self.context.quirks, || {
            let above = line
                .placed
                .iter()
                .filter_map(|p| match p.piece {
                    Piece::Object { height, raised, .. }
                        if raised < Length::ZERO || (text && raised == Length::ZERO) =>
                    {
                        Some(height + raised)
                    }
                    _ => None,
                })
                .max()
                .unwrap_or(Length::ZERO);
            (above > ascent && above <= ascent + descent)
                .then(|| (above, rise + (above - ascent), None, above - ascent))
        })
        .unwrap_or(kept)
    }

    /// The part of a line of spacing `rule` that comes on top of it unscaled, as a list label's
    /// rise does, for its face room `room` ([`LineMetrics::face_room`]), as a length and in
    /// whole parts: on a target whose variant is `FaceRoomSpacing::Once`, in automatic multiple
    /// spacing above single spacing, all of it, so that the spacing scales only the largest
    /// single line of one face and the baseline stays at the line's ascent; otherwise none.
    fn face_room_once(
        &self,
        rule: LineSpacing,
        room: (Length, Option<i64>),
    ) -> (Length, Option<i64>) {
        matches!(rule, LineSpacing::Auto(n) if n > LINE)
            .then(|| decisions::face_room_once(&self.context.quirks, room))
            .flatten()
            .unwrap_or((Length::ZERO, Some(0)))
    }

    /// The part of a line of spacing `rule` that comes on top of it unscaled, as a list label's
    /// rise does, for its shift room `shift_room` ([`LineMetrics::shift_room`]): on a target
    /// whose variant is `RaisedRunSpacing::Once`, in automatic multiple spacing above single
    /// spacing, all of it, so that the spacing scales only the single line without the shifts
    /// and the baseline stays at the line's ascent; otherwise none.
    fn room_once(&self, rule: LineSpacing, shift_room: Length) -> Length {
        matches!(rule, LineSpacing::Auto(n) if n > LINE)
            .then(|| decisions::raised_room_once(&self.context.quirks, shift_room))
            .flatten()
            .unwrap_or(Length::ZERO)
    }

    /// Whether the pieces of `line` other than spaces and tabs have two heights: glyphs and
    /// marks of faces of another ascent or descent, as of runs of two font sizes, or an inline
    /// object beside text or beside an object of another height. A raised or lowered run counts
    /// by its face, so beside text of its own size it has the same height, and the paragraph
    /// mark does not count.
    pub(in crate::layout) fn holds_two_heights(&self, line: &Line) -> bool {
        let mut heights =
            line.placed
                .iter()
                .filter(|p| !is_blank(p))
                .filter_map(|p| match p.piece {
                    Piece::Object { height, raised, .. } => {
                        Some((height + raised, (-raised).max(Length::ZERO)))
                    }
                    ref piece => face_of(piece)
                        .and_then(|i| self.shaper.faces().get(i))
                        .map(|face| (face.ascent(), face.descent())),
                });
        heights
            .next()
            .is_some_and(|first| heights.any(|height| height != first))
    }

    /// How far the ink of a display's n-ary operators drawn with the larger variants of their
    /// glyphs, of their limits, of the parts of fractions in a math font, and of the scripts
    /// whose face has the room of its font's lines and of its ink, reaches above the baseline
    /// of a line, with the math font's `MathLeading` over it, and below it, and how far the
    /// bars over and under expressions reach with the room beyond them; nothing on a line
    /// without them.
    fn operator_ink(&self, sizing: &[&Placed]) -> (Length, Length) {
        sizing
            .iter()
            .filter_map(|placed| {
                let glyph = match placed.piece {
                    Piece::Glyph(glyph) => glyph,
                    Piece::Vinculum {
                        face,
                        top,
                        thickness,
                        beyond: (above, below),
                        ..
                    } => {
                        let rise = self.device.shift_dots(self.shaper.faces().get(face)?.rise);
                        return Some((top + rise + above, thickness - top - rise + below));
                    }
                    _ => return None,
                };
                let face = self.shaper.faces().get(glyph.face)?;
                // A script's ink stands at its rise, and its font lines stay on the line's
                // baseline; the other faces with the room of their ink take their line raised
                // with their text.
                let (leading, shift) = match face.math.room {
                    MathRoom::Ink { leading } => (leading, face.raised),
                    MathRoom::LinesAndInk { leading } => (leading, face.rise),
                    MathRoom::Lines | MathRoom::InkBelow => return None,
                };
                let (low, high) = self.shaper.ink(&glyph)?;
                Some((high + shift + leading, -(low + shift)))
            })
            .fold(
                (Length::ZERO, Length::ZERO),
                |(top, bottom), (high, low)| (top.max(high), bottom.max(low)),
            )
    }

    /// How far the ink of the parts of fractions of inline equations in a font without a
    /// `MATH` table on a line reaches below its baseline; nothing on a line without such ink.
    fn fraction_ink_depth(&self, sizing: &[&Placed]) -> Length {
        let mut depth = Length::ZERO;
        for placed in sizing {
            let Piece::Glyph(glyph) = placed.piece else {
                continue;
            };
            let Some(face) = self.shaper.faces().get(glyph.face) else {
                continue;
            };
            if face.math.room != MathRoom::InkBelow {
                continue;
            }
            let Some((low, _)) = self.shaper.ink(&glyph) else {
                continue;
            };
            depth = depth.max(-(low + face.raised));
        }
        depth
    }

    /// How far below the baseline an inline VML shape or picture stands on a line: on a line
    /// of multiple spacing that holds no text and no taller object, the part of the spacing
    /// above single spacing, and else nothing.
    pub(super) fn shape_drop(&self, line: &Line, rule: LineSpacing, size: &LineBox) -> Length {
        match rule {
            LineSpacing::Auto(n)
                if n != LINE
                    && !holds_glyph_besides_white_space(line)
                    && self.object_excess(line, rule, size.ascent, size.descent)
                        <= Length::ZERO =>
            {
                size.height - (size.ascent + size.descent)
            }
            _ => Length::ZERO,
        }
    }

    /// Whether the tallest inline object on a line, which sets its room ([`Self::object_excess`]),
    /// draws an underline below it. On an object-alone line taller than its font line, Word keeps
    /// room below the baseline for that underline.
    fn tallest_object_underlined(&self, line: &Line, rule: LineSpacing) -> bool {
        let anchored = self.anchor_line(line, rule);
        line.placed
            .iter()
            .filter_map(|p| match p.piece {
                Piece::Object {
                    height,
                    raised,
                    drawing,
                    underlined,
                    ..
                } => {
                    let room = drawing
                        .filter(|_| anchored)
                        .and_then(|index| self.anchor_room(index))
                        .map_or(height, |room| room.above + room.below);
                    Some((room + raised, underlined))
                }
                _ => None,
            })
            .max_by_key(|(room, _)| *room)
            .is_some_and(|(_, underlined)| underlined)
    }

    /// The height of a line that holds a tall inline object alone, adjusted for the room Word keeps
    /// below the object, from its `height` before them with the baseline at `baseline` and the
    /// text's `descent`: the part of a multiple spacing above single spacing scaled by the object
    /// run's single line in place of the paragraph mark's (`ObjectLineMultiple::ObjectRun`), and
    /// the object run's font descent below the baseline for an underline its run draws
    /// (`UnderlinedObjectRoom::FontDescent`). A line with text, with no taller object, or of other
    /// spacing keeps its `height`.
    fn object_alone_room(
        &self,
        line: &Line,
        rule: LineSpacing,
        (descent, excess): (Length, Length),
        (height, baseline): (Length, Length),
    ) -> Length {
        if !matches!(rule, LineSpacing::Auto(_))
            || excess <= Length::ZERO
            || holds_glyph_besides_white_space(line)
        {
            return height;
        }
        let mut height = height;
        // The multiple spacing below the object scales by the object run's own single line.
        // quirk: ObjectLineMultiple::ObjectRun (src/quirks.rs)
        if let LineSpacing::Auto(n) = rule
            && n > LINE
            && self.uses_object_run_faces()
            && let Some(run_line) = self.object_runs_line(line)
        {
            height = baseline + above_single(rule, run_line);
        }
        // An underlined object keeps its run's font descent below the baseline for the underline.
        // quirk: UnderlinedObjectRoom::FontDescent (src/quirks.rs)
        if decisions::underlined_object_room(&self.context.quirks)
            && self.tallest_object_underlined(line, rule)
        {
            height = height.max(baseline + descent);
        }
        height
    }

    /// The largest single line among the runs of a line's inline objects, short ones too: each
    /// run's face's ascent plus descent at the run's font and size. On a multiple-spaced
    /// object-alone line, Word scales the part of the spacing above single spacing by it; the runs
    /// of the line's spaces do not count. `None` where no object's run has a face.
    fn object_runs_line(&self, line: &Line) -> Option<Length> {
        line.placed
            .iter()
            .filter_map(|p| match p.piece {
                Piece::Object {
                    run_face: Some(face),
                    ..
                } => self.shaper.faces().get(face).map(Face::line_height),
                _ => None,
            })
            .max()
            .filter(|run_line| *run_line > Length::ZERO)
    }

    /// The height (including raising) of the tallest real inline object (`picture` or `drawing`,
    /// excluding zero-height legacy list spacers) on `line`, or `None` when `line` holds none.
    fn tallest_real_object_room(&self, line: &Line, rule: LineSpacing) -> Option<Length> {
        let anchored = self.anchor_line(line, rule);
        line.placed
            .iter()
            .filter_map(|p| match p.piece {
                Piece::Object {
                    height,
                    raised,
                    picture,
                    drawing,
                    ..
                } if picture.is_some() || drawing.is_some() => {
                    let room = drawing
                        .filter(|_| anchored)
                        .and_then(|index| self.anchor_room(index))
                        .map_or(height, |room| room.above + room.below);
                    // A raised or lowered object reaches its raising above its height.
                    Some(room + raised)
                }
                _ => None,
            })
            .max()
    }

    /// Whether `line` holds any inline VML object whose vertical placement follows its own VML
    /// rule: any inline VML drawing (`drawing.extent.is_none()`, including `<v:rect>` and
    /// `<o:hr>`), or a VML picture (`picture.drops`) under multiple spacing.
    fn holds_vml_baseline_object(&self, line: &Line, multiple: bool) -> bool {
        line.placed.iter().any(|p| match p.piece {
            Piece::Object {
                drawing: Some(index),
                ..
            } => self
                .output
                .drawing(index)
                .is_some_and(|d| d.extent.is_none()),
            Piece::Object {
                picture: Some(index),
                ..
            } if multiple => self.output.pictures.get(index).is_some_and(|pic| pic.drops),
            _ => false,
        })
    }

    /// Whether `line` holds only inline objects and optional ASCII spaces/tabs (no text glyphs —
    /// including non-breaking spaces `\u{00A0}`, which Word treats as text — and no struts,
    /// rules, check boxes, notes, or equation pieces).
    fn holds_only_objects_and_space(line: &Line) -> bool {
        !line.placed.iter().any(|p| {
            matches!(
                p.piece,
                Piece::Glyph(g) if g.ch != ' '
            ) || matches!(
                p.piece,
                Piece::Strut(_)
                    | Piece::Rule { .. }
                    | Piece::CheckBox { .. }
                    | Piece::Note(_)
                    | Piece::Endnote(_)
                    | Piece::NoteMarkEnd
                    | Piece::EndnoteMarkEnd(_)
                    | Piece::Shift(_)
                    | Piece::Advance(_)
                    | Piece::Bar { .. }
                    | Piece::Vinculum { .. }
                    | Piece::Diagonal { .. }
            )
        })
    }

    /// Computes `(single, multiple, text_bottom, hold_after)` for [`Self::line_box_of`].
    fn line_box_tail(
        &self,
        line: &Line,
        rule: LineSpacing,
        (ascent, descent, excess, drop, spaced): (Length, Length, Length, Length, bool),
        (baseline, depth, last, smartart_tall): (Length, Length, bool, bool),
    ) -> (bool, bool, Length, bool) {
        let text = ascent + descent;
        let single = !spaced
            && excess <= Length::ZERO
            && match rule {
                LineSpacing::Auto(n) => n == LINE && self.grid_pitch.is_none(),
                LineSpacing::AtLeast(h) => h <= text + drop && self.grid_pitch.is_none(),
                LineSpacing::Exact(_) => false,
            };
        let multiple = !smartart_tall
            && excess <= Length::ZERO
            && self.grid_pitch.is_none()
            && matches!(rule, LineSpacing::Auto(n) if n != LINE);
        let end_drop = if matches!(rule, LineSpacing::AtLeast(_)) {
            drop
        } else {
            Length::ZERO
        };
        let text_bottom = reaching_below(
            text_end(
                ascent,
                descent,
                rule,
                excess,
                baseline,
                self.object_alone_no_descent(line, rule),
            ) + end_drop,
            baseline,
            (depth, Length::ZERO),
        ) + self.foot_border_room(last);
        let hold_after = !smartart_tall
            && spaced
            && excess <= Length::ZERO
            && (drop <= Length::ZERO || !matches!(rule, LineSpacing::AtLeast(_)));
        (single, multiple, text_bottom, hold_after)
    }

    /// The baseline offset for a SmartArt line whose automatic spacing is below or above single
    /// spacing, and whether the tall-spacing rule applied.
    fn smartart_baseline(
        &self,
        rule: LineSpacing,
        (ascent, descent, height, excess): (Length, Length, Length, Length),
        baseline: Length,
    ) -> (Length, bool) {
        if !self.smartart_text() || excess > Length::ZERO {
            return (baseline, false);
        }
        let spacing = decisions::SmartArtSpacing::of(&self.context.quirks);
        match rule {
            LineSpacing::Auto(n) if n < LINE => {
                (spacing.low_baseline((height, descent), baseline), false)
            }
            LineSpacing::Auto(n) if n > LINE => {
                match spacing.tall_baseline((ascent, descent, height)) {
                    Some(tall) => (tall, true),
                    None => (baseline, false),
                }
            }
            _ => (baseline, false),
        }
    }

    /// Adjusts `(height, baseline)` for a line of `LineSpacing::AtLeast(h)` that carries
    /// below-text room (`drop > 0`, e.g., stacked fraction denominators):
    /// - Without a taller inline object (`excess <= 0`): natural line height is
    ///   `ascent + descent + drop`. When `h <= text + drop`, the line takes `text + drop` with the
    ///   single-line baseline; when `h > text + drop`, the line takes `h` with
    ///   `baseline = h - descent - drop`.
    /// - With a taller inline object (`excess > 0`) alongside non-whitespace text: the line takes
    ///   `max(h, text + excess + descent + drop)` with `baseline = height - descent - drop`.
    fn adjust_at_least_drop(
        &self,
        line: &Line,
        rule: LineSpacing,
        (ascent, descent, rise, excess, drop, spaced): (
            Length,
            Length,
            Length,
            Length,
            Length,
            bool,
        ),
        (height, text_height, baseline): (&mut Length, &mut Length, &mut Length),
    ) {
        let LineSpacing::AtLeast(h) = rule else {
            return;
        };
        if drop <= Length::ZERO {
            return;
        }
        let text = ascent + descent;
        if excess <= Length::ZERO {
            if h <= text + drop {
                let (single_h, single_b) = line_box(
                    &self.device,
                    (ascent, descent, rise),
                    LineSpacing::Auto(LINE),
                    (excess, spaced),
                );
                *text_height = single_h;
                *height = single_h + drop;
                *baseline = single_b;
            } else {
                *text_height = h;
                *height = h;
                *baseline = h - descent - drop;
            }
        } else if holds_glyph_besides_white_space(line) {
            *height = h.max(text + excess + descent + drop);
            *baseline = *height - descent - drop;
        }
    }

    /// Places `(baseline, form, unrounded_offset)` for `line`, using [`Self::object_alone_baseline`]
    /// when a short non-underlined inline object stands alone on its line and
    /// [`placed_baseline_and_form`] otherwise.
    pub(in crate::layout) fn placed_line_baseline(
        &self,
        line: &Line,
        rule: LineSpacing,
        size: &LineBox,
        at: (Length, SpaceBefore),
        rounding: (Ties, BoxTop),
        rests: (i64, Option<i64>),
    ) -> (Length, BaselineForm, Length) {
        if let Some(offset) = self.object_alone_baseline(line, rule, size) {
            let (base, form) = placed_object_baseline(&self.device, at.0, offset, rounding, rests);
            (base, form, offset)
        } else {
            let (base, form) = placed_baseline_and_form(&self.device, at, size, rounding, rests);
            (base, form, size.baseline)
        }
    }

    /// The baseline offset from the line's top for a short non-underlined inline object standing
    /// alone on its line (`excess == 0`, not lowered, no non-whitespace text, struts, rules, or
    /// check boxes, no document line grid, and no inline VML drawing or multiple-spaced VML
    /// picture): the bottom of the single line (`ascent + descent`, or `size.height` for
    /// `auto < 1x` and `atLeast >= single`) without font descent. `None` for any other line.
    pub(in crate::layout) fn object_alone_baseline(
        &self,
        line: &Line,
        rule: LineSpacing,
        size: &LineBox,
    ) -> Option<Length> {
        let text = size.ascent + size.descent;
        if self.grid_pitch.is_some()
            || self.smartart_text()
            || !Self::holds_only_objects_and_space(line)
            || self
                .tallest_real_object_room(line, rule)
                .is_none_or(|room| room <= Length::ZERO)
            || self.object_excess(line, rule, size.ascent, size.descent) > Length::ZERO
            || object_depth(line, rule) > Length::ZERO
            || !self.object_alone_no_descent(line, rule)
        {
            return None;
        }
        match rule {
            LineSpacing::Auto(n) if !self.holds_vml_baseline_object(line, n != LINE) => {
                Some(if n >= LINE { text } else { size.height })
            }
            LineSpacing::AtLeast(h)
                if h >= text && !self.holds_vml_baseline_object(line, false) =>
            {
                Some(size.height)
            }
            _ => None,
        }
    }

    /// How much the tallest inline object on a line is taller than the text's single line.
    pub(super) fn object_excess(
        &self,
        line: &Line,
        rule: LineSpacing,
        ascent: Length,
        descent: Length,
    ) -> Length {
        self.tallest_real_object_room(line, rule)
            .map_or(Length::ZERO, |room| {
                (room - ascent - descent).max(Length::ZERO)
            })
    }
    /// Whether a line's tall inline object stands alone without text or an underline that keeps
    /// the font's descent below the baseline.
    fn object_alone_no_descent(&self, line: &Line, rule: LineSpacing) -> bool {
        let underlined = decisions::underlined_object_room(&self.context.quirks)
            && self.tallest_object_underlined(line, rule);
        !holds_glyph_besides_white_space(line) && !underlined
    }
}

/// How far below the top of a line its text reaches, which must fit above the bottom margin.
/// The extra space that multiple line spacing adds below the text may run into the margin.
/// With automatic spacing, the text part is the single line, wherever the rounding puts the
/// baseline in it. A line of exact height needs its whole height, whatever its font. On a line
/// sized by a tall inline object alone without text or an underline (`object_alone`), the
/// object's bottom at `baseline` ends the line without font descent. Otherwise the text ends a
/// descent below the baseline.
pub(in crate::layout) fn text_end(
    ascent: Length,
    descent: Length,
    rule: LineSpacing,
    excess: Length,
    baseline: Length,
    object_alone: bool,
) -> Length {
    match rule {
        LineSpacing::Auto(_) if excess == Length::ZERO => ascent + descent,
        LineSpacing::Auto(_) if excess > Length::ZERO && object_alone => baseline,
        LineSpacing::AtLeast(h) if excess <= Length::ZERO && h <= ascent + descent => {
            ascent + descent
        }
        LineSpacing::AtLeast(h)
            if excess > Length::ZERO && object_alone && h < ascent + descent + excess =>
        {
            baseline
        }
        LineSpacing::Exact(h) => h,
        _ => baseline + descent,
    }
}

/// The offset of the baseline from the top of a text line with automatic spacing. With single
/// spacing, when the line height rounds up, the baseline sits the rounded descent above the
/// exact bottom of the line. When it rounds down, [`Device::rounded_down_baseline`] places
/// it. With other spacing, and on a line that the paragraph's space after follows (`spaced`), the
/// baseline sits the rounded ascent below the top of the line.
pub(in crate::layout) fn text_baseline(
    device: &Device,
    (ascent, descent): (Length, Length),
    lines: i64,
    spaced: bool,
) -> Length {
    let single = ascent + descent;
    if lines != LINE || spaced {
        device.snap(ascent)
    } else if device.snap(single) > single {
        single - device.snap(descent)
    } else {
        device.rounded_down_baseline((ascent, descent), single, false)
    }
}

/// The paragraph's own space before above a line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) enum SpaceBefore {
    /// The line is not the first line of a paragraph that sets its own space before.
    Absent,
    /// The first line of a paragraph with this own space before above it, more than 0.
    Held(Length),
    /// The first line of a paragraph that sets its own space before, this space as the
    /// paragraph started, which a new page left out, or which went above a drawing or a band
    /// that moved the line down; after a page break in a paragraph without text, the part of it
    /// that is larger than that paragraph's space after.
    Dropped(Length),
}

impl SpaceBefore {
    /// The space above a line of a paragraph: `before` of its own space before, which a new
    /// page or a drawing may have taken, on the first line of a paragraph whose own space
    /// before was `first` as it started, and 0 on its other lines.
    pub(in crate::layout) fn of(first: Length, before: Length) -> Self {
        if before > Length::ZERO {
            Self::Held(before)
        } else if first > Length::ZERO {
            Self::Dropped(first)
        } else {
            Self::Absent
        }
    }

    /// The space that the line's box holds.
    pub(in crate::layout) fn length(self) -> Length {
        match self {
            Self::Held(before) => before,
            Self::Absent | Self::Dropped(_) => Length::ZERO,
        }
    }

    /// Whether the line is the first line of a paragraph that sets its own space before.
    fn below_space(self) -> bool {
        self != Self::Absent
    }
}

/// Which way the page rounds a position of a line that lies exactly halfway between two device
/// units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) enum Ties {
    /// Down the page, as in the body.
    AwayFromTop,
    /// Down the page as in the body, in a table cell of the body whose text top starts its
    /// twips rest anew, except the top of a single line's box, which takes the dot of its place
    /// as one length (`Device::top_dot`): the cursor's twips rest does not decide it there.
    Cell,
    /// Up the page, as in a header, except where the device's quirk `HeaderHalves` gives
    /// another dot (`Device::header_dot`).
    TowardTop,
    /// Down the page as in the body, except a line's exact bottom from which the page rounds
    /// its baseline, which takes the dot that the device's quirk `FooterHalves` gives
    /// (`Device::footer_bottom_dot`): in a footer.
    Footer,
    /// Down the frame of a turned cell's text, whose places turn into places across the page,
    /// with no rule of whole twips: in a frame whose lines lie on the page's dots
    /// (`TurnedAcrossDots::PageDots`), so that a line's place across depends on the cell's side
    /// and not on where its row lies down the page.
    TurnedFrame,
}

/// Where the top of a line's box lies on its page, for the rounding of a top that lies exactly
/// half a dot past a whole dot.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) enum BoxTop {
    /// The body's top on the page: the body's first line on a page, or a line in a table row
    /// at the page's top.
    PageTop,
    /// Any other place, and every place outside the body.
    Lower,
}

/// Rounds a position on the page to the device, with a half to the side that `ties` says.
fn place(device: &Device, at: ExactPlace, ties: Ties) -> Length {
    if let Some(dot) = at.rested_dot(device) {
        return dot;
    }
    match ties {
        Ties::AwayFromTop | Ties::Cell | Ties::Footer | Ties::TurnedFrame => device.snap(at.at),
        // quirk: HeaderHalves::FixedPoint (src/quirks.rs)
        Ties::TowardTop => device.header_dot(at.at),
    }
}

/// Rounds the exact bottom of a line of single spacing, from which the page rounds its
/// baseline, to the device: as [`place`], except that in a footer the device's quirk
/// `FooterHalves` decides a bottom without a height rest that lies exactly half a dot past a
/// whole dot.
fn bottom_place(device: &Device, at: ExactPlace, ties: Ties) -> Length {
    match ties {
        Ties::Footer if at.rest == 0 => device.footer_bottom_dot(at.at),
        Ties::AwayFromTop | Ties::Cell | Ties::TowardTop | Ties::Footer | Ties::TurnedFrame => {
            place(device, at, ties)
        }
    }
}

/// Rounds the top of a line box of single spacing, whose height rounds down, to the device: as
/// [`place`], except that in the body and a footer, outside a turned cell's frame, a top that
/// lies exactly half a dot past a whole dot takes the dot that the device's quirk `TopHalves`
/// gives (`Device::top_dot`).
fn top_place(device: &Device, at: ExactPlace, ties: Ties) -> Length {
    if let Some(dot) = at.rested_dot(device) {
        return dot;
    }
    match ties {
        Ties::AwayFromTop | Ties::Cell | Ties::Footer => device.top_dot(at.at),
        Ties::TowardTop | Ties::TurnedFrame => place(device, at, ties),
    }
}

/// Rounds the top of a line box of multiple spacing, or of a box that holds its paragraph's
/// spaces where the descent goes above the extra spacing ([`boxes_spaces`]), to the device: as
/// [`top_place`] at the body's top on a page, and as [`place`] below it.
fn box_top_place(device: &Device, at: ExactPlace, ties: Ties, box_top: BoxTop) -> Length {
    match box_top {
        // quirk: TopHalves::FixedPoint (src/quirks.rs)
        BoxTop::PageTop => top_place(device, at, ties),
        BoxTop::Lower => place(device, at, ties),
    }
}

/// The dot of a table row's line whose top is at `top`, where the cursor's twips rest is
/// `rest`: the dot that the top of a line box takes there ([`box_top_place`]). A top that lies
/// exactly half a dot past a whole dot takes the dot on the side of its rest; without a rest,
/// at the body's top on a page (`box_top`) the dot that the device's quirk `TopHalves` gives,
/// and below it the nearest dot, a half down the page.
pub(in crate::layout) fn row_line_dot(
    device: &Device,
    top: Length,
    rest: Option<i64>,
    box_top: BoxTop,
) -> Length {
    // quirk: TwipLengthUnit::Nearest4096ths (src/quirks.rs)
    let at = ExactPlace::carried(top, rest.unwrap_or(0));
    box_top_place(device, at, Ties::AwayFromTop, box_top)
}

/// Where the page puts the baseline of a line whose exact top is at `top`, with `space` of
/// its paragraph's own space before above it, outside tables and in table cells alike. The
/// first line's box holds that space when the rules of single spacing place the line. When
/// multiple spacing places it, the top of the box and the space before round each on their
/// own, and the baseline sits the rounded ascent below them; where the descent goes above the
/// extra spacing, the box holds the space too, as part of the ascent and the height that
/// [`descent_above_extra`] rounds, and so does the box of a last line that holds its
/// paragraph's space after ([`LineBox::after`]). The box of a line whose at-least minimum sets its height
/// holds that space as well: when the box's height rounds down, the line's bottom is the box's
/// rounded top plus its rounded height, and the baseline sits the line's rounded part below the
/// baseline above that bottom; otherwise [`exact_baseline`] places it. So does the box of an
/// exact line on a device whose quirk `ExactBaseline` is `BoxForms`: when the box's height
/// rounds down, the baseline sits below the box's rounded top as
/// [`Device::rounded_down_baseline`] says for a single line, with the line's baseline four fifths
/// down; otherwise
/// [`exact_baseline`] places it. A position that lies halfway between two device dots rounds as
/// `ties` says, except the top of a box of multiple spacing, or of one that holds its spaces,
/// at the body's top on a page (`box_top`), which rounds as [`box_top_place`] says. `rest` is the height rest of `top`
/// (the layout's cursor), which gives the dot of a place that lies exactly half a dot past a
/// whole dot when it is not 0 (`ExactPlace`), and `twips` its twips rest, where every length
/// above `top` is whole twips ([`twips_rest`]), which the place adds to that rest. The top of a
/// single line's box lies above the space before that the box holds, and adds the rest at that
/// top. Gives the baseline and the form that placed it.
fn boxed_baseline_and_form(
    device: &Device,
    (top, space): (Length, SpaceBefore),
    size: &LineBox,
    (ties, box_top): (Ties, BoxTop),
    (rest, twips): (i64, Option<i64>),
) -> (Length, BaselineForm) {
    let space = boxed_space(device, space, box_top);
    let before = space.length();
    let boxed = before + size.height;
    // The twips rest of a long sum can reach past a half-EMU, so the top carries it.
    let exact_top = top;
    let top = ExactPlace::carried(exact_top, rest + twips.unwrap_or(0));
    let own = bottom_rest(size, twips);
    let found = own_box_baseline(
        device,
        (exact_top, top, space),
        size,
        ties,
        (rest, twips, own),
    )
    .or_else(|| bottom_room_baseline(device, (top, before), size, ties))
    .or_else(|| low_room_baseline(device, (top, before), size, ties));
    if let Some(found) = found {
        found
    } else if boxes_spaces(device, before, size) {
        // quirk: MultipleBaseline::DescentAboveExtra (src/quirks.rs)
        // quirk: AtLeastSpaceAfter::Held (src/quirks.rs)
        let ascent = held_ascent(size);
        let height = before + size.text_height + size.after;
        let descent = descent_part(device, (before + ascent, size.descent), height);
        // The box's top rounds as a box of multiple spacing does at the body's top on a page.
        let held = ExactPlace::carried(
            exact_top,
            rest + box_twips(device, twips, before).unwrap_or(0),
        );
        let at = box_top_place(device, held - before, ties, box_top)
            + held_ascent_part(device, before, size).max(descent);
        (at, BaselineForm::HeldSpaces)
    } else if size.from_bottom == FromBottom::AtLeast && device.snap(boxed) < boxed {
        let at = place(device, top - before, ties) + device.snap(boxed)
            - device.snap(size.height - size.baseline);
        (at, BaselineForm::AtLeastBox)
    } else if size.from_bottom.exact()
        && let Some(offset) = device.exact_box_baseline(
            before,
            (size.height, size.baseline, exact_below(device, size)),
            (twips_rest(device, before), twips_rest(device, size.height)),
            space.below_space(),
        )
    {
        let at = place(device, top - before, ties) + offset;
        (at, BaselineForm::ExactBox)
    } else if size.from_bottom != FromBottom::No {
        bottom_baseline_and_form(device, top, (size, own), ties)
    } else if size.multiple && before > Length::ZERO {
        let at = box_top_place(device, top - before, ties, box_top)
            + device.snap(before)
            + device.snap(size.baseline);
        (at, BaselineForm::SpaceAndAscent)
    } else if device.snap(size.baseline) == size.baseline {
        // A baseline whole dots below the top rounds with the top, on every line that comes
        // here: of multiple spacing, beside a taller object, or with its space after outside
        // its box.
        let at = box_top_place(device, top, ties, box_top) + size.baseline;
        (at, BaselineForm::WholeDotsBelowTop)
    } else {
        rounded_baseline_and_form(device, top, size, ties)
    }
}

/// The baseline and its form of an exact line whose box holds a bottom border's room
/// (`size.after`) as well as the room `before` above the line, with the box's exact top `before`
/// above `top`: [`Device::centred_room_baseline`] places it below the box's rounded top. `None`
/// for another line.
fn bottom_room_baseline(
    device: &Device,
    (top, before): (ExactPlace, Length),
    size: &LineBox,
    ties: Ties,
) -> Option<(Length, BaselineForm)> {
    if !size.from_bottom.exact() || size.after <= Length::ZERO {
        return None;
    }
    // quirk: BorderSpace::Held (src/quirks.rs)
    let offset = device.centred_room_baseline((before, size.after), (size.height, size.baseline));
    Some((
        place(device, top - before, ties) + offset,
        BaselineForm::ExactBox,
    ))
}

/// The baseline and its form of a line below single spacing whose box holds its paragraph's
/// border rooms, with the box's exact top `before` (with the top border's room) above the line's
/// top `top`. With a bottom room (`size.after`), the baseline lies below the box's rounded top by
/// the larger of the rounded space above the line plus the rounded offset of the baseline, and
/// the rounded box less the rounded bottom room and the rounded part of the line below the
/// baseline. With a top room alone, the box's bottom lies at the higher of its exact bottom
/// rounded and its rounded top plus its rounded height, and the baseline the rounded part of the
/// line below the baseline above it. `None` for another line.
fn low_room_baseline(
    device: &Device,
    (top, before): (ExactPlace, Length),
    size: &LineBox,
    ties: Ties,
) -> Option<(Length, BaselineForm)> {
    if !size.low_multiple() || (size.after <= Length::ZERO && size.top_room <= Length::ZERO) {
        return None;
    }
    // quirk: BorderSpace::Held (src/quirks.rs)
    if size.after <= Length::ZERO {
        let bottom = place(device, top + size.height, ties)
            .min(place(device, top - before, ties) + device.snap(before + size.height));
        let at = bottom - device.snap(size.height - size.baseline);
        return Some((at, BaselineForm::HeldSpaces));
    }
    let ascent = device.snap(before) + device.snap(size.baseline);
    let descent = device.snap(before + size.height + size.after)
        - device.snap(size.after)
        - device.snap(size.height - size.baseline);
    let at = place(device, top - before, ties) + ascent.max(descent);
    Some((at, BaselineForm::HeldSpaces))
}

/// The baseline and its form of a line that takes its own box at the exact place `exact_top`
/// (`top` with the cursor's rest carried) below the space before `space`: a single line's box
/// ([`rested_boxed_baseline`]), or the steps of a line grid whose top rounds as the line's
/// `grid_ties` say, whatever rest the cursor carries. `rest` and `twips` are the cursor's height
/// and twips rests, and `own` the line's own rest below its bottom ([`bottom_rest`]). `None` for
/// another line.
fn own_box_baseline(
    device: &Device,
    (exact_top, top, space): (Length, ExactPlace, SpaceBefore),
    size: &LineBox,
    ties: Ties,
    (rest, twips, own): (i64, Option<i64>, i64),
) -> Option<(Length, BaselineForm)> {
    if size.single {
        let box_size = (size.ascent, size.descent, own);
        let held = ExactPlace::carried(
            exact_top,
            rest + box_twips(device, twips, space.length()).unwrap_or(0),
        );
        let box_top = single_box_top(ties, (exact_top, rest), held);
        return Some(rested_boxed_baseline(
            device,
            (top, box_top, space),
            box_size,
            ties,
        ));
    }
    // quirk: GridSingleLine::PartsRounded (src/quirks.rs)
    size.grid_ties.map(|grid| {
        let at = device.dots(device.count(exact_top, grid));
        (at + size.baseline, BaselineForm::GridSteps)
    })
}

/// The baseline of a line at the exact place `top` that no box form of
/// [`boxed_baseline_and_form`] places: a line below single spacing from the dot of its box
/// that [`Device::low_multiple_baseline`] gives, where it gives one, and otherwise the exact
/// baseline, rounded once. Gives the baseline and the form that placed it.
fn rounded_baseline_and_form(
    device: &Device,
    top: ExactPlace,
    size: &LineBox,
    ties: Ties,
) -> (Length, BaselineForm) {
    if size.low_multiple()
        && let Some(low) = device.low_multiple_baseline(size.height, size.baseline)
    {
        let at = match low {
            LowBaseline::BelowTop(offset) => place(device, top, ties) + offset,
            LowBaseline::AboveBottom(offset) => place(device, top + size.height, ties) - offset,
        };
        (at, BaselineForm::HeightFraction)
    } else {
        (
            place(device, top + size.baseline, ties),
            BaselineForm::Baseline,
        )
    }
}

/// Places the baseline of a short non-underlined inline object standing alone on its line
/// ([`Layout::object_alone_baseline`]) at `offset` below `top`.
pub(in crate::layout) fn placed_object_baseline(
    device: &Device,
    top: Length,
    offset: Length,
    (ties, box_top): (Ties, BoxTop),
    (rest, twips): (i64, Option<i64>),
) -> (Length, BaselineForm) {
    let top = ExactPlace::carried(top, rest + twips.unwrap_or(0));
    if device.snap(offset) == offset {
        (
            box_top_place(device, top, ties, box_top) + offset,
            BaselineForm::WholeDotsBelowTop,
        )
    } else {
        (place(device, top + offset, ties), BaselineForm::Baseline)
    }
}

/// Where the page puts the baseline of a line, as [`boxed_baseline_and_form`] says, except a
/// centered line of multiple spacing whose box carries its face, which [`centered_baseline`]
/// places. Gives the baseline and the form that placed it.
pub(in crate::layout) fn placed_baseline_and_form(
    device: &Device,
    at: (Length, SpaceBefore),
    size: &LineBox,
    rounding: (Ties, BoxTop),
    rests: (i64, Option<i64>),
) -> (Length, BaselineForm) {
    centered_baseline(device, at, size, rounding, rests).map_or_else(
        || boxed_baseline_and_form(device, at, size, rounding, rests),
        |at| (at, BaselineForm::CenteredMiddle),
    )
}

/// The baseline of a centered line of multiple spacing whose box carries its face
/// (`LineBox::centered`, `CenteredMultiple::MiddleRounded`), with the place, the space before
/// and the rounding of [`boxed_baseline_and_form`]: the middle of the face's win line goes
/// where the box of a line that holds its spaces puts the baseline with the line's ascent less
/// the middle in place of the ascent, or, where that is lower, with half the win line in place
/// of the descent, and the baseline lies half the face's pixel line below it. `None` for
/// another line.
fn centered_baseline(
    device: &Device,
    (top, space): (Length, SpaceBefore),
    size: &LineBox,
    (ties, box_top): (Ties, BoxTop),
    (rest, twips): (i64, Option<i64>),
) -> Option<Length> {
    // quirk: CenteredMultiple::MiddleRounded (src/quirks.rs)
    let face = size
        .centered
        .filter(|_| !size.single && size.text_height >= size.ascent + size.descent)?;
    let before = boxed_space(device, space, box_top).length();
    let top = ExactPlace::carried(top, rest + twips.unwrap_or(0));
    let height = before + size.text_height + size.after;
    let from_top = device.ascent_part(before, size.ascent - face.middle);
    let from_bottom = device.snap(height)
        - device.snap(height - (before + size.ascent + size.descent))
        - device.snap(face.half);
    Some(
        box_top_place(device, top - before, ties, box_top)
            + from_top.max(from_bottom)
            + face.pixels,
    )
}

/// The baseline that [`placed_baseline_and_form`] gives, without its form.
pub(in crate::layout) fn placed_baseline(
    device: &Device,
    at: (Length, SpaceBefore),
    size: &LineBox,
    rounding: (Ties, BoxTop),
    rests: (i64, Option<i64>),
) -> Length {
    placed_baseline_and_form(device, at, size, rounding, rests).0
}

/// The space before that the box of a line holds for the rounding of its baseline: at the body's
/// top on its page (`box_top`), under `DroppedSpaceBox::HeldAbove`, the paragraph's own space
/// before that a natural break dropped (`SpaceBefore::Dropped`), above the page's top; else
/// `space`. The line's top stays where it is.
fn boxed_space(device: &Device, space: SpaceBefore, box_top: BoxTop) -> SpaceBefore {
    match (space, box_top) {
        (SpaceBefore::Dropped(dropped), BoxTop::PageTop) => device
            .held_dropped_space(dropped)
            .map_or(space, SpaceBefore::Held),
        _ => space,
    }
}

/// The twips rest of the top of a line's box that holds `before` of its paragraph's space
/// before, from the twips rest `twips` at the line's top: the box's top lies above that space,
/// so its rest is the line's less the space's. `None` where the line's top has no twips rest or
/// the space is no length of whole twips.
fn box_twips(device: &Device, twips: Option<i64>, before: Length) -> Option<i64> {
    // quirk: TwipLengthUnit::Nearest4096ths (src/quirks.rs)
    twips
        .zip(twips_rest(device, before))
        .map(|(at, space)| at - space)
}

/// The ascent of a line in a box that holds spaces: on a line whose at-least minimum sets its
/// height, whose extra lies above its text, the offset of its exact baseline below its top;
/// otherwise its text's ascent, whose extra lies below the text.
fn held_ascent(size: &LineBox) -> Length {
    if size.from_bottom == FromBottom::AtLeast {
        size.baseline
    } else {
        size.ascent
    }
}

/// The ascent part of a line whose box holds spaces: its space before `before` and the offset
/// of its baseline below its top, rounded as [`Device::ascent_part`] rounds them. On a line whose
/// at-least minimum sets its height, the extra space above the text takes the place of the
/// offset there, and the text's ascent rounds on its own below it. The room of a top border
/// that the space holds ([`LineBox::top_room`]) is the rounded room and line less the rounded
/// line, as if the line's bottom rounded first.
fn held_ascent_part(device: &Device, before: Length, size: &LineBox) -> Length {
    if size.from_bottom == FromBottom::AtLeast {
        // quirk: AtLeastSpaceAfter::Held (src/quirks.rs)
        let room = size.top_room.min(before);
        device.ascent_part(before - room, size.baseline - size.ascent)
            + device.snap(room + size.height)
            - device.snap(size.height)
            + device.snap(size.ascent)
    } else {
        device.ascent_part(before, size.ascent)
    }
}

/// Whether the box of a line holds its paragraph's space before, `before` on its first line
/// of multiple spacing, or the space after that it holds ([`LineBox::after`]), where the
/// descent goes above the extra spacing; a line whose at-least minimum sets its height holds
/// spaces only with a space after, which [`Device::held_after`] gives it under its own quirk.
fn boxes_spaces(device: &Device, before: Length, size: &LineBox) -> bool {
    if size.from_bottom == FromBottom::AtLeast {
        // quirk: AtLeastSpaceAfter::Held (src/quirks.rs)
        return size.after > Length::ZERO;
    }
    (size.multiple && before > Length::ZERO || size.after > Length::ZERO)
        && device
            .descent_above_extra(|| size.text_height >= size.ascent + size.descent)
            .unwrap_or(false)
}

/// Where the page puts the baseline of a line of exact height, or of one whose at-least
/// minimum sets its height, whose exact top is at `top`, with its `height`, the rounded part of
/// the line below its baseline (`below`, [`exact_below`]) and its height rest (`rest`): the
/// page rounds the line's bottom, with the line's own height rest, to the device, and the
/// baseline sits `below` above it.
fn exact_baseline(
    device: &Device,
    top: ExactPlace,
    (height, below, rest): (Length, Length, i64),
    ties: Ties,
) -> Length {
    let bottom = ExactPlace::carried(top.at + height, top.rest + rest);
    place(device, bottom, ties) - below
}

/// The baseline of a line at the exact place `top` that the page places up from its bottom, with
/// its height rest `own`, and the form that placed it: [`spaced_exact_baseline`] for a line of
/// [`FromBottom::ExactSpaced`], and [`exact_baseline`] otherwise.
fn bottom_baseline_and_form(
    device: &Device,
    top: ExactPlace,
    (size, own): (&LineBox, i64),
    ties: Ties,
) -> (Length, BaselineForm) {
    let below = exact_below(device, size);
    if size.from_bottom == FromBottom::ExactSpaced {
        // quirk: ExactSpacedBottom::PartsRounded (src/quirks.rs)
        let at = spaced_exact_baseline(device, top, (size.height, below), ties);
        (at, BaselineForm::SpacedBottom)
    } else {
        let at = exact_baseline(device, top, (size.height, below, own), ties);
        (at, BaselineForm::Bottom)
    }
}

/// Where the page puts the baseline of a line of exact height that ends its paragraph, with the
/// space after following it, whose exact top is at `top`, with its `height` and the rounded
/// part of the line below its baseline (`below`, [`exact_below`]): the page rounds the line's
/// top and its height each on their own, and the baseline sits `below` above their sum.
fn spaced_exact_baseline(
    device: &Device,
    top: ExactPlace,
    (height, below): (Length, Length),
    ties: Ties,
) -> Length {
    place(device, top, ties) + device.snap(height) - below
}

/// The rounded part below the baseline of a line that [`exact_baseline`] places, as
/// [`Device::exact_below`] rounds it, with the rest of [`entered_below_rest`] for a line of exact
/// spacing of whole twips.
fn exact_below(device: &Device, size: &LineBox) -> Length {
    let below = size.height - size.baseline;
    let entered = size
        .twips
        .filter(|_| size.from_bottom.exact())
        .map(|rest| entered_below_rest(size.height, below, rest));
    device.exact_below(below, entered)
}

/// The rest of the part `below` the baseline of a line of exact spacing of the height `height`,
/// whose twips rest is `rest` ([`twips_rest`]): how far that part's share of the entered height,
/// in whole parts of `params::HEIGHT_PARTS_PER_POINT` of a point, rounded down, lies past
/// `below`, in 1/[`REST_PARTS`] of a half-EMU.
fn entered_below_rest(height: Length, below: Length, rest: i64) -> i64 {
    let (part, whole) = params::EXACT_BASELINE;
    let entered = height.units() * REST_PARTS + rest;
    let parts = (entered * (whole - part)).div_euclid(whole * REST_PER_PART);
    parts * REST_PER_PART - below.units() * REST_PARTS
}

/// The place from which the box of a single line whose exact top is `exact_top`, with the
/// height rest `rest`, rounds its top: in a table cell of the body whose text top starts its
/// twips rest anew that place with its height rest only, and elsewhere `held`, which holds the
/// twips rest at the box's top too.
fn single_box_top(ties: Ties, (exact_top, rest): (Length, i64), held: ExactPlace) -> ExactPlace {
    match ties {
        // quirk: TwipLengthUnit::Nearest4096ths (src/quirks.rs)
        Ties::Cell => ExactPlace::carried(exact_top, rest),
        Ties::AwayFromTop | Ties::TowardTop | Ties::Footer | Ties::TurnedFrame => held,
    }
}

/// [`rested_boxed_baseline`] for a top without a height rest, as the tests place lines.
#[cfg(test)]
pub(in crate::layout) fn boxed_baseline(
    device: &Device,
    (top, space): (Length, SpaceBefore),
    (ascent, descent): (Length, Length),
    ties: Ties,
) -> Length {
    let top = ExactPlace { at: top, rest: 0 };
    rested_boxed_baseline(device, (top, top, space), (ascent, descent, 0), ties).0
}

/// Where the page puts the baseline of a line that the rules of single spacing place, whose
/// exact top is at `top`, with `space` of its paragraph's own space before above it on the
/// first line. The line's box holds that space: when the box's height rounds up, the baseline
/// sits the rounded descent above the exact bottom. When it rounds down, the baseline sits
/// below the box's rounded top as [`Device::rounded_down_baseline`] says for a first line of a
/// paragraph that sets space before, even where the box holds none of it, and that top rounds
/// as [`top_place`] says. Without space before, these are the rules of [`text_baseline`]. A
/// height rest of the top gives the dot of a place on half a dot ([`ExactPlace`]), and the
/// exact bottom also holds `rest`, the line's own height rest ([`LineBox::rest`]). The box's
/// rounded top takes the rests of `box_top`, the same place as `top` with the rests that
/// decide its half. Gives the baseline and the form that placed it.
fn rested_boxed_baseline(
    device: &Device,
    (top, box_top, space): (ExactPlace, ExactPlace, SpaceBefore),
    (ascent, descent, rest): (Length, Length, i64),
    ties: Ties,
) -> (Length, BaselineForm) {
    let before = space.length();
    let single = ascent + descent;
    let height = before + single;
    if device.snap(height) > height {
        let bottom = ExactPlace::carried(top.at + single, top.rest + rest);
        // The rounded descent is whole dots, so the bottom rounds first.
        let at = bottom_place(device, bottom, ties) - device.snap(descent);
        (at, BaselineForm::SingleBottom)
    } else {
        let at = top_place(device, box_top - before, ties)
            + device.rounded_down_baseline((before + ascent, descent), height, space.below_space());
        (at, BaselineForm::SingleTop)
    }
}

/// The height of a line of the multiple spacing `n` that holds text beside an object taller
/// than the text's single line, with the baseline `baseline` below its top: down to the
/// baseline, the descent of the text, and the part of the spacing above single spacing.
pub(in crate::layout) fn text_below_object(
    n: i64,
    (ascent, descent): (Length, Length),
    baseline: Length,
) -> Length {
    let single = ascent + descent;
    baseline + descent + times_lines(single, n) - single
}

/// The offset of the baseline from the top of a text line with multiple spacing `n`, below a
/// list label that rises `rise` above the text. Below single spacing, the spacing scales the
/// text's ascent as it scales its line, so that the line loses height above and below its text
/// in the ratio of its ascent and descent, and the page rounds the baseline together with the
/// line's top. Above single spacing, the device's variant of the quirk `MultipleBaseline`
/// places it. At single spacing, and above it with `MultipleBaseline::RoundedAscent`,
/// [`text_baseline`] places it.
fn multiple_baseline(
    device: &Device,
    (ascent, descent): (Length, Length),
    (rise, n): (Length, i64),
    spaced: bool,
) -> Length {
    if n < LINE {
        return rise + times_lines(ascent - rise, n);
    }
    let above_extra = || {
        let height = times_lines(ascent + descent - rise, n) + rise;
        descent_above_extra(device, (ascent, descent), height)
    };
    (n > LINE)
        .then(|| device.descent_above_extra(above_extra))
        .flatten()
        .unwrap_or_else(|| text_baseline(device, (ascent, descent), n, spaced))
}

/// The offset of the baseline from the top of a box of `height` above single spacing, whose
/// text has `ascent` and `descent`, when the descent goes above the extra spacing: the rounded
/// height less the rounded part above single spacing, which goes below the text, less the
/// rounded descent, but no less than the rounded ascent. On the first line of a paragraph with
/// space before, the box holds the space, which `ascent` and `height` then include.
fn descent_above_extra(
    device: &Device,
    (ascent, descent): (Length, Length),
    height: Length,
) -> Length {
    device
        .snap(ascent)
        .max(descent_part(device, (ascent, descent), height))
}

/// The descent part of [`descent_above_extra`]: the line's rounded height less the rounded part
/// of it below its single line, less the rounded descent.
fn descent_part(device: &Device, (ascent, descent): (Length, Length), height: Length) -> Length {
    device.snap(height) - device.snap(height - (ascent + descent)) - device.snap(descent)
}

/// The height of a line and the offset of its baseline from the top of the line, from the
/// line's ascent and descent and the rise of a list label above the text's ascent, with the
/// shift room of raised and lowered runs that comes once ([`Layout::room_once`]). `excess` is
/// how much an inline object is taller than the single line of the text, and `spaced` tells
/// whether the paragraph's space after follows the line. Multiple line spacing scales neither
/// the rise nor the excess.
pub(in crate::layout) fn line_box(
    device: &Device,
    (ascent, descent, rise): (Length, Length, Length),
    rule: LineSpacing,
    (excess, spaced): (Length, bool),
) -> (Length, Length) {
    let single = ascent + descent;
    match rule {
        // Multiple spacing scales the text's single line, and the part of a list label that
        // rises above the text comes on top unscaled.
        LineSpacing::Auto(n) if rise > Length::ZERO && excess <= Length::ZERO => {
            let text = ascent - rise;
            (
                times_lines(text + descent, n) + rise,
                multiple_baseline(device, (ascent, descent), (rise, n), spaced),
            )
        }
        // A taller object stands on the baseline with its top at the line top.
        LineSpacing::Auto(n) if excess > Length::ZERO => {
            (times_lines(single, n) + excess, ascent + excess + descent)
        }
        LineSpacing::Auto(n) => (
            times_lines(single, n),
            multiple_baseline(device, (ascent, descent), (Length::ZERO, n), spaced),
        ),
        // An exact height puts the baseline at four fifths of the line, whatever the font.
        LineSpacing::Exact(h) => {
            let (part, whole) = params::EXACT_BASELINE;
            (h, (h * part).div_round(whole))
        }
        // A minimum below the single line leaves a single line.
        LineSpacing::AtLeast(h) if excess <= Length::ZERO && h <= single => line_box(
            device,
            (ascent, descent, rise),
            LineSpacing::Auto(LINE),
            (excess, spaced),
        ),
        // A taller object than the minimum also has its top at the line top.
        LineSpacing::AtLeast(h) if excess > Length::ZERO && h < single + excess => {
            (single + excess, single + excess)
        }
        LineSpacing::AtLeast(h) => {
            let height = h.max(single + excess);
            (height, height - descent)
        }
    }
}

/// The room that the parts of fractions need below the descent of a line's text, `drop`, which
/// comes below a line of automatic spacing once, unscaled by multiple spacing, unless a taller
/// object sizes the line.
pub(in crate::layout) fn below_text(rule: LineSpacing, excess: Length, drop: Length) -> Length {
    if matches!(rule, LineSpacing::Auto(_)) && excess <= Length::ZERO {
        drop
    } else {
        Length::ZERO
    }
}

/// How far the objects of lowered runs on a line of spacing `rule` reach below its baseline:
/// the largest lowering among them, or nothing, also on a line of exact height, which keeps
/// its height.
fn object_depth(line: &Line, rule: LineSpacing) -> Length {
    if matches!(rule, LineSpacing::Exact(_)) {
        return Length::ZERO;
    }
    line.placed
        .iter()
        .filter_map(|p| match p.piece {
            Piece::Object { raised, .. } => Some(-raised),
            _ => None,
        })
        .fold(Length::ZERO, Length::max)
}

/// A length down from a line's top, `length`, that reaches at least `depth` and then `below`
/// below the baseline at `baseline` where an object of a lowered run reaches that deep, and
/// else stays.
fn reaching_below(length: Length, baseline: Length, (depth, below): (Length, Length)) -> Length {
    if depth > Length::ZERO {
        length.max(baseline + depth + below)
    } else {
        length
    }
}

/// The part of a line of spacing `rule` above the single line `single` of its text: the
/// single line times the multiple of automatic spacing above single spacing, less the single
/// line, and nothing for other spacing.
fn above_single(rule: LineSpacing, single: Length) -> Length {
    match rule {
        LineSpacing::Auto(n) if n > LINE => times_lines(single, n) - single,
        _ => Length::ZERO,
    }
}

/// Whether a piece is a space, also one that an equation holds, or a tab, which sizes its line
/// only when the line holds nothing else. Continuation glyphs of math assemblies carry `' '` for
/// text extraction but draw ink and are not blank.
/// The face that sizes a line holding only spaces and tabs: the manual line break's face when the
/// line ends in `<w:br/>`, or the paragraph mark's face on the paragraph's last line.
fn blank_line_end_face(end: LineEnd, mark: Option<FaceIndex>, last: bool) -> Option<FaceIndex> {
    match end {
        LineEnd::Break(face) => face,
        _ if last => mark,
        _ => None,
    }
}

pub(super) fn is_blank(placed: &Placed) -> bool {
    matches!(placed.piece, Piece::Glyph(g) if g.ch == ' ' && g.space != crate::text::SpaceKind::Assembly)
        || matches!(placed.piece, Piece::Tab(_) | Piece::PositionTab(..))
}

/// Whether a line holds a glyph whose character is not white space (`char::is_whitespace`,
/// Unicode's `White_Space`): a line of only white space, such as spaces, no-break spaces
/// (U+00A0), ideographic spaces (U+3000) or em spaces (U+2003), holds none. The line's height
/// asks it, also for an inline VML shape on the line (`shape_drop`, `anchor_line`).
///
/// It differs from `paragraph::holds_glyph_besides_ascii_space`, which the free pieces beside
/// a drawing ask, on a line of only white space with a space other than U+0020, such as a
/// no-break, ideographic or em space.
pub(in crate::layout) fn holds_glyph_besides_white_space(line: &Line) -> bool {
    line.placed
        .iter()
        .any(|p| matches!(p.piece, Piece::Glyph(g) if !g.ch.is_whitespace()))
}

#[cfg(test)]
mod tests;