gpui-ce 0.3.0

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

/// An [`Element`] that lays out and paints one text string.
///
/// In general, [`Text`] objects should be created via the [`text!`](crate::text!) macro:
/// ```rust
/// # use gpui::*;
/// # fn render() -> impl IntoElement {
/// div().child(text!("hello"))
/// # }
/// ```
/// # IDs and accessibility
///
/// A [`Text`] id identifies its node in the accessibility tree. Screen readers use that node to
/// read the text and to observe later changes.
///
/// Keep the id stable when the text represents the same piece of content. With the same id,
/// AccessKit reports a text update; with a new id, it reports a removed node and a new node.
///
/// When using the [`text!`](crate::text!) macro, each invocation of the macro will get a
/// unique ID, derived from its position in the source code (filename, line, and
/// column). For example:
/// ```rust
/// # use gpui::*;
/// let x = text!("hello");
/// let y = text!("hello");
/// // not equal, because different `text!` invocations produced them
/// assert_ne!(x.id(), y.id());
///
/// fn make_text(s: &str) -> Text { text!(s) }
/// let x = make_text("hello");
/// let y = make_text("hello");
/// // equal, because the same `text!` invocation produced them
/// assert_eq!(x.id(), y.id());
/// ```
/// When the contents do not change, the distinction usually does not matter, but duplicate ids
/// still produce ambiguous accessibility nodes.
///
/// When the argument changes, choose whether that is an update to the existing node or a new
/// piece of content, and keep or change the id accordingly.
#[derive(Debug, Clone)]
pub struct Text {
    id: Option<ElementId>,
    text: SharedString,
}

impl Text {
    /// Create a new [`Text`] element with a specific ID.
    ///
    /// If you want a unique ID to be assigned automatically, use the [`text!`](crate::text!)
    /// macro. The docs for [`Text`] have more detail about choosing IDs.
    #[inline]
    pub const fn new(id: ElementId, text: SharedString) -> Self {
        Self { id: Some(id), text }
    }

    /// Create a new [`Text`] element that is inaccessible to screen readers.
    ///
    /// Text without an id has no accessibility node. Use [`text!`](crate::text!) for a generated
    /// id or [`Text::new`] to choose one.
    ///
    /// Use it for decorative text or text whose parent supplies the accessible representation.
    #[inline]
    pub const fn new_inaccessible(text: SharedString) -> Self {
        Self { id: None, text }
    }

    /// The ID of this [`Text`] element.
    #[inline]
    pub const fn id(&self) -> Option<&ElementId> {
        self.id.as_ref()
    }

    /// Produce a new [`Text`] with the given `id`.
    pub fn with_id(mut self, id: impl Into<ElementId>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// The text that this [`Text`] element will display.
    #[inline]
    pub const fn text(&self) -> &SharedString {
        &self.text
    }
}

impl Deref for Text {
    type Target = SharedString;
    fn deref(&self) -> &Self::Target {
        &self.text
    }
}

impl DerefMut for Text {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.text
    }
}

/// Hashes the source location that the [`text`] macro records.
///
/// This is an implementation detail of the macro. It is not covered by semver
/// guarantees, so don't call it directly. Performance doesn't matter because it
/// runs only on short strings in const contexts.
#[doc(hidden)]
pub const fn __hash_text_macro_location_unstable_do_not_use(s: &'static str) -> u64 {
    const BASIS: u64 = 0xcbf29ce484222325;
    const PRIME: u64 = 0x100000001b3;

    let bytes = s.as_bytes();
    let mut hash = BASIS;
    let mut i = 0;
    while i < bytes.len() {
        hash ^= bytes[i] as u64;
        hash = hash.wrapping_mul(PRIME);
        i += 1;
    }
    hash
}

/// Creates a [`Text`] element that has an ID, so that screen readers can read it.
///
/// Without `id = ...`, the macro derives the ID from the file, line, and column
/// of the call. Two calls on different lines get different IDs, and the same
/// call produces the same ID every time. With `id = ...`, you choose the ID,
/// which is useful when the text must keep its ID even if the code moves.
///
/// Use [`Text::new_inaccessible`] to skip the accessibility node.
///
/// # Examples
///
/// ```rust
/// # use gpui::*;
/// let a = text!("hello");
/// let b = text!(id = "farewell-message", "hello");
/// assert_ne!(a.id(), b.id());
/// ```
///
/// See the docs for [`Text`] for how the ID affects accessibility updates.
#[macro_export]
macro_rules! text {
    (id = $id:expr, $text:expr) => {{ $crate::Text::new($id.into(), $text.into()) }};
    ($text:expr) => {{
        const ID: &'static str = concat!(file!(), "/", line!(), ":", column!());
        const HASH: u64 = $crate::__hash_text_macro_location_unstable_do_not_use(ID);
        $crate::Text::new($crate::ElementId::Integer(HASH), $text.into())
    }};
}

impl IntoElement for Text {
    type Element = Self;
    #[inline]
    fn into_element(self) -> Self::Element {
        self
    }
}

impl Element for Text {
    type RequestLayoutState = TextLayout;
    type PrepaintState = ();

    fn id(&self) -> Option<ElementId> {
        self.id.clone()
    }

    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
        None
    }

    fn a11y_role(&self) -> Option<accesskit::Role> {
        if self.id.is_some() {
            Some(accesskit::Role::Label)
        } else {
            None
        }
    }

    fn write_a11y_info(&self, node: &mut accesskit::Node) {
        node.set_value(self.text.to_string());
    }

    fn request_layout(
        &mut self,
        id: Option<&GlobalElementId>,
        inspector_id: Option<&InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, Self::RequestLayoutState) {
        <SharedString as Element>::request_layout(&mut self.text, id, inspector_id, window, cx)
    }

    fn prepaint(
        &mut self,
        id: Option<&GlobalElementId>,
        inspector_id: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        request_layout: &mut Self::RequestLayoutState,
        window: &mut Window,
        cx: &mut App,
    ) -> Self::PrepaintState {
        <SharedString as Element>::prepaint(
            &mut self.text,
            id,
            inspector_id,
            bounds,
            request_layout,
            window,
            cx,
        )
    }

    fn paint(
        &mut self,
        id: Option<&GlobalElementId>,
        inspector_id: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        request_layout: &mut Self::RequestLayoutState,
        prepaint: &mut Self::PrepaintState,
        window: &mut Window,
        cx: &mut App,
    ) {
        <SharedString as Element>::paint(
            &mut self.text,
            id,
            inspector_id,
            bounds,
            request_layout,
            prepaint,
            window,
            cx,
        );
    }
}

impl Element for &'static str {
    type RequestLayoutState = TextLayout;
    type PrepaintState = ();

    fn id(&self) -> Option<ElementId> {
        None
    }

    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
        None
    }

    fn request_layout(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, Self::RequestLayoutState) {
        let mut state = TextLayout::default();
        let layout_id = state.layout(SharedString::from(*self), None, window, cx);
        (layout_id, state)
    }

    fn prepaint(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        text_layout: &mut Self::RequestLayoutState,
        window: &mut Window,
        _cx: &mut App,
    ) {
        text_layout.prepaint(bounds, self, window)
    }

    fn paint(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        _bounds: Bounds<Pixels>,
        text_layout: &mut TextLayout,
        _: &mut (),
        window: &mut Window,
        cx: &mut App,
    ) {
        text_layout.paint(self, window, cx)
    }
}

impl IntoElement for &'static str {
    type Element = Self;

    fn into_element(self) -> Self::Element {
        self
    }
}

impl IntoElement for String {
    type Element = SharedString;

    fn into_element(self) -> Self::Element {
        self.into()
    }
}

impl IntoElement for Cow<'static, str> {
    type Element = SharedString;

    fn into_element(self) -> Self::Element {
        self.into()
    }
}

impl Element for SharedString {
    type RequestLayoutState = TextLayout;
    type PrepaintState = ();

    fn id(&self) -> Option<ElementId> {
        None
    }

    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
        None
    }

    fn request_layout(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, Self::RequestLayoutState) {
        let mut state = TextLayout::default();
        let layout_id = state.layout(self.clone(), None, window, cx);
        (layout_id, state)
    }

    fn prepaint(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        text_layout: &mut Self::RequestLayoutState,
        window: &mut Window,
        _cx: &mut App,
    ) {
        text_layout.prepaint(bounds, self.as_ref(), window)
    }

    fn paint(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        _bounds: Bounds<Pixels>,
        text_layout: &mut Self::RequestLayoutState,
        _: &mut Self::PrepaintState,
        window: &mut Window,
        cx: &mut App,
    ) {
        text_layout.paint(self.as_ref(), window, cx)
    }
}

impl IntoElement for SharedString {
    type Element = Self;

    fn into_element(self) -> Self::Element {
        self
    }
}

/// Text that is laid out and painted with a different style for each run.
///
/// Use `StyledText` when part of the text needs its own color, weight, font, or
/// decoration. Pass the text to [`StyledText::new`], then add highlights or
/// explicit runs. Text with a single style doesn't need this type. Pass a
/// `&str` or [`SharedString`] to the element tree directly.
///
/// `StyledText` wraps to the width it is given and paints each run with its own
/// [`TextRun`]. Read the laid-out text with [`StyledText::layout`], which returns a
/// [`TextLayout`] for hit testing and measurement.
///
/// # Examples
///
/// ```
/// # use gpui::*;
/// # fn render() -> impl IntoElement {
/// StyledText::new("Warning: disk almost full").with_highlights([(
///     0..8,
///     HighlightStyle {
///         color: Some(hsla(0., 0.8, 0.5, 1.)),
///         font_weight: Some(FontWeight::BOLD),
///         ..Default::default()
///     },
/// )])
/// # }
/// ```
///
/// See [text](crate::_documentation::guides::text) for an overview of text in GPUI.
pub struct StyledText {
    text: SharedString,
    runs: Option<Vec<TextRun>>,
    delayed_highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
    delayed_font_family_overrides: Option<Vec<(Range<usize>, SharedString)>>,
    layout: TextLayout,
}

impl StyledText {
    /// Creates a styled text element for `text`, with no styling beyond the inherited text style.
    ///
    /// Add styling with [`StyledText::with_highlights`], [`StyledText::with_default_highlights`],
    /// [`StyledText::with_runs`], or [`StyledText::with_font_family_overrides`].
    pub fn new(text: impl Into<SharedString>) -> Self {
        StyledText {
            text: text.into(),
            runs: None,
            delayed_highlights: None,
            delayed_font_family_overrides: None,
            layout: TextLayout::default(),
        }
    }

    /// Returns the layout of this element, for mapping between byte indices and pixels.
    ///
    /// The layout is filled in while the element is laid out and prepainted. Its query
    /// methods panic if called before that, so call them from event handlers or after
    /// the frame has been drawn. [`TextLayout`] is cheap to clone and shares its state.
    pub fn layout(&self) -> &TextLayout {
        &self.layout
    }

    /// Styles the text with `default_style`, with `highlights` applied over it.
    ///
    /// The runs are computed now, from `default_style`. Use this when you have a
    /// [`TextStyle`] in hand. Otherwise use [`StyledText::with_highlights`], which
    /// takes the inherited style at layout time.
    ///
    /// Each range must lie on character boundaries inside the text. The ranges must
    /// be sorted by start and must not overlap.
    ///
    /// # Panics
    ///
    /// Panics in debug builds if a range is outside the text, or if this element
    /// already has highlights from [`StyledText::with_highlights`].
    pub fn with_default_highlights(
        mut self,
        default_style: &TextStyle,
        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
    ) -> Self {
        debug_assert!(
            self.delayed_highlights.is_none(),
            "Can't use `with_default_highlights` and `with_highlights`"
        );
        let runs = Self::compute_runs(&self.text, default_style, highlights);
        self.with_runs(runs)
    }

    /// Applies `highlights` over the inherited text style of the element.
    ///
    /// Each highlight is a byte range and a [`HighlightStyle`]. The inherited style
    /// is read from the window when the element is laid out, so a highlight changes
    /// only the properties it sets. Text outside every range keeps the inherited style.
    ///
    /// The ranges must be sorted by start, must not overlap, and must lie on
    /// character boundaries. Debug builds check that each range is inside the text.
    /// Release builds don't check, and unsorted ranges give wrong layouts or panic.
    ///
    /// # Examples
    ///
    /// ```
    /// # use gpui::*;
    /// # fn render() -> impl IntoElement {
    /// StyledText::new("Press Enter to save").with_highlights([(
    ///     6..11,
    ///     HighlightStyle {
    ///         font_weight: Some(FontWeight::BOLD),
    ///         ..Default::default()
    ///     },
    /// )])
    /// # }
    /// ```
    pub fn with_highlights(
        mut self,
        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
    ) -> Self {
        debug_assert!(
            self.runs.is_none(),
            "Can't use `with_highlights` and `with_default_highlights`"
        );
        self.delayed_highlights = Some(
            highlights
                .into_iter()
                .inspect(|(run, _)| {
                    debug_assert!(self.text.contains_range(run));
                })
                .collect::<Vec<_>>(),
        );
        self
    }

    fn compute_runs(
        text: &str,
        default_style: &TextStyle,
        highlights: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
    ) -> Vec<TextRun> {
        let mut runs = Vec::new();
        let mut ix = 0;
        for (range, highlight) in highlights {
            debug_assert!(text.contains_range(&range));

            if ix < range.start {
                runs.push(default_style.clone().to_run(range.start - ix));
            }
            runs.push(
                default_style
                    .clone()
                    .highlight(highlight)
                    .to_run(range.len()),
            );
            ix = range.end;
        }
        if ix < text.len() {
            runs.push(default_style.to_run(text.len() - ix));
        }
        runs
    }

    /// Sets the font family for byte ranges of the text.
    ///
    /// The family is applied at layout time, on top of the inherited style. An
    /// override changes the family of a run only when that run lies entirely
    /// inside the override's range. Runs are split only at highlight boundaries,
    /// so to make an override cover part of the text, add a highlight at each
    /// edge of the range. Can be combined with [`with_highlights`](Self::with_highlights).
    ///
    /// The overrides must be sorted by range start and non-overlapping.
    /// Each override range must fall on character boundaries.
    pub fn with_font_family_overrides(
        mut self,
        overrides: impl IntoIterator<Item = (Range<usize>, SharedString)>,
    ) -> Self {
        self.delayed_font_family_overrides = Some(
            overrides
                .into_iter()
                .inspect(|(range, _)| {
                    debug_assert!(self.text.contains_range(range));
                })
                .collect(),
        );
        self
    }

    fn apply_font_family_overrides(
        runs: &mut [TextRun],
        overrides: &[(Range<usize>, SharedString)],
    ) {
        let mut byte_offset = 0;
        let mut override_idx = 0;
        for run in runs.iter_mut() {
            let run_end = byte_offset + run.len;
            while override_idx < overrides.len() && overrides[override_idx].0.end <= byte_offset {
                override_idx += 1;
            }
            if override_idx < overrides.len() {
                let (ref range, ref family) = overrides[override_idx];
                if byte_offset >= range.start && run_end <= range.end {
                    run.font.family = family.clone();
                }
            }
            byte_offset = run_end;
        }
    }

    fn take_runs(&mut self, default_style: &TextStyle) -> Vec<TextRun> {
        let font_family_overrides = self.delayed_font_family_overrides.take();
        let mut runs = self.runs.take().or_else(|| {
            self.delayed_highlights.take().map(|delayed_highlights| {
                Self::compute_runs(&self.text, default_style, delayed_highlights)
            })
        });

        if let Some(ref overrides) = font_family_overrides {
            let runs = runs.get_or_insert_with(|| vec![default_style.to_run(self.text.len())]);
            Self::apply_font_family_overrides(runs, overrides);
        }

        runs.unwrap_or_else(|| vec![default_style.to_run(self.text.len())])
    }

    /// Sets the runs that style the text. Each run gives its byte length and its [`TextRun`].
    ///
    /// The run lengths must add up to the length of the text exactly, and each run
    /// must end on a character boundary.
    ///
    /// # Panics
    ///
    /// Panics if the runs don't cover the text exactly, or if a run ends inside a
    /// character. In debug builds the message includes the text and the run.
    pub fn with_runs(mut self, runs: Vec<TextRun>) -> Self {
        let mut text = &*self.text;
        for run in &runs {
            text = text.get(run.len..).unwrap_or_else(|| {
                #[cfg(debug_assertions)]
                panic!("invalid text run. Text: '{text}', run: {run:?}");
                #[cfg(not(debug_assertions))]
                panic!("invalid text run");
            });
        }
        assert!(text.is_empty(), "invalid text run");
        self.runs = Some(runs);
        self
    }
}

impl Element for StyledText {
    type RequestLayoutState = ();
    type PrepaintState = ();

    fn id(&self) -> Option<ElementId> {
        None
    }

    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
        None
    }

    fn request_layout(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, Self::RequestLayoutState) {
        let runs = self.take_runs(&window.text_style());
        let layout_id = self
            .layout
            .layout(self.text.clone(), Some(runs), window, cx);
        (layout_id, ())
    }

    fn prepaint(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        _: &mut Self::RequestLayoutState,
        window: &mut Window,
        _cx: &mut App,
    ) {
        self.layout.prepaint(bounds, &self.text, window)
    }

    fn paint(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        _bounds: Bounds<Pixels>,
        _: &mut Self::RequestLayoutState,
        _: &mut Self::PrepaintState,
        window: &mut Window,
        cx: &mut App,
    ) {
        self.layout.paint(&self.text, window, cx)
    }
}

impl IntoElement for StyledText {
    type Element = Self;

    fn into_element(self) -> Self::Element {
        self
    }
}

/// The laid-out state of a text element, for mapping between byte indices and pixels.
///
/// Get one from [`StyledText::layout`], or from the text state that other text
/// elements keep. Clones share the same state. The query methods read the most
/// recent layout, so a query made after a relayout returns the new result.
///
/// The text elements fill this in during layout and prepaint. The query methods
/// panic if the element hasn't been laid out yet, and the ones that need pixel
/// positions panic if it hasn't been prepainted.
#[derive(Default, Clone)]
pub struct TextLayout(Rc<TextLayoutState>);

#[derive(Default)]
struct TextLayoutState {
    layout_id: Cell<Option<LayoutId>>,
    layout: RefCell<Option<TextLayoutInner>>,
}

#[derive(Clone, Copy)]
enum TextPaintPass {
    All,
    Background,
    Foreground,
}

struct TextLayoutInner {
    len: usize,
    document: Option<ShapedText>,
    line_height: Pixels,
    truncate_width: Option<Pixels>,
    options: TextLayoutOptions,
    size: Size<Pixels>,
    bounds: Option<Bounds<Pixels>>,
}

fn apply_text_transform_preserving_byte_len(
    text: SharedString,
    transform: Option<TextTransform>,
) -> SharedString {
    let Some(transform) = transform else {
        return text;
    };
    if matches!(transform, TextTransform::None) {
        return text;
    }

    let mut output = String::with_capacity(text.len());
    match transform {
        TextTransform::Uppercase => {
            for character in text.as_ref().chars() {
                push_case_mapped_character(&mut output, character, CaseMapKind::Upper);
            }
        }
        TextTransform::Lowercase => {
            for character in text.as_ref().chars() {
                push_case_mapped_character(&mut output, character, CaseMapKind::Lower);
            }
        }
        TextTransform::Capitalize => {
            for piece in text.as_ref().split_word_bounds() {
                let mut seen_first_letter = false;
                for character in piece.chars() {
                    if !seen_first_letter && character.is_alphabetic() {
                        push_case_mapped_character(&mut output, character, CaseMapKind::Upper);
                        seen_first_letter = true;
                    } else {
                        output.push(character);
                    }
                }
            }
        }
        TextTransform::None => return text,
    }

    SharedString::from(output)
}

#[derive(Copy, Clone)]
enum CaseMapKind {
    Upper,
    Lower,
}

fn push_case_mapped_character(output: &mut String, character: char, kind: CaseMapKind) {
    let mapped = match kind {
        CaseMapKind::Upper => character.to_uppercase().collect::<String>(),
        CaseMapKind::Lower => character.to_lowercase().collect::<String>(),
    };

    if mapped.len() == character.len_utf8() && mapped.chars().count() == 1 {
        output.push_str(&mapped);
    } else {
        output.push(character);
    }
}

#[cfg(test)]
mod text_transform_tests {
    use super::apply_text_transform_preserving_byte_len;
    use crate::{SharedString, TextTransform};

    #[test]
    fn text_transforms_preserve_bytes_and_spacing() {
        let input = SharedString::from("hello   WORLD\tfoo-bar 123baz déjà vu");
        let uppercase =
            apply_text_transform_preserving_byte_len(input.clone(), Some(TextTransform::Uppercase));
        let lowercase =
            apply_text_transform_preserving_byte_len(input.clone(), Some(TextTransform::Lowercase));
        let capitalize = apply_text_transform_preserving_byte_len(
            input.clone(),
            Some(TextTransform::Capitalize),
        );

        assert_eq!(uppercase.as_ref(), "HELLO   WORLD\tFOO-BAR 123BAZ DÉJÀ VU");
        assert_eq!(lowercase.as_ref(), "hello   world\tfoo-bar 123baz déjà vu");
        assert_eq!(capitalize.as_ref(), "Hello   WORLD\tFoo-Bar 123Baz Déjà Vu");
        assert_eq!(input.len(), uppercase.len());
        assert_eq!(input.len(), lowercase.len());
        assert_eq!(input.len(), capitalize.len());
    }

    #[test]
    fn text_transforms_skip_expanding_unicode_mappings() {
        let input = SharedString::from("straße İSTANBUL");
        let uppercase =
            apply_text_transform_preserving_byte_len(input.clone(), Some(TextTransform::Uppercase));
        let lowercase =
            apply_text_transform_preserving_byte_len(input.clone(), Some(TextTransform::Lowercase));

        assert_eq!(uppercase.as_ref(), "STRAßE İSTANBUL");
        assert_eq!(lowercase.as_ref(), "straße İstanbul");
        assert_eq!(input.len(), uppercase.len());
        assert_eq!(input.len(), lowercase.len());
    }

    #[test]
    fn capitalize_preserves_letters_after_digit_prefix() {
        let input = SharedString::from("123BAZ");
        let output = apply_text_transform_preserving_byte_len(
            input.clone(),
            Some(TextTransform::Capitalize),
        );
        assert_eq!(output.as_ref(), "123BAZ");
        assert_eq!(input.len(), output.len());
    }

    #[test]
    fn capitalize_does_not_fold_remaining_letters() {
        let input = SharedString::from("foo2BAR");
        let output =
            apply_text_transform_preserving_byte_len(input, Some(TextTransform::Capitalize));
        assert_eq!(output.as_ref(), "Foo2BAR");
    }

    #[test]
    fn capitalize_handles_apostrophe_contractions() {
        let input = SharedString::from("don't panic");
        let output =
            apply_text_transform_preserving_byte_len(input, Some(TextTransform::Capitalize));
        assert_eq!(output.as_ref(), "Don't Panic");
    }
}

/// The part of an overflowing line that is removed and replaced by the affix.
///
/// The variants correspond to [`TextOverflow::Truncate`], [`TextOverflow::TruncateStart`],
/// and [`TextOverflow::TruncateMiddle`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TruncateFrom {
    /// Remove text from the start, keeping the end visible.
    Start,
    /// Remove text from the end, keeping the start visible.
    End,
    /// Remove text from the middle, keeping both ends visible.
    Middle,
}

/// How a text element should truncate its text to fit, computed during layout.
///
/// [`TextLayout::evaluate_overflow`] creates this from the [`TextStyle`]'s
/// `text_overflow`. Pass it to [`TextLayout::apply_truncation`] to get the
/// shortened text.
pub struct TextLayoutTruncation {
    /// The width that each visual line can occupy before it is truncated, or `None` for no limit.
    pub width: Option<Pixels>,
    /// The text to show in place of the removed text, such as `"…"`.
    pub affix: SharedString,
    /// The side of the text that is removed when it doesn't fit.
    pub source: TruncateFrom,
}

impl TextLayoutTruncation {
    /// Creates a truncation by using the overflow as the affix, given the provided width.
    fn overflow_width(text_overflow: TextOverflow, width: Option<Pixels>) -> Self {
        let (affix, source) = match text_overflow {
            TextOverflow::Truncate(affix) => (affix, TruncateFrom::End),
            TextOverflow::TruncateStart(affix) => (affix, TruncateFrom::Start),
            TextOverflow::TruncateMiddle(affix) => (affix, TruncateFrom::Middle),
        };

        Self {
            width,
            affix,
            source,
        }
    }
}

impl TextLayout {
    /// Returns the width that text wraps at, or `None` when it doesn't wrap.
    ///
    /// Text does not wrap when `white_space` is [`WhiteSpace::Nowrap`]. Otherwise
    /// the width comes from [`TextLayout::evaluate_alignment_width`].
    pub fn evaluate_wrap_width(
        white_space: &WhiteSpace,
        known_dimensions: Size<Option<Pixels>>,
        available_space: Size<crate::AvailableSpace>,
    ) -> Option<Pixels> {
        match white_space {
            WhiteSpace::Nowrap => None,
            WhiteSpace::Normal => known_dimensions.width.or(match available_space.width {
                crate::AvailableSpace::Definite(width) => Some(width),
                // Wrap at every opportunity, so the min-content width is the longest unbreakable run.
                crate::AvailableSpace::MinContent => Some(Pixels::ZERO),
                crate::AvailableSpace::MaxContent => None,
            }),
        }
    }

    /// Returns the width that text aligns within, from the known or available width.
    ///
    /// The known width wins. Otherwise a definite available width is used. Under
    /// min-content or max-content sizing, this returns `None`.
    pub fn evaluate_alignment_width(
        known_dimensions: Size<Option<Pixels>>,
        available_space: Size<crate::AvailableSpace>,
    ) -> Option<Pixels> {
        known_dimensions.width.or(match available_space.width {
            crate::AvailableSpace::Definite(width) => Some(width),
            crate::AvailableSpace::MinContent | crate::AvailableSpace::MaxContent => None,
        })
    }

    /// Returns how the text should be truncated, from the style's `text_overflow`.
    ///
    /// When the style has no `text_overflow`, the result has no width and an empty affix,
    /// so the text is never truncated.
    pub fn evaluate_overflow(
        text_style: &TextStyle,
        known_dimensions: Size<Option<Pixels>>,
        available_space: Size<crate::AvailableSpace>,
    ) -> TextLayoutTruncation {
        match text_style.text_overflow.clone() {
            Some(text_overflow) => {
                // Overflow is checked against each visual row's available width.
                let width = Self::evaluate_alignment_width(known_dimensions, available_space);

                TextLayoutTruncation::overflow_width(text_overflow, width)
            }
            None => TextLayoutTruncation {
                width: None,
                affix: SharedString::default(),
                source: TruncateFrom::End,
            },
        }
    }

    pub(crate) fn layout_options(
        text_style: &TextStyle,
        known_dimensions: Size<Option<Pixels>>,
        available_space: Size<crate::AvailableSpace>,
        resolved_direction: crate::ResolvedDirection,
        unicode_bidi: UnicodeBidi,
    ) -> (TextLayoutOptions, TextLayoutTruncation) {
        let alignment_width = Self::evaluate_alignment_width(known_dimensions, available_space);
        let direction = match unicode_bidi {
            UnicodeBidi::Plaintext => ParagraphDirection::Auto,
            _ => resolved_direction.into(),
        };
        let options = TextLayoutOptions {
            wrap_width: match text_style.white_space {
                WhiteSpace::Normal => alignment_width,
                WhiteSpace::Nowrap => None,
            },
            line_clamp: text_style.line_clamp,
            alignment_width,
            text_align: text_style.text_align,
            direction,
            unicode_bidi,
        };
        let truncation = Self::evaluate_overflow(text_style, known_dimensions, available_space);

        (options, truncation)
    }

    /// Shortens `text` so that it fits `truncation.width`, and returns the text to display.
    ///
    /// When `truncation.width` is `None`, the text and runs come back unchanged. Otherwise
    /// the removed part is replaced by `truncation.affix`, on the side given by
    /// `truncation.source`. Wrapping and `line_clamp` from `text_style` still apply.
    /// The returned runs match the returned text. They borrow `runs` when nothing changes.
    pub fn apply_truncation<'runs>(
        text: SharedString,
        text_style: &TextStyle,
        font_size: Pixels,
        line_height: Pixels,
        wrap_width: Option<Pixels>,
        truncation: &TextLayoutTruncation,
        runs: &'runs [TextRun],
        paragraph_direction: ParagraphDirection,
        unicode_bidi: UnicodeBidi,
        window: &mut Window,
        cx: &mut App,
    ) -> (SharedString, Cow<'runs, [TextRun]>) {
        let _ = (line_height, cx);
        let Some(truncate_width) = truncation.width else {
            return (text, Cow::Borrowed(runs));
        };
        truncate_to_shaped_layout(
            text,
            font_size,
            wrap_width,
            truncate_width,
            text_style.line_clamp,
            &truncation.affix,
            runs,
            truncation.source,
            paragraph_direction,
            unicode_bidi,
            window,
        )
    }

    fn layout(
        &self,
        text: SharedString,
        runs: Option<Vec<TextRun>>,
        window: &mut Window,
        _: &mut App,
    ) -> LayoutId {
        /// What the text's size depends on, besides the space it gets, and its layout.
        struct TextKey {
            text: SharedString,
            runs: Arc<[TextRun]>,
            text_style: TextStyle,
            font_size: Pixels,
            line_height: Pixels,
            font_generation: u64,
            state: TextLayout,
        }

        impl crate::taffy::MeasureKey for TextKey {
            fn same(&self, previous: &dyn crate::taffy::MeasureKey) -> bool {
                previous
                    .as_any()
                    .downcast_ref::<Self>()
                    .is_some_and(|previous| {
                        self.text == previous.text
                            && self.runs == previous.runs
                            && self.text_style == previous.text_style
                            && self.font_size == previous.font_size
                            && self.line_height == previous.line_height
                            && self.font_generation == previous.font_generation
                    })
            }

            fn inherit(&self, previous: &dyn crate::taffy::MeasureKey) -> bool {
                let Some(previous) = previous.as_any().downcast_ref::<Self>() else {
                    return false;
                };
                let layout =
                    previous
                        .state
                        .0
                        .layout
                        .borrow()
                        .as_ref()
                        .map(|layout| TextLayoutInner {
                            document: layout.document.as_ref().map(|document| ShapedText {
                                layout: document.layout.clone(),
                                text: document.text.clone(),
                            }),
                            bounds: None,
                            ..*layout
                        });
                let measured = layout.is_some();
                *self.state.0.layout.borrow_mut() = layout;
                measured
            }

            fn as_any(&self) -> &dyn std::any::Any {
                self
            }
        }

        let text_style = window.text_style();
        let text = apply_text_transform_preserving_byte_len(text, text_style.text_transform);
        let font_size = text_style.font_size.to_pixels(window.rem_size());
        let line_height = window.pixel_snap(
            text_style
                .line_height
                .to_pixels(font_size.into(), window.rem_size()),
        );

        let runs = if let Some(runs) = runs {
            runs
        } else {
            vec![text_style.to_run(text.len())]
        };

        let runs: Arc<[TextRun]> = runs.into();
        let content = crate::InlineContent::Text {
            text: text.clone(),
            runs: runs.clone(),
            font_size,
            line_height,
        };

        let key = TextKey {
            text: text.clone(),
            runs: runs.clone(),
            text_style: text_style.clone(),
            font_size,
            line_height,
            font_generation: window.text_system().font_generation(),
            state: self.clone(),
        };
        let layout_id = window.request_keyed_measured_layout(Default::default(), key, {
            let element_state = self.clone();

            move |known_dimensions, available_space, window, cx| {
                let unicode_bidi = window.resolved_unicode_bidi();
                let (options, truncation) = Self::layout_options(
                    &text_style,
                    known_dimensions,
                    available_space,
                    window.resolved_direction(),
                    unicode_bidi,
                );
                let truncate_width = truncation.width;

                // Only use cached layout if:
                // 1. truncate_width is None (if truncate_width is Some, we need to re-layout
                //    because the previous layout may have been computed without truncation)
                // 2. the cached layout was not truncated (a truncated layout answers an
                //    unconstrained probe with the truncated size, which poisons intrinsic
                //    sizing with whatever width some earlier measure pass happened to use)
                // 3. the complete layout options match.
                if let Some(text_layout) = element_state.0.layout.borrow().as_ref()
                    && truncate_width.is_none()
                    && text_layout.truncate_width.is_none()
                    && text_layout.options == options
                {
                    return text_layout.size;
                }

                let (text, runs) = Self::apply_truncation(
                    text.clone(),
                    &text_style,
                    font_size,
                    line_height,
                    options.wrap_width,
                    &truncation,
                    &runs,
                    options.direction,
                    options.unicode_bidi,
                    window,
                    cx,
                );
                let document = window
                    .text_system()
                    .shape_text_with_options(text, font_size, &runs, options)
                    .log_err();

                let size = document
                    .as_ref()
                    .map_or_else(Size::default, |document| document.size(line_height));

                let len = document
                    .as_ref()
                    .map(|document| document.len())
                    .unwrap_or_default();

                element_state
                    .0
                    .layout
                    .borrow_mut()
                    .replace(TextLayoutInner {
                        document,
                        len,
                        line_height,
                        truncate_width,
                        options,
                        size,
                        bounds: None,
                    });

                size
            }
        });

        window.publish_inline_content(layout_id, content);
        self.0.layout_id.set(Some(layout_id));
        layout_id
    }

    fn prepaint(&self, bounds: Bounds<Pixels>, text: &str, window: &mut Window) {
        if window.current_inline_fragments.is_some() {
            return;
        }

        let bounds = self
            .0
            .layout_id
            .get()
            .map(|layout_id| window.parent_relative_layout_bounds(layout_id))
            .unwrap_or(bounds);
        let mut element_state = self.0.layout.borrow_mut();
        let element_state = element_state
            .as_mut()
            .with_context(|| format!("measurement has not been performed on {text}"))
            .unwrap();
        element_state.bounds = Some(bounds);
    }

    fn paint(&self, text: &str, window: &mut Window, cx: &mut App) {
        if window.current_inline_fragments.is_some() {
            return;
        }

        self.paint_lines(TextPaintPass::All, window, cx)
            .with_context(|| format!("failed to paint {text}"))
            .unwrap();
    }

    /// Paints the backgrounds of the text runs without the glyphs, so callers can paint
    /// content such as highlights between the backgrounds and text.
    pub fn paint_background(&self, window: &mut Window, cx: &mut App) -> anyhow::Result<()> {
        self.paint_lines(TextPaintPass::Background, window, cx)
    }

    /// Paints the glyphs and decorations without the run backgrounds.
    pub fn paint_foreground(&self, window: &mut Window, cx: &mut App) -> anyhow::Result<()> {
        self.paint_lines(TextPaintPass::Foreground, window, cx)
    }

    fn paint_lines(
        &self,
        pass: TextPaintPass,
        window: &mut Window,
        cx: &mut App,
    ) -> anyhow::Result<()> {
        let element_state = self.0.layout.borrow();
        let element_state = element_state
            .as_ref()
            .context("measurement has not been performed")?;
        let bounds = element_state
            .bounds
            .context("prepaint has not been performed")?;

        let line_height = element_state.line_height;
        if let Some(document) = &element_state.document {
            if matches!(pass, TextPaintPass::All | TextPaintPass::Background) {
                document
                    .paint_background(
                        bounds.origin,
                        line_height,
                        TextAlign::Left,
                        None,
                        window,
                        cx,
                    )
                    .log_err();
            }
            if matches!(pass, TextPaintPass::All | TextPaintPass::Foreground) {
                document
                    .paint(
                        bounds.origin,
                        line_height,
                        TextAlign::Left,
                        None,
                        window,
                        cx,
                    )
                    .log_err();
            }
        }
        Ok(())
    }

    fn measured(&self) -> Ref<'_, TextLayoutInner> {
        Ref::map(self.0.layout.borrow(), |layout| {
            layout.as_ref().expect("measurement has not been performed")
        })
    }

    /// Returns the UTF-8 byte index of the character at `pixel_point`, in window coordinates.
    ///
    /// Returns `Ok` with the index of the character under the point. Returns `Err`
    /// with `0` when the point is above the text. Points to the side of or below the
    /// text return `Err` with the closest index. Use this for hit testing, such as
    /// placing a caret on click.
    ///
    /// # Panics
    ///
    /// Panics if the element hasn't been laid out or prepainted.
    pub fn index_for_position(&self, pixel_point: Point<Pixels>) -> Result<usize, usize> {
        let element_state = self.measured();
        let bounds = element_state
            .bounds
            .expect("prepaint has not been performed");

        if pixel_point.y < bounds.top() {
            return Err(0);
        }

        let line_height = element_state.line_height;
        let Some(document) = &element_state.document else {
            return Err(0);
        };

        document.byte_index_for_pixel_point(pixel_point - bounds.origin, line_height)
    }

    /// Returns the top-left corner of the caret for `byte_index`, in window coordinates.
    ///
    /// Returns `None` if the text has no shaped layout, or if `byte_index` is past the end
    /// of the text. Use this to place a caret or an overlay at a position in the text.
    ///
    /// # Panics
    ///
    /// Panics if the element hasn't been laid out or prepainted.
    pub fn position_for_index(&self, byte_index: usize) -> Option<Point<Pixels>> {
        let element_state = self.measured();
        let bounds = element_state
            .bounds
            .expect("prepaint has not been performed");
        let line_height = element_state.line_height;

        let document = element_state.document.as_ref()?;
        Some(bounds.origin + document.visual_position_for_byte_index(byte_index, line_height)?)
    }

    /// Returns the shaped layout of the text, or `None` if `index` is past the end or the
    /// text has not been shaped.
    ///
    /// The layout covers the whole text, not one visual line or paragraph.
    /// Use [`TextLayout::line_layouts`] to get every layout in source order.
    ///
    /// # Panics
    ///
    /// Panics if the element hasn't been laid out.
    pub fn line_layout_for_index(&self, index: usize) -> Option<Arc<ShapedTextLayout>> {
        let element_state = self.measured();
        let document = element_state.document.as_ref()?;
        (index <= document.len()).then(|| document.layout.clone())
    }

    /// Returns the shaped layout of the text as a collection with one entry.
    ///
    /// This returns an empty collection if the text has not been shaped.
    ///
    /// # Panics
    ///
    /// Panics if the element hasn't been laid out.
    pub fn line_layouts(&self) -> SmallVec<[Arc<ShapedTextLayout>; 1]> {
        self.measured()
            .document
            .iter()
            .map(|document| document.layout.clone())
            .collect()
    }

    /// Returns the window bounds of the element, as set during prepaint.
    ///
    /// # Panics
    ///
    /// Panics if the element hasn't been prepainted.
    pub fn bounds(&self) -> Bounds<Pixels> {
        self.measured().bounds.unwrap()
    }

    /// Returns the line height that the text is laid out with, in logical pixels.
    ///
    /// # Panics
    ///
    /// Panics if the element hasn't been laid out.
    pub fn line_height(&self) -> Pixels {
        self.measured().line_height
    }

    /// Returns the length of the shaped text in UTF-8 bytes.
    ///
    /// This is the length after any text transform or truncation. It is `0`
    /// when the text has not been shaped.
    ///
    /// # Panics
    ///
    /// Panics if the element hasn't been laid out.
    pub fn len(&self) -> usize {
        self.measured().len
    }

    /// Returns the text that was shaped, as a `String`.
    ///
    /// This is the text after any [`TextTransform`] and truncation. A truncated
    /// text includes the affix, such as an ellipsis. It returns an empty string if
    /// the text has not been shaped.
    ///
    /// # Panics
    ///
    /// Panics if the element hasn't been laid out.
    pub fn text(&self) -> String {
        self.measured()
            .document
            .as_ref()
            .map_or_else(String::new, |document| document.text.to_string())
    }

    /// Returns the shaped text with each visual line followed by a `\n`, except the last.
    ///
    /// Soft wraps therefore become `\n`. A hard line break keeps its own `\n` as part of
    /// its line, so it is followed by one more `\n`. Use this to copy wrapped text as it
    /// appears on screen.
    ///
    /// # Panics
    ///
    /// Panics if the element hasn't been laid out.
    pub fn wrapped_text(&self) -> String {
        let mut accumulator = String::new();
        let element_state = self.measured();

        if let Some(document) = &element_state.document {
            for visual_line in document.layout.visual_lines() {
                accumulator.push_str(&document.text[visual_line.text_range.clone()]);
                accumulator.push('\n');
            }
        }
        // Remove trailing newline
        accumulator.pop();
        accumulator
    }
}

fn truncate_to_shaped_layout<'a>(
    text: SharedString,
    font_size: Pixels,
    wrap_width: Option<Pixels>,
    truncate_width: Pixels,
    max_lines: Option<usize>,
    affix: &str,
    runs: &'a [TextRun],
    direction: TruncateFrom,
    paragraph_direction: ParagraphDirection,
    unicode_bidi: UnicodeBidi,
    window: &mut Window,
) -> (SharedString, Cow<'a, [TextRun]>) {
    let options = TextLayoutOptions {
        wrap_width,
        direction: paragraph_direction,
        unicode_bidi,
        text_align: TextAlign::Left,
        ..Default::default()
    };
    let Ok(document) =
        window
            .text_system()
            .shape_text_with_options(text.clone(), font_size, runs, options)
    else {
        return (text, Cow::Borrowed(runs));
    };
    let width = wrap_width.unwrap_or(truncate_width);
    let fits = text_layout_fits(&document.layout.layout, width, max_lines);

    if fits {
        return (text, Cow::Borrowed(runs));
    }

    let mut boundaries = text
        .grapheme_indices(true)
        .map(|(index, _)| index)
        .collect::<Vec<_>>();
    boundaries.push(text.len());
    let grapheme_count = boundaries.len().saturating_sub(1);
    let grapheme_ranges = boundaries
        .windows(2)
        .map(|boundary| boundary[0]..boundary[1])
        .collect::<Vec<_>>();
    let grapheme_widths = document
        .platform_layout
        .inline_geometry_for_ranges(&grapheme_ranges)
        .into_iter()
        .map(|regions| {
            regions
                .into_iter()
                .map(|geometry| geometry.bounds.size.width)
                .sum::<Pixels>()
        })
        .collect::<Vec<_>>();
    let mut prefix_widths = Vec::with_capacity(grapheme_widths.len() + 1);
    prefix_widths.push(Pixels::ZERO);
    for width in &grapheme_widths {
        prefix_widths.push(prefix_widths.last().copied().unwrap_or_default() + *width);
    }

    let affix_width = if affix.is_empty() {
        Pixels::ZERO
    } else {
        let candidate = make_truncation_candidate(
            &text,
            &TruncationBoundaries::new(boundaries.iter().copied(), grapheme_count),
            0,
            affix,
            runs,
            direction,
        );

        window
            .text_system()
            .shape_text_with_options(
                SharedString::from(affix),
                font_size,
                &candidate.runs,
                TextLayoutOptions {
                    wrap_width: None,
                    ..options
                },
            )
            .map_or(Pixels::ZERO, |layout| layout.width())
    };
    let available_width = (width - affix_width).max(Pixels::ZERO);

    let keep = if direction == TruncateFrom::End
        && let (Some(wrap_width), Some(max_lines)) = (wrap_width, max_lines)
    {
        let last_line_idx = max_lines.max(1).saturating_sub(1);
        let line_start = document
            .visual_lines()
            .get(last_line_idx)
            .map_or(0, |line| line.text_range.start);
        let fixed_count = grapheme_ranges.partition_point(|range| range.end <= line_start);
        fixed_count
            + grapheme_widths[fixed_count..]
                .iter()
                .scan(Pixels::ZERO, |used, advance| {
                    *used += *advance;
                    Some(*used <= (wrap_width - affix_width).max(Pixels::ZERO))
                })
                .take_while(|fits| *fits)
                .count()
    } else {
        (0..grapheme_count)
            .take_while(|keep| {
                let candidate_count = keep + 1;
                let width: Pixels = match direction {
                    TruncateFrom::End => prefix_widths[candidate_count],
                    TruncateFrom::Start => {
                        prefix_widths[grapheme_count]
                            - prefix_widths[grapheme_count - candidate_count]
                    }
                    TruncateFrom::Middle => {
                        let front_count = candidate_count.saturating_mul(2).div_ceil(3);
                        let back_count = candidate_count - front_count;
                        prefix_widths[front_count] + prefix_widths[grapheme_count]
                            - prefix_widths[grapheme_count - back_count]
                    }
                };

                width <= available_width
            })
            .count()
    };

    let (candidate, ()) = truncate_with_measured_candidates(
        &text,
        boundaries.iter().copied(),
        Some(keep),
        affix,
        runs,
        direction,
        |candidate| {
            let fits = window
                .text_system()
                .shape_text_with_options(
                    candidate.text.clone(),
                    font_size,
                    &candidate.runs,
                    options,
                )
                .is_ok_and(|document| text_layout_fits(&document.layout.layout, width, max_lines));

            ((), fits)
        },
    );

    (candidate.text, Cow::Owned(candidate.runs))
}

pub(crate) fn text_layout_fits(
    layout: &LineLayout,
    width: Pixels,
    max_lines: Option<usize>,
) -> bool {
    max_lines.is_none_or(|count| layout.platform_layout.line_count() <= count.max(1))
        && layout.platform_layout.size().width <= width + px(0.01)
}

pub(crate) struct TruncationCandidate {
    pub text: SharedString,
    pub runs: Vec<TextRun>,
    retained: SmallVec<[(Range<usize>, usize); 2]>,
    affix_range: Range<usize>,
    affix_source: usize,
}

impl TruncationCandidate {
    pub(crate) fn display_ranges(&self, source: &Range<usize>) -> SmallVec<[Range<usize>; 3]> {
        let mut ranges: SmallVec<[Range<usize>; 3]> = SmallVec::new();

        for (retained, display_start) in &self.retained {
            let start = source.start.max(retained.start);
            let end = source.end.min(retained.end);

            if start < end {
                ranges.push(
                    start - retained.start + display_start..end - retained.start + display_start,
                );
            }
        }

        if source.contains(&self.affix_source) && !self.affix_range.is_empty() {
            ranges.push(self.affix_range.clone());
        }

        ranges.sort_by_key(|range| range.start);

        ranges
    }
}

/// Keeps independent prefix and suffix iterators because middle truncation moves
/// their cuts in opposite directions. Narrowing them with the candidate search
/// limits rescanning without collecting offsets into a vector. Bounds remain
/// inclusive so adjacent middle candidates can reuse the same cut.
struct TruncationBoundaries<Boundaries> {
    grapheme_count: usize,
    front: BoundaryWindow<Boundaries>,
    back: BoundaryWindow<Boundaries>,
}

impl<Boundaries: DoubleEndedIterator<Item = usize> + Clone> TruncationBoundaries<Boundaries> {
    fn new(boundaries: Boundaries, grapheme_count: usize) -> Self {
        Self {
            grapheme_count,
            front: BoundaryWindow {
                boundaries: boundaries.clone(),
                first: 0,
                last: grapheme_count,
            },
            back: BoundaryWindow {
                boundaries,
                first: 0,
                last: grapheme_count,
            },
        }
    }

    fn narrow(&mut self, keep: usize, direction: TruncateFrom, fits: bool) {
        let (front_count, back_count) = match direction {
            TruncateFrom::End => (keep, 0),
            TruncateFrom::Start => (0, keep),
            TruncateFrom::Middle => {
                let front_count = keep.saturating_mul(2).div_ceil(3);

                (front_count, keep - front_count)
            }
        };

        if direction != TruncateFrom::Start {
            if fits {
                self.front.retain_after(front_count);
            } else {
                self.front.retain_before(front_count);
            }
        }

        if direction != TruncateFrom::End {
            let back_index = self.grapheme_count - back_count;

            if fits {
                self.back.retain_before(back_index);
            } else {
                self.back.retain_after(back_index);
            }
        }
    }
}

struct BoundaryWindow<Boundaries> {
    boundaries: Boundaries,
    first: usize,
    last: usize,
}

impl<Boundaries: DoubleEndedIterator<Item = usize> + Clone> BoundaryWindow<Boundaries> {
    fn get(&self, index: usize) -> usize {
        let from_start = index - self.first;
        let from_end = self.last - index;

        if from_start <= from_end {
            self.boundaries.clone().nth(from_start)
        } else {
            self.boundaries.clone().nth_back(from_end)
        }
        .expect("grapheme boundary is present")
    }

    fn retain_after(&mut self, index: usize) {
        if index > self.first {
            let _boundary = self.boundaries.nth(index - self.first - 1);
            self.first = index;
        }
    }

    fn retain_before(&mut self, index: usize) {
        if index < self.last {
            let _boundary = self.boundaries.nth_back(self.last - index - 1);
            self.last = index;
        }
    }
}

/// Returns the largest fitting candidate with its measured output, or the marker-only
/// candidate when none fits. The starting `keep` is only an estimate; a candidate that
/// doesn't fit narrows the search.
pub(crate) fn truncate_with_measured_candidates<Layout>(
    text: &str,
    boundaries: impl DoubleEndedIterator<Item = usize> + Clone,
    initial_keep: Option<usize>,
    affix: &str,
    runs: &[TextRun],
    direction: TruncateFrom,
    mut measure: impl FnMut(&TruncationCandidate) -> (Layout, bool),
) -> (TruncationCandidate, Layout) {
    let boundary_count = boundaries.clone().count();
    let grapheme_count = boundary_count.saturating_sub(1);
    let mut boundaries = TruncationBoundaries::new(boundaries, grapheme_count);

    let mut lower = 0;
    let mut upper = boundary_count.saturating_sub(2);
    let mut keep = initial_keep.unwrap_or(boundary_count / 2).min(upper);
    let mut best = None;

    loop {
        let candidate = make_truncation_candidate(text, &boundaries, keep, affix, runs, direction);
        let (layout, fits) = measure(&candidate);

        if fits {
            best = Some((candidate, layout));
            lower = keep + 1;
        } else if keep == 0 {
            // Preserve the requested marker when even the marker alone is too wide.
            return best.unwrap_or((candidate, layout));
        } else {
            upper = keep - 1;
        }

        if lower > upper {
            return best.expect("a fitting candidate was measured");
        }

        boundaries.narrow(keep, direction, fits);
        keep = lower + (upper - lower) / 2;
    }
}

fn make_truncation_candidate(
    text: &str,
    boundaries: &TruncationBoundaries<impl DoubleEndedIterator<Item = usize> + Clone>,
    keep: usize,
    affix: &str,
    runs: &[TextRun],
    direction: TruncateFrom,
) -> TruncationCandidate {
    let grapheme_count = boundaries.grapheme_count;
    let keep = keep.min(grapheme_count);
    let (front_end, back_start, affix_source) = match direction {
        TruncateFrom::End => {
            let prefix = text[..boundaries.front.get(keep)]
                .trim_end_matches(|ch: char| ch.is_whitespace() || ch.is_ascii_punctuation());
            let end = prefix.len();

            (end, text.len(), end.min(text.len().saturating_sub(1)))
        }
        TruncateFrom::Start => {
            let start = boundaries.back.get(grapheme_count - keep);

            (0, start, start.saturating_sub(1))
        }
        TruncateFrom::Middle => {
            let front_count = keep.saturating_mul(2).div_ceil(3);
            let back_count = keep - front_count;
            let end = boundaries.front.get(front_count);

            (
                end,
                boundaries.back.get(grapheme_count - back_count),
                end.saturating_sub(1),
            )
        }
    };

    let mut candidate = TruncationCandidate {
        text: format!("{}{affix}{}", &text[..front_end], &text[back_start..]).into(),
        runs: Vec::new(),
        retained: SmallVec::from_buf([
            (0..front_end, 0),
            (back_start..text.len(), front_end + affix.len()),
        ]),
        affix_range: front_end..front_end + affix.len(),
        affix_source,
    };
    let mut offset = 0;
    let mut display_runs = Vec::new();

    for run in runs {
        let source = offset..offset + run.len;
        offset = source.end;

        for range in candidate.display_ranges(&source) {
            display_runs.push((
                range.start,
                TextRun {
                    len: range.len(),
                    ..run.clone()
                },
            ));
        }
    }

    display_runs.sort_by_key(|(start, _run)| *start);
    candidate.runs = display_runs.into_iter().map(|(_start, run)| run).collect();

    candidate
}

#[cfg(test)]
mod truncation_tests {
    use super::*;

    #[test]
    fn truncation_candidates_keep_complete_graphemes_and_cover_output_with_runs() {
        const FAMILY: &str = "👩‍👩‍👧‍👦";
        let text = format!("Ae\u{301}{FAMILY}🦀");
        let split = "Ae\u{301}".len();
        let runs = [
            TextRun {
                len: split,
                ..Default::default()
            },
            TextRun {
                len: text.len() - split,
                ..Default::default()
            },
        ];
        let boundaries = text
            .grapheme_indices(true)
            .map(|(index, _grapheme)| index)
            .chain(std::iter::once(text.len()));
        let grapheme_count = boundaries.clone().count().saturating_sub(1);
        let boundaries = TruncationBoundaries::new(boundaries, grapheme_count);

        for (direction, keep, expected) in [
            (TruncateFrom::Start, 0, "…".to_owned()),
            (TruncateFrom::End, 0, "…".to_owned()),
            (TruncateFrom::Middle, 0, "…".to_owned()),
            (TruncateFrom::Start, 1, "…🦀".to_owned()),
            (TruncateFrom::Middle, 1, "A…".to_owned()),
            (TruncateFrom::Start, 2, format!("…{FAMILY}🦀")),
            (TruncateFrom::End, 2, "Ae\u{301}…".to_owned()),
            (TruncateFrom::Middle, 3, "Ae\u{301}…🦀".to_owned()),
            (TruncateFrom::Start, usize::MAX, format!("…{text}")),
            (TruncateFrom::End, usize::MAX, format!("{text}…")),
            (
                TruncateFrom::Middle,
                usize::MAX,
                format!("Ae\u{301}{FAMILY}…🦀"),
            ),
        ] {
            let candidate =
                make_truncation_candidate(&text, &boundaries, keep, "…", &runs, direction);
            assert_eq!(candidate.text.as_ref(), expected, "{direction:?}");
            assert_eq!(
                candidate.runs.iter().map(|run| run.len).sum::<usize>(),
                candidate.text.len(),
                "style runs must cover {:?} after {direction:?} truncation",
                candidate.text
            );
        }
    }

    #[test]
    fn measured_truncation_keeps_the_selected_output_and_marker_fallback() {
        let text = "Ae\u{301}👩‍👩‍👧‍👦🦀";

        for (text, direction, expected) in [
            ("", TruncateFrom::Start, "…"),
            ("", TruncateFrom::End, "…"),
            ("", TruncateFrom::Middle, "…"),
            ("🦀", TruncateFrom::Start, "…"),
            ("🦀", TruncateFrom::End, "…"),
            ("🦀", TruncateFrom::Middle, "…"),
            (text, TruncateFrom::Start, "…🦀"),
            (text, TruncateFrom::End, "A…"),
            (text, TruncateFrom::Middle, "A…"),
        ] {
            let runs = [TextRun {
                len: text.len(),
                ..Default::default()
            }];
            let boundaries = text
                .grapheme_indices(true)
                .map(|(index, _grapheme)| index)
                .chain(std::iter::once(text.len()));

            for initial_keep in [None, Some(0), Some(usize::MAX)] {
                let (candidate, measured_text) = truncate_with_measured_candidates(
                    text,
                    boundaries.clone(),
                    initial_keep,
                    "…",
                    &runs,
                    direction,
                    |candidate| {
                        let fits = candidate.text.graphemes(true).count() <= 2;

                        (candidate.text.clone(), fits)
                    },
                );
                assert_eq!(
                    candidate.text.as_ref(),
                    expected,
                    "{text:?} {direction:?} {initial_keep:?}"
                );
                assert_eq!(measured_text, candidate.text);
            }

            let (candidate, measured_text) = truncate_with_measured_candidates(
                text,
                boundaries,
                None,
                "…",
                &runs,
                direction,
                |candidate| (candidate.text.clone(), false),
            );
            assert_eq!(candidate.text.as_ref(), "…");
            assert_eq!(measured_text, candidate.text);
        }
    }
}

/// A [`StyledText`] that reports clicks, hovers, and tooltips for character ranges.
///
/// Give it an ID, so that GPUI can track the mouse between frames. Then attach
/// the behavior you need: [`InteractiveText::on_click`] for ranges of text,
/// [`InteractiveText::on_hover`] for the character under the mouse, and
/// [`InteractiveText::tooltip`] for a tooltip per character.
///
/// # Examples
///
/// ```
/// # use gpui::*;
/// # fn render() -> impl IntoElement {
/// InteractiveText::new(
///     "terms",
///     StyledText::new("Read the terms or skip"),
/// )
/// .on_click(vec![9..14], |_range_index, _window, _cx| {
///     // Open the terms here.
/// })
/// # }
/// ```
pub struct InteractiveText {
    element_id: ElementId,
    text: StyledText,
    click_listener:
        Option<Box<dyn Fn(&[Range<usize>], InteractiveTextClickEvent, &mut Window, &mut App)>>,
    hover_listener: Option<Box<dyn Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App)>>,
    tooltip_builder: Option<Rc<dyn Fn(usize, &mut Window, &mut App) -> Option<AnyView>>>,
    tooltip_id: Option<TooltipId>,
    clickable_ranges: Vec<Range<usize>>,
}

struct InteractiveTextClickEvent {
    mouse_down_index: usize,
    mouse_up_index: usize,
}

/// The per-element state that [`InteractiveText`] keeps between frames.
///
/// This is an implementation detail. Application code doesn't use it.
#[doc(hidden)]
#[derive(Default)]
pub struct InteractiveTextState {
    mouse_down_index: Rc<Cell<Option<usize>>>,
    hovered_index: Rc<Cell<Option<usize>>>,
    active_tooltip: Rc<RefCell<Option<ActiveTooltip>>>,
    long_press_tooltip_active: Rc<Cell<bool>>,
}

impl InteractiveText {
    /// Creates an interactive text element with the given ID and styled text.
    ///
    /// The ID must be unique among siblings. It keys the mouse state that
    /// survives between frames.
    pub fn new(id: impl Into<ElementId>, text: StyledText) -> Self {
        Self {
            element_id: id.into(),
            text,
            click_listener: None,
            hover_listener: None,
            tooltip_builder: None,
            tooltip_id: None,
            clickable_ranges: Vec::new(),
        }
    }

    /// Calls `listener` when the user presses and releases the mouse inside one of `ranges`.
    ///
    /// The listener receives the index in `ranges` of the matching range. The press
    /// and the release must both fall inside the same range. A press in one range
    /// and a release in another calls nothing. If the ranges overlap, the listener
    /// runs once for each range that contains both points.
    pub fn on_click(
        mut self,
        ranges: Vec<Range<usize>>,
        listener: impl Fn(usize, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.click_listener = Some(Box::new(move |ranges, event, window, cx| {
            for (range_ix, range) in ranges.iter().enumerate() {
                if range.contains(&event.mouse_down_index) && range.contains(&event.mouse_up_index)
                {
                    listener(range_ix, window, cx);
                }
            }
        }));
        self.clickable_ranges = ranges;
        self
    }

    /// Calls `listener` as the mouse moves over the text.
    ///
    /// The listener receives the byte index of the character under the mouse, or
    /// `None` when the mouse is over the element but not over a character. It runs only
    /// when that value changes, and not when the mouse leaves the element. It also
    /// receives the [`MouseMoveEvent`].
    pub fn on_hover(
        mut self,
        listener: impl Fn(Option<usize>, MouseMoveEvent, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.hover_listener = Some(Box::new(listener));
        self
    }

    /// Sets a tooltip for each character, as chosen by `builder`.
    ///
    /// `builder` receives the byte index of the character under the mouse. It returns
    /// the view to show as the tooltip, or `None` for no tooltip at that character.
    pub fn tooltip(
        mut self,
        builder: impl Fn(usize, &mut Window, &mut App) -> Option<AnyView> + 'static,
    ) -> Self {
        self.tooltip_builder = Some(Rc::new(builder));
        self
    }
}

impl Element for InteractiveText {
    type RequestLayoutState = ();
    type PrepaintState = Hitbox;

    fn id(&self) -> Option<ElementId> {
        Some(self.element_id.clone())
    }

    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
        None
    }

    fn a11y_role(&self) -> Option<accesskit::Role> {
        Some(accesskit::Role::Label)
    }

    fn write_a11y_info(&self, node: &mut accesskit::Node) {
        node.set_value(self.text.text.to_string());
    }

    fn request_layout(
        &mut self,
        _id: Option<&GlobalElementId>,
        inspector_id: Option<&InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, Self::RequestLayoutState) {
        let result = self.text.request_layout(None, inspector_id, window, cx);

        // InteractiveText owns range-based selection and hit testing in its independent layout.
        window.publish_inline_content(result.0, crate::InlineContent::Atomic);
        result
    }

    fn prepaint(
        &mut self,
        global_id: Option<&GlobalElementId>,
        inspector_id: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        state: &mut Self::RequestLayoutState,
        window: &mut Window,
        cx: &mut App,
    ) -> Hitbox {
        window.with_optional_element_state::<InteractiveTextState, _>(
            global_id,
            |interactive_state, window| {
                let mut interactive_state = interactive_state
                    .map(|interactive_state| interactive_state.unwrap_or_default());

                if let Some(interactive_state) = interactive_state.as_mut() {
                    if self.tooltip_builder.is_some() {
                        self.tooltip_id =
                            set_tooltip_on_window(&interactive_state.active_tooltip, window);
                    } else {
                        // If there is no longer a tooltip builder, remove the active tooltip.
                        interactive_state.long_press_tooltip_active.set(false);
                        interactive_state.active_tooltip.take();
                    }
                }

                self.text
                    .prepaint(None, inspector_id, bounds, state, window, cx);
                let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
                (hitbox, interactive_state)
            },
        )
    }

    fn paint(
        &mut self,
        global_id: Option<&GlobalElementId>,
        inspector_id: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        _: &mut Self::RequestLayoutState,
        hitbox: &mut Hitbox,
        window: &mut Window,
        cx: &mut App,
    ) {
        let current_view = window.current_view();
        let text_layout = self.text.layout().clone();
        window.with_element_state::<InteractiveTextState, _>(
            global_id.unwrap(),
            |interactive_state, window| {
                let mut interactive_state = interactive_state.unwrap_or_default();
                if let Some(click_listener) = self.click_listener.take() {
                    let mouse_position = window.mouse_position();
                    if let Ok(ix) = text_layout.index_for_position(mouse_position)
                        && self
                            .clickable_ranges
                            .iter()
                            .any(|range| range.contains(&ix))
                    {
                        window.set_cursor_style(crate::CursorStyle::PointingHand, hitbox)
                    }

                    let text_layout = text_layout.clone();
                    let mouse_down = interactive_state.mouse_down_index.clone();
                    let current_view = window.current_view();
                    if let Some(mouse_down_index) = mouse_down.get() {
                        let hitbox = hitbox.clone();
                        let clickable_ranges = mem::take(&mut self.clickable_ranges);
                        window.on_mouse_event(
                            move |event: &MouseUpEvent, phase, window: &mut Window, cx| {
                                if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
                                    if let Ok(mouse_up_index) =
                                        text_layout.index_for_position(event.position)
                                    {
                                        click_listener(
                                            &clickable_ranges,
                                            InteractiveTextClickEvent {
                                                mouse_down_index,
                                                mouse_up_index,
                                            },
                                            window,
                                            cx,
                                        )
                                    }

                                    mouse_down.take();
                                    cx.notify(current_view);
                                }
                            },
                        );
                    } else {
                        let hitbox = hitbox.clone();
                        window.on_mouse_event(move |event: &MouseDownEvent, phase, window, cx| {
                            if phase == DispatchPhase::Bubble
                                && hitbox.is_hovered(window)
                                && let Ok(mouse_down_index) =
                                    text_layout.index_for_position(event.position)
                            {
                                mouse_down.set(Some(mouse_down_index));
                                cx.notify(current_view);
                            }
                        });
                    }
                }

                window.on_mouse_event({
                    let mut hover_listener = self.hover_listener.take();
                    let hitbox = hitbox.clone();
                    let text_layout = text_layout.clone();
                    let hovered_index = interactive_state.hovered_index.clone();
                    move |event: &MouseMoveEvent, phase, window, cx| {
                        if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
                            let current = hovered_index.get();
                            let updated = text_layout.index_for_position(event.position).ok();
                            if current != updated {
                                hovered_index.set(updated);
                                if let Some(hover_listener) = hover_listener.as_ref() {
                                    hover_listener(updated, event.clone(), window, cx);
                                }
                                cx.notify(current_view);
                            }
                        }
                    }
                });

                if let Some(tooltip_builder) = self.tooltip_builder.clone() {
                    let active_tooltip = interactive_state.active_tooltip.clone();
                    let build_tooltip = Rc::new({
                        let tooltip_is_hoverable = false;
                        let text_layout = text_layout.clone();
                        move |window: &mut Window, cx: &mut App| {
                            text_layout
                                .index_for_position(window.mouse_position())
                                .ok()
                                .and_then(|position| tooltip_builder(position, window, cx))
                                .map(|view| (view, tooltip_is_hoverable))
                        }
                    });

                    // Check hitbox geometry directly because hover state is unavailable during prepaint.
                    let check_is_hovered_during_prepaint = Rc::new({
                        let source_hitbox = hitbox.clone();
                        let text_layout = text_layout.clone();
                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
                        move |window: &Window| {
                            text_layout
                                .index_for_position(window.mouse_position())
                                .is_ok()
                                && source_hitbox.contains(&window.mouse_position())
                                && pending_mouse_down.get().is_none()
                        }
                    });

                    let check_is_hovered = Rc::new({
                        let hitbox = hitbox.clone();
                        let text_layout = text_layout.clone();
                        let pending_mouse_down = interactive_state.mouse_down_index.clone();
                        move |window: &Window| {
                            text_layout
                                .index_for_position(window.mouse_position())
                                .is_ok()
                                && hitbox.is_hovered(window)
                                && pending_mouse_down.get().is_none()
                        }
                    });

                    register_tooltip_mouse_handlers(
                        &active_tooltip,
                        self.tooltip_id,
                        build_tooltip,
                        check_is_hovered,
                        check_is_hovered_during_prepaint,
                        interactive_state.long_press_tooltip_active.clone(),
                        None,
                        window,
                    );
                }

                self.text
                    .paint(None, inspector_id, bounds, &mut (), &mut (), window, cx);

                ((), interactive_state)
            },
        );
    }
}

impl IntoElement for InteractiveText {
    type Element = Self;

    fn into_element(self) -> Self::Element {
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        AvailableSpace, Context, Hsla, Render, ScaledPixels, TestApp, TestAppContext, div, hsla,
        prelude::*, size,
    };
    use std::collections::HashSet;

    const CONTAINER_COLOR: Hsla = hsla(0.72, 0.45, 0.32, 1.0);
    const TEXT_BACKGROUND_COLOR: Hsla = hsla(0.37, 0.65, 0.42, 1.0);

    #[test]
    fn wrap_width_of_a_min_content_probe_breaks_at_every_opportunity() {
        let space = |width| Size {
            width,
            height: AvailableSpace::MaxContent,
        };
        let unknown = Size::default();
        let wrap_width = |white_space, known: Size<Option<Pixels>>, space| {
            TextLayout::evaluate_wrap_width(&white_space, known, space)
        };

        assert_eq!(
            wrap_width(
                WhiteSpace::Normal,
                unknown,
                space(AvailableSpace::MinContent)
            ),
            Some(Pixels::ZERO)
        );
        assert_eq!(
            wrap_width(
                WhiteSpace::Normal,
                unknown,
                space(AvailableSpace::MaxContent)
            ),
            None
        );
        assert_eq!(
            wrap_width(
                WhiteSpace::Normal,
                unknown,
                space(AvailableSpace::Definite(px(80.)))
            ),
            Some(px(80.))
        );
        let known = Size {
            width: Some(px(50.)),
            height: None,
        };
        assert_eq!(
            wrap_width(WhiteSpace::Normal, known, space(AvailableSpace::MinContent)),
            Some(px(50.))
        );
        assert_eq!(
            wrap_width(
                WhiteSpace::Nowrap,
                unknown,
                space(AvailableSpace::MinContent)
            ),
            None
        );
    }

    #[gpui::test]
    fn text_measurement_replaces_state_when_wrap_width_changes(cx: &mut TestAppContext) {
        let cx = cx.add_empty_window();

        cx.draw(Point::default(), size(px(240.), px(100.)), |window, cx| {
            let layout = TextLayout::default();
            let text = SharedString::from("Measure café over multiple words");

            for (width, cached) in [(240., false), (240., true), (80., false)] {
                let previous_bounds = layout
                    .0
                    .layout
                    .borrow()
                    .as_ref()
                    .and_then(|state| state.bounds);

                let previous_document = layout
                    .0
                    .layout
                    .borrow()
                    .as_ref()
                    .and_then(|state| state.document.as_ref())
                    .map(|document| document.layout.clone());

                let layout_id = layout.layout(text.clone(), None, window, cx);

                window.compute_layout(
                    layout_id,
                    size(
                        AvailableSpace::Definite(px(width)),
                        AvailableSpace::MaxContent,
                    ),
                    cx,
                );

                let bounds = window.layout_bounds(layout_id);

                {
                    let state = layout.0.layout.borrow();
                    let state = state.as_ref().unwrap();
                    let document = state.document.as_ref().unwrap();

                    assert_eq!(document.text, text);
                    assert_eq!(state.len, text.len());
                    assert_eq!(state.size, bounds.size);
                    assert_eq!(state.size, document.size(state.line_height));
                    assert_eq!(state.options.wrap_width, Some(px(width)));
                    assert_eq!(state.truncate_width, None);
                    assert_eq!(state.bounds, if cached { previous_bounds } else { None });

                    if let Some(previous_document) = previous_document {
                        assert_eq!(Arc::ptr_eq(&document.layout, &previous_document), cached);
                    }
                }

                layout.prepaint(bounds, &text, window);

                assert_eq!(layout.bounds(), bounds);
            }

            div()
        });
    }

    struct CenteredTextView {
        extent: f32,
    }

    impl Render for CenteredTextView {
        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
            div()
                .flex()
                .items_center()
                .justify_center()
                .w(px(320.0 + self.extent))
                .h(px(160.0 + self.extent))
                .child(
                    div()
                        .flex()
                        .items_center()
                        .justify_center()
                        .w(px(118.0))
                        .h(px(31.0))
                        .bg(CONTAINER_COLOR)
                        .text_size(px(14.0))
                        .child(StyledText::new("x").with_highlights([(
                            0..1,
                            HighlightStyle {
                                background_color: Some(TEXT_BACKGROUND_COLOR),
                                ..Default::default()
                            },
                        )])),
                )
        }
    }

    fn only_quad(window: &Window, color: Hsla) -> Bounds<ScaledPixels> {
        let color = color.into();
        let mut bounds = window
            .rendered_frame
            .scene
            .quads
            .iter()
            .filter(|quad| quad.background.solid == color)
            .map(|quad| quad.bounds);
        let result = bounds.next().expect("expected a rendered quad");
        assert!(bounds.next().is_none(), "expected only one rendered quad");
        result
    }

    #[test]
    fn test_into_element_for() {
        use crate::{ParentElement as _, SharedString, div};
        use std::borrow::Cow;

        let _ = div().child("static str");
        let _ = div().child("String".to_string());
        let _ = div().child(Cow::Borrowed("Cow"));
        let _ = div().child(SharedString::from("SharedString"));
    }

    #[test]
    fn text_macro_id() {
        // one call to `text!` = one id
        fn make_text_stable_id(happy: bool) -> Text {
            text!(if happy { "happy" } else { "sad" })
        }

        // two calls to `text!` = two ids
        fn make_text_unstable_id(happy: bool) -> Text {
            if happy { text!("happy") } else { text!("sad") }
        }

        assert_eq!(make_text_stable_id(false).id, make_text_stable_id(true).id);
        assert_ne!(
            make_text_unstable_id(false).id,
            make_text_unstable_id(true).id
        );
    }

    #[test]
    fn accessible_text_keeps_its_unicode_value_and_stable_identity() {
        let first = Text::new("status".into(), "Ready العربية 👩🏽‍💻".into());
        let second = Text::new("status".into(), "Done 日本語 ✅".into());
        assert_eq!(first.id(), second.id());
        assert_eq!(first.a11y_role(), Some(accesskit::Role::Label));

        let mut node = accesskit::Node::new(accesskit::Role::Label);
        second.write_a11y_info(&mut node);
        assert_eq!(node.value(), Some("Done 日本語 ✅"));

        let hidden = Text::new_inaccessible("decorative 👀".into());
        assert_eq!(hidden.a11y_role(), None);
    }

    #[test]
    fn centered_text_keeps_its_device_pixel_offset_when_its_parent_moves() {
        for scale_factor in [1.0, 1.5] {
            let mut app = TestApp::new();
            let mut test_window = app.open_window(|window, _| {
                window.set_scale_factor(scale_factor);
                CenteredTextView { extent: 0.0 }
            });
            test_window.draw();

            let (initial_container, initial_background) = test_window.update(|_, window, _| {
                (
                    only_quad(window, CONTAINER_COLOR),
                    only_quad(window, TEXT_BACKGROUND_COLOR),
                )
            });
            let expected_offset = initial_background.origin - initial_container.origin;
            let mut container_origins = HashSet::from([(
                initial_container.origin.x.as_f32() as i32,
                initial_container.origin.y.as_f32() as i32,
            )]);

            for step in 1..=32 {
                test_window.update(|view, _, cx| {
                    view.extent = step as f32;
                    cx.notify();
                });
                test_window.draw();

                let (container, background) = test_window.update(|_, window, _| {
                    (
                        only_quad(window, CONTAINER_COLOR),
                        only_quad(window, TEXT_BACKGROUND_COLOR),
                    )
                });
                assert_eq!(
                    background.origin - container.origin,
                    expected_offset,
                    "text moved within its parent at scale {scale_factor}, step {step}"
                );
                container_origins.insert((
                    container.origin.x.as_f32() as i32,
                    container.origin.y.as_f32() as i32,
                ));
            }

            assert!(
                container_origins.len() > 8,
                "fixture did not cross enough device pixels at scale {scale_factor}"
            );
        }
    }
}