gpui-base 0.6.2

Behavior, interaction, and infrastructure foundations for GPUI applications.
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
use gpui::Corners;
use std::{
    cell::RefCell,
    collections::HashMap,
    mem,
    ops::Range,
    rc::Rc,
    sync::{Arc, Mutex, Weak},
};

use gpui::{
    App, BorderStyle, Bounds, ClickEvent, CursorStyle, Edges, Element, ElementId, GlobalElementId,
    Half, HighlightStyle, Hitbox, HitboxBehavior, InspectorElementId, IntoElement, LayoutId,
    MouseButton, MouseClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point,
    SharedString, StyledText, TextLayout, TextRun, TextStyle, Window, point, px, quad, size,
};

use crate::{
    GlobalState, TextSelection,
    input::Selection,
    text::TextViewMultiClickKind,
    text::node::LinkMark,
    text::selection::word_range_at,
    text::state::LineSpan,
    text::text_view::{LinkClickHandlerFn, handle_link_click},
};

/// The style applied to one range of inline text.
///
/// A [`HighlightStyle`] carries no font family, so the family an inline code
/// span is set in rides beside it; `None` keeps the family of the enclosing
/// text style.
#[derive(Clone, Debug, Default, PartialEq)]
pub(super) struct InlineHighlight {
    pub(super) style: HighlightStyle,
    pub(super) font_family: Option<SharedString>,
    pub(super) font_size_scale: Option<f32>,
}

impl InlineHighlight {
    /// Layers `other` over `self`, the way [`HighlightStyle::highlight`] does.
    fn highlight(mut self, other: &InlineHighlight) -> Self {
        self.style = self.style.highlight(other.style);
        if other.font_family.is_some() {
            self.font_family = other.font_family.clone();
        }
        if other.font_size_scale.is_some() {
            self.font_size_scale = other.font_size_scale;
        }
        self
    }
}

impl From<HighlightStyle> for InlineHighlight {
    fn from(style: HighlightStyle) -> Self {
        Self {
            style,
            font_family: None,
            font_size_scale: None,
        }
    }
}

/// Merges two highlight lists over one text into non-overlapping ranges,
/// cutting at every endpoint of every input range. Same sweep as
/// [`gpui::combine_highlights`], for [`InlineHighlight`] payloads.
pub(super) fn combine_highlights(
    a: impl IntoIterator<Item = (Range<usize>, InlineHighlight)>,
    b: impl IntoIterator<Item = (Range<usize>, InlineHighlight)>,
) -> Vec<(Range<usize>, InlineHighlight)> {
    let mut endpoints = Vec::new();
    let mut highlights = Vec::new();
    for (range, highlight) in a.into_iter().chain(b) {
        if !range.is_empty() {
            let id = highlights.len();
            endpoints.push((range.start, id, true));
            endpoints.push((range.end, id, false));
            highlights.push(highlight);
        }
    }
    endpoints.sort_unstable_by_key(|(position, _, _)| *position);

    let mut combined = Vec::new();
    let mut active: Vec<usize> = Vec::new();
    let mut ix = 0;
    for (position, id, is_start) in endpoints {
        if position > ix && !active.is_empty() {
            let style = active.iter().fold(InlineHighlight::default(), |acc, id| {
                acc.highlight(&highlights[*id])
            });
            combined.push((ix..position, style));
        }
        ix = position;
        if is_start {
            active.push(id);
        } else {
            active.retain(|active_id| *active_id != id);
        }
    }
    combined
}

/// Layers a streamed fade-in over `highlights`: text inside each fade range
/// loses that share of its color, and a highlight background fades with it so
/// an inline code chip does not appear before its text.
pub(super) fn fade_highlights(
    highlights: Vec<(Range<usize>, InlineHighlight)>,
    fades: &[(Range<usize>, f32)],
) -> Vec<(Range<usize>, InlineHighlight)> {
    if fades.is_empty() {
        return highlights;
    }
    let fade_highlights = fades.iter().map(|(range, fade_out)| {
        (
            range.clone(),
            InlineHighlight::from(HighlightStyle {
                fade_out: Some(*fade_out),
                ..Default::default()
            }),
        )
    });
    let mut combined = combine_highlights(highlights, fade_highlights);
    for (_, highlight) in &mut combined {
        if let Some(fade_out) = highlight.style.fade_out
            && let Some(background) = highlight.style.background_color.as_mut()
        {
            background.fade_out(fade_out);
        }
    }
    combined
}

/// Builds the [`TextRun`]s for `text_len` bytes of inline text: each
/// highlight refines `default_style` over its range, and a highlight that
/// names a font family shapes its run in that family.
pub(super) fn text_runs(
    text_len: usize,
    default_style: &TextStyle,
    highlights: &[(Range<usize>, InlineHighlight)],
) -> Vec<TextRun> {
    let mut runs = Vec::with_capacity(highlights.len() * 2 + 1);
    let mut ix = 0;
    for (range, highlight) in highlights {
        if ix < range.start {
            runs.push(default_style.clone().to_run(range.start - ix));
        }
        let mut run = default_style
            .clone()
            .highlight(highlight.style)
            .to_run(range.len());
        if let Some(family) = &highlight.font_family {
            run.font.family = family.clone();
        }
        runs.push(run);
        ix = range.end;
    }
    if ix < text_len {
        runs.push(default_style.to_run(text_len - ix));
    }
    runs
}

/// Splits text into contiguous ranges sharing one font size. GPUI runs can
/// vary the font but not its size, so each range needs its own shaped line.
pub(super) fn text_size_ranges(
    text_len: usize,
    highlights: &[(Range<usize>, InlineHighlight)],
) -> Vec<(Range<usize>, f32)> {
    let mut ranges: Vec<(Range<usize>, f32)> = Vec::new();
    let mut push = |range: Range<usize>, scale: f32| {
        if range.is_empty() {
            return;
        }
        if let Some((last, last_scale)) = ranges.last_mut()
            && *last_scale == scale
            && last.end == range.start
        {
            last.end = range.end;
        } else {
            ranges.push((range, scale));
        }
    };
    let mut cursor = 0;
    for (range, highlight) in highlights {
        push(cursor..range.start, 1.);
        push(range.clone(), highlight.font_size_scale.unwrap_or(1.));
        cursor = range.end;
    }
    push(cursor..text_len, 1.);
    ranges
}

/// A inline element used to render a inline text and support selectable.
///
/// All text in TextView (including the CodeBlock) used this for text rendering.
pub(super) struct Inline {
    text: SharedString,
    links: Rc<Vec<(Range<usize>, LinkMark)>>,
    highlights: Vec<(Range<usize>, InlineHighlight)>,
    styled_text: StyledText,
    /// The resolved style from a parent deferred layout, when there is one.
    text_style: Option<TextStyle>,
    paint_origin: Option<Point<Pixels>>,
    selection_bounds: Option<Bounds<Pixels>>,
    selection_source: Option<(Arc<Mutex<InlineState>>, Range<usize>)>,
    link_click_handler: Option<Arc<LinkClickHandlerFn>>,
    /// What this frame's layout was shaped with, to hand the shaped text to
    /// the next frame (see [`RetainedLayout`]).
    retained_key: Option<(Vec<TextRun>, TextStyle)>,
    /// The shaped text is in the table, not in `styled_text`, until paint
    /// takes it back.
    handed_over: bool,

    state: Arc<Mutex<InlineState>>,
}

/// The inline text state, used RefCell to keep the selection state.
#[derive(Debug, Default, PartialEq)]
pub(crate) struct InlineState {
    hovered_index: Option<usize>,
    /// The text that actually rendering, matched with selection.
    pub(super) text: SharedString,
    pub(super) selection: Option<Selection>,
}

/// One frame's [`StyledText`], kept for the next frame's [`Inline`] of the
/// same [`InlineState`].
///
/// A [`TextLayout`] remembers the size and the shaped lines of its last
/// measurement and answers a repeated measure at the same wrap width from
/// them, but a fresh `StyledText` every frame throws that away, so every
/// frame of a scroll paid for a line wrapper, a shaping-cache lookup that
/// hashes the whole paragraph, and the allocations around them for every
/// visible paragraph. Handing the same `StyledText` to the next frame makes
/// those measurements hits. A layout is only reused when the text, the runs
/// (colors, fades, fonts) and the text style (font size, line height) it was
/// shaped with are unchanged; a different wrap width misses inside
/// `TextLayout` and reshapes as before.
///
/// `StyledText` is main-thread only (an `Rc` inside), while `InlineState`
/// travels through the background parse, so the layouts live in a
/// thread-local table keyed by the state's address, with a `Weak` to tell a
/// live state from a reused address.
struct RetainedLayout {
    state: Weak<Mutex<InlineState>>,
    styled_text: StyledText,
    text: SharedString,
    runs: Vec<TextRun>,
    text_style: TextStyle,
}

thread_local! {
    static RETAINED_LAYOUTS: RefCell<HashMap<usize, RetainedLayout>> = RefCell::new(HashMap::new());
}

/// Dead entries (states that were dropped without a final paint, e.g. a
/// replaced document) are swept once the table grows past this many.
const RETAINED_SWEEP_AT: usize = 4096;

fn state_key(state: &Arc<Mutex<InlineState>>) -> usize {
    Arc::as_ptr(state) as usize
}

/// Takes the layout retained for `state`, if the previous frame left one.
fn take_retained_layout(state: &Arc<Mutex<InlineState>>) -> Option<RetainedLayout> {
    RETAINED_LAYOUTS.with(|layouts| {
        let retained = layouts.borrow_mut().remove(&state_key(state))?;
        // The address may belong to a new state by now.
        retained
            .state
            .upgrade()
            .is_some_and(|live| Arc::ptr_eq(&live, state))
            .then_some(retained)
    })
}

/// Whether the table already holds a layout for `state`: every entry left
/// by the previous frame is taken at layout time, so one that is present
/// afterwards was put there this frame, by another element of the same state.
fn has_retained_layout(state: &Arc<Mutex<InlineState>>) -> bool {
    RETAINED_LAYOUTS.with(|layouts| layouts.borrow().contains_key(&state_key(state)))
}

fn retain_layout(state: &Arc<Mutex<InlineState>>, retained: RetainedLayout) {
    RETAINED_LAYOUTS.with(|layouts| {
        let mut layouts = layouts.borrow_mut();
        if layouts.len() >= RETAINED_SWEEP_AT {
            layouts.retain(|_, retained| retained.state.strong_count() > 0);
        }
        layouts.insert(state_key(state), retained);
    });
}

impl InlineState {
    /// Save actually rendered text for selected text to use.
    pub(crate) fn set_text(&mut self, text: SharedString) {
        self.text = text;
    }
}

impl Inline {
    /// Hands the shaped text to the next frame (see [`RetainedLayout`]).
    /// Called after prepaint, so an element that is laid out but never
    /// painted (scrolled out of view) keeps its layout too; paint takes it
    /// back for the duration of painting.
    ///
    /// When another element of the same state already handed one over this
    /// frame (the same document shown twice), this one keeps its own: the
    /// table holds one layout per state, and an element must never be left
    /// to paint without its shaped text.
    fn retain_styled_text(&mut self) {
        if self.handed_over || self.retained_key.is_none() || has_retained_layout(&self.state) {
            return;
        }
        let Some((runs, text_style)) = self.retained_key.take() else {
            return;
        };
        retain_layout(
            &self.state,
            RetainedLayout {
                state: Arc::downgrade(&self.state),
                styled_text: mem::replace(&mut self.styled_text, StyledText::new("")),
                text: self.text.clone(),
                runs,
                text_style,
            },
        );
        self.handed_over = true;
    }

    /// Takes the shaped text back from the table for painting. `false` when
    /// it is gone, in which case there is nothing to paint with.
    fn reclaim_styled_text(&mut self) -> bool {
        if !self.handed_over {
            return true;
        }
        let Some(retained) = take_retained_layout(&self.state) else {
            return false;
        };
        self.styled_text = retained.styled_text;
        self.retained_key = Some((retained.runs, retained.text_style));
        self.handed_over = false;
        true
    }

    pub(super) fn new(
        state: Arc<Mutex<InlineState>>,
        links: Vec<(Range<usize>, LinkMark)>,
        highlights: Vec<(Range<usize>, InlineHighlight)>,
        link_click_handler: Option<Arc<LinkClickHandlerFn>>,
    ) -> Self {
        let text = state
            .lock()
            .map(|state| state.text.clone())
            .unwrap_or_default();

        Self {
            links: Rc::new(links),
            highlights,
            text: text.clone(),
            styled_text: StyledText::new(text),
            text_style: None,
            paint_origin: None,
            selection_bounds: None,
            selection_source: None,
            link_click_handler,
            retained_key: None,
            handed_over: false,
            state,
        }
    }

    /// Use the resolved style captured by a deferred parent layout.
    pub(super) fn text_style(mut self, text_style: TextStyle) -> Self {
        self.text_style = Some(text_style);
        self
    }

    /// Preserve the shared inline-flow baseline through GPUI's element-bound snapping.
    pub(super) fn paint_origin(mut self, origin: Point<Pixels>) -> Self {
        self.paint_origin = Some(origin);
        self
    }

    pub(super) fn selection_bounds(mut self, bounds: Bounds<Pixels>) -> Self {
        self.selection_bounds = Some(bounds);
        self
    }

    pub(super) fn selection_source(
        mut self,
        state: Arc<Mutex<InlineState>>,
        range: Range<usize>,
    ) -> Self {
        self.selection_source = Some((state, range));
        self
    }

    /// Get link at given mouse position.
    fn link_for_position(
        layout: &TextLayout,
        links: &Vec<(Range<usize>, LinkMark)>,
        position: Point<Pixels>,
    ) -> Option<LinkMark> {
        let offset = layout.index_for_position(position).ok()?;
        for (range, link) in links.iter() {
            if range.contains(&offset) {
                return Some(link.clone());
            }
        }

        None
    }

    /// Paint selected bounds for debug.
    #[allow(unused)]
    fn paint_selected_bounds(&self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
        window.paint_quad(gpui::PaintQuad {
            bounds,
            background: gpui::hsla(0.58, 0.85, 0.62, 0.01).into(),
            corner_radii: Corners::default(),
            border_color: gpui::transparent_black(),
            border_style: BorderStyle::default(),
            border_widths: gpui::Edges::all(px(0.)),
        });
    }

    fn layout_selections(
        &self,
        text_layout: &TextLayout,
        bounds: &Bounds<Pixels>,
        window: &mut Window,
        cx: &mut App,
    ) -> (bool, bool, Option<Selection>) {
        let Some(text_view_state) = GlobalState::global(cx).text_view_state() else {
            return (false, false, None);
        };

        let text_view_state = text_view_state.read(cx);
        let is_selectable = text_view_state.is_selectable();
        if !is_selectable {
            return (false, false, None);
        }

        if text_view_state.is_all_selected() {
            return (is_selectable, true, Some((0..self.text.len()).into()));
        }

        if text_view_state.preserve_inline_selection {
            let selection = if let Some((source, range)) = &self.selection_source {
                source
                    .lock()
                    .ok()
                    .and_then(|state| state.selection)
                    .and_then(|selection| {
                        let start = selection.start.max(range.start);
                        let end = selection.end.min(range.end);
                        (start < end)
                            .then(|| Selection::new(start - range.start, end - range.start))
                    })
            } else {
                self.state.lock().ok().and_then(|state| state.selection)
            };
            return (true, selection.is_some(), selection);
        }

        if let Some(selection) = text_view_state.multi_click_selection() {
            if selection.kind == TextViewMultiClickKind::Line {
                return (
                    true,
                    true,
                    selection
                        .line_bounds
                        .filter(|row| row.contains(&bounds.center()))
                        .map(|_| Selection::new(0, self.text.len())),
                );
            }
            return (
                is_selectable,
                true,
                selection_for_multi_click(
                    &self.text,
                    text_layout,
                    *bounds,
                    selection.pos,
                    selection.kind,
                )
                .map(Selection::from),
            );
        }

        let Some((selection_start, selection_end)) = text_view_state.selection_points(cx) else {
            return (is_selectable, false, None);
        };
        let line_height = window.line_height();

        // Use for debug selection bounds
        // self.paint_selected_bounds(Bounds::from_corners(selection_start, selection_end), window, cx);

        // NOTE: the selection is computed purely from the geometric band
        // (`selection_start`..`selection_end`), NOT from what is currently
        // visible. Every glyph of a *painted* element is laid out (its
        // `position_for_index` is valid) even when it is scrolled out of, or
        // clipped by, an ancestor's viewport — the content mask only clips the
        // painted pixels. Because the copied text is derived from
        // `InlineState.selection`, gating the selection on `content_mask` here
        // used to drop scrolled-out-but-selected glyphs, so a selection taller
        // than the viewport (e.g. a long chat message, or a drag with
        // auto-scroll) copied only the portion that happened to be on screen.
        //
        // This does not resurrect the #2156 clipped-hit-testing behavior: a
        // selection can only START on visible text (window selection resolves
        // endpoints with hitbox hover testing against visible Inline bounds),
        // so the band's endpoints are always anchored to on-screen text.
        // Content that is merely `overflow_hidden`
        // (not scrolled) lies outside that band and is still excluded, while
        // the highlight quads painted for off-screen glyphs are clipped away by
        // GPUI's content mask as before.
        let mut selection: Option<Selection> = None;
        let mut offset = 0;
        let mut chars = self.text.chars().peekable();
        while let Some(c) = chars.next() {
            let Some(pos) = text_layout.position_for_index(offset) else {
                offset += c.len_utf8();
                continue;
            };

            let next_offset = offset + c.len_utf8();
            let mut char_width = line_height.half();
            if let Some(next_pos) = text_layout.position_for_index(next_offset) {
                if next_pos.y == pos.y {
                    char_width = next_pos.x - pos.x;
                }
            }

            let selection_pos = self
                .selection_bounds
                .map_or(pos, |bounds| point(pos.x, bounds.top()));
            let selection_height = self
                .selection_bounds
                .map_or(line_height, |bounds| bounds.size.height);
            if point_in_text_selection(
                selection_pos,
                char_width,
                selection_start,
                selection_end,
                selection_height,
            ) {
                if selection.is_none() {
                    selection = Some((offset..offset).into());
                }

                if let Some(selection) = selection.as_mut() {
                    selection.end = next_offset;
                }
            }

            offset = next_offset;
        }

        (true, true, selection)
    }

    /// One box per laid-out row, from the row's start to its last character,
    /// clipped to `mask_bounds`.
    ///
    /// Walks the wrapped line layouts rather than every character:
    /// [`TextLayout::position_for_index`] scans a line's rows and glyphs on
    /// each call, so a per-character walk cost O(chars × glyphs) for every
    /// selectable inline on every frame — the largest single cost of painting
    /// a long chat message while it scrolls.
    ///
    /// A row followed by another row (a wrap or a newline) is extended by half
    /// a line height past its last glyph: the character walk gave that width
    /// to a character whose successor sits on the next row, and the selection
    /// geometry was tuned against it.
    fn text_line_bounds(
        text_layout: &TextLayout,
        line_height: Pixels,
        mask_bounds: Bounds<Pixels>,
    ) -> Vec<Bounds<Pixels>> {
        let origin = text_layout.bounds().origin;
        let lines = text_layout.line_layouts();
        let row_count: usize = lines
            .iter()
            .map(|line| line.wrap_boundaries.len() + 1)
            .sum();
        let mut line_bounds = Vec::with_capacity(row_count);
        let mut row_ix = 0;
        let mut y = origin.y;
        for line in &lines {
            let layout = &line.unwrapped_layout;
            let mut row_start = 0;
            let row_ends = line
                .wrap_boundaries
                .iter()
                .map(|boundary| layout.runs[boundary.run_ix].glyphs[boundary.glyph_ix].index)
                .chain([line.len()]);
            for row_end in row_ends {
                let mut width = layout.x_for_index(row_end) - layout.x_for_index(row_start);
                row_ix += 1;
                if row_ix < row_count {
                    width += line_height.half();
                }
                let bounds = Bounds::new(point(origin.x, y), size(width, line_height))
                    .intersect(&mask_bounds);
                if bounds.size.width > px(0.) && bounds.size.height > px(0.) {
                    line_bounds.push(bounds);
                }
                y += line_height;
                row_start = row_end;
            }
        }
        line_bounds
    }

    /// The caret line boxes at the two ends of a painted selection, where the
    /// touch handles are drawn.
    fn selection_edges(
        selection: &Selection,
        text_layout: &TextLayout,
    ) -> Option<(Bounds<Pixels>, Bounds<Pixels>)> {
        let (start, end) = (
            selection.start.min(selection.end),
            selection.start.max(selection.end),
        );
        let line_height = text_layout.line_height();
        Some((
            crate::touch_selection::caret_line_box(
                text_layout.position_for_index(start)?,
                line_height,
            ),
            crate::touch_selection::caret_line_box(
                text_layout.position_for_index(end)?,
                line_height,
            ),
        ))
    }

    /// Paint the selection background.
    fn paint_selection(
        selection: &Selection,
        text_layout: &TextLayout,
        bounds: &Bounds<Pixels>,
        window: &mut Window,
        color: gpui::Hsla,
    ) {
        let mut start = selection.start;
        let mut end = selection.end;
        if end < start {
            std::mem::swap(&mut start, &mut end);
        }
        let Some(start_position) = text_layout.position_for_index(start) else {
            return;
        };
        let Some(end_position) = text_layout.position_for_index(end) else {
            return;
        };

        let line_height = text_layout.line_height();
        if start_position.y == end_position.y {
            window.paint_quad(quad(
                Bounds::from_corners(
                    start_position,
                    point(end_position.x, end_position.y + line_height),
                ),
                px(0.),
                color,
                Edges::default(),
                gpui::transparent_black(),
                BorderStyle::default(),
            ));
        } else {
            window.paint_quad(quad(
                Bounds::from_corners(
                    start_position,
                    point(bounds.right(), start_position.y + line_height),
                ),
                px(0.),
                color,
                Edges::default(),
                gpui::transparent_black(),
                BorderStyle::default(),
            ));

            if end_position.y > start_position.y + line_height {
                window.paint_quad(quad(
                    Bounds::from_corners(
                        point(bounds.left(), start_position.y + line_height),
                        point(bounds.right(), end_position.y),
                    ),
                    px(0.),
                    color,
                    Edges::default(),
                    gpui::transparent_black(),
                    BorderStyle::default(),
                ));
            }

            window.paint_quad(quad(
                Bounds::from_corners(
                    point(bounds.left(), end_position.y),
                    point(end_position.x, end_position.y + line_height),
                ),
                px(0.),
                color,
                Edges::default(),
                gpui::transparent_black(),
                BorderStyle::default(),
            ));
        }
    }
}

impl IntoElement for Inline {
    type Element = Self;

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

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

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

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

    fn request_layout(
        &mut self,
        global_element_id: Option<&GlobalElementId>,
        inspector_id: Option<&InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, Self::RequestLayoutState) {
        let text_style = self
            .text_style
            .clone()
            .unwrap_or_else(|| window.text_style());
        let runs = text_runs(self.text.len(), &text_style, &self.highlights);

        // Reuse the previous frame's shaped text when it was shaped from the
        // same text, runs and style; `StyledText` consumes its runs on every
        // layout, so they are handed over again either way.
        let retained = take_retained_layout(&self.state).filter(|retained| {
            retained.text == self.text && retained.runs == runs && retained.text_style == text_style
        });
        self.styled_text = match retained {
            Some(retained) => retained.styled_text.with_runs(runs.clone()),
            None => StyledText::new(self.text.clone()).with_runs(runs.clone()),
        };
        self.retained_key = Some((runs, text_style));
        let (layout_id, _) =
            self.styled_text
                .request_layout(global_element_id, inspector_id, 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::PrepaintState {
        let bounds = Bounds::new(self.paint_origin.unwrap_or(bounds.origin), bounds.size);
        self.styled_text
            .prepaint(id, inspector_id, bounds, &mut (), window, cx);

        // Report this element's laid-out extent so an ancestor TextView with
        // `max_lines` can snap its clip to a whole-line boundary. The state
        // stack only holds an entry during prepaint when that view set
        // `max_lines`, so this is a no-op otherwise.
        if let Some(text_view_state) = GlobalState::global(cx).text_view_state().cloned() {
            let state = text_view_state.read(cx);
            if state.max_lines.is_some()
                && let Ok(mut line_spans) = state.line_spans.lock()
            {
                line_spans.push(LineSpan {
                    top: bounds.top(),
                    bottom: bounds.bottom(),
                    line_height: window.line_height(),
                });
            }
        }

        let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
        self.retain_styled_text();
        hitbox
    }

    fn paint(
        &mut self,
        global_id: Option<&GlobalElementId>,
        _: Option<&InspectorElementId>,
        bounds: Bounds<Pixels>,
        _: &mut Self::RequestLayoutState,
        prepaint: &mut Self::PrepaintState,
        window: &mut Window,
        cx: &mut App,
    ) {
        let bounds = Bounds::new(self.paint_origin.unwrap_or(bounds.origin), bounds.size);
        let current_view = window.current_view();
        let hitbox = prepaint;
        if !self.reclaim_styled_text() {
            // Cannot happen (only this element takes what it handed over,
            // and a live state is never swept); skip the frame rather than
            // paint an unmeasured placeholder.
            return;
        }
        let text_layout = self.styled_text.layout().clone();
        self.styled_text
            .paint(global_id, None, bounds, &mut (), &mut (), window, cx);

        // layout selections
        let (is_selectable, is_selection, selection) =
            self.layout_selections(&text_layout, &bounds, window, cx);

        let Ok(mut state) = self.state.lock() else {
            return;
        };

        state.selection = selection;
        if let Some((source, range)) = &self.selection_source
            && let Some(selection) = selection
            && let Ok(mut source) = source.lock()
        {
            let start = range.start + selection.start;
            let end = range.start + selection.end;
            source.selection = Some(match source.selection {
                Some(previous) => Selection::new(previous.start.min(start), previous.end.max(end)),
                None => Selection::new(start, end),
            });
        }

        if is_selection || is_selectable {
            window.set_cursor_style(CursorStyle::IBeam, &hitbox);
        }

        // link cursor pointer
        let mouse_position = window.mouse_position();
        if let Some(_) = Self::link_for_position(&text_layout, &self.links, mouse_position) {
            window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
        }

        if let Some(selection) = &state.selection {
            let color = GlobalState::global(cx)
                .text_view_state()
                .map(|state| state.read(cx).text_view_style.selection())
                .unwrap_or_else(|| crate::Theme::global(cx).tokens.colors.selection);
            Self::paint_selection(selection, &text_layout, &bounds, window, color);
            if let Some((start, end)) = Self::selection_edges(selection, &text_layout)
                && let Some(text_view_state) = GlobalState::global(cx).text_view_state().cloned()
            {
                text_view_state.update(cx, |state, _| {
                    state.selection_adapter.register_selection_edges(start, end);
                });
            }
        }

        if is_selectable {
            if let Some(text_view_state) = GlobalState::global(cx).text_view_state().cloned() {
                let text_bounds = Self::text_line_bounds(
                    &text_layout,
                    text_layout.line_height(),
                    window.content_mask().bounds,
                );
                text_view_state.update(cx, |state, _| {
                    state.selection_adapter.register_inline(text_bounds);
                    state
                        .selection_adapter
                        .register_text_run(crate::TextSelectionRun::new(
                            self.text.clone(),
                            text_layout.clone(),
                            hitbox.bounds,
                        ));
                });
            }

            window.on_mouse_event({
                let hitbox = hitbox.clone();
                let text_layout = text_layout.clone();
                let inline_state = self.state.clone();
                let text = self.text.clone();
                let text_view_state = GlobalState::global(cx).text_view_state().cloned();
                let line_bounds = self.selection_bounds;
                move |event: &MouseDownEvent, phase, window, cx| {
                    if !phase.bubble()
                        || !hitbox.is_hovered(window)
                        || event.button != MouseButton::Left
                    {
                        return;
                    }

                    if event.click_count == 3
                        && let Some(line_bounds) = line_bounds
                    {
                        GlobalState::suppress_text_selection(cx);
                        if let Some(view) = &text_view_state {
                            view.update(cx, |state, cx| {
                                state.set_multi_click_line(line_bounds, cx)
                            });
                        }
                        cx.notify(current_view);
                        return;
                    }

                    // A finger selects read-only text with a long press only;
                    // a double tap selects nothing here, neither the mouse's
                    // plain word nor the window layer's touch selection. The
                    // handles and the menu on a double tap belong to `Input`.
                    if event.click_count == 2 && GlobalState::is_touch_press(cx) {
                        GlobalState::suppress_text_selection(cx);
                        return;
                    }

                    let kind = match event.click_count {
                        2 => TextViewMultiClickKind::Word,
                        3 => TextViewMultiClickKind::Paragraph,
                        _ => return,
                    };

                    let Some(range) = selection_for_multi_click(
                        &text,
                        &text_layout,
                        hitbox.bounds,
                        event.position,
                        kind,
                    ) else {
                        return;
                    };

                    let selected_text = text[range.clone()].to_string();

                    // This renderer owns multi-click selection. Prevent the
                    // window selection layer from handling the same press.
                    GlobalState::suppress_text_selection(cx);

                    if let Ok(mut inline_state) = inline_state.lock() {
                        inline_state.selection = Some(range.into());
                    }
                    if let Some(text_view_state) = &text_view_state {
                        text_view_state.update(cx, |state, cx| {
                            state.set_multi_click_selection(
                                event.position,
                                kind,
                                selected_text,
                                cx,
                            );
                        });
                    }
                    cx.notify(current_view);
                }
            });
        }

        // mouse move, update hovered link
        window.on_mouse_event({
            let hitbox = hitbox.clone();
            let text_layout = text_layout.clone();
            let mut hovered_index = state.hovered_index;
            move |event: &MouseMoveEvent, phase, window, cx| {
                if !phase.bubble() || !hitbox.is_hovered(window) {
                    return;
                }

                let current = hovered_index;
                let updated = text_layout.index_for_position(event.position).ok();
                //  notify update when hovering over different links
                if current != updated {
                    hovered_index = updated;
                    cx.notify(current_view);
                }
            }
        });

        if !is_selection {
            // click to open link
            window.on_mouse_event({
                let links = self.links.clone();
                let text_layout = text_layout.clone();
                let hitbox = hitbox.clone();
                let text_view_state = GlobalState::global(cx).text_view_state().cloned();
                let link_click_handler = self.link_click_handler.clone();

                move |event: &MouseUpEvent, phase, window, cx| {
                    if !phase.bubble() || !hitbox.is_hovered(window) {
                        return;
                    }
                    if text_view_state
                        .as_ref()
                        .is_some_and(|state| state.read(cx).has_selection(cx))
                    {
                        return;
                    }

                    if let Some(link) =
                        Self::link_for_position(&text_layout, &links, event.position)
                    {
                        TextSelection::end(window, cx);
                        cx.stop_propagation();
                        let click = ClickEvent::Mouse(MouseClickEvent {
                            down: MouseDownEvent {
                                button: event.button,
                                position: event.position,
                                modifiers: event.modifiers,
                                click_count: event.click_count,
                                first_mouse: false,
                            },
                            up: event.clone(),
                        });
                        handle_link_click(&link_click_handler, link.url, click, window, cx);
                    }
                }
            });
        }

        drop(state);
        self.retain_styled_text();
    }
}

fn selection_for_multi_click(
    text: &str,
    text_layout: &TextLayout,
    bounds: Bounds<Pixels>,
    pos: Point<Pixels>,
    kind: TextViewMultiClickKind,
) -> Option<std::ops::Range<usize>> {
    if !bounds.contains(&pos) {
        return None;
    }

    let offset = text_layout.index_for_position(pos).ok()?;

    match kind {
        TextViewMultiClickKind::Word => word_range_at(text, offset),
        // Known limitation: a paragraph maps to a single Inline run here. When a
        // paragraph embeds an inline image it is split into multiple Inline runs,
        // so triple-click only selects the run on the clicked side of the image.
        TextViewMultiClickKind::Paragraph | TextViewMultiClickKind::Line => {
            (!text.is_empty()).then_some(0..text.len())
        }
    }
}

/// Check if a `pos` is within a `bounds`, considering multi-line selections.
pub(super) fn point_in_text_selection(
    pos: Point<Pixels>,
    char_width: Pixels,
    selection_start: Point<Pixels>,
    selection_end: Point<Pixels>,
    line_height: Pixels,
) -> bool {
    let point_in_line = |point: Point<Pixels>| point.y >= pos.y && point.y < pos.y + line_height;
    let top = selection_start.y.min(selection_end.y);
    let bottom = selection_start.y.max(selection_end.y);
    let x = pos.x + char_width.half();

    // Out of the vertical bounds
    if pos.y + line_height <= top || pos.y > bottom {
        return false;
    }

    // Treat the selection as single-line when both drag points fall within the
    // same rendered line, even if their y coordinates differ inside that line.
    if point_in_line(selection_start) && point_in_line(selection_end) {
        let left = selection_start.x.min(selection_end.x);
        let right = selection_start.x.max(selection_end.x);
        return x >= left && x <= right;
    }

    let (top_point, bottom_point) = if selection_start.y < selection_end.y {
        (selection_start, selection_end)
    } else {
        (selection_end, selection_start)
    };
    let is_top_line = point_in_line(top_point);
    let is_bottom_line = point_in_line(bottom_point);

    if is_top_line {
        return x >= top_point.x;
    } else if is_bottom_line {
        return x <= bottom_point.x;
    } else {
        return true;
    }
}

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

    #[test]
    fn fades_text_and_background_only_inside_the_range() {
        let code = InlineHighlight::from(HighlightStyle {
            background_color: Some(gpui::red()),
            ..Default::default()
        });
        let combined = fade_highlights(vec![(0..4, code)], &[(2..6, 0.5)]);

        let ranges: Vec<_> = combined.iter().map(|(range, _)| range.clone()).collect();
        assert_eq!(ranges, vec![0..2, 2..4, 4..6]);

        let (_, untouched) = &combined[0];
        assert_eq!(untouched.style.fade_out, None);
        assert_eq!(untouched.style.background_color.unwrap().a, 1.0);

        let (_, faded_code) = &combined[1];
        assert_eq!(faded_code.style.fade_out, Some(0.5));
        assert_eq!(faded_code.style.background_color.unwrap().a, 0.5);

        let (_, faded_text) = &combined[2];
        assert_eq!(faded_text.style.fade_out, Some(0.5));
        assert!(faded_text.style.background_color.is_none());
    }

    #[test]
    fn no_fades_leave_highlights_untouched() {
        let bold = InlineHighlight::from(HighlightStyle {
            font_weight: Some(gpui::FontWeight::BOLD),
            ..Default::default()
        });
        let highlights = vec![(1..3, bold)];
        assert_eq!(fade_highlights(highlights.clone(), &[]), highlights);
    }
}

#[cfg(test)]
mod line_bounds_tests {
    use super::*;
    use super::{
        test_draw::in_prepaint,
        test_fonts::{BODY, WideMonoTextSystem},
    };
    use gpui::{AvailableSpace, TestApp, size};

    /// The character walk this replaced, kept as the oracle: one box per
    /// character from `position_for_index`, unioned per row.
    fn by_character(
        text: &str,
        text_layout: &TextLayout,
        line_height: Pixels,
        mask_bounds: Bounds<Pixels>,
    ) -> Vec<Bounds<Pixels>> {
        let mut line_bounds = Vec::new();
        let mut current_line_y = None;
        let mut current_bounds: Option<Bounds<Pixels>> = None;
        let mut offset = 0;
        for c in text.chars() {
            let next_offset = offset + c.len_utf8();
            let Some(pos) = text_layout.position_for_index(offset) else {
                offset = next_offset;
                continue;
            };
            let mut char_width = line_height.half();
            if let Some(next_pos) = text_layout.position_for_index(next_offset)
                && next_pos.y == pos.y
            {
                char_width = next_pos.x - pos.x;
            }
            let bounds = Bounds::from_corners(pos, point(pos.x + char_width, pos.y + line_height))
                .intersect(&mask_bounds);
            if bounds.size.width > px(0.) && bounds.size.height > px(0.) {
                if current_line_y == Some(pos.y) {
                    if let Some(current) = current_bounds.as_mut() {
                        *current = current.union(&bounds);
                    }
                } else {
                    if let Some(current) = current_bounds.take() {
                        line_bounds.push(current);
                    }
                    current_line_y = Some(pos.y);
                    current_bounds = Some(bounds);
                }
            }
            offset = next_offset;
        }
        if let Some(current) = current_bounds {
            line_bounds.push(current);
        }
        line_bounds
    }

    #[test]
    fn row_walk_matches_the_character_walk() {
        let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
        in_prepaint(&mut app, |window, cx| {
            let style = TextStyle {
                font_family: BODY.into(),
                font_size: px(16.).into(),
                ..Default::default()
            };
            let origin = point(px(7.), px(11.));
            let mask = Bounds::new(point(px(0.), px(0.)), size(px(1000.), px(1000.)));
            let clipped = Bounds::new(point(px(20.), px(30.)), size(px(50.), px(60.)));
            for text in [
                "",
                "one row",
                "a long paragraph that wraps onto several rows of eight pixel glyphs",
                "first line\nsecond line that also wraps around\n\nfourth",
                "中文与 English 混排的一段文字也会换行",
                "trailing newline\n",
            ] {
                for wrap_width in [40., 100., 1000.] {
                    let runs = text_runs(text.len(), &style, &[]);
                    let styled =
                        StyledText::new(SharedString::from(text.to_string())).with_runs(runs);
                    let layout = styled.layout().clone();
                    let mut element = styled.into_any_element();
                    element.layout_as_root(
                        size(
                            AvailableSpace::Definite(px(wrap_width)),
                            AvailableSpace::MinContent,
                        ),
                        window,
                        cx,
                    );
                    element.prepaint_at(origin, window, cx);
                    let line_height = layout.line_height();
                    for mask in [mask, clipped] {
                        let expected = by_character(text, &layout, line_height, mask);
                        let actual = Inline::text_line_bounds(&layout, line_height, mask);
                        let context = format!("{text:?} at {wrap_width}px in {mask:?}");
                        // The character walk placed a wrapped row's first
                        // character at the end of the row before it: that row's
                        // box started one glyph in, and a row holding only that
                        // one glyph had no box at all. The row walk covers every
                        // row from its start, so it may see more rows, never
                        // fewer, and agrees on every row the walk could see.
                        assert!(
                            actual.len() >= expected.len(),
                            "rows of {context}: {} < {}",
                            actual.len(),
                            expected.len()
                        );
                        for (row, expected) in expected.iter().enumerate() {
                            let actual = actual
                                .iter()
                                .find(|actual| actual.top() == expected.top())
                                .unwrap_or_else(|| panic!("row {row} of {context} is missing"));
                            assert_eq!(
                                actual.bottom(),
                                expected.bottom(),
                                "row {row} of {context}"
                            );
                            assert_eq!(actual.right(), expected.right(), "row {row} of {context}");
                            assert!(
                                actual.left() <= expected.left(),
                                "row {row} of {context} starts at {:?}, after {:?}",
                                actual.left(),
                                expected.left()
                            );
                        }
                        for actual in &actual {
                            assert_eq!(
                                actual.left(),
                                origin.x.max(mask.left()),
                                "left of {context}"
                            );
                        }
                    }
                }
            }
        });
    }
}

/// A platform text system for tests where the `Mono` family shapes twice as
/// wide as every other family, so a measurement that ignores the family of a
/// run comes out visibly short.
#[cfg(test)]
pub(super) mod test_draw {
    use gpui::{App, Context, IntoElement, Render, Styled as _, TestApp, Window, canvas, px};
    use std::{cell::RefCell, rc::Rc};

    struct Probe {
        body: Option<Box<dyn FnOnce(&mut Window, &mut App)>>,
    }

    impl Render for Probe {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            let body = self.body.take();
            canvas(
                move |_, window, cx| {
                    if let Some(body) = body {
                        body(window, cx);
                    }
                },
                |_, _, _, _| {},
            )
            .w(px(1000.))
            .h(px(1000.))
        }
    }

    /// Runs `f` inside a real prepaint pass and returns its value.
    ///
    /// Measuring an inline object lays its GPUI element out through the
    /// window, which GPUI only permits while a frame is being drawn, so a test
    /// that builds a real element cannot call the measurement helpers straight
    /// from `TestAppWindow::update`.
    pub(crate) fn in_prepaint<R: 'static>(
        app: &mut TestApp,
        f: impl FnOnce(&mut Window, &mut App) -> R + 'static,
    ) -> R {
        let slot: Rc<RefCell<Option<R>>> = Rc::new(RefCell::new(None));
        let out = slot.clone();
        let mut window = app.open_window(|_, _| Probe {
            body: Some(Box::new(move |window, cx| {
                *out.borrow_mut() = Some(f(window, cx));
            })),
        });
        window.draw();
        let value = slot.borrow_mut().take();
        value.expect("prepaint probe did not run")
    }
}

#[cfg(test)]
pub(super) mod test_fonts {
    use gpui::{
        Bounds, DevicePixels, Font, FontId, FontMetrics, FontRun, FontWeight, GlyphId, LineLayout,
        Pixels, PlatformTextSystem, RenderGlyphParams, ShapedGlyph, ShapedRun, Size,
        TextRenderingMode, point, px, size,
    };
    use std::borrow::Cow;

    pub(crate) const BODY: &str = "Body";
    pub(crate) const MONO: &str = "Mono";
    const BODY_ID: FontId = FontId(1);
    const MONO_ID: FontId = FontId(2);
    const BOLD_BODY_ID: FontId = FontId(3);
    const BOLD_MONO_ID: FontId = FontId(4);
    const UNITS_PER_EM: f32 = 1000.;

    pub(crate) struct WideMonoTextSystem;

    impl WideMonoTextSystem {
        /// Advance of one glyph in `font_id`, in em units.
        fn advance_units(font_id: FontId) -> f32 {
            match font_id {
                MONO_ID => 1000.,
                BOLD_MONO_ID => 1250.,
                BODY_ID => 500.,
                BOLD_BODY_ID => 750.,
                _ => 500.,
            }
        }

        /// Width of `text` shaped entirely in `family` at `font_size`.
        pub(crate) fn width_of(text: &str, family: &str, font_size: Pixels) -> Pixels {
            let font_id = if family == MONO { MONO_ID } else { BODY_ID };
            font_size * (Self::advance_units(font_id) / UNITS_PER_EM) * text.chars().count() as f32
        }
    }

    impl PlatformTextSystem for WideMonoTextSystem {
        fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> anyhow::Result<()> {
            Ok(())
        }

        fn all_font_names(&self) -> Vec<String> {
            vec![BODY.into(), MONO.into()]
        }

        fn font_id(&self, descriptor: &Font) -> anyhow::Result<FontId> {
            Ok(
                match (
                    descriptor.family.as_ref() == MONO,
                    descriptor.weight == FontWeight::BOLD,
                ) {
                    (true, true) => BOLD_MONO_ID,
                    (true, false) => MONO_ID,
                    (false, true) => BOLD_BODY_ID,
                    (false, false) => BODY_ID,
                },
            )
        }

        fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
            FontMetrics {
                units_per_em: UNITS_PER_EM as u32,
                ascent: 800.,
                descent: -200.,
                line_gap: 0.,
                underline_position: -100.,
                underline_thickness: 50.,
                cap_height: 700.,
                x_height: 500.,
                bounding_box: Bounds {
                    origin: point(0., -200.),
                    size: size(1000., 1000.),
                },
            }
        }

        fn typographic_bounds(
            &self,
            font_id: FontId,
            _glyph_id: GlyphId,
        ) -> anyhow::Result<Bounds<f32>> {
            Ok(Bounds {
                origin: point(0., 0.),
                size: size(Self::advance_units(font_id), 700.),
            })
        }

        fn advance(&self, font_id: FontId, _glyph_id: GlyphId) -> anyhow::Result<Size<f32>> {
            Ok(size(Self::advance_units(font_id), 0.))
        }

        fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
            Some(GlyphId(ch as u32))
        }

        fn glyph_raster_bounds(
            &self,
            _params: &RenderGlyphParams,
        ) -> anyhow::Result<Bounds<DevicePixels>> {
            Ok(Bounds::default())
        }

        fn rasterize_glyph(
            &self,
            _params: &RenderGlyphParams,
            raster_bounds: Bounds<DevicePixels>,
        ) -> anyhow::Result<(Size<DevicePixels>, Vec<u8>)> {
            Ok((raster_bounds.size, Vec::new()))
        }

        fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
            let mut position = px(0.);
            let mut shaped_runs = Vec::new();
            let mut run_start = 0;
            for run in runs {
                let run_text = &text[run_start..run_start + run.len];
                let advance = font_size * (Self::advance_units(run.font_id) / UNITS_PER_EM);
                let mut glyphs = Vec::new();
                for (ix, ch) in run_text.char_indices() {
                    glyphs.push(ShapedGlyph {
                        id: GlyphId(ch as u32),
                        position: point(position, px(0.)),
                        index: run_start + ix,
                        is_emoji: false,
                    });
                    position += advance;
                }
                shaped_runs.push(ShapedRun {
                    font_id: run.font_id,
                    glyphs,
                });
                run_start += run.len;
            }
            let metrics = self.font_metrics(BODY_ID);
            LineLayout {
                font_size,
                width: position,
                ascent: font_size * (metrics.ascent / UNITS_PER_EM),
                // Native backends normalize the signed font metric for shaped lines.
                descent: font_size * (-metrics.descent / UNITS_PER_EM),
                runs: shaped_runs,
                len: text.len(),
            }
        }

        fn recommended_rendering_mode(
            &self,
            _font_id: FontId,
            _font_size: Pixels,
        ) -> TextRenderingMode {
            TextRenderingMode::Grayscale
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{InlineHighlight, combine_highlights, point_in_text_selection, text_runs};
    use gpui::{FontWeight, HighlightStyle, SharedString, TextStyle, point, px};

    fn mono(style: HighlightStyle) -> InlineHighlight {
        InlineHighlight {
            style,
            font_family: Some(SharedString::from("Mono")),
            font_size_scale: None,
        }
    }

    #[test]
    fn text_runs_shape_a_code_highlight_in_its_font_family() {
        let style = TextStyle {
            font_family: SharedString::from("Body"),
            ..Default::default()
        };
        let highlights = vec![(4..8, mono(HighlightStyle::default()))];

        let runs = text_runs(12, &style, &highlights);

        let families = runs
            .iter()
            .map(|run| (run.len, run.font.family.as_ref()))
            .collect::<Vec<_>>();
        assert_eq!(families, vec![(4, "Body"), (4, "Mono"), (4, "Body")]);
    }

    #[test]
    fn combine_highlights_cuts_a_bold_span_at_the_code_boundary() {
        // `**bold `code`**`: the bold mark spans the code mark, so the
        // combined list carries the weight on both sides and the family on
        // the code side only.
        let bold = InlineHighlight::from(HighlightStyle {
            font_weight: Some(FontWeight::BOLD),
            ..Default::default()
        });
        let combined = combine_highlights(
            vec![(0..10, bold)],
            vec![(6..10, mono(HighlightStyle::default()))],
        );

        assert_eq!(combined.len(), 2);
        assert_eq!(combined[0].0, 0..6);
        assert_eq!(combined[0].1.style.font_weight, Some(FontWeight::BOLD));
        assert_eq!(combined[0].1.font_family, None);
        assert_eq!(combined[1].0, 6..10);
        assert_eq!(combined[1].1.style.font_weight, Some(FontWeight::BOLD));
        assert_eq!(combined[1].1.font_family.as_deref(), Some("Mono"));
    }

    #[test]
    fn test_point_in_text_selection() {
        let line_height = px(20.);
        let char_width = px(10.);
        let start = point(px(50.), px(50.));
        let end = point(px(150.), px(150.));

        // First line but haft line height, true
        // | p --------|
        // | selection |
        // |-----------|
        assert!(point_in_text_selection(
            point(px(50.), px(40.)),
            char_width,
            start,
            end,
            line_height
        ));

        // First line in selection, true
        // | p --------|
        // | selection |
        // |-----------|
        assert!(point_in_text_selection(
            point(px(50.), px(50.)),
            char_width,
            start,
            end,
            line_height
        ));
        // First line, but left out of selection, false
        // p |-----------|
        //   | selection |
        //   |-----------|
        assert!(!point_in_text_selection(
            point(px(40.), px(50.)),
            char_width,
            start,
            end,
            line_height
        ));
        // First line but right out of selection, true
        // |-----------| p
        // | selection |
        // |-----------|
        assert!(point_in_text_selection(
            point(px(160.), px(50.)),
            char_width,
            start,
            end,
            line_height
        ));

        // Middle line in selection, true
        // |-----------|
        // |     p     |
        // |-----------|
        assert!(point_in_text_selection(
            point(px(100.), px(70.)),
            char_width,
            start,
            end,
            line_height
        ));
        // Middle line, but left out of selection, true
        //   |-----------|
        // p | selection |
        //   |-----------|
        assert!(point_in_text_selection(
            point(px(40.), px(70.)),
            char_width,
            start,
            end,
            line_height
        ));
        // Middle line, but right out of selection, true
        // |-----------|
        // | selection | p
        // |-----------|
        assert!(point_in_text_selection(
            point(px(160.), px(70.)),
            char_width,
            start,
            end,
            line_height
        ));

        // Last line in selection, true
        // |-----------|
        // | selection |
        // |------- p -|
        assert!(point_in_text_selection(
            point(px(100.), px(140.)),
            char_width,
            start,
            end,
            line_height
        ));
        // Last line, but left out of selection, true
        //
        //   |-----------|
        //   | selection |
        // p |-----------|
        assert!(point_in_text_selection(
            point(px(40.), px(140.)),
            char_width,
            start,
            end,
            line_height
        ));
        // Last line, but right out of selection, false
        // |-----------|
        // | selection |
        // |-----------| p
        assert!(!point_in_text_selection(
            point(px(160.), px(140.)),
            char_width,
            start,
            end,
            line_height
        ));

        // Out of vertical bounds (top), false
        //       p
        // |-----------|
        // | selection |
        // |-----------|
        assert!(!point_in_text_selection(
            point(px(100.), px(20.)),
            char_width,
            start,
            end,
            line_height
        ));
        // Out of vertical bounds (bottom), false
        // |-----------|
        // | selection |
        // |-----------|
        //       p
        assert!(!point_in_text_selection(
            point(px(100.), px(160.)),
            char_width,
            start,
            end,
            line_height
        ));
    }

    #[test]
    fn test_point_in_text_selection_reversed_drag_direction() {
        let line_height = px(20.);
        let char_width = px(10.);

        // Mouse down on lower line then drag upward to x=150.
        // Top line should follow current mouse x, bottom line should keep anchor x.
        let start = point(px(80.), px(150.));
        let end = point(px(150.), px(50.));

        // On top line, selection starts from top cursor x (150), so x=140 should be excluded.
        assert!(!point_in_text_selection(
            point(px(140.), px(50.)),
            char_width,
            start,
            end,
            line_height
        ));
        assert!(point_in_text_selection(
            point(px(150.), px(50.)),
            char_width,
            start,
            end,
            line_height
        ));

        // On bottom line, selection ends at anchor x (80), so x=90 should be excluded.
        assert!(point_in_text_selection(
            point(px(75.), px(140.)),
            char_width,
            start,
            end,
            line_height
        ));
        assert!(!point_in_text_selection(
            point(px(80.), px(140.)),
            char_width,
            start,
            end,
            line_height
        ));
    }

    #[test]
    fn test_point_in_text_selection_same_visual_line_with_different_y() {
        let line_height = px(20.);
        let char_width = px(10.);
        let start = point(px(100.), px(55.));
        let end = point(px(60.), px(58.));

        assert!(!point_in_text_selection(
            point(px(40.), px(50.)),
            char_width,
            start,
            end,
            line_height
        ));
        assert!(point_in_text_selection(
            point(px(70.), px(50.)),
            char_width,
            start,
            end,
            line_height
        ));
        assert!(!point_in_text_selection(
            point(px(110.), px(50.)),
            char_width,
            start,
            end,
            line_height
        ));
    }

    #[test]
    fn test_point_in_text_selection_same_visual_line_with_reversed_y() {
        let line_height = px(20.);
        let char_width = px(10.);
        let start = point(px(60.), px(58.));
        let end = point(px(100.), px(55.));

        assert!(!point_in_text_selection(
            point(px(40.), px(50.)),
            char_width,
            start,
            end,
            line_height
        ));
        assert!(point_in_text_selection(
            point(px(70.), px(50.)),
            char_width,
            start,
            end,
            line_height
        ));
        assert!(!point_in_text_selection(
            point(px(110.), px(50.)),
            char_width,
            start,
            end,
            line_height
        ));
    }
}

#[cfg(test)]
mod retained_layout_tests {
    use gpui::{
        AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _,
        TestAppContext, Window, div, px,
    };

    use super::RETAINED_LAYOUTS;
    use crate::text::{TextView, TextViewState};

    /// The same document shown twice in one window, as a preview beside the
    /// text: both `Inline`s share every `InlineState`.
    struct Twice {
        state: Entity<TextViewState>,
    }

    impl Render for Twice {
        fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
            div()
                .w(px(300.))
                .child(TextView::new(&self.state))
                .child(TextView::new(&self.state))
        }
    }

    /// Without the hand-over rule the second copy's prepaint replaced the
    /// first copy's entry, and the first copy painted with the second's
    /// layout — at the second's bounds.
    #[gpui::test]
    fn the_same_paragraph_rendered_twice_in_a_frame_keeps_one_layout_and_paints_both(
        cx: &mut TestAppContext,
    ) {
        cx.update(crate::init);
        let (_, cx) = cx.add_window_view(|_, cx| Twice {
            state: cx
                .new(|cx| TextViewState::markdown("First paragraph.\n\nSecond **paragraph**.", cx)),
        });
        cx.run_until_parked();

        // Frame 1 fills the table, frame 2 reuses it; neither may lose the
        // shaped text of either copy (painting an unmeasured placeholder
        // panics inside GPUI).
        for _ in 0..3 {
            cx.update(|window, cx| window.draw(cx).clear(cx));
        }

        let retained = RETAINED_LAYOUTS.with(|layouts| layouts.borrow().len());
        assert_eq!(retained, 2, "one layout per paragraph state");
    }
}