parley 0.14.0

Parley provides an API for implementing rich text layout.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
// Copyright 2021 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Greedy line breaking.

use alloc::vec::Vec;

#[cfg(feature = "libm")]
#[allow(unused_imports)]
use core_maths::CoreFloat;
use parlance::BidiLevel;

use crate::inline_box::{LayoutInlineBox, inline_object_box_index};
use crate::layout::Style;
use crate::layout::data::{AlignedSubtreeOffset, run_box_metrics};
use crate::layout::spacing::{EffectiveSpacing, Justification, Spacing, is_word_separator};
use crate::layout::style_metrics::{BoxMetrics, StyleMetrics, inline_box_placement};
use crate::layout::whitespace::{atom_hanging_advance, whitespace_hangs};
use crate::layout::{BreakReason, Layout, LayoutData, LineData, LineItemData, LineMetrics, Run};
use crate::style::Brush;
use crate::{BaselineShift, OverflowWrap, TextWrapMode, VerticalAlign, WhiteSpaceCollapse};

use core::range::Range;
use parley_engine::shape::{
    Character, PendingLine, ReshapedTextMark, Reshaper, ShapedCluster, Whitespace,
};
use parley_engine::{ShapedSlice, ShapedText};
use smallvec::SmallVec;

#[derive(Default)]
struct LineLayout {
    lines: Vec<LineData>,
    line_items: Vec<LineItemData>,
    aligned_subtree_offsets: Vec<AlignedSubtreeOffset>,
}

impl LineLayout {
    fn swap<B: Brush>(&mut self, layout: &mut LayoutData<B>) {
        core::mem::swap(&mut self.lines, &mut layout.lines);
        core::mem::swap(&mut self.line_items, &mut layout.line_items);
        core::mem::swap(
            &mut self.aligned_subtree_offsets,
            &mut layout.aligned_subtree_offsets,
        );
    }

    /// Drops the lines from `len` onwards, along with their aligned subtree offsets.
    fn truncate(&mut self, len: usize) {
        self.lines.truncate(len);
        let offsets = self
            .lines
            .last()
            .map_or(0, |line| line.aligned_subtree_offsets.end as usize);
        self.aligned_subtree_offsets.truncate(offsets);
    }
}

#[derive(Clone, Default)]
struct LineState {
    x: f32,
    /// Whether we're walking the line's reshaped start.
    ///
    /// A line starting where it was unsafe to break starts with reshaped clusters (see
    /// [`Reshaper::measure_start`]). We walk those first, and then continue walking the source
    /// shaped clusters after them.
    ///
    /// While this is set, [`BreakerState::cluster_idx`] and `clusters.end` index the reshaped
    /// start's shaped clusters.
    in_reshaped_start: bool,
    items: Range<usize>,
    /// The line's characters, as a range into [`ShapedText::characters`].
    ///
    /// Line edges can be at any character boundary, including inside source shaped clusters. As the
    /// line gets reshaped if necessary, the committed line's (re)shaped clusters start and end at
    /// its edges.
    chars: Range<u32>,
    /// The source shaped clusters whose first character is on this line, as a range into
    /// [`ShapedText::shaped_clusters`]. These make up the line's
    /// [source advance](Reshaper#advances).
    clusters: Range<u32>,
    box_metrics: LineBoxMetrics,
    /// This is set to true if we encounter something on the line (either a glyph or an inline box)
    /// that is taller than the `line_max_height`. When in this state `break_next` should yield control
    /// flow to the caller to handle the constraint violation.
    ///
    /// This never happens when calling `break_all_lines` as it never sets `line_max_height`, and it defaults to `f32::MAX`.
    max_height_exceeded: bool,

    /// We lag the text-wrap-mode by one cluster due to line-breaking boundaries only
    /// being triggered on the cluster after the linebreak.
    text_wrap_mode: TextWrapMode,

    /// The number of word separators appended to the line so far.
    ///
    /// These are the line's justification opportunities, before subtracting those that end up in
    /// the line's hanging whitespace.
    num_word_separators: u32,
}

impl LineState {
    /// Reset the per-line running state in preparation for building a new line.
    fn reset(&mut self) {
        self.x = 0.0;
        self.in_reshaped_start = false;
        self.box_metrics.reset();
        self.num_word_separators = 0;
    }
}

/// The metrics of a line box.
///
/// Note a line box is distinct from an *inline* box. A line box is a single line within the layout,
/// and can hold multiple text runs and inline boxes.
///
/// Following CSS 2.2 § 10.8 (line height calculations in "Visual formatting model details"), line
/// boxes are sized to fit the line's inline content. Span boxes and inline boxes with a
/// parent-relative `vertical-align` are first aligned to each other relative to the baseline of
/// their parent span; the boxes aligned to each other in this way form an
/// [independent aligned subtree], rooted at the root span box or at a box with
/// `vertical-align: top | bottom`. Each subtree's extents are tracked relative to its own
/// baseline: the root aligned subtree's in [`Self::root`], those rooted at a `top`/`bottom` span
/// in [`SubtreeHistory`]. The subtrees are only positioned against each other once the line is
/// complete (see `BreakLines::finish_line`).
/// See <https://www.w3.org/TR/CSS22/visudet.html#line-height>.
///
/// [independent aligned subtree]: crate::layout::style_metrics#aligned-subtrees
#[derive(Clone, Copy, Debug)]
struct LineBoxMetrics {
    /// Extents of the root aligned subtree.
    root: SubtreeExtents,
    /// Height of the tallest aligned subtree rooted at a `top`/`bottom` span (see
    /// [`SubtreeHistory`]).
    non_root_height: f32,
    /// Height of the tallest `vertical-align: top` inline box, which is positioned against the
    /// line box rather than a baseline.
    line_relative_top_height: f32,
    /// Height of the tallest `vertical-align: bottom` inline box.
    line_relative_bottom_height: f32,
    /// The run and style of the last text atom added, whose boxes are already on the line.
    last_text: (usize, u16),
}

/// Extents of one [independent aligned subtree] on the current line, measured from the subtree's
/// own baseline.
///
/// [independent aligned subtree]: crate::layout::style_metrics#aligned-subtrees
#[derive(Clone, Copy, Debug, PartialEq)]
struct SubtreeExtents {
    /// Style index of the subtree root: `0` for the root span box, otherwise a style with
    /// `vertical-align: top | bottom`.
    root: u16,
    /// The line-height expanded extents.
    ///
    /// The extents are in block flow direction; i.e., for horizontal text, these are vertical, and
    /// for vertical text, these are horizontal.
    line_box: Extents,
    /// The content extents.
    ///
    /// This covers, roughly, the glyphs and inline boxes. This does not take into account
    /// typographic leading, but only the typographic ascent and descent. In case of negative
    /// leading, this can be larger than [`Self::line_box`].
    ///
    /// Like [`Self::line_box`], these are in block flow direction.
    content_box: Extents,
}

#[derive(Clone, Copy, Debug, PartialEq)]
struct Extents {
    /// The space over the baseline.
    over: f32,
    /// The space under the baseline.
    under: f32,
}

impl Default for Extents {
    fn default() -> Self {
        // Content with small line heights and/or with inline boxes sitting entirely above or
        // below the baseline can cause the baseline to fall outside the line box; i.e., extents
        // can be negative. Hence, we initialize the space over and under the baseline to negative
        // infinity. Lines with no contributing content resolve to zero via [`Self::or_zero`],
        // keeping the sentinel internal.
        Self {
            over: f32::NEG_INFINITY,
            under: f32::NEG_INFINITY,
        }
    }
}

impl Extents {
    /// Resolve unset (default) extents to zero.
    fn or_zero(self) -> Self {
        if self.over == f32::NEG_INFINITY && self.under == f32::NEG_INFINITY {
            Self {
                over: 0.,
                under: 0.,
            }
        } else {
            self
        }
    }

    /// Grow to include a box extending `over` above and `under` below a baseline that is itself
    /// `baseline_offset` above the extents' baseline.
    #[inline(always)]
    fn add(&mut self, baseline_offset: f32, over: f32, under: f32) {
        self.over = self.over.max(baseline_offset + over);
        self.under = self.under.max(under - baseline_offset);
    }

    fn height(self) -> f32 {
        let this = self.or_zero();
        this.over + this.under
    }
}

impl SubtreeExtents {
    fn new(root: u16) -> Self {
        Self {
            root,
            line_box: Extents::default(),
            content_box: Extents::default(),
        }
    }

    /// Grow to include a box whose baseline is `baseline_offset` above the subtree's baseline.
    #[inline(always)]
    fn add(&mut self, baseline_offset: f32, metrics: BoxMetrics) {
        self.line_box
            .add(baseline_offset, metrics.over, metrics.under);
        self.content_box
            .add(baseline_offset, metrics.ascent, metrics.descent);
    }
}

/// The extents of every [independent aligned subtree] on the current line other than the root
/// one (which is in [`LineBoxMetrics::root`]), i.e. those rooted at a span with
/// `vertical-align: top | bottom`. Empty for lines without such spans.
///
/// Reverting to a saved line-breaking opportunity has to restore these extents to what they were
/// at that opportunity. So that saving an opportunity doesn't have to copy them, this is a
/// history: [saving](Self::save) freezes the entries pushed so far, and growing a subtree whose
/// entry is frozen pushes its new extents instead of overwriting the old ones. Hence:
///
/// - the current extents of a subtree are the *last* entry with its root, and
/// - [restoring](Self::restore) a save drops every entry pushed since, leaving the frozen
///   entries as they were at that save.
///
/// [independent aligned subtree]: crate::layout::style_metrics#aligned-subtrees
#[derive(Default)]
struct SubtreeHistory {
    entries: Vec<SubtreeExtents>,
    /// The first `frozen_count` entries may be needed by a save, so are never modified.
    frozen_count: usize,
}

impl Clone for SubtreeHistory {
    fn clone(&self) -> Self {
        Self {
            entries: self.entries.clone(),
            frozen_count: self.frozen_count,
        }
    }

    fn clone_from(&mut self, source: &Self) {
        self.entries.clone_from(&source.entries);
        self.frozen_count = source.frozen_count;
    }
}

impl SubtreeHistory {
    /// The current extents of every subtree with content on the line, in no particular order.
    fn current(&self) -> SmallVec<[SubtreeExtents; 4]> {
        let mut current = SmallVec::<[SubtreeExtents; 4]>::new();
        for entry in self.entries.iter().rev() {
            if current.iter().rev().all(|s| s.root != entry.root) {
                current.push(*entry);
            }
        }
        current
    }

    /// Grow the subtree rooted at `root` to include a box whose baseline is `baseline_offset`
    /// above the subtree's baseline. Returns the subtree's new extents.
    fn grow(&mut self, root: u16, baseline_offset: f32, metrics: BoxMetrics) -> SubtreeExtents {
        let index = self.entries.iter().rposition(|s| s.root == root);
        let old = index.map(|i| self.entries[i]);
        let mut new = old.unwrap_or(SubtreeExtents::new(root));
        new.add(baseline_offset, metrics);
        if old != Some(new) {
            match index {
                Some(i) if i >= self.frozen_count => self.entries[i] = new,
                _ => self.entries.push(new),
            }
        }
        new
    }

    /// Save the current extents of every subtree, returning the length of the history to pass
    /// to [`Self::restore`].
    fn save(&mut self) -> usize {
        self.frozen_count = self.entries.len();
        self.frozen_count
    }

    /// Restore the extents of every subtree to what they were at the save that returned `len`.
    /// Earlier saves can still be restored afterwards; later ones can't.
    fn restore(&mut self, len: usize) {
        self.entries.truncate(len);
        self.frozen_count = len;
    }

    fn clear(&mut self) {
        self.entries.clear();
        self.frozen_count = 0;
    }
}

impl Default for LineBoxMetrics {
    /// An empty line containing only the root aligned subtree, without a strut.
    fn default() -> Self {
        Self {
            root: SubtreeExtents::new(0),
            non_root_height: 0.,
            line_relative_top_height: 0.,
            line_relative_bottom_height: 0.,
            last_text: (usize::MAX, 0),
        }
    }
}

impl LineBoxMetrics {
    /// Reset to an empty line.
    fn reset(&mut self) {
        *self = Self::default();
    }

    /// Add a box whose baseline is `baseline_offset` above the baseline of the aligned subtree
    /// rooted at `aligned_subtree_root`.
    #[inline]
    fn add_box(
        &mut self,
        aligned_subtree_root: u16,
        baseline_offset: f32,
        metrics: BoxMetrics,
        subtrees: &mut SubtreeHistory,
    ) {
        if aligned_subtree_root == 0 {
            self.root.add(baseline_offset, metrics);
        } else {
            let subtree = subtrees.grow(aligned_subtree_root, baseline_offset, metrics);
            self.non_root_height = self.non_root_height.max(subtree.line_box.height());
        }
    }

    /// The line height seen so far.
    #[inline]
    fn line_height(&self) -> f32 {
        self.root
            .line_box
            .height()
            .max(self.non_root_height)
            .max(self.line_relative_top_height)
            .max(self.line_relative_bottom_height)
    }

    /// Add the span box generated by `style_index`, and those of any of its ancestors that are
    /// not yet on the line.
    fn add_style(
        &mut self,
        style_index: u16,
        style_metrics: &[StyleMetrics],
        contributed: &mut Vec<u16>,
        subtrees: &mut SubtreeHistory,
    ) {
        let mut index = style_index;
        while !contributed.contains(&index) {
            contributed.push(index);
            let Some(metrics) = style_metrics.get(usize::from(index)) else {
                return;
            };
            let span_box = BoxMetrics {
                ascent: metrics.ascent,
                descent: metrics.descent,
                over: metrics.over,
                under: metrics.under,
            };
            self.add_box(
                metrics.aligned_subtree_root,
                metrics.baseline_offset,
                span_box,
                subtrees,
            );
            if index == 0 {
                return;
            }
            index = metrics.parent;
        }
    }

    /// Add the glyphs of a text atom of `style_index` in text run `run_idx`. The atom's characters
    /// are `characters`, the first of which has style `style_index`.
    ///
    /// This adds the span boxes of the atom's styles together with its ancestors. When the first
    /// style's line height is [`LineHeight::MetricsRelative`] (which corresponds to CSS
    /// `line-height: normal`), it also adds the run's box, which matters when the run was shaped
    /// with a fallback font whose metrics differ from the style's first available font, the font
    /// the span box is built from. See [`run_box_metrics`]. If the atom is an inline object, it adds
    /// the inline object's box too.
    ///
    /// [`LineHeight::MetricsRelative`]: crate::LineHeight::MetricsRelative
    #[inline]
    fn add_text<B: Brush>(
        &mut self,
        run_idx: usize,
        style_index: u16,
        characters: &[Character],
        data: &LayoutData<B>,
        contributed: &mut Vec<u16>,
        subtrees: &mut SubtreeHistory,
    ) {
        // Consecutive atoms almost always come from the same run and style, whose boxes are then
        // already on the line, so we can exit early. In case the run has atoms with mixed styles,
        // new boxes may still be added.
        if self.last_text == (run_idx, style_index) && !data.runs[run_idx].has_mixed_style_atoms {
            return;
        }
        self.add_text_boxes(
            run_idx,
            style_index,
            characters,
            data,
            contributed,
            subtrees,
        );
    }

    /// The part of [`Self::add_text`] for atoms whose boxes may not be on the line yet.
    ///
    /// Note we mark this `inline(never)`, to keep the common case fast.
    #[inline(never)]
    fn add_text_boxes<B: Brush>(
        &mut self,
        run_idx: usize,
        style_index: u16,
        characters: &[Character],
        data: &LayoutData<B>,
        contributed: &mut Vec<u16>,
        subtrees: &mut SubtreeHistory,
    ) {
        self.last_text = (run_idx, style_index);
        if contributed.last() != Some(&style_index) {
            self.add_style(style_index, &data.style_metrics, contributed, subtrees);
        }
        if data.runs[run_idx].has_mixed_style_atoms {
            // Add the spans of all the atom's other styles.
            for character in characters.iter().skip(1) {
                if character.style_index != style_index {
                    self.add_style(
                        character.style_index,
                        &data.style_metrics,
                        contributed,
                        subtrees,
                    );
                }
            }
        }
        let style = usize::from(style_index);
        let shaped_run = &data.shaped_text.runs()[run_idx];
        if let Some(run_box) = data.runs[run_idx]
            .run_box
            .or_else(|| run_box_metrics(&data.styles[style], shaped_run, data.quantize))
        {
            let (baseline_offset, aligned_subtree_root) = data
                .style_metrics
                .get(style)
                .map_or((0., 0), |m| (m.baseline_offset, m.aligned_subtree_root));
            self.add_box(aligned_subtree_root, baseline_offset, run_box, subtrees);
        }
        if let Some(first) = characters.first()
            && first.flags.is_inline_object()
        {
            let index = inline_object_box_index(&data.inline_boxes, first.text_byte_start as usize);
            self.add_inline_object(&data.inline_boxes[index], data, subtrees);
        }
    }

    /// Add the box of an inline object, aligned relative to the span box of the style containing
    /// it.
    fn add_inline_object<B: Brush>(
        &mut self,
        layout_box: &LayoutInlineBox,
        data: &LayoutData<B>,
        subtrees: &mut SubtreeHistory,
    ) {
        let inline_box = &layout_box.inline_box;
        if inline_box.vertical_align.is_line_relative() {
            self.add_line_relative_inline_box(
                inline_box.vertical_align,
                inline_box.height,
                data.quantize,
            );
        } else {
            let placement = inline_box_placement(
                inline_box,
                layout_box.parent_style_index,
                &data.style_metrics,
                data.quantize,
            );
            self.add_inline_box(
                placement.aligned_subtree_root,
                placement.baseline_offset,
                placement.ascent,
                placement.descent,
                subtrees,
            );
        }
    }

    /// Add an inline box extending `ascent` above and `descent` below a baseline that is
    /// `baseline_offset` above the baseline of the aligned subtree rooted at
    /// `aligned_subtree_root`.
    fn add_inline_box(
        &mut self,
        aligned_subtree_root: u16,
        baseline_offset: f32,
        ascent: f32,
        descent: f32,
        subtrees: &mut SubtreeHistory,
    ) {
        // Inline box extents are exact box sizes supplied by the caller, not font metrics;
        // rounding them would change the space the box reserves relative to its height.
        let inline_box = BoxMetrics {
            ascent,
            descent,
            over: ascent,
            under: descent,
        };
        self.add_box(aligned_subtree_root, baseline_offset, inline_box, subtrees);
    }

    /// Add an inline box with `vertical-align: top | bottom`, which only constrains the line
    /// box's height.
    fn add_line_relative_inline_box(&mut self, align: VerticalAlign, height: f32, quantize: bool) {
        let height = if quantize { height.round() } else { height };
        let slot = match align.shift {
            BaselineShift::Bottom => &mut self.line_relative_bottom_height,
            _ => &mut self.line_relative_top_height,
        };
        *slot = slot.max(height);
    }
}

#[derive(Clone)]
struct PrevBoundaryState {
    run_idx: usize,
    cluster_idx: u32,
    floated_box_idx: usize,
    state: LineState,
    /// The advance at which the line ends if this opportunity is taken (without taking further
    /// reshaping into account). We take the last opportunity whose positions fits.
    ///
    /// For opportunities inside shaped clusters this is an estimate (see
    /// [`BreakerState::mark_break_opportunity_inside_shaped_cluster`]). This only decides which
    /// opportunities are tried: the line after reshaping also has to fit (see
    /// [`BreakLines::overflows_once_reshaped`]). In other words, if this is under-estimating, we'll
    /// notice after reshaping and break the line again one opportunity earlier. If this is
    /// over-estimating, we may end up breaking one opportunity too early.
    ///
    /// `state.x` will include the advance of that whole cluster, which is what the reshaped line's
    /// advance delta is relative to (see [`Reshaper`](Reshaper#advances)).
    position: f32,
    /// Length of [`BreakerState::contributed`] at this opportunity.
    contributed_len: usize,
    /// Length of [`BreakerState::subtrees`] at this opportunity, as [saved](SubtreeHistory::save).
    subtrees_len: usize,
}

/// Reason that the line breaker has yielded control flow
#[derive(Clone, Debug)]
pub enum YieldData {
    /// Control flow was yielded because a line break occurred.
    /// The `reason` field of the [`LineBreakData`] contains a specific reason about what caused a
    /// line break at this location.
    LineBreak(LineBreakData),
    /// Control flow was yielded because content on the line caused the line to exceed the max height
    ///
    /// The caller is responsible for finding a new location for the line with a greater available height
    /// adjusting the line geometry to the new position and resuming iteration.
    ///
    /// Note: that by default no max height is set (and one is not required for laying out text into
    /// rectangular regions), so you will only encounter this if you explicitly set a max height
    /// using [`BreakerState::set_line_max_height`].
    MaxHeightExceeded(MaxHeightBreakData),
    /// Control flow was yielded because a [floated box](crate::FloatedBox) was encountered.
    ///
    /// Parley does not position these boxes itself. The caller is responsible for
    /// placing the box (e.g. via a caller-owned algorithm), adjusting the line geometry through
    /// [`BreakerState`], and then resuming iteration.
    FloatedBox(FloatedBoxData),
}

#[derive(Clone, Debug)]
/// Information about a line break
pub struct LineBreakData {
    /// The reason for the line break (see [`BreakReason`] for details)
    pub reason: BreakReason,
    /// The metrics of the line.
    ///
    /// As the line isn't aligned yet, [`LineMetrics::offset`] is 0.
    pub metrics: LineMetrics,
    /// The position of the top of the line
    pub line_y_start: f64,
    /// The position of the bottom of the line
    pub line_y_end: f64,
}

#[derive(Clone, Debug)]
/// Information about a "max height break" (where control flow has been yielded due to the
/// line's configured max height being exceeded by content by laid out into the line).
pub struct MaxHeightBreakData {
    /// The current advance of the in-progress line
    pub advance: f32,
    /// The current line height of the in-progress line
    pub line_height: f32,
}

#[derive(Clone, Debug)]
/// Information about a floated box (where control flow has been yielded due to a
/// [floated box](crate::FloatedBox) being encountered during layout).
pub struct FloatedBoxData {
    /// The [`FloatedBox::id`](crate::FloatedBox::id) of the floated box that was encountered.
    pub id: u64,
    /// The index of the floated box within [`Layout::floated_boxes`]
    pub index: usize,
    /// The current advance of the line (up to the floated box)
    pub advance: f32,
}

/// The mutable state of the line breaker.
///
/// This is exposed so that callers using [`BreakLines`] directly can inspect and
/// adjust line geometry between calls to [`BreakLines::break_next`].
///
/// A `BreakerState` can be cloned and later passed to [`BreakLines::revert_to`]
/// to retry layout from a saved checkpoint.
pub struct BreakerState {
    /// The number of items that have been processed (used to revert state)
    items: usize,
    /// The number of lines that have been processed (used to revert state)
    lines: usize,
    /// A mark in a [`LayoutData::reshaped`] (used to revert state)
    reshaped: ReshapedTextMark,

    /// Iteration state: the current run (within the layout)
    run_idx: usize,
    /// Iteration state: the current shaped cluster.
    ///
    /// This indexes into [`parley_engine::ShapedText::shaped_clusters`], or into the line's
    /// reshaped start clusters while the breaker is walking that (see
    /// [`LineState::in_reshaped_start`]).
    //
    // TODO: rename this `shaped_cluster_idx`
    cluster_idx: u32,
    /// Iteration state: the next floated box to yield (within the layout)
    floated_box_idx: usize,

    /// The x coordinate of the left/start of the current line
    line_x: f32,
    /// The y coordinate of the top/start of the current line
    /// Use of f64 here is important. f32 causes test failures due to accumulated error
    line_y: f64,

    /// The max advance of the entire layout.
    layout_max_advance: f32,
    /// The max advance (max width) of the current line. This must be <= the `layout_max_advance`.
    line_max_advance: f32,
    /// The max height available to the current line.
    line_max_height: f32,

    /// The state of the current line
    line: LineState,
    /// Style indices whose span box has already been added to the current line (see
    /// [`LineBoxMetrics::add_style`]). Lives here rather than in [`LineState`] so that saving a
    /// line-breaking opportunity only records its length; reverting truncates it back.
    contributed: Vec<u16>,
    /// Extents of the aligned subtrees rooted at `top`/`bottom` spans on the current line. Like
    /// [`Self::contributed`], saving a line-breaking opportunity only records its length.
    subtrees: SubtreeHistory,

    // Saved breaker states for reverting to a previously encountered line-breaking opportunity
    /// Saved breaker state for the last non-emergency line-breaking opportunity
    prev_boundary: Option<PrevBoundaryState>,
    /// Saved breaker state for the last emergency line-breaking opportunity
    emergency_boundary: Option<PrevBoundaryState>,
}

impl Clone for BreakerState {
    fn clone(&self) -> Self {
        Self {
            items: self.items,
            lines: self.lines,
            reshaped: self.reshaped,
            run_idx: self.run_idx,
            cluster_idx: self.cluster_idx,
            floated_box_idx: self.floated_box_idx,
            line_x: self.line_x,
            line_y: self.line_y,
            layout_max_advance: self.layout_max_advance,
            line_max_advance: self.line_max_advance,
            line_max_height: self.line_max_height,
            line: self.line.clone(),
            contributed: self.contributed.clone(),
            subtrees: self.subtrees.clone(),
            prev_boundary: self.prev_boundary.clone(),
            emergency_boundary: self.emergency_boundary.clone(),
        }
    }

    /// Reuses the allocations of `self`, as a state is saved at the start of every line.
    fn clone_from(&mut self, source: &Self) {
        let Self {
            items,
            lines,
            reshaped,
            run_idx,
            cluster_idx,
            floated_box_idx,
            line_x,
            line_y,
            layout_max_advance,
            line_max_advance,
            line_max_height,
            line,
            contributed,
            subtrees,
            prev_boundary,
            emergency_boundary,
        } = source;
        self.items = *items;
        self.lines = *lines;
        self.reshaped = *reshaped;
        self.run_idx = *run_idx;
        self.cluster_idx = *cluster_idx;
        self.floated_box_idx = *floated_box_idx;
        self.line_x = *line_x;
        self.line_y = *line_y;
        self.layout_max_advance = *layout_max_advance;
        self.line_max_advance = *line_max_advance;
        self.line_max_height = *line_max_height;
        self.line.clone_from(line);
        self.contributed.clone_from(contributed);
        self.subtrees.clone_from(subtrees);
        self.prev_boundary.clone_from(prev_boundary);
        self.emergency_boundary.clone_from(emergency_boundary);
    }
}

impl Default for BreakerState {
    fn default() -> Self {
        Self {
            items: 0,
            lines: 0,
            reshaped: ReshapedTextMark::default(),
            run_idx: 0,
            cluster_idx: 0,
            floated_box_idx: 0,
            line_x: 0.0,
            line_y: 0.0,
            layout_max_advance: 0.0,
            line_max_advance: 0.0,
            line_max_height: f32::MAX,
            line: LineState::default(),
            contributed: Vec::new(),
            subtrees: SubtreeHistory::default(),
            prev_boundary: None,
            emergency_boundary: None,
        }
    }
}

impl BreakerState {
    /// Add a shaped cluster to the current line.
    ///
    /// `cluster_idx` is the index of `cluster`. Its characters are `characters`.
    ///
    /// The span boxes of the shaped cluster's styles (and those of their ancestors) are added to
    /// the line too, as is the box of the shaped cluster's run, see [`LineBoxMetrics::add_text`].
    /// `is_word_separator` should be `true` only for the first shaped cluster of an atom that is a
    /// [word separator](`is_word_separator`), i.e., a justification opportunity.
    #[inline(always)]
    fn append_shaped_cluster_to_line<B: Brush>(
        &mut self,
        cluster: &ShapedCluster,
        cluster_idx: u32,
        next_x: f32,
        characters: &[Character],
        data: &LayoutData<B>,
        is_word_separator: bool,
    ) {
        self.line.items.end = self.run_idx + 1;
        self.line.chars.end = cluster.chars_range().end;
        self.line.clusters.end = cluster_idx + 1;
        self.cluster_idx = cluster_idx + 1;
        self.line.x = next_x;
        self.line.num_word_separators += u32::from(is_word_separator);
        self.line.box_metrics.add_text(
            self.run_idx,
            cluster.style_index,
            characters,
            data,
            &mut self.contributed,
            &mut self.subtrees,
        );
        self.update_max_height_exceeded();
    }

    /// Add the newline atom starting at shaped cluster `first` of `slice` to the current line.
    ///
    /// The whole newline atom goes on the line (e.g., both clusters of a CRLF).
    ///
    /// This is only used for forced breaks, so we don't inline it into the breaker's loop.
    ///
    /// Note this only works for newline atoms: it assumes the atom has zero advance and doesn't
    /// take spacing, which is only guaranteed for newlines.
    #[inline(never)]
    fn append_newline_atom_to_line<B: Brush>(
        &mut self,
        slice: ShapedSlice<'_>,
        first: u32,
        data: &LayoutData<B>,
    ) {
        let clusters = slice.shaped_clusters_in(first..slice.shaped_clusters_range().end);
        for (cluster_idx, cluster) in (first..).zip(clusters) {
            if cluster_idx != first && cluster.is_grapheme_start() {
                break;
            }
            self.append_shaped_cluster_to_line(
                cluster,
                cluster_idx,
                self.line.x,
                slice.characters_in(cluster.chars_range()),
                data,
                // Newlines are not word separators.
                false,
            );
        }
    }

    /// Mark the last line-breaking opportunities inside `cluster` that fits.
    ///
    /// These are its internal soft wrap opportunities, or (with `emergency`) the emergency
    /// opportunities at its grapheme boundaries. For example, an "ffi" ligature will have an
    /// emergency opportunity before each character.
    ///
    /// `cluster` is the shaped cluster about to be added to the line, with the arguments it
    /// would be [added](Self::append_shaped_cluster_to_line) with. A line ending inside it takes
    /// the cluster's characters before that point, and the next line starts with the rest. Both
    /// are reshaped, so the advance the line ends at is only known once the opportunity is taken
    /// (see [`PrevBoundaryState::position`]). Until then, the cluster's advance is taken to be
    /// divided evenly over its graphemes.
    #[cold]
    #[inline(never)]
    fn mark_break_opportunity_inside_shaped_cluster<B: Brush>(
        &mut self,
        emergency: bool,
        cluster: &ShapedCluster,
        cluster_idx: u32,
        advance: f32,
        characters: &[Character],
        data: &LayoutData<B>,
        is_word_separator: bool,
        fit_max_advance: f32,
    ) {
        let style = &data.styles[cluster.style_index as usize];
        if self.line.text_wrap_mode != TextWrapMode::Wrap
            || (emergency && style.overflow_wrap == OverflowWrap::Normal)
        {
            return;
        }
        let graphemes = 1 + characters[1..]
            .iter()
            .map(|character| u32::from(character.grapheme_start))
            .sum::<u32>();
        // The number of the cluster's graphemes that end at or before the current character.
        let mut grapheme = 0_u32;
        for (i, character) in characters.iter().enumerate().skip(1) {
            grapheme += u32::from(character.grapheme_start);
            let is_opportunity = if emergency {
                character.grapheme_start
            } else {
                character.flags.is_soft_wrap_opportunity()
            };
            if !is_opportunity {
                continue;
            }
            let position = self.line.x + advance * grapheme as f32 / graphemes as f32;
            // A line's first grapheme stays on the line whether or not it fits, as for whole
            // clusters.
            if position > fit_max_advance && (self.line.x != 0. || grapheme > 1) {
                break;
            }

            // The line then holds the characters before this one.
            self.line.box_metrics.add_text(
                self.run_idx,
                cluster.style_index,
                &characters[..i],
                data,
                &mut self.contributed,
                &mut self.subtrees,
            );
            let mut state = self.line.clone();
            state.items.end = self.run_idx + 1;
            state.chars.end = cluster.chars_range().start + i as u32;
            state.clusters.end = cluster_idx + 1;
            state.x += advance;
            state.num_word_separators += u32::from(is_word_separator);
            let boundary = Some(PrevBoundaryState {
                run_idx: self.run_idx,
                cluster_idx: cluster_idx + 1,
                floated_box_idx: self.floated_box_idx,
                state,
                position,
                contributed_len: self.contributed.len(),
                subtrees_len: self.subtrees.save(),
            });
            if emergency {
                self.emergency_boundary = boundary;
            } else {
                self.prev_boundary = boundary;
            }
        }
    }

    /// Store the current iteration state so that we can revert to it if we later want to take
    /// the line breaking opportunity at this point.
    #[inline]
    fn mark_line_break_opportunity(&mut self) {
        self.prev_boundary = Some(PrevBoundaryState {
            run_idx: self.run_idx,
            cluster_idx: self.cluster_idx,
            floated_box_idx: self.floated_box_idx,
            state: self.line.clone(),
            position: self.line.x,
            contributed_len: self.contributed.len(),
            subtrees_len: self.subtrees.save(),
        });
    }

    /// Store the current iteration state so that we can revert to it if we later want to take
    /// an *emergency* line breaking opportunity at this point.
    #[inline]
    fn mark_emergency_break_opportunity(&mut self) {
        self.emergency_boundary = Some(PrevBoundaryState {
            run_idx: self.run_idx,
            cluster_idx: self.cluster_idx,
            floated_box_idx: self.floated_box_idx,
            state: self.line.clone(),
            position: self.line.x,
            contributed_len: self.contributed.len(),
            subtrees_len: self.subtrees.save(),
        });
    }

    /// Stop walking the line's reshaped start at the current position (see
    /// [`LineState::in_reshaped_start`]).
    ///
    /// This points [`Self::cluster_idx`] and the line's `clusters.end` at the first source shaped
    /// cluster starting at or after that position.
    fn leave_reshaped_start(&mut self, shaped_text: &ShapedText) {
        let line = &mut self.line;
        let clusters = &shaped_text.shaped_clusters()[line.clusters.start as usize..];
        line.clusters.end = line.clusters.start
            + clusters.partition_point(|c| c.chars_range().start < line.chars.end) as u32;
        line.in_reshaped_start = false;
        self.cluster_idx = line.clusters.end;
    }

    /// Revert boundary state to prev state
    fn reset_to(&mut self, prev_state: PrevBoundaryState) {
        self.run_idx = prev_state.run_idx;
        self.cluster_idx = prev_state.cluster_idx;
        self.floated_box_idx = prev_state.floated_box_idx;
        self.line = prev_state.state;
        self.contributed.truncate(prev_state.contributed_len);
        self.subtrees.restore(prev_state.subtrees_len);
    }

    #[inline(always)]
    fn update_max_height_exceeded(&mut self) {
        self.line.max_height_exceeded = self.line_max_height != f32::MAX
            && self.line.box_metrics.line_height() > self.line_max_height;
    }

    /// Get the max-advance of the entire layout
    #[inline(always)]
    pub fn layout_max_advance(&self) -> f32 {
        self.layout_max_advance
    }
    /// Set the max-advance of the entire layout
    #[inline(always)]
    pub fn set_layout_max_advance(&mut self, advance: f32) {
        self.layout_max_advance = advance;
    }

    /// Get the max-advance of the current line
    #[inline(always)]
    pub fn line_max_advance(&self) -> f32 {
        self.line_max_advance
    }
    /// Set the max-advance of the current line
    #[inline(always)]
    pub fn set_line_max_advance(&mut self, advance: f32) {
        self.line_max_advance = advance;
    }

    /// Get the max-height of the current line
    #[inline(always)]
    pub fn line_max_height(&self) -> f32 {
        self.line_max_height
    }
    /// Set the max-height of the current line.
    #[inline(always)]
    pub fn set_line_max_height(&mut self, height: f32) {
        self.line_max_height = height;
        self.update_max_height_exceeded();
    }

    /// Get the x-offset of the current line
    #[inline(always)]
    pub fn line_x(&self) -> f32 {
        self.line_x
    }
    /// Set the x-offset for the current line.
    #[inline(always)]
    pub fn set_line_x(&mut self, x: f32) {
        self.line_x = x;
    }

    /// Get the y-offset of the current line
    #[inline(always)]
    pub fn line_y(&self) -> f64 {
        self.line_y
    }
    /// Set the y-offset for the current line.
    #[inline(always)]
    pub fn set_line_y(&mut self, y: f64) {
        self.line_y = y;
    }
}

/// Line breaking support for a paragraph.
pub struct BreakLines<'a, B: Brush> {
    layout: &'a mut Layout<B>,
    lines: LineLayout,
    reshaper: Reshaper,
    state: BreakerState,
    prev_state: Option<BreakerState>,
    /// Reshaping a line at a break can cause it to overflow `max_advance`. When that happens, we
    /// break the line again (see [`Self::break_line_again`]), this time with a `max_advance` just
    /// below the [position](PrevBoundaryState::position) of the failed break.
    ///
    /// This is `f32::INFINITY` if we're breaking the line for the first time.
    step_back_max_advance: f32,
    done: bool,
}

impl<'a, B: Brush> BreakLines<'a, B> {
    pub(crate) fn new(layout: &'a mut Layout<B>) -> Self {
        layout.data.width = 0.;
        layout.data.height = 0.;
        layout.data.reshaped.clear();
        let mut lines = LineLayout::default();
        lines.swap(&mut layout.data);
        lines.lines.clear();
        lines.line_items.clear();
        lines.aligned_subtree_offsets.clear();
        let mut this = Self {
            layout,
            lines,
            reshaper: Reshaper::default(),
            state: BreakerState::default(),
            prev_state: None,
            step_back_max_advance: f32::INFINITY,
            done: false,
        };
        this.reset_line();
        this
    }

    /// Reset the per-line running state in preparation for building a new line.
    ///
    /// The line starts out containing the root span box (the "strut", CSS 2 §10.8).
    fn reset_line(&mut self) {
        let state = &mut self.state;
        state.line.reset();
        state.contributed.clear();
        state.subtrees.clear();
        state.line.box_metrics.add_style(
            0,
            &self.layout.data.style_metrics,
            &mut state.contributed,
            &mut state.subtrees,
        );
        state.update_max_height_exceeded();

        let data = &self.layout.data;
        let (text, shaped_text) = (&data.text, &data.shaped_text);
        let line = &mut state.line;
        if edge_is_unsafe_to_break(shaped_text, line.chars.start, line.clusters.start)
            && let Some(start) =
                reshaped_start(&mut self.reshaper, text, shaped_text, line.chars.start)
        {
            line.in_reshaped_start = true;
            state.cluster_idx = start.shaped_clusters_range().start;
        }
    }

    /// Returns whether the line ended at the current position would no longer fit once reshaped.
    /// `position` is the [position](PrevBoundaryState::position) of the opportunity taken.
    ///
    /// See also [`Self::break_line_again`].
    #[inline(always)]
    fn overflows_once_reshaped(&mut self, max_advance: f32, position: f32) -> bool {
        /// Usually the break positions we try will be safe to break. Marking this path as cold and
        /// ensuring it's not inlined keeps that expected common path faster.
        ///
        /// If our assumption is wrong for some combination of text and font, the pessimization will
        /// be tiny compared to the cost of reshaping.
        #[cold]
        #[inline(never)]
        fn overflows<B: Brush>(
            this: &mut BreakLines<'_, B>,
            max_advance: f32,
            position: f32,
        ) -> bool {
            if this.step_back_max_advance.is_finite() {
                // We already stepped back once, so let's just accept this line. There's technically
                // a small chance it may overflow again, but that should be quite unlikely.
                return false;
            }

            let line = &this.state.line;

            // A line that already doesn't fit before its end is reshaped either only hangs
            // whitespace (see the comment below), or was broken at its first opportunity, so there
            // is no narrower break to step back to.
            if position > max_advance {
                return false;
            }

            let data = &this.layout.data;
            let (text, shaped_text) = (&data.text, &data.shaped_text);
            let last = &shaped_text.characters()[line.chars.end as usize - 1];
            if whitespace_hangs(last.whitespace, &data.styles[last.style_index as usize]) {
                // As a shortcut, we don't check if reshaping hanging whitespace causes overflow.
                // The hanging whitespace itself doesn't need to fit, and reshaping would only
                // change how far it hangs, except in the rare instance where a font's lookups reach
                // across the trailing whitespace. Doing this fully correctly would entail walking
                // the reshaped end's clusters to figure out if any part of the change in advance is
                // in the non-hanging part.
                return false;
            }
            let (_, advance) = reshape_line(&mut this.reshaper, text, shaped_text, line);
            advance > max_advance
        }

        let line = &self.state.line;
        // We explicitly test whether we're ending the line in the reshaped start of the line, as we
        // can't pass reshaped clusters' indices into `edge_is_unsafe_to_break`. Such lines need to
        // be reshaped as a whole.
        let end_is_unsafe_to_break = line.in_reshaped_start
            || edge_is_unsafe_to_break(
                &self.layout.data.shaped_text,
                line.chars.end,
                line.clusters.end,
            );

        // Note that, if the end needs no reshaping, reshaping changes only the line's start. We
        // already took that into account when fitting the line.
        end_is_unsafe_to_break && overflows(self, max_advance, position)
    }

    /// Attempt breaking the line again, this time ending it before the opportunity at `position`
    /// (see [`PrevBoundaryState::position`]).
    ///
    /// To be used when reshaping a line caused it to overflow. Using this only once should *almost
    /// always* be enough, as taking away a character normally takes away more advance than e.g. a
    /// change in kerning introduces.
    ///
    /// This retries from where the call to [`Self::break_next`] started.
    #[cold]
    #[inline(never)]
    fn break_line_again(&mut self, position: f32) -> Option<YieldData> {
        self.step_back_max_advance = position.next_down();
        let start = self.prev_state.as_ref().expect("saved by `break_next`");
        self.state.clone_from(start);
        self.break_next()
    }

    /// Reset state when a line has been committed
    fn start_new_line(
        &mut self,
        reason: BreakReason,
        max_advance: f32,
        line_indent: f32,
    ) -> Option<YieldData> {
        if self.state.line.in_reshaped_start {
            self.state
                .leave_reshaped_start(&self.layout.data.shaped_text);
        }
        commit_line(
            self.layout,
            &mut self.reshaper,
            &mut self.lines,
            &mut self.state.line,
            max_advance,
            reason,
            line_indent,
        );

        // A line containing only floated boxes (and no text) is an invisible line box with
        // zero height; the strut only applies once the line has content.
        let invisible =
            self.layout.data.text.is_empty() && !self.layout.data.floated_boxes.is_empty();
        let line_height = if invisible {
            0.
        } else {
            self.state.line.box_metrics.line_height()
        };
        let line_y_start = self.state.line_y;

        self.state.items = self.lines.line_items.len();
        self.state.lines = self.lines.lines.len();
        self.state.reshaped = self.layout.data.reshaped.mark();
        self.state.prev_boundary = None;
        self.state.emergency_boundary = None;
        self.step_back_max_advance = f32::INFINITY;

        // `finish_line` reads the line's accumulated vertical metrics from `self.state.line`, so
        // it must run before we reset the per-line running state. It may grow the line (e.g. the
        // trailing line after a final newline), so use the returned height.
        let line_height = self.finish_line(self.lines.lines.len() - 1, line_height, invisible);
        self.reset_line();

        self.state.line_y += line_height as f64;

        Some(YieldData::LineBreak(
            self.last_line_data(reason, line_y_start),
        ))
    }

    #[inline(always)]
    fn last_line_data(&self, reason: BreakReason, line_y_start: f64) -> LineBreakData {
        LineBreakData {
            reason,
            metrics: self.lines.lines.last().unwrap().metrics,
            line_y_start,
            line_y_end: self.state.line_y,
        }
    }

    /// Yield the next [`crate::FloatedBox`].
    fn yield_floated_box(&mut self) -> Option<YieldData> {
        let index = self.state.floated_box_idx;
        self.state.floated_box_idx += 1;
        Some(YieldData::FloatedBox(FloatedBoxData {
            id: self.layout.data.floated_boxes[index].id,
            index,
            advance: self.state.line.x,
        }))
    }

    #[inline(always)]
    fn max_height_break_data(&self, line_height: f32) -> Option<YieldData> {
        Some(YieldData::MaxHeightExceeded(MaxHeightBreakData {
            advance: self.state.line.x,
            line_height,
        }))
    }

    #[inline(always)]
    pub fn state(&self) -> &BreakerState {
        &self.state
    }

    #[inline(always)]
    pub fn state_mut(&mut self) -> &mut BreakerState {
        &mut self.state
    }

    /// Set the max-advance of the previous line.
    ///
    /// This is an escape-hatch for allowing a custom width for
    /// alignment on each line, which is different to the breaking width.
    ///
    /// Should be used in combination with [`AlignmentOptions`](crate::AlignmentOptions::align_when_overflowing).
    ///
    /// This method changes a line's reported [`inline_max_coord`](LineMetrics::inline_max_coord), so
    /// if you use this method and read that value, you should be cautious.
    // This escape hatch has not been carefully evaluated for unexpected consequences.
    // It's current motivation is cases where Parley gives different line breaking results
    // than blink, for reasons which haven't been fully understood.
    #[doc(hidden)]
    pub fn set_prior_line_width(&mut self, advance: f32) {
        if let Some(line) = self.lines.lines.last_mut() {
            line.metrics.inline_max_coord = line.metrics.inline_min_coord + advance;
        }
    }

    /// Reverts the to an externally saved state.
    pub fn revert_to(&mut self, state: BreakerState) {
        self.state = state;
        self.lines.truncate(self.state.lines);
        self.lines.line_items.truncate(self.state.items);
        self.layout.data.reshaped.truncate(self.state.reshaped);
        self.done = false;
    }

    /// Reverts the last computed line, returning to the previous state.
    #[inline(always)]
    pub fn revert(&mut self) -> bool {
        if let Some(state) = self.prev_state.take() {
            self.revert_to(state);
            true
        } else {
            false
        }
    }

    /// Returns the y-coordinate of the top of the current line
    #[inline(always)]
    pub fn committed_y(&self) -> f64 {
        self.state.line_y
    }

    /// Returns true if all the text has been placed into lines.
    #[inline(always)]
    pub fn is_done(&self) -> bool {
        self.done
    }

    /// Computes the next line in the paragraph. Returns the advance and size
    /// (width and height for horizontal layouts) of the line.
    pub fn break_next(&mut self) -> Option<YieldData> {
        assert!(
            self.state.layout_max_advance == f32::INFINITY
                || self.state.line_max_advance - self.state.layout_max_advance < 1.0
        );

        // Maintain iterator state
        if self.done {
            return None;
        }
        match &mut self.prev_state {
            Some(prev_state) => prev_state.clone_from(&self.state),
            None => self.prev_state = Some(self.state.clone()),
        }

        let line_indent = self.resolve_indent();

        let max_advance = self.state.line_max_advance - line_indent;
        let fit_max_advance = max_advance.min(self.step_back_max_advance);

        // The text index of the next floated box.
        let floated_box_yield_index = self
            .layout
            .data
            .floated_boxes
            .get(self.state.floated_box_idx)
            .map_or(usize::MAX, |floated_box| floated_box.index);

        // Iterate over remaining runs in the Layout
        let run_count = self.layout.data.runs.len();
        while self.state.run_idx < run_count {
            let run_idx = self.state.run_idx;
            let run = Run::new(self.layout, 0, 0, run_idx, None);
            let slice = run.line_slice();

            // The height to report if the maximum line height is exceeded.
            let mut line_height = run.data.line_height;
            // An inline object is a run of its own. It exceeds the maximum line height by
            // itself if its box is too tall.
            if self.state.line_max_height != f32::MAX
                && slice
                    .shaped_clusters()
                    .first()
                    .is_some_and(|cluster| cluster.is_inline_object())
            {
                let first_character = &slice.characters()[0];
                // This may have been set by an earlier yield before this object.
                self.state.update_max_height_exceeded();
                let inline_boxes = &self.layout.data.inline_boxes;
                let index =
                    inline_object_box_index(inline_boxes, first_character.text_byte_start as usize);
                let height = inline_boxes[index].inline_box.height;
                if !self.state.line.max_height_exceeded && height > self.state.line_max_height {
                    self.state.line.max_height_exceeded = true;
                    line_height = height;
                }
            }

            // If the line's start was reshaped, we first walk those reshaped clusters, then come
            // back for the rest of the run.
            let in_reshaped_start = self.state.line.in_reshaped_start;
            let slice = if in_reshaped_start {
                let data = &self.layout.data;
                let start = self.state.line.chars.start;
                reshaped_start(&mut self.reshaper, &data.text, &data.shaped_text, start).unwrap()
            } else {
                slice
            };

            // Iterate over the remaining shaped clusters in the run.
            //
            // A line can end at any character that is a soft wrap opportunity or starts a grapheme,
            // and in particular that means it can end inside a source shaped cluster.
            //
            // We use the atom's first shaped cluster's wrapping style and spacing.
            let styles = &self.layout.data.styles;
            let characters = self.layout.data.shaped_text.characters();
            let run_spacing = run.data.spacing;
            let is_spaced = !run_spacing.is_zero();
            let first = self.state.cluster_idx;
            let clusters = slice.shaped_clusters_in(first..slice.shaped_clusters_range().end);
            // We treat the first shaped cluster of the line as an atom for layout purposes, even if
            // it isn't the start of a grapheme. This can happen if we broke inside a grapheme.
            let mut is_atom_start = true;
            let mut max_height_exceeded = false;
            for (cluster_idx, cluster) in (first..).zip(clusters) {
                is_atom_start |= cluster.is_grapheme_start();
                let mut advance = cluster.advance;
                // Whether this cluster starts an atom that is a justification opportunity.
                let mut is_separator = false;

                if is_atom_start {
                    is_atom_start = false;
                    let first_character = &characters[cluster.chars_range().start as usize];
                    // Yield floated boxes once the characters before them are on the line.
                    if first_character.text_byte_start as usize >= floated_box_yield_index {
                        return self.yield_floated_box();
                    }
                    let whitespace = cluster.whitespace();
                    is_separator = is_word_separator(whitespace);
                    max_height_exceeded = self.state.line.max_height_exceeded;
                    let style = &styles[cluster.style_index as usize];

                    // Lag text_wrap_mode style by one atom
                    let text_wrap_mode = self.state.line.text_wrap_mode;
                    self.state.line.text_wrap_mode = style.text_wrap_mode;

                    // Take mandatory line breaks before checking for line wrapping.
                    if whitespace == Whitespace::Newline {
                        if max_height_exceeded {
                            return self.max_height_break_data(line_height);
                        }
                        self.state.append_newline_atom_to_line(
                            slice,
                            cluster_idx,
                            &self.layout.data,
                        );
                        return self.start_new_line(
                            BreakReason::Explicit,
                            max_advance,
                            line_indent,
                        );
                    } else if cluster.is_soft_wrap_opportunity_before()
                        && text_wrap_mode == TextWrapMode::Wrap
                    {
                        // We don't record boundaries when the advance is 0. As we do not want overflowing content to cause extra consecutive
                        // line breaks. We should accept the overflowing fragment in that scenario.
                        if self.state.line.x != 0.0 {
                            self.state.mark_line_break_opportunity();
                        }
                    } else if
                    // This text can contribute "emergency" line breaks.
                    style.overflow_wrap != OverflowWrap::Normal
                        && text_wrap_mode == TextWrapMode::Wrap
                        // If we're at the start of the line, this particular atom will never fit, so it's not a valid emergency break opportunity.
                        && self.state.line.x != 0.0
                    {
                        self.state.mark_emergency_break_opportunity();
                    }

                    // The atom's spacing is added along with its first cluster.
                    if is_spaced {
                        advance += run_spacing
                            .gaps(whitespace, cluster.is_default_ignorable())
                            .total();
                    }
                } else if cluster.is_soft_wrap_opportunity_before()
                    && self.state.line.text_wrap_mode == TextWrapMode::Wrap
                    && self.state.line.x != 0.0
                {
                    // This is a soft wrap opportunity inside a grapheme. This can happen as
                    // Unicode's line segmenter has some opportunities inside extended graphemes
                    // clusters, like between a space and a combining mark that follows it
                    // (SPACE + U+0301, say).
                    self.state.mark_line_break_opportunity();
                }

                if cluster.has_internal_soft_wrap_opportunity() {
                    self.state.mark_break_opportunity_inside_shaped_cluster(
                        false,
                        cluster,
                        cluster_idx,
                        advance,
                        slice.characters_in(cluster.chars_range()),
                        &self.layout.data,
                        is_separator,
                        fit_max_advance,
                    );
                }

                // Compute the x position of the content being currently processed
                let next_x = self.state.line.x + advance;

                // If the content fits (the x position does NOT exceed max_advance)
                //
                // We simply append the shaped cluster to the current line
                if next_x <= fit_max_advance {
                    if max_height_exceeded {
                        return self.max_height_break_data(line_height);
                    }
                    self.state.append_shaped_cluster_to_line(
                        cluster,
                        cluster_idx,
                        next_x,
                        slice.characters_in(cluster.chars_range()),
                        &self.layout.data,
                        is_separator,
                    );
                }
                // Else we attempt to line break:
                //
                // This will only succeed if there is an available line-break opportunity that has been marked earlier
                // in the line. If there is no such line-breaking opportunity (such as if wrapping is disabled), then
                // we fall back to appending the content to the line anyway.
                else {
                    // Without a regular line-breaking opportunity to take, the line can end inside
                    // this cluster as an emergency.
                    if cluster.char_len() > 1 && self.state.prev_boundary.is_none() {
                        self.state.mark_break_opportunity_inside_shaped_cluster(
                            true,
                            cluster,
                            cluster_idx,
                            advance,
                            slice.characters_in(cluster.chars_range()),
                            &self.layout.data,
                            is_separator,
                            fit_max_advance,
                        );
                    }

                    // Case: the shaped cluster is whitespace that hangs.
                    //
                    // We append it to the line, with the whitespace hanging past the end.
                    if hangs(slice.characters_in(cluster.chars_range()), styles) {
                        if max_height_exceeded {
                            return self.max_height_break_data(line_height);
                        }
                        self.state.append_shaped_cluster_to_line(
                            cluster,
                            cluster_idx,
                            next_x,
                            slice.characters_in(cluster.chars_range()),
                            &self.layout.data,
                            is_separator,
                        );
                    }
                    // Case: we have previously encountered a REGULAR line-breaking opportunity in the current line
                    //
                    // We "take" the line-breaking opportunity by starting a new line and resetting our
                    // item/run/cluster iteration state back to how it was when the line-breaking opportunity was encountered
                    else if let Some(prev) = self.state.prev_boundary.take() {
                        let position = prev.position;
                        self.state.reset_to(prev);
                        if self.overflows_once_reshaped(max_advance, position) {
                            return self.break_line_again(position);
                        }
                        return self.start_new_line(BreakReason::Regular, max_advance, line_indent);
                    }
                    // Case: we have previously encountered an EMERGENCY line-breaking opportunity in the current line
                    //
                    // We "take" the line-breaking opportunity by starting a new line and resetting our
                    // item/run/cluster iteration state back to how it was when the line-breaking opportunity was encountered
                    else if let Some(prev_emergency) = self.state.emergency_boundary.take() {
                        let position = prev_emergency.position;
                        self.state.reset_to(prev_emergency);
                        if self.overflows_once_reshaped(max_advance, position) {
                            return self.break_line_again(position);
                        }
                        return self.start_new_line(
                            BreakReason::Emergency,
                            max_advance,
                            line_indent,
                        );
                    }
                    // Case: no line-breaking opportunities available
                    //
                    // This can happen when wrapping is disabled (TextWrapMode::NoWrap) or when no wrapping opportunities
                    // (according to our `OverflowWrap` and `WordBreak` styles) have yet been encountered.
                    //
                    // We fall back to appending the content to the line.
                    else {
                        if max_height_exceeded {
                            return self.max_height_break_data(line_height);
                        }
                        self.state.append_shaped_cluster_to_line(
                            cluster,
                            cluster_idx,
                            next_x,
                            slice.characters_in(cluster.chars_range()),
                            &self.layout.data,
                            is_separator,
                        );
                    }
                }
            }
            if in_reshaped_start {
                self.state
                    .leave_reshaped_start(&self.layout.data.shaped_text);
                continue;
            }
            self.state.run_idx += 1;
        }

        // Floated boxes at the end of the text.
        if self.state.floated_box_idx < self.layout.data.floated_boxes.len() {
            return self.yield_floated_box();
        }

        self.done = true;
        self.start_new_line(BreakReason::None, max_advance, line_indent)
    }

    /// Computes the next line in the paragraph by character count.
    ///
    /// This method breaks lines based on the number of characters rather than advance width.
    /// Each character of text (including whitespace and newlines) counts as 1.
    /// Each in-flow inline box also counts as 1 character (that of its U+FFFC).
    ///
    /// Unlike `break_next`, this method does not respect normal line break opportunities and
    /// will break when the character limit is reached. It does not break on newlines, for example.
    ///
    /// A line can end at any character, including inside a ligature or a multi-character grapheme.
    /// The lines on either side of such a break are reshaped.
    #[expect(clippy::cast_possible_truncation, reason = "deferred")]
    pub fn break_next_with_length(&mut self, max_chars: u32) -> Option<()> {
        if self.done {
            return None;
        }

        let line_indent = self.resolve_indent();

        let characters = self.layout.data.shaped_text.characters();
        // The exclusive end of the line's character range.
        let end_char = (self.state.line.chars.start)
            .saturating_add(max_chars.max(1))
            .min(characters.len() as u32);

        let run_count = self.layout.data.runs.len();
        'runs: while self.state.run_idx < run_count {
            let run = Run::new(self.layout, 0, 0, self.state.run_idx, None);
            let mut slice = run.line_slice();
            let spacing = run.data.spacing;

            // Like in `break_next`, we first walk the line's reshaped start.
            let in_reshaped_start = self.state.line.in_reshaped_start;
            if in_reshaped_start {
                let data = &self.layout.data;
                let start = self.state.line.chars.start;
                slice = reshaped_start(&mut self.reshaper, &data.text, &data.shaped_text, start)
                    .unwrap();
            }

            let first = self.state.cluster_idx;
            let clusters = slice.shaped_clusters_in(first..slice.shaped_clusters_range().end);
            for (cluster_idx, cluster) in (first..).zip(clusters) {
                let chars = cluster.chars_range();
                if chars.start >= end_char {
                    break 'runs;
                }

                // Skip floated boxes.
                let text_index = characters[chars.start as usize].text_byte_start as usize;
                let floated_boxes = &self.layout.data.floated_boxes;
                while floated_boxes
                    .get(self.state.floated_box_idx)
                    .is_some_and(|floated_box| floated_box.index <= text_index)
                {
                    self.state.floated_box_idx += 1;
                }

                let whitespace = cluster.whitespace();
                let is_atom_start = cluster_idx == first || cluster.is_grapheme_start();
                // For measuring purposes, the atom's spacing is added at its first cluster.
                let mut advance = cluster.advance;
                if is_atom_start {
                    advance += spacing
                        .gaps(whitespace, cluster.is_default_ignorable())
                        .total();
                }
                // Note the line may end inside a shaped cluster (e.g., inside a ligature). The line
                // then gets reshaped.
                self.state.append_shaped_cluster_to_line(
                    cluster,
                    cluster_idx,
                    self.state.line.x + advance,
                    slice.characters_in(chars.start..chars.end.min(end_char)),
                    &self.layout.data,
                    is_atom_start && is_word_separator(whitespace),
                );
                if chars.end > end_char {
                    // The next line starts with the rest of this cluster.
                    break 'runs;
                }
            }
            if in_reshaped_start {
                self.state
                    .leave_reshaped_start(&self.layout.data.shaped_text);
                continue;
            }
            self.state.run_idx += 1;
        }
        self.state.line.chars.end = end_char;

        // - BreakReason::None for the last line (end of content)
        // - BreakReason::Explicit if this line ends with a newline
        // - BreakReason::Regular for soft wraps
        let break_reason = if end_char as usize == characters.len() {
            BreakReason::None
        } else if characters[end_char as usize - 1].whitespace == Whitespace::Newline {
            BreakReason::Explicit
        } else {
            BreakReason::Regular
        };
        self.done = break_reason == BreakReason::None;
        self.start_new_line(break_reason, f32::MAX, line_indent);
        Some(())
    }

    /// Breaks all remaining lines with the specified maximum advance. This
    /// consumes the line breaker.
    pub fn break_remaining(mut self, max_advance: f32) {
        self.state.layout_max_advance = max_advance;
        self.state.line_max_advance = max_advance;

        // Floated boxes are ignored.
        while self.break_next().is_some() {}
        self.finish();
    }

    /// Consumes the line breaker and finalizes all line computations.
    pub fn finish(self) {
        // TODO: kept because of the related todo on `BreakLine`'s drop impl.
    }

    #[inline]
    fn resolve_indent(&self) -> f32 {
        let options = self.layout.data.indent_options;
        let amount = self.layout.data.indent_amount;
        match self.lines.lines.last().map(|line| line.break_reason) {
            None => options.indent_for_first_line(amount),
            Some(BreakReason::Explicit) => options.indent_following_forced_line_break(amount),
            Some(_) => options.indent_following_soft_wrap_break(amount),
        }
    }

    fn finish_line(&mut self, line_idx: usize, line_height: f32, invisible: bool) -> f32 {
        let line = &mut self.lines.lines[line_idx];

        // Reset metrics for line
        line.metrics.offset = 0.;

        line.metrics.line_height = line_height;

        if line.item_range.is_empty() {
            let text_len = self.layout.data.text.len();
            line.text_range = Range::from(text_len..text_len);
        }

        // Whether metrics should be quantized to pixel boundaries
        let quantize = self.layout.data.quantize;

        if line.item_range.is_empty() && line_idx > 0 {
            // If we have no items on this line, it must be the last (empty)
            // line in a layout following a newline. Commit an empty run so
            // that consumers, such as accessibility integrations, have
            // something with which to identify the visual cursor position.
            if let Some((index, run)) = self
                .layout
                .data
                .shaped_text
                .runs()
                .iter()
                .enumerate()
                .rfind(|(_, run)| !run.range.byte_range.is_empty())
            {
                let run_index = self.lines.line_items.len();
                let cluster = run.shaped_clusters_range.end;
                let text = run.range.byte_range.end;
                // The empty run carries the style of the newline that produced this line, so the
                // line is sized by that style's span box (and its ancestors), not just the strut.
                let style_index = self.layout.data.shaped_text.shaped_clusters()
                    [cluster as usize - 1]
                    .style_index;
                self.state.line.box_metrics.add_text(
                    index,
                    style_index,
                    &[],
                    &self.layout.data,
                    &mut self.state.contributed,
                    &mut self.state.subtrees,
                );
                line.metrics.line_height = self.state.line.box_metrics.line_height();
                self.lines.line_items.push(LineItemData {
                    index,
                    bidi_level: BidiLevel::new(0),
                    shaped_cluster_range: Range::from(cluster..cluster),
                    text_range: Range::from(text..text),
                    gaps_start: None,
                    split_off_by_l1: false,
                    reshaped_run: None,
                });
                line.item_range = Range::from(run_index..run_index + 1);
            }
        }

        // Position the independent aligned subtrees against each other (CSS 2.2 §10.8.1).
        //
        // The root aligned subtree determines the line's baseline. Those rooted at a `top`/`bottom`
        // span sit flush with the line box's top/bottom edge. If taller than the root aligned
        // subtree then top-aligned subtrees grow the line box downwards and bottom-aligned subtrees
        // grow it upwards.
        let box_metrics = &self.state.line.box_metrics;
        let (mut line_box_extents, mut content_box_extents) = if invisible {
            (Extents::default().or_zero(), Extents::default().or_zero())
        } else {
            (
                box_metrics.root.line_box.or_zero(),
                box_metrics.root.content_box.or_zero(),
            )
        };

        let subtrees = self.state.subtrees.current();
        let mut top_height = box_metrics.line_relative_top_height;
        let mut bottom_height = box_metrics.line_relative_bottom_height;
        for subtree in &subtrees {
            let height = subtree.line_box.height();
            match self.layout.data.styles[usize::from(subtree.root)]
                .vertical_align
                .shift
            {
                BaselineShift::Bottom => bottom_height = bottom_height.max(height),
                _ => top_height = top_height.max(height),
            }
        }
        let root_height = line_box_extents.over + line_box_extents.under;
        if top_height > root_height {
            line_box_extents.under += top_height - root_height;
        }
        let root_height = line_box_extents.over + line_box_extents.under;
        if bottom_height > root_height {
            line_box_extents.over += bottom_height - root_height;
        }

        let offsets = &mut self.lines.aligned_subtree_offsets;
        line.aligned_subtree_offsets.start = offsets.len() as u32;
        for subtree in &subtrees {
            let extents = subtree.line_box.or_zero();
            let offset = match self.layout.data.styles[usize::from(subtree.root)]
                .vertical_align
                .shift
            {
                BaselineShift::Bottom => extents.under - line_box_extents.under,
                _ => line_box_extents.over - extents.over,
            };
            let offset = if quantize { offset.round() } else { offset };
            offsets.push(AlignedSubtreeOffset {
                root: subtree.root,
                baseline_offset: offset,
            });
            let content = subtree.content_box.or_zero();
            content_box_extents.add(offset, content.over, content.under);
        }
        line.aligned_subtree_offsets.end = offsets.len() as u32;
        if box_metrics.line_relative_top_height > 0. {
            content_box_extents.add(
                0.,
                line_box_extents.over,
                box_metrics.line_relative_top_height - line_box_extents.over,
            );
        }
        if box_metrics.line_relative_bottom_height > 0. {
            content_box_extents.add(
                0.,
                box_metrics.line_relative_bottom_height - line_box_extents.under,
                line_box_extents.under,
            );
        }

        let top = if quantize {
            self.state.line_y.round() as f32
        } else {
            self.state.line_y as f32
        };
        line.metrics.baseline = top + line_box_extents.over;
        line.metrics.block_min_coord = top;
        line.metrics.block_max_coord = if quantize {
            // TODO: perhaps this should be something like the following, to ensure quantized line
            // boxes tile exactly without gaps or overlap. However, that would cause some
            // line height asserts to fail in the tests.
            // ```
            // (self.state.line_y as f32 + self.state.line.box_metrics.line_height()).round()
            // ```
            (line.metrics.baseline + line_box_extents.under).round()
        } else {
            line.metrics.baseline + line_box_extents.under
        };
        line.metrics.content_block_min_coord = line.metrics.baseline - content_box_extents.over;
        line.metrics.content_block_max_coord = line.metrics.baseline + content_box_extents.under;

        line.metrics.inline_min_coord = self.state.line_x;
        line.metrics.inline_max_coord = self.state.line_x + self.state.line_max_advance;
        line.metrics.line_height
    }
}

impl<B: Brush> Drop for BreakLines<'_, B> {
    fn drop(&mut self) {
        // TODO: Maybe move all of this into `finish`?

        // Compute the overall width and height of the entire layout
        // The "width" excludes hanging whitespace. The "full_width" includes it.
        let mut layout_width = 0_f32;
        let mut layout_full_width = 0_f32;
        let mut height = 0_f64; // f32 causes test failures due to accumulated error
        for line in &self.lines.lines {
            let indent_extra = line.metrics.indent.max(0.0);
            let line_max = line.metrics.inline_min_coord + line.metrics.advance + indent_extra;
            layout_full_width = layout_full_width.max(line_max);
            layout_width = layout_width.max(line_max - line.metrics.hanging_advance);
            height += line.metrics.line_height as f64;
        }

        // If laying out with infinite width constraint, then set all lines' "max_width"
        // to the measured width of the longest line.
        if self.state.layout_max_advance >= f32::MAX {
            for line in &mut self.lines.lines {
                if line.metrics.inline_max_coord >= f32::MAX {
                    line.metrics.inline_max_coord = layout_width;
                }
            }
        }

        // Save the computed widths/height to the layout
        self.layout.data.width = layout_width;
        self.layout.data.full_width = layout_full_width;
        self.layout.data.height = height as f32;
        self.layout.data.layout_max_advance = self.state.layout_max_advance;

        // Save the computed lines to the layout
        self.lines.swap(&mut self.layout.data);

        crate::layout::alignment::align(&mut self.layout.data);
    }
}

fn commit_line<B: Brush>(
    layout: &mut Layout<B>,
    reshaper: &mut Reshaper,
    lines: &mut LineLayout,
    state: &mut LineState,
    max_advance: f32,
    break_reason: BreakReason,
    line_indent: f32,
) {
    let shaped_text = &layout.data.shaped_text;
    let shaped_clusters = shaped_text.shaped_clusters();

    // Ensure that the shaped cluster and item endpoints are within range
    state.clusters.end = state.clusters.end.min(shaped_clusters.len() as u32);
    state.items.end = state.items.end.min(layout.data.runs.len());

    // Reshape the line if its edges fell at positions that are unsafe to break at.
    let (reshaped_line, reshaped_advance) =
        (edge_is_unsafe_to_break(shaped_text, state.chars.start, state.clusters.start)
            || edge_is_unsafe_to_break(shaped_text, state.chars.end, state.clusters.end))
        .then(
            #[inline(never)]
            || {
                let text = &layout.data.text;
                let (line, advance) = reshape_line(reshaper, text, shaped_text, state);
                let line = reshaper.push_line(text, shaped_text, &line, &mut layout.data.reshaped);
                (line, advance)
            },
        )
        .unzip();
    let source_clusters =
        reshaped_line.map_or(state.clusters, |l| l.source_shaped_clusters_range().into());
    let (reshaped_start_run, reshaped_end_run) =
        reshaped_line.map_or((None, None), |l| (l.start_run(), l.end_run()));
    let advance = reshaped_advance.unwrap_or(state.x);

    let start_item_idx = lines.line_items.len();

    // Iterate over the items to commit
    let mut committed_text_run = false;
    // The line's source text range, as the union of the ranges of the text runs committed to it.
    let mut text_range = (usize::MAX, 0);
    // Mark line as needing bidi re-ordering if it contains any runs with non-zero bidi level
    // (zero is the default level, so this is equivalent to marking lines that have multiple levels)
    let mut needs_reorder = false;
    let mut has_spacing = false;
    for run_idx in state.items {
        let shaped_run = &shaped_text.runs()[run_idx];

        /// Commit a reshaped run of the line.
        ///
        /// This will run at most twice per line, and only if the line was actually
        /// reshaped. Therefore, it should be quite cold and we ensure it's not inlined.
        #[cold]
        #[inline(never)]
        fn commit_reshaped_run<B: Brush>(
            data: &LayoutData<B>,
            lines: &mut LineLayout,
            run_idx: usize,
            reshaped_run: u32,
            text_range: &mut (usize, usize),
            committed_text_run: &mut bool,
            needs_reorder: &mut bool,
            has_spacing: &mut bool,
        ) {
            let bidi_level = data.shaped_text.runs()[run_idx].bidi_level;
            let slice = data.reshaped.run_slice(&data.shaped_text, reshaped_run);
            let item_text_range = slice.text_byte_range(slice.char_range());
            text_range.0 = text_range.0.min(item_text_range.start);
            text_range.1 = text_range.1.max(item_text_range.end);
            *committed_text_run = true;
            *needs_reorder |= bidi_level != BidiLevel::new(0);
            *has_spacing |= !data.runs[run_idx].spacing.is_zero();
            lines.line_items.push(LineItemData {
                index: run_idx,
                bidi_level,
                shaped_cluster_range: Range::from(slice.shaped_clusters_range()),
                text_range: Range::from(item_text_range),
                gaps_start: None,
                split_off_by_l1: false,
                reshaped_run: Some(reshaped_run),
            });
        }

        // Compute cluster range
        let mut cluster_range = shaped_run.shaped_clusters_range;
        if run_idx == state.items.start {
            cluster_range.start = source_clusters.start;
            if let Some(reshaped_run) = reshaped_start_run {
                commit_reshaped_run(
                    &layout.data,
                    lines,
                    run_idx,
                    reshaped_run,
                    &mut text_range,
                    &mut committed_text_run,
                    &mut needs_reorder,
                    &mut has_spacing,
                );
            }
        }
        if run_idx + 1 == state.items.end {
            cluster_range.end = source_clusters.end.max(cluster_range.start);
        }

        if !cluster_range.is_empty() {
            committed_text_run = true;

            // Map the shaped cluster range to the source-text range.
            let slice = shaped_text.run_slice(run_idx as u32);
            let char_range = shaped_clusters[cluster_range.start as usize]
                .chars_range()
                .start
                ..shaped_clusters[cluster_range.end as usize - 1]
                    .chars_range()
                    .end;
            let item_text_range = slice.text_byte_range(char_range);

            // Compute the text range for the line
            // Q: Can we not simplify this computation by assuming that items are in order?
            text_range.0 = text_range.0.min(item_text_range.start);
            text_range.1 = text_range.1.max(item_text_range.end);
            needs_reorder |= shaped_run.bidi_level != BidiLevel::new(0);
            has_spacing |= !layout.data.runs[run_idx].spacing.is_zero();

            lines.line_items.push(LineItemData {
                index: run_idx,
                bidi_level: shaped_run.bidi_level,
                shaped_cluster_range: cluster_range,
                text_range: Range::from(item_text_range),
                gaps_start: None,
                split_off_by_l1: false,
                reshaped_run: None,
            });
        }

        if run_idx + 1 == state.items.end
            && let Some(reshaped_run) = reshaped_end_run
        {
            commit_reshaped_run(
                &layout.data,
                lines,
                run_idx,
                reshaped_run,
                &mut text_range,
                &mut committed_text_run,
                &mut needs_reorder,
                &mut has_spacing,
            );
        }
    }

    if needs_reorder {
        reset_trailing_whitespace_bidi_levels(&layout.data, &mut lines.line_items, start_item_idx);
    }

    // let end_run_idx = lines.line_items.last().map(|item| item.index).unwrap_or(0);
    let end_item_idx = lines.line_items.len();

    // Trailing whitespace under `WhiteSpaceCollapse::Preserve` directly preceding a forced break
    // hangs conditionally (CSS Text 4 § 4.3.2): only the part that doesn't fit hangs. Whitespace
    // that fits, stays inside the line box, and counts towards alignment and the layout width. The
    // end of the layout is considered to be a forced line break as well (CSS Text 4 § 5). Other
    // trailing whitespace hangs unconditionally.
    //
    // When a line wrapped (i.e., not because of a forced line break), whitespace always hangs
    // unconditionally. That's equivalent to considering that whitespace to be overflowing fully.
    // Hence an `overflow` of `f32::INFINITY` can be used to model that case.
    let overflow = match break_reason {
        BreakReason::Regular | BreakReason::Emergency => f32::INFINITY,
        BreakReason::Explicit | BreakReason::None => advance - max_advance,
    };
    let (hanging_advance, justification_end_char, hanging_opportunities) = hanging_whitespace(
        layout,
        &lines.line_items[start_item_idx..end_item_idx],
        overflow,
    );
    // The word separators counted as the line was built include the line's hanging whitespace, and
    // hanging whitespace is not stretched by justification.
    let num_justification_opportunities = state.num_word_separators - hanging_opportunities;

    // Reorder the items within the line (if required). Reordering is required if the line contains
    // a mix of bidi levels (a mix of LTR and RTL text)
    if needs_reorder && end_item_idx - start_item_idx > 1 {
        reorder_line_items(&mut lines.line_items[start_item_idx..end_item_idx]);
    }

    lines.lines.push(LineData {
        item_range: Range::from(start_item_idx..end_item_idx),
        text_range: Range::from(text_range.0..text_range.1),
        max_advance,
        break_reason,
        num_justification_opportunities,
        justification: Justification {
            justification_end_char,
            ..Justification::NONE
        },
        has_spacing,
        metrics: LineMetrics {
            indent: line_indent,
            advance,
            hanging_advance,
            ..Default::default()
        },
        aligned_subtree_offsets: Range::default(),
    });

    // Reset state for the new line
    if committed_text_run {
        state.chars.start = state.chars.end;
        state.clusters.start = state.clusters.end;
    }

    // The first item of line N+1 needs to be the SAME as the last item for line N. This is
    // because the item may be split across the two lines with some clusters in line N and some
    // in line N+1. The item is later filtered out (see `continue` in loop above) if there are not
    // actually any clusters in line N+1.
    state.items.start = state.items.end.saturating_sub(1);
}

/// Whether a shaped cluster with the given `characters` is whitespace that hangs past the end of a
/// line.
///
/// Cold and kept out-of-line, as this is called only for overflowing clusters.
#[cold]
#[inline(never)]
fn hangs<B: Brush>(characters: &[Character], styles: &[Style<B>]) -> bool {
    (characters.iter()).all(|c| whitespace_hangs(c.whitespace, &styles[c.style_index as usize]))
}

/// The reshaped clusters starting a line at character index `line_start_char`, if its start needs
/// reshaping.
///
/// See [`LineState::in_reshaped_start`].
#[cold]
#[inline(never)]
fn reshaped_start<'a>(
    reshaper: &'a mut Reshaper,
    text: &str,
    shaped_text: &'a ShapedText,
    line_start_char: u32,
) -> Option<ShapedSlice<'a>> {
    // In our normal line breaking paths, the reshaper will still have this cached.
    (reshaper.measure_start(text, shaped_text, line_start_char, None)).1
}

/// Measure reshaping `line`, returning the pending reshaped line and its advance.
fn reshape_line(
    reshaper: &mut Reshaper,
    text: &str,
    shaped_text: &ShapedText,
    line: &LineState,
) -> (PendingLine<'static>, f32) {
    let (start, start_slice) = reshaper.measure_start(text, shaped_text, line.chars.start, None);
    // We've walked the reshaped start of the line at least partially, and so part of the line's
    // advance delta will already be in `line.x`.
    //
    // The following calculates how much of that delta is already in `line.x`.
    let already_applied_delta = match start_slice {
        // The line ends inside its reshaped start, so we walked only part of it.
        Some(slice) if line.chars.end < slice.char_range().end => {
            let advance = |clusters: &[ShapedCluster]| -> f32 {
                clusters
                    .iter()
                    .take_while(|cluster| cluster.chars_range().start < line.chars.end)
                    .map(|cluster| cluster.advance)
                    .sum()
            };
            advance(slice.shaped_clusters())
                - advance(&shaped_text.shaped_clusters()[line.clusters.start as usize..])
        }
        // We walked the whole reshaped start (including if there is no reshaped start).
        _ => start.advance_delta(),
    };
    let end = reshaper.measure_end(text, shaped_text, line.chars.end, None);
    let pending = reshaper.line(text, shaped_text, &start, &end);
    (
        pending,
        line.x + (pending.advance_delta() - already_applied_delta),
    )
}

/// Whether a line edge at character index `char` needs reshaping. `cluster` is the first shaped
/// cluster starting at or after `char`.
#[inline(always)]
fn edge_is_unsafe_to_break(shaped_text: &ShapedText, char: u32, cluster: u32) -> bool {
    match shaped_text.shaped_clusters().get(cluster as usize) {
        Some(c) => c.chars_range().start != char || !c.is_safe_to_break_before(),
        None => shaped_text.characters().len() as u32 != char,
    }
}

/// Returns the advance of the whitespace hanging past the end of the line made up of `line_items`,
/// the index one past its logically last character that's eligible for justification (see
/// [`Justification::justification_end_char`]), and the number of justification opportunities
/// that are no longer eligible, as they are at or beyond that character.
///
/// `line_items` must be in logical order.
///
/// `overflow` is the advance by which the line's content overflows the available width (including
/// all of its trailing whitespace). Following CSS Text 4 § 9.2, conditionally hanging whitespace
/// only hangs as far as it overflows the available width. Pass [`f32::INFINITY`] to hang
/// conditional whitespace in full.
///
/// See the module-level docs of [`crate::layout::whitespace`] for an explanation of how
/// conditionally and unconditionally hanging whitespace are determined; in short, we can treat the
/// trailing whitespace as being a suffix of conditionally hanging whitespace preceded by
/// unconditionally hanging whitespace (and either can be empty). If the conditionally hanging
/// suffix hangs in full, the unconditionally hanging whitespace hangs in full.
//
// Note: This runs once per line, but it called in the line breaker's per-atom loop. The compiler
// sometimes decides to inline it, which (as of writing) makes the line breaker 5-10% slower.
#[inline(never)]
fn hanging_whitespace<B: Brush>(
    layout: &Layout<B>,
    line_items: &[LineItemData],
    overflow: f32,
) -> (f32, u32, u32) {
    let mut hanging_whitespace_advance = 0.;
    // Atoms with characters before this index may be stretched by justification.
    let mut justification_end_char = u32::MAX;
    let mut hanging_opportunities = 0;
    // Following CSS Text 4 § 4.3.2, a sequence of whitespace with `WhiteSpaceCollapse::Preserve`
    // directly preceding a forced line break hangs conditionally. All other whitespace hangs
    // unconditionally. Note that, in particular, a sequence of `WhiteSpaceCollapse::Preserve`
    // preceding a sequence of unconditionally hanging whitespace, also hangs unconditionally.
    //
    // Conditionally hanging whitespace hangs only as far as it overflows.
    //
    // Following CSS Text 4 § 9.2, unconditionally hanging whitespace before conditionally hanging
    // whitespace, hangs only if the conditionally hanging whitespace hangs in full.
    let mut in_conditional_suffix = true;
    let mut conditional_advance: Option<f32> = None;

    'items: for line_item in line_items.iter().rev() {
        let effective_spacing = EffectiveSpacing::new(
            layout.data.runs[line_item.index].spacing,
            Justification::NONE,
        );
        let slice = line_item.slice(&layout.data);

        for atom in slice.atoms_end().rev() {
            // When line breaking we measured the grapheme with its spacing as a whole. L1
            // reordering may have split the grapheme, in which case we only apply spacing to its
            // first part.
            let continues_grapheme = line_item.split_off_by_l1 && atom.grapheme_continues_before();
            let (hanging, all_hang) = atom_hanging_advance(
                slice,
                &atom,
                &layout.data.styles,
                if continues_grapheme {
                    EffectiveSpacing::new(
                        Spacing {
                            word: 0.,
                            letter: 0.,
                        },
                        Justification::NONE,
                    )
                } else {
                    effective_spacing
                },
            );
            let whitespace = atom.shaped_clusters()[0].whitespace();
            if in_conditional_suffix && whitespace != Whitespace::Newline {
                // The atom hangs from its logical end, so use the last cluster's style to
                // decide whether it hangs conditionally.
                let last_cluster = atom.shaped_clusters().last().unwrap();
                if layout.data.styles[last_cluster.style_index as usize].white_space_collapse
                    == WhiteSpaceCollapse::Preserve
                {
                    *conditional_advance.get_or_insert(0.) += hanging;
                } else {
                    in_conditional_suffix = false;
                    // A conditionally hanging atom that fits (including one with a
                    // non-positive advance) doesn't hang, and so whitespace before it isn't
                    // at the line's end.
                    if conditional_advance
                        .is_some_and(|advance| advance <= 0. || advance > overflow)
                    {
                        break 'items;
                    }
                }
            }
            hanging_whitespace_advance += hanging;
            // Justification can't stretch within an atom, so it stops at the start of the
            // last atom that hangs in its entirety or only partially.
            justification_end_char = atom.char_range().start;
            if !continues_grapheme && is_word_separator(whitespace) {
                hanging_opportunities += 1;
            }
            if !all_hang {
                break 'items;
            }
        }
    }

    if let Some(advance) = conditional_advance {
        hanging_whitespace_advance -= advance - advance.min(overflow).max(0.);
    }

    (
        hanging_whitespace_advance,
        justification_end_char,
        hanging_opportunities,
    )
}

/// Resets the bidi level of the whitespace ending the line made up of `line_items[start..]` to the
/// paragraph level, following [UAX #9 rule L1][l1].
///
/// Bidi reordering will then place that whitespace at the line's end edge.
///
/// As an edge case, this can cause graphemes to be torn apart: for example, a prepend character and
/// whitespace are a grapheme, but may end up visually discontiguous after applying L1. We also
/// don't reshape after this, which technically can cause characters to be kerned against whitespace
/// that's no longer there, and which also means we do not break shaped clusters (so in the rare
/// case only some of a shaped cluster's characters need to be reset, we reset none of them).
///
/// `line_items[start..]` must be in logical order.
///
/// [l1]: https://www.unicode.org/reports/tr9/#L1
#[inline(never)]
#[expect(clippy::cast_possible_truncation, reason = "deferred")]
fn reset_trailing_whitespace_bidi_levels<B: Brush>(
    data: &LayoutData<B>,
    line_items: &mut Vec<LineItemData>,
    start: usize,
) {
    let base_level = data.base_level;
    if (line_items[start..].iter()).all(|item| item.bidi_level == base_level) {
        return;
    }
    for idx in (start..line_items.len()).rev() {
        let item = &line_items[idx];
        let slice = item.slice(data);
        let clusters = slice.shaped_clusters();
        let is_reset = |cluster: &&ShapedCluster| {
            (slice.characters_in(cluster.chars_range()).iter())
                .all(|character| character.flags.is_bidi_reset_at_line_end())
        };
        let content_len = clusters.len() - clusters.iter().rev().take_while(is_reset).count();
        if content_len == 0 {
            // The whole item is whitespace, so whitespace before it ends the line as well.
            line_items[idx].bidi_level = base_level;
            continue;
        }
        if content_len < clusters.len() && item.bidi_level != base_level {
            let split = item.shaped_cluster_range.start + content_len as u32;
            let text = slice
                .text_byte_range(clusters[content_len].chars_range())
                .start;
            let mut whitespace = item.clone();
            whitespace.bidi_level = base_level;
            whitespace.split_off_by_l1 = !clusters[content_len].is_grapheme_start();
            whitespace.shaped_cluster_range.start = split;
            whitespace.text_range.start = text;
            line_items[idx].shaped_cluster_range.end = split;
            line_items[idx].text_range.end = text;
            line_items.insert(idx + 1, whitespace);
        }
        return;
    }
}

/// Reorder items within line according to the bidi levels of the items
fn reorder_line_items(runs: &mut [LineItemData]) {
    let run_count = runs.len();

    // Find the max level and the min *odd* level
    let mut max_level = 0;
    let mut lowest_odd_level = 255;
    for run in runs.iter() {
        let level = run.bidi_level;
        let is_odd = level.to_u8() & 1 != 0;

        // Update max level
        if level.to_u8() > max_level {
            max_level = level.to_u8();
        }

        // Update min odd level
        if is_odd && level.to_u8() < lowest_odd_level {
            lowest_odd_level = level.to_u8();
        }
    }

    // Iterate over bidi levels
    for level in (lowest_odd_level..=max_level).rev() {
        // Iterate over text runs
        let mut i = 0;
        while i < run_count {
            if runs[i].bidi_level.to_u8() >= level {
                let mut end = i + 1;
                while end < run_count && runs[end].bidi_level.to_u8() >= level {
                    end += 1;
                }

                runs[i..end].reverse();
                i = end;
            }
            i += 1;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{BoxMetrics, BreakerState};

    #[test]
    fn subtree_extents_restored_at_break_opportunities() {
        let metrics = BoxMetrics {
            ascent: 6.,
            descent: 2.,
            over: 6.,
            under: 2.,
        };
        for emergency in [false, true] {
            let mut state = BreakerState::default();
            let add_box = |state: &mut BreakerState, baseline_offset| {
                state
                    .line
                    .box_metrics
                    .add_box(1, baseline_offset, metrics, &mut state.subtrees);
            };
            let subtree_height =
                |state: &BreakerState| state.subtrees.current()[0].line_box.height();

            add_box(&mut state, 0.);
            add_box(&mut state, 1.);
            state.mark_line_break_opportunity();
            add_box(&mut state, 4.);
            state.mark_emergency_break_opportunity();
            add_box(&mut state, -4.);
            assert_eq!(state.line.box_metrics.line_height(), 16.);
            assert_eq!(subtree_height(&state), 16.);
            assert_eq!(state.subtrees.current().len(), 1);

            let boundary = if emergency {
                state.emergency_boundary.take().unwrap()
            } else {
                state.prev_boundary.take().unwrap()
            };
            state.reset_to(boundary);
            let expected = if emergency { 12. } else { 9. };
            assert_eq!(state.line.box_metrics.line_height(), expected);
            assert_eq!(subtree_height(&state), expected);
            assert_eq!(state.subtrees.current().len(), 1);
        }
    }
}