BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-base / src / text / inline.rs

inline.rs

eef6c0a4 History
inline.rs 87.3 KiB Download Raw
1use gpui::Corners;
2use std::{
3 cell::RefCell,
4 collections::HashMap,
5 mem,
6 ops::Range,
7 rc::Rc,
8 sync::{Arc, Mutex, Weak},
9};
10
11use gpui::{
12 App, BorderStyle, Bounds, ClickEvent, CursorStyle, Edges, Element, ElementId, GlobalElementId,
13 Half, HighlightStyle, Hitbox, HitboxBehavior, Hsla, InspectorElementId, IntoElement, LayoutId,
14 MouseButton, MouseClickEvent, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point,
15 SharedString, StyledText, TextAlign, TextLayout, TextRun, TextStyle, Window, point, px, quad,
16 size,
17};
18
19use crate::{
20 GlobalState, TextSelection,
21 input::Selection,
22 text::TextViewMultiClickKind,
23 text::node::LinkMark,
24 text::range_highlight::RevealAt,
25 text::selection::word_range_at,
26 text::state::LineSpan,
27 text::text_view::{LinkClickHandlerFn, handle_link_click},
28 text_selection::text_rows_extent,
29};
30
31/// The style applied to one range of inline text.
32///
33/// A [`HighlightStyle`] carries no font family, so the family an inline code
34/// span is set in rides beside it; `None` keeps the family of the enclosing
35/// text style.
36#[derive(Clone, Debug, Default, PartialEq)]
37pub(super) struct InlineHighlight {
38 pub(super) style: HighlightStyle,
39 pub(super) font_family: Option<SharedString>,
40 pub(super) font_size_scale: Option<f32>,
41}
42
43impl InlineHighlight {
44 /// Layers `other` over `self`, the way [`HighlightStyle::highlight`] does.
45 fn highlight(mut self, other: &InlineHighlight) -> Self {
46 self.style = self.style.highlight(other.style);
47 if other.font_family.is_some() {
48 self.font_family = other.font_family.clone();
49 }
50 if other.font_size_scale.is_some() {
51 self.font_size_scale = other.font_size_scale;
52 }
53 self
54 }
55}
56
57impl From<HighlightStyle> for InlineHighlight {
58 fn from(style: HighlightStyle) -> Self {
59 Self {
60 style,
61 font_family: None,
62 font_size_scale: None,
63 }
64 }
65}
66
67/// Merges two highlight lists over one text into non-overlapping ranges,
68/// cutting at every endpoint of every input range. Same sweep as
69/// [`gpui::combine_highlights`], for [`InlineHighlight`] payloads.
70pub(super) fn combine_highlights(
71 a: impl IntoIterator<Item = (Range<usize>, InlineHighlight)>,
72 b: impl IntoIterator<Item = (Range<usize>, InlineHighlight)>,
73) -> Vec<(Range<usize>, InlineHighlight)> {
74 let mut endpoints = Vec::new();
75 let mut highlights = Vec::new();
76 for (range, highlight) in a.into_iter().chain(b) {
77 if !range.is_empty() {
78 let id = highlights.len();
79 endpoints.push((range.start, id, true));
80 endpoints.push((range.end, id, false));
81 highlights.push(highlight);
82 }
83 }
84 endpoints.sort_unstable_by_key(|(position, _, _)| *position);
85
86 let mut combined = Vec::new();
87 let mut active: Vec<usize> = Vec::new();
88 let mut ix = 0;
89 for (position, id, is_start) in endpoints {
90 if position > ix && !active.is_empty() {
91 let style = active.iter().fold(InlineHighlight::default(), |acc, id| {
92 acc.highlight(&highlights[*id])
93 });
94 combined.push((ix..position, style));
95 }
96 ix = position;
97 if is_start {
98 active.push(id);
99 } else {
100 active.retain(|active_id| *active_id != id);
101 }
102 }
103 combined
104}
105
106/// Layers a streamed fade-in over `highlights`: text inside each fade range
107/// loses that share of its color, and a highlight background fades with it so
108/// an inline code chip does not appear before its text.
109pub(super) fn fade_highlights(
110 highlights: Vec<(Range<usize>, InlineHighlight)>,
111 fades: &[(Range<usize>, f32)],
112) -> Vec<(Range<usize>, InlineHighlight)> {
113 if fades.is_empty() {
114 return highlights;
115 }
116 let fade_highlights = fades.iter().map(|(range, fade_out)| {
117 (
118 range.clone(),
119 InlineHighlight::from(HighlightStyle {
120 fade_out: Some(*fade_out),
121 ..Default::default()
122 }),
123 )
124 });
125 let mut combined = combine_highlights(highlights, fade_highlights);
126 for (_, highlight) in &mut combined {
127 if let Some(fade_out) = highlight.style.fade_out
128 && let Some(background) = highlight.style.background_color.as_mut()
129 {
130 background.fade_out(fade_out);
131 }
132 }
133 combined
134}
135
136/// Builds the [`TextRun`]s for `text_len` bytes of inline text: each
137/// highlight refines `default_style` over its range, and a highlight that
138/// names a font family shapes its run in that family.
139pub(super) fn text_runs(
140 text_len: usize,
141 default_style: &TextStyle,
142 highlights: &[(Range<usize>, InlineHighlight)],
143) -> Vec<TextRun> {
144 let mut runs = Vec::with_capacity(highlights.len() * 2 + 1);
145 let mut ix = 0;
146 for (range, highlight) in highlights {
147 if ix < range.start {
148 runs.push(default_style.clone().to_run(range.start - ix));
149 }
150 let mut run = default_style
151 .clone()
152 .highlight(highlight.style)
153 .to_run(range.len());
154 if let Some(family) = &highlight.font_family {
155 run.font.family = family.clone();
156 }
157 runs.push(run);
158 ix = range.end;
159 }
160 if ix < text_len {
161 runs.push(default_style.to_run(text_len - ix));
162 }
163 runs
164}
165
166/// Splits text into contiguous ranges sharing one font size. GPUI runs can
167/// vary the font but not its size, so each range needs its own shaped line.
168pub(super) fn text_size_ranges(
169 text_len: usize,
170 highlights: &[(Range<usize>, InlineHighlight)],
171) -> Vec<(Range<usize>, f32)> {
172 let mut ranges: Vec<(Range<usize>, f32)> = Vec::new();
173 let mut push = |range: Range<usize>, scale: f32| {
174 if range.is_empty() {
175 return;
176 }
177 if let Some((last, last_scale)) = ranges.last_mut()
178 && *last_scale == scale
179 && last.end == range.start
180 {
181 last.end = range.end;
182 } else {
183 ranges.push((range, scale));
184 }
185 };
186 let mut cursor = 0;
187 for (range, highlight) in highlights {
188 push(cursor..range.start, 1.);
189 push(range.clone(), highlight.font_size_scale.unwrap_or(1.));
190 cursor = range.end;
191 }
192 push(cursor..text_len, 1.);
193 ranges
194}
195
196/// A inline element used to render a inline text and support selectable.
197///
198/// All text in TextView (including the CodeBlock) used this for text rendering.
199pub(super) struct Inline {
200 text: SharedString,
201 links: Rc<Vec<(Range<usize>, LinkMark)>>,
202 highlights: Vec<(Range<usize>, InlineHighlight)>,
203 styled_text: StyledText,
204 /// The resolved style from a parent deferred layout, when there is one.
205 text_style: Option<TextStyle>,
206 paint_origin: Option<Point<Pixels>>,
207 selection_bounds: Option<Bounds<Pixels>>,
208 selection_source: Option<(Arc<Mutex<InlineState>>, Range<usize>)>,
209 /// Range highlight backgrounds, painted behind the text.
210 range_backgrounds: Vec<(Range<usize>, Hsla)>,
211 /// The start of a pending reveal, when it is in this text.
212 reveal: Option<RevealAt>,
213 link_click_handler: Option<Arc<LinkClickHandlerFn>>,
214 /// What this frame's layout was shaped with, to hand the shaped text to
215 /// the next frame (see [`RetainedLayout`]).
216 retained_key: Option<(Vec<TextRun>, TextStyle)>,
217 /// The shaped text is in the table, not in `styled_text`, until paint
218 /// takes it back.
219 handed_over: bool,
220
221 state: Arc<Mutex<InlineState>>,
222}
223
224/// The inline text state, used RefCell to keep the selection state.
225#[derive(Debug, Default, PartialEq)]
226pub(crate) struct InlineState {
227 /// The text that actually rendering, matched with selection.
228 pub(super) text: SharedString,
229 pub(super) selection: Option<Selection>,
230}
231
232/// One frame's [`StyledText`], kept for the next frame's [`Inline`] of the
233/// same [`InlineState`].
234///
235/// A [`TextLayout`] remembers the size and the shaped lines of its last
236/// measurement and answers a repeated measure at the same wrap width from
237/// them, but a fresh `StyledText` every frame throws that away, so every
238/// frame of a scroll paid for a line wrapper, a shaping-cache lookup that
239/// hashes the whole paragraph, and the allocations around them for every
240/// visible paragraph. Handing the same `StyledText` to the next frame makes
241/// those measurements hits. A layout is only reused when the text, the runs
242/// (colors, fades, fonts) and the text style (font size, line height) it was
243/// shaped with are unchanged; a different wrap width misses inside
244/// `TextLayout` and reshapes as before.
245///
246/// `StyledText` is main-thread only (an `Rc` inside), while `InlineState`
247/// travels through the background parse, so the layouts live in a
248/// thread-local table keyed by the state's address, with a `Weak` to tell a
249/// live state from a reused address.
250struct RetainedLayout {
251 state: Weak<Mutex<InlineState>>,
252 styled_text: StyledText,
253 text: SharedString,
254 runs: Vec<TextRun>,
255 text_style: TextStyle,
256}
257
258thread_local! {
259 static RETAINED_LAYOUTS: RefCell<HashMap<usize, RetainedLayout>> = RefCell::new(HashMap::new());
260}
261
262/// Dead entries (states that were dropped without a final paint, e.g. a
263/// replaced document) are swept once the table grows past this many.
264const RETAINED_SWEEP_AT: usize = 4096;
265
266fn state_key(state: &Arc<Mutex<InlineState>>) -> usize {
267 Arc::as_ptr(state) as usize
268}
269
270/// Takes the layout retained for `state`, if the previous frame left one.
271fn take_retained_layout(state: &Arc<Mutex<InlineState>>) -> Option<RetainedLayout> {
272 RETAINED_LAYOUTS.with(|layouts| {
273 let retained = layouts.borrow_mut().remove(&state_key(state))?;
274 // The address may belong to a new state by now.
275 retained
276 .state
277 .upgrade()
278 .is_some_and(|live| Arc::ptr_eq(&live, state))
279 .then_some(retained)
280 })
281}
282
283/// Whether the table already holds a layout for `state`: every entry left
284/// by the previous frame is taken at layout time, so one that is present
285/// afterwards was put there this frame, by another element of the same state.
286fn has_retained_layout(state: &Arc<Mutex<InlineState>>) -> bool {
287 RETAINED_LAYOUTS.with(|layouts| layouts.borrow().contains_key(&state_key(state)))
288}
289
290fn retain_layout(state: &Arc<Mutex<InlineState>>, retained: RetainedLayout) {
291 RETAINED_LAYOUTS.with(|layouts| {
292 let mut layouts = layouts.borrow_mut();
293 if layouts.len() >= RETAINED_SWEEP_AT {
294 layouts.retain(|_, retained| retained.state.strong_count() > 0);
295 }
296 layouts.insert(state_key(state), retained);
297 });
298}
299
300impl InlineState {
301 /// Save actually rendered text for selected text to use.
302 pub(crate) fn set_text(&mut self, text: SharedString) {
303 self.text = text;
304 }
305}
306
307impl Inline {
308 /// Hands the shaped text to the next frame (see [`RetainedLayout`]).
309 /// Called after prepaint, so an element that is laid out but never
310 /// painted (scrolled out of view) keeps its layout too; paint takes it
311 /// back for the duration of painting.
312 ///
313 /// When another element of the same state already handed one over this
314 /// frame (the same document shown twice), this one keeps its own: the
315 /// table holds one layout per state, and an element must never be left
316 /// to paint without its shaped text.
317 fn retain_styled_text(&mut self) {
318 if self.handed_over || self.retained_key.is_none() || has_retained_layout(&self.state) {
319 return;
320 }
321 let Some((runs, text_style)) = self.retained_key.take() else {
322 return;
323 };
324 retain_layout(
325 &self.state,
326 RetainedLayout {
327 state: Arc::downgrade(&self.state),
328 styled_text: mem::replace(&mut self.styled_text, StyledText::new("")),
329 text: self.text.clone(),
330 runs,
331 text_style,
332 },
333 );
334 self.handed_over = true;
335 }
336
337 /// Takes the shaped text back from the table for painting. `false` when
338 /// it is gone, in which case there is nothing to paint with.
339 fn reclaim_styled_text(&mut self) -> bool {
340 if !self.handed_over {
341 return true;
342 }
343 let Some(retained) = take_retained_layout(&self.state) else {
344 return false;
345 };
346 self.styled_text = retained.styled_text;
347 self.retained_key = Some((retained.runs, retained.text_style));
348 self.handed_over = false;
349 true
350 }
351
352 pub(super) fn new(
353 state: Arc<Mutex<InlineState>>,
354 links: Vec<(Range<usize>, LinkMark)>,
355 highlights: Vec<(Range<usize>, InlineHighlight)>,
356 link_click_handler: Option<Arc<LinkClickHandlerFn>>,
357 ) -> Self {
358 let text = state
359 .lock()
360 .map(|state| state.text.clone())
361 .unwrap_or_default();
362
363 Self {
364 links: Rc::new(links),
365 highlights,
366 text: text.clone(),
367 styled_text: StyledText::new(text),
368 text_style: None,
369 paint_origin: None,
370 selection_bounds: None,
371 selection_source: None,
372 range_backgrounds: Vec::new(),
373 reveal: None,
374 link_click_handler,
375 retained_key: None,
376 handed_over: false,
377 state,
378 }
379 }
380
381 /// Use the resolved style captured by a deferred parent layout.
382 pub(super) fn text_style(mut self, text_style: TextStyle) -> Self {
383 self.text_style = Some(text_style);
384 self
385 }
386
387 /// Preserve the shared inline-flow baseline through GPUI's element-bound snapping.
388 pub(super) fn paint_origin(mut self, origin: Point<Pixels>) -> Self {
389 self.paint_origin = Some(origin);
390 self
391 }
392
393 pub(super) fn selection_bounds(mut self, bounds: Bounds<Pixels>) -> Self {
394 self.selection_bounds = Some(bounds);
395 self
396 }
397
398 pub(super) fn selection_source(
399 mut self,
400 state: Arc<Mutex<InlineState>>,
401 range: Range<usize>,
402 ) -> Self {
403 self.selection_source = Some((state, range));
404 self
405 }
406
407 /// Paint `backgrounds` behind the text. They are not part of the text
408 /// runs, so changing them does not shape the text again.
409 pub(super) fn range_backgrounds(mut self, backgrounds: Vec<(Range<usize>, Hsla)>) -> Self {
410 self.range_backgrounds = backgrounds;
411 self
412 }
413
414 /// Scroll the line `reveal` starts on into view during prepaint.
415 pub(super) fn reveal(mut self, reveal: Option<RevealAt>) -> Self {
416 self.reveal = reveal;
417 self
418 }
419
420 /// Ask the enclosing list to scroll the line of the pending reveal into
421 /// view, and report where it is and whether it is inside the visible
422 /// area.
423 fn request_reveal(&self, window: &mut Window) {
424 let Some(reveal) = &self.reveal else {
425 return;
426 };
427 let text_layout = self.styled_text.layout();
428 let bounds = text_layout.bounds();
429 let line_height = text_layout.line_height();
430 let glyphs = glyph_boxes(
431 text_layout,
432 window.text_style().text_align,
433 bounds.size.width,
434 );
435 // The glyph drawing the text at the offset, or, for text with no
436 // glyph of its own such as a line break, the next glyph, or the last.
437 let offset = reveal.offset();
438 let (row, left, right) = range_boxes(&glyphs, offset..offset + 1)
439 .first()
440 .copied()
441 .or_else(|| {
442 glyphs
443 .iter()
444 .find(|glyph| glyph.text.start >= offset)
445 .or(glyphs.last())
446 .map(|glyph| (glyph.row, glyph.left, glyph.right))
447 })
448 .unwrap_or((0, Pixels::ZERO, Pixels::ZERO));
449 let line = Bounds::from_corners(
450 point(
451 bounds.left() + left,
452 bounds.top() + line_height * row as f32,
453 ),
454 point(
455 bounds.left() + right.max(left + px(1.)),
456 bounds.top() + line_height * (row + 1) as f32,
457 ),
458 );
459 window.request_autoscroll(line);
460 // A list scrolls the line to its edge, which layout may miss by a
461 // fraction of a pixel.
462 let visible = window.content_mask().bounds.dilate(px(0.5));
463 reveal.report(
464 line,
465 line.top() >= visible.top() && line.bottom() <= visible.bottom(),
466 );
467 }
468
469 /// Get link at given mouse position.
470 fn link_for_position(
471 layout: &TextLayout,
472 links: &Vec<(Range<usize>, LinkMark)>,
473 position: Point<Pixels>,
474 ) -> Option<LinkMark> {
475 let offset = layout.index_for_position(position).ok()?;
476 for (range, link) in links.iter() {
477 if range.contains(&offset) {
478 return Some(link.clone());
479 }
480 }
481
482 None
483 }
484
485 /// Get the range of the link at given mouse position.
486 fn link_range_for_position(
487 layout: &TextLayout,
488 links: &[(Range<usize>, LinkMark)],
489 position: Point<Pixels>,
490 ) -> Option<Range<usize>> {
491 let offset = layout.index_for_position(position).ok()?;
492 links
493 .iter()
494 .find(|(range, _)| range.contains(&offset))
495 .map(|(range, _)| range.clone())
496 }
497
498 /// Paint selected bounds for debug.
499 #[allow(unused)]
500 fn paint_selected_bounds(&self, bounds: Bounds<Pixels>, window: &mut Window, cx: &mut App) {
501 window.paint_quad(gpui::PaintQuad {
502 bounds,
503 background: gpui::hsla(0.58, 0.85, 0.62, 0.01).into(),
504 corner_radii: Corners::default(),
505 border_color: gpui::transparent_black(),
506 border_style: BorderStyle::default(),
507 border_widths: gpui::Edges::all(px(0.)),
508 });
509 }
510
511 fn layout_selections(
512 &self,
513 text_layout: &TextLayout,
514 bounds: &Bounds<Pixels>,
515 window: &mut Window,
516 cx: &mut App,
517 ) -> (bool, bool, Option<Selection>) {
518 let Some(text_view_state) = GlobalState::global(cx).text_view_state() else {
519 return (false, false, None);
520 };
521
522 let text_view_state = text_view_state.read(cx);
523 let is_selectable = text_view_state.is_selectable();
524 if !is_selectable {
525 return (false, false, None);
526 }
527
528 if text_view_state.is_all_selected() {
529 return (is_selectable, true, Some((0..self.text.len()).into()));
530 }
531
532 if text_view_state.preserve_inline_selection {
533 let selection = if let Some((source, range)) = &self.selection_source {
534 source
535 .lock()
536 .ok()
537 .and_then(|state| state.selection)
538 .and_then(|selection| {
539 let start = selection.start.max(range.start);
540 let end = selection.end.min(range.end);
541 (start < end)
542 .then(|| Selection::new(start - range.start, end - range.start))
543 })
544 } else {
545 self.state.lock().ok().and_then(|state| state.selection)
546 };
547 return (true, selection.is_some(), selection);
548 }
549
550 if let Some(selection) = text_view_state.multi_click_selection() {
551 if selection.kind == TextViewMultiClickKind::Line {
552 return (
553 true,
554 true,
555 selection
556 .line_bounds
557 .filter(|row| row.contains(&bounds.center()))
558 .map(|_| Selection::new(0, self.text.len())),
559 );
560 }
561 return (
562 is_selectable,
563 true,
564 selection_for_multi_click(
565 &self.text,
566 text_layout,
567 *bounds,
568 selection.pos,
569 selection.kind,
570 )
571 .map(Selection::from),
572 );
573 }
574
575 let Some((selection_start, selection_end)) = text_view_state.selection_points(cx) else {
576 return (is_selectable, false, None);
577 };
578 let line_height = window.line_height();
579
580 // Use for debug selection bounds
581 // self.paint_selected_bounds(Bounds::from_corners(selection_start, selection_end), window, cx);
582
583 // NOTE: the selection is computed purely from the geometric band
584 // (`selection_start`..`selection_end`), NOT from what is currently
585 // visible. Every glyph of a *painted* element is laid out (its
586 // `position_for_index` is valid) even when it is scrolled out of, or
587 // clipped by, an ancestor's viewport — the content mask only clips the
588 // painted pixels. Because the copied text is derived from
589 // `InlineState.selection`, gating the selection on `content_mask` here
590 // used to drop scrolled-out-but-selected glyphs, so a selection taller
591 // than the viewport (e.g. a long chat message, or a drag with
592 // auto-scroll) copied only the portion that happened to be on screen.
593 //
594 // This does not resurrect the #2156 clipped-hit-testing behavior: a
595 // selection can only START on visible text (window selection resolves
596 // endpoints with hitbox hover testing against visible Inline bounds),
597 // so the band's endpoints are always anchored to on-screen text.
598 // Content that is merely `overflow_hidden`
599 // (not scrolled) lies outside that band and is still excluded, while
600 // the highlight quads painted for off-screen glyphs are clipped away by
601 // GPUI's content mask as before.
602 //
603 // Each character is tested with its row's top and height, so an inline
604 // whose rows all miss the band, or all lie strictly inside it with no
605 // endpoint on any row, has the same answer for every character. Decide
606 // those without the walk below, which scans the layout twice per
607 // character: one long code block alone made every paint of a held
608 // selection cost tens of milliseconds.
609 if self.text.is_empty() {
610 return (true, true, None);
611 }
612 let (rows_top, rows_bottom) = match self.selection_bounds {
613 Some(bounds) => (bounds.top(), bounds.top() + bounds.size.height),
614 None => text_rows_extent(text_layout, line_height),
615 };
616 let band_top = selection_start.y.min(selection_end.y);
617 let band_bottom = selection_start.y.max(selection_end.y);
618 if rows_bottom <= band_top || rows_top > band_bottom {
619 return (true, true, None);
620 }
621 if band_top < rows_top && band_bottom >= rows_bottom && text_layout.len() >= self.text.len()
622 {
623 return (true, true, Some((0..self.text.len()).into()));
624 }
625
626 let mut selection: Option<Selection> = None;
627 let mut offset = 0;
628 let mut chars = self.text.chars().peekable();
629 while let Some(c) = chars.next() {
630 let Some(pos) = text_layout.position_for_index(offset) else {
631 offset += c.len_utf8();
632 continue;
633 };
634
635 let next_offset = offset + c.len_utf8();
636 let mut char_width = line_height.half();
637 if let Some(next_pos) = text_layout.position_for_index(next_offset) {
638 if next_pos.y == pos.y {
639 char_width = next_pos.x - pos.x;
640 }
641 }
642
643 let selection_pos = self
644 .selection_bounds
645 .map_or(pos, |bounds| point(pos.x, bounds.top()));
646 let selection_height = self
647 .selection_bounds
648 .map_or(line_height, |bounds| bounds.size.height);
649 if point_in_text_selection(
650 selection_pos,
651 char_width,
652 selection_start,
653 selection_end,
654 selection_height,
655 ) {
656 if selection.is_none() {
657 selection = Some((offset..offset).into());
658 }
659
660 if let Some(selection) = selection.as_mut() {
661 selection.end = next_offset;
662 }
663 }
664
665 offset = next_offset;
666 }
667
668 (true, true, selection)
669 }
670
671 /// One box per laid-out row, from the row's start to its last character,
672 /// clipped to `mask_bounds`.
673 ///
674 /// Walks the wrapped line layouts rather than every character:
675 /// [`TextLayout::position_for_index`] scans a line's rows and glyphs on
676 /// each call, so a per-character walk cost O(chars × glyphs) for every
677 /// selectable inline on every frame — the largest single cost of painting
678 /// a long chat message while it scrolls.
679 ///
680 /// A row followed by another row (a wrap or a newline) is extended by half
681 /// a line height past its last glyph: the character walk gave that width
682 /// to a character whose successor sits on the next row, and the selection
683 /// geometry was tuned against it.
684 fn text_line_bounds(
685 text_layout: &TextLayout,
686 line_height: Pixels,
687 mask_bounds: Bounds<Pixels>,
688 ) -> Vec<Bounds<Pixels>> {
689 let origin = text_layout.bounds().origin;
690 let lines = text_layout.line_layouts();
691 let row_count: usize = lines
692 .iter()
693 .map(|line| line.wrap_boundaries.len() + 1)
694 .sum();
695 let mut line_bounds = Vec::with_capacity(row_count);
696 let mut row_ix = 0;
697 let mut y = origin.y;
698 for line in &lines {
699 let layout = &line.unwrapped_layout;
700 let mut row_start = 0;
701 let row_ends = line
702 .wrap_boundaries
703 .iter()
704 .map(|boundary| layout.runs[boundary.run_ix].glyphs[boundary.glyph_ix].index)
705 .chain([line.len()]);
706 for row_end in row_ends {
707 let mut width = layout.x_for_index(row_end) - layout.x_for_index(row_start);
708 row_ix += 1;
709 if row_ix < row_count {
710 width += line_height.half();
711 }
712 let bounds = Bounds::new(point(origin.x, y), size(width, line_height))
713 .intersect(&mask_bounds);
714 if bounds.size.width > px(0.) && bounds.size.height > px(0.) {
715 line_bounds.push(bounds);
716 }
717 y += line_height;
718 row_start = row_end;
719 }
720 }
721 line_bounds
722 }
723
724 /// The caret line boxes at the two ends of a painted selection, where the
725 /// touch handles are drawn.
726 fn selection_edges(
727 selection: &Selection,
728 text_layout: &TextLayout,
729 ) -> Option<(Bounds<Pixels>, Bounds<Pixels>)> {
730 let (start, end) = (
731 selection.start.min(selection.end),
732 selection.start.max(selection.end),
733 );
734 let line_height = text_layout.line_height();
735 Some((
736 crate::touch_selection::caret_line_box(
737 text_layout.position_for_index(start)?,
738 line_height,
739 ),
740 crate::touch_selection::caret_line_box(
741 text_layout.position_for_index(end)?,
742 line_height,
743 ),
744 ))
745 }
746
747 /// Paint the selection background.
748 fn paint_selection(
749 selection: &Selection,
750 text_layout: &TextLayout,
751 bounds: &Bounds<Pixels>,
752 window: &mut Window,
753 color: gpui::Hsla,
754 ) {
755 let mut start = selection.start;
756 let mut end = selection.end;
757 if end < start {
758 std::mem::swap(&mut start, &mut end);
759 }
760 let Some(start_position) = text_layout.position_for_index(start) else {
761 return;
762 };
763 let Some(end_position) = text_layout.position_for_index(end) else {
764 return;
765 };
766
767 let line_height = text_layout.line_height();
768 if start_position.y == end_position.y {
769 window.paint_quad(quad(
770 Bounds::from_corners(
771 start_position,
772 point(end_position.x, end_position.y + line_height),
773 ),
774 px(0.),
775 color,
776 Edges::default(),
777 gpui::transparent_black(),
778 BorderStyle::default(),
779 ));
780 } else {
781 window.paint_quad(quad(
782 Bounds::from_corners(
783 start_position,
784 point(bounds.right(), start_position.y + line_height),
785 ),
786 px(0.),
787 color,
788 Edges::default(),
789 gpui::transparent_black(),
790 BorderStyle::default(),
791 ));
792
793 if end_position.y > start_position.y + line_height {
794 window.paint_quad(quad(
795 Bounds::from_corners(
796 point(bounds.left(), start_position.y + line_height),
797 point(bounds.right(), end_position.y),
798 ),
799 px(0.),
800 color,
801 Edges::default(),
802 gpui::transparent_black(),
803 BorderStyle::default(),
804 ));
805 }
806
807 window.paint_quad(quad(
808 Bounds::from_corners(
809 point(bounds.left(), end_position.y),
810 point(end_position.x, end_position.y + line_height),
811 ),
812 px(0.),
813 color,
814 Edges::default(),
815 gpui::transparent_black(),
816 BorderStyle::default(),
817 ));
818 }
819 }
820
821 /// Paint each range highlight behind the text of its range.
822 fn paint_range_highlights(&self, text_layout: &TextLayout, window: &mut Window) {
823 let glyphs = glyph_boxes(
824 text_layout,
825 window.text_style().text_align,
826 text_layout.bounds().size.width,
827 );
828 let origin = text_layout.bounds().origin;
829 let line_height = text_layout.line_height();
830 for (range, color) in &self.range_backgrounds {
831 for (row, left, right) in range_boxes(&glyphs, range.clone()) {
832 window.paint_quad(gpui::fill(
833 Bounds::from_corners(
834 point(origin.x + left, origin.y + line_height * row as f32),
835 point(origin.x + right, origin.y + line_height * (row + 1) as f32),
836 ),
837 *color,
838 ));
839 }
840 }
841 }
842}
843
844impl IntoElement for Inline {
845 type Element = Self;
846
847 fn into_element(self) -> Self::Element {
848 self
849 }
850}
851
852impl Element for Inline {
853 type RequestLayoutState = ();
854 type PrepaintState = Hitbox;
855
856 fn id(&self) -> Option<ElementId> {
857 None
858 }
859
860 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
861 None
862 }
863
864 fn request_layout(
865 &mut self,
866 global_element_id: Option<&GlobalElementId>,
867 inspector_id: Option<&InspectorElementId>,
868 window: &mut Window,
869 cx: &mut App,
870 ) -> (LayoutId, Self::RequestLayoutState) {
871 let text_style = self
872 .text_style
873 .clone()
874 .unwrap_or_else(|| window.text_style());
875 let runs = text_runs(self.text.len(), &text_style, &self.highlights);
876
877 // Reuse the previous frame's shaped text when it was shaped from the
878 // same text, runs and style; `StyledText` consumes its runs on every
879 // layout, so they are handed over again either way.
880 let retained = take_retained_layout(&self.state).filter(|retained| {
881 retained.text == self.text && retained.runs == runs && retained.text_style == text_style
882 });
883 self.styled_text = match retained {
884 Some(retained) => retained.styled_text.with_runs(runs.clone()),
885 None => StyledText::new(self.text.clone()).with_runs(runs.clone()),
886 };
887 self.retained_key = Some((runs, text_style));
888 let (layout_id, _) =
889 self.styled_text
890 .request_layout(global_element_id, inspector_id, window, cx);
891
892 (layout_id, ())
893 }
894
895 fn prepaint(
896 &mut self,
897 id: Option<&GlobalElementId>,
898 inspector_id: Option<&InspectorElementId>,
899 bounds: Bounds<Pixels>,
900 _: &mut Self::RequestLayoutState,
901 window: &mut Window,
902 cx: &mut App,
903 ) -> Self::PrepaintState {
904 let bounds = Bounds::new(self.paint_origin.unwrap_or(bounds.origin), bounds.size);
905 self.styled_text
906 .prepaint(id, inspector_id, bounds, &mut (), window, cx);
907
908 // Report this element's laid-out extent so an ancestor TextView with
909 // `max_lines` can snap its clip to a whole-line boundary. The state
910 // stack only holds an entry during prepaint when that view set
911 // `max_lines`, so this is a no-op otherwise.
912 if let Some(text_view_state) = GlobalState::global(cx).text_view_state().cloned() {
913 let state = text_view_state.read(cx);
914 if state.max_lines.is_some()
915 && let Ok(mut line_spans) = state.line_spans.lock()
916 {
917 line_spans.push(LineSpan {
918 top: bounds.top(),
919 bottom: bounds.bottom(),
920 line_height: window.line_height(),
921 });
922 }
923 }
924
925 self.request_reveal(window);
926
927 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
928 self.retain_styled_text();
929 hitbox
930 }
931
932 fn paint(
933 &mut self,
934 global_id: Option<&GlobalElementId>,
935 _: Option<&InspectorElementId>,
936 bounds: Bounds<Pixels>,
937 _: &mut Self::RequestLayoutState,
938 prepaint: &mut Self::PrepaintState,
939 window: &mut Window,
940 cx: &mut App,
941 ) {
942 let bounds = Bounds::new(self.paint_origin.unwrap_or(bounds.origin), bounds.size);
943 let current_view = window.current_view();
944 let hitbox = prepaint;
945 if !self.reclaim_styled_text() {
946 // Cannot happen (only this element takes what it handed over,
947 // and a live state is never swept); skip the frame rather than
948 // paint an unmeasured placeholder.
949 return;
950 }
951 let text_layout = self.styled_text.layout().clone();
952 if !self.range_backgrounds.is_empty() {
953 self.paint_range_highlights(&text_layout, window);
954 }
955 self.styled_text
956 .paint(global_id, None, bounds, &mut (), &mut (), window, cx);
957
958 // layout selections
959 let (is_selectable, is_selection, selection) =
960 self.layout_selections(&text_layout, &bounds, window, cx);
961
962 let Ok(mut state) = self.state.lock() else {
963 return;
964 };
965
966 state.selection = selection;
967 if let Some((source, range)) = &self.selection_source
968 && let Some(selection) = selection
969 && let Ok(mut source) = source.lock()
970 {
971 let start = range.start + selection.start;
972 let end = range.start + selection.end;
973 source.selection = Some(match source.selection {
974 Some(previous) => Selection::new(previous.start.min(start), previous.end.max(end)),
975 None => Selection::new(start, end),
976 });
977 }
978
979 if is_selection || is_selectable {
980 window.set_cursor_style(CursorStyle::IBeam, &hitbox);
981 }
982
983 // link cursor pointer
984 let hovered_link =
985 Self::link_range_for_position(&text_layout, &self.links, window.mouse_position());
986 if hovered_link.is_some() {
987 window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
988 }
989
990 if let Some(selection) = &state.selection {
991 let color = GlobalState::global(cx)
992 .text_view_state()
993 .map(|state| state.read(cx).text_view_style.selection())
994 .unwrap_or_else(|| crate::Theme::global(cx).tokens.colors.selection);
995 Self::paint_selection(selection, &text_layout, &bounds, window, color);
996 if let Some((start, end)) = Self::selection_edges(selection, &text_layout)
997 && let Some(text_view_state) = GlobalState::global(cx).text_view_state().cloned()
998 {
999 text_view_state.update(cx, |state, _| {
1000 state.selection_adapter.register_selection_edges(start, end);
1001 });
1002 }
1003 }
1004
1005 if is_selectable {
1006 if let Some(text_view_state) = GlobalState::global(cx).text_view_state().cloned() {
1007 let text_bounds = Self::text_line_bounds(
1008 &text_layout,
1009 text_layout.line_height(),
1010 window.content_mask().bounds,
1011 );
1012 text_view_state.update(cx, |state, _| {
1013 state.selection_adapter.register_inline(text_bounds);
1014 state
1015 .selection_adapter
1016 .register_text_run(crate::TextSelectionRun::new(
1017 self.text.clone(),
1018 text_layout.clone(),
1019 hitbox.bounds,
1020 ));
1021 });
1022 }
1023
1024 window.on_mouse_event({
1025 let hitbox = hitbox.clone();
1026 let text_layout = text_layout.clone();
1027 let inline_state = self.state.clone();
1028 let text = self.text.clone();
1029 let text_view_state = GlobalState::global(cx).text_view_state().cloned();
1030 let line_bounds = self.selection_bounds;
1031 move |event: &MouseDownEvent, phase, window, cx| {
1032 if !phase.bubble()
1033 || !hitbox.is_hovered(window)
1034 || event.button != MouseButton::Left
1035 {
1036 return;
1037 }
1038
1039 if event.click_count == 3
1040 && let Some(line_bounds) = line_bounds
1041 {
1042 GlobalState::suppress_text_selection(cx);
1043 if let Some(view) = &text_view_state {
1044 view.update(cx, |state, cx| {
1045 state.set_multi_click_line(line_bounds, cx)
1046 });
1047 }
1048 cx.notify(current_view);
1049 return;
1050 }
1051
1052 // A finger selects read-only text with a long press only;
1053 // a double tap selects nothing here, neither the mouse's
1054 // plain word nor the window layer's touch selection. The
1055 // handles and the menu on a double tap belong to `Input`.
1056 if event.click_count == 2 && GlobalState::is_touch_press(cx) {
1057 GlobalState::suppress_text_selection(cx);
1058 return;
1059 }
1060
1061 let kind = match event.click_count {
1062 2 => TextViewMultiClickKind::Word,
1063 3 => TextViewMultiClickKind::Paragraph,
1064 _ => return,
1065 };
1066
1067 let Some(range) = selection_for_multi_click(
1068 &text,
1069 &text_layout,
1070 hitbox.bounds,
1071 event.position,
1072 kind,
1073 ) else {
1074 return;
1075 };
1076
1077 let selected_text = text[range.clone()].to_string();
1078
1079 // This renderer owns multi-click selection. Prevent the
1080 // window selection layer from handling the same press.
1081 GlobalState::suppress_text_selection(cx);
1082
1083 if let Ok(mut inline_state) = inline_state.lock() {
1084 inline_state.selection = Some(range.into());
1085 }
1086 if let Some(text_view_state) = &text_view_state {
1087 text_view_state.update(cx, |state, cx| {
1088 state.set_multi_click_selection(
1089 event.position,
1090 kind,
1091 selected_text,
1092 cx,
1093 );
1094 });
1095 }
1096 cx.notify(current_view);
1097 }
1098 });
1099 }
1100
1101 // Mouse move: repaint only when the pointer enters, leaves or moves
1102 // between links, so the link cursor follows it. Hovering plain text
1103 // changes nothing painted.
1104 if !self.links.is_empty() {
1105 window.on_mouse_event({
1106 let hitbox = hitbox.clone();
1107 let text_layout = text_layout.clone();
1108 let links = self.links.clone();
1109 let mut hovered_link = hovered_link;
1110 move |event: &MouseMoveEvent, phase, window, cx| {
1111 if !phase.bubble() || !hitbox.is_hovered(window) {
1112 return;
1113 }
1114
1115 let updated =
1116 Self::link_range_for_position(&text_layout, &links, event.position);
1117 if hovered_link != updated {
1118 hovered_link = updated;
1119 cx.notify(current_view);
1120 }
1121 }
1122 });
1123 }
1124
1125 if !is_selection {
1126 // click to open link
1127 window.on_mouse_event({
1128 let links = self.links.clone();
1129 let text_layout = text_layout.clone();
1130 let hitbox = hitbox.clone();
1131 let text_view_state = GlobalState::global(cx).text_view_state().cloned();
1132 let link_click_handler = self.link_click_handler.clone();
1133
1134 move |event: &MouseUpEvent, phase, window, cx| {
1135 if !phase.bubble() || !hitbox.is_hovered(window) {
1136 return;
1137 }
1138 if text_view_state
1139 .as_ref()
1140 .is_some_and(|state| state.read(cx).has_selection(cx))
1141 {
1142 return;
1143 }
1144
1145 if let Some(link) =
1146 Self::link_for_position(&text_layout, &links, event.position)
1147 {
1148 TextSelection::end(window, cx);
1149 cx.stop_propagation();
1150 let click = ClickEvent::Mouse(MouseClickEvent {
1151 down: MouseDownEvent {
1152 button: event.button,
1153 position: event.position,
1154 modifiers: event.modifiers,
1155 click_count: event.click_count,
1156 first_mouse: false,
1157 },
1158 up: event.clone(),
1159 });
1160 handle_link_click(&link_click_handler, link.url, click, window, cx);
1161 }
1162 }
1163 });
1164 }
1165
1166 drop(state);
1167 self.retain_styled_text();
1168 }
1169}
1170
1171/// Where one glyph of laid-out text paints: its row, and its horizontal
1172/// extent past the text's origin, alignment applied. `text` is the byte range
1173/// of the text it draws.
1174#[derive(Clone, Debug, PartialEq)]
1175struct GlyphBox {
1176 text: Range<usize>,
1177 row: usize,
1178 left: Pixels,
1179 right: Pixels,
1180}
1181
1182/// The glyphs of `text_layout`, sorted by the text they draw, each placed
1183/// the way GPUI paints it: every row aligned in `align_width` by `align`,
1184/// and a glyph reaching to the next one on its row, or to the row's end.
1185///
1186/// Glyphs are read in the order they paint, so right-to-left text, whose
1187/// glyphs paint in the reverse order of its text, is placed as it shows.
1188fn glyph_boxes(text_layout: &TextLayout, align: TextAlign, align_width: Pixels) -> Vec<GlyphBox> {
1189 let mut boxes = Vec::new();
1190 let mut row = 0;
1191 let mut line_start = 0;
1192 for line in text_layout.line_layouts() {
1193 let layout = &line.unwrapped_layout;
1194 let glyphs = layout
1195 .runs
1196 .iter()
1197 .flat_map(|run| run.glyphs.iter())
1198 .collect::<Vec<_>>();
1199 // Each row starts at a wrap boundary glyph, and ends where the next
1200 // row starts, or at the end of the line.
1201 let run_offsets = layout
1202 .runs
1203 .iter()
1204 .scan(0, |offset, run| {
1205 let start = *offset;
1206 *offset += run.glyphs.len();
1207 Some(start)
1208 })
1209 .collect::<Vec<_>>();
1210 let row_starts = line
1211 .wrap_boundaries
1212 .iter()
1213 .map(|boundary| run_offsets[boundary.run_ix] + boundary.glyph_ix)
1214 .collect::<Vec<_>>();
1215 let line_boxes = boxes.len();
1216 let mut from = 0;
1217 for (row_in_line, to) in row_starts.iter().copied().chain([glyphs.len()]).enumerate() {
1218 let start_x = if row_in_line == 0 {
1219 Pixels::ZERO
1220 } else {
1221 glyphs[from].position.x
1222 };
1223 let end_x = glyphs
1224 .get(to)
1225 .map_or(layout.width, |glyph| glyph.position.x);
1226 let shift = aligned_row_left(align, align_width, end_x - start_x) - start_x;
1227 for ix in from..to {
1228 let glyph = glyphs[ix];
1229 let right = if ix + 1 < to {
1230 glyphs[ix + 1].position.x
1231 } else {
1232 end_x
1233 };
1234 boxes.push(GlyphBox {
1235 text: line_start + glyph.index..line_start + glyph.index,
1236 row: row + row_in_line,
1237 left: shift + glyph.position.x,
1238 right: shift + right,
1239 });
1240 }
1241 from = to;
1242 }
1243
1244 // A glyph draws its text up to where the next glyph's text starts.
1245 let line_boxes = &mut boxes[line_boxes..];
1246 line_boxes.sort_by_key(|glyph| glyph.text.start);
1247 let line_end = line_start + line.len();
1248 for ix in 0..line_boxes.len() {
1249 let start = line_boxes[ix].text.start;
1250 line_boxes[ix].text.end = line_boxes[ix + 1..]
1251 .iter()
1252 .map(|glyph| glyph.text.start)
1253 .find(|next| *next > start)
1254 .unwrap_or(line_end);
1255 }
1256
1257 row += line.wrap_boundaries.len() + 1;
1258 line_start = line_end + 1;
1259 }
1260 boxes
1261}
1262
1263fn aligned_row_left(align: TextAlign, align_width: Pixels, width: Pixels) -> Pixels {
1264 match align {
1265 TextAlign::Left => Pixels::ZERO,
1266 TextAlign::Center => (align_width - width) / 2.,
1267 TextAlign::Right => align_width - width,
1268 }
1269}
1270
1271/// The boxes behind the text of `range`, as a row and the horizontal extent
1272/// on it, from `glyphs` sorted by the text they draw: every glyph drawing
1273/// some of that text, joined where they touch on a row.
1274fn range_boxes(glyphs: &[GlyphBox], range: Range<usize>) -> Vec<(usize, Pixels, Pixels)> {
1275 let first = glyphs.partition_point(|glyph| glyph.text.end <= range.start);
1276 let mut hits = glyphs[first..]
1277 .iter()
1278 .take_while(|glyph| glyph.text.start < range.end)
1279 .map(|glyph| (glyph.row, glyph.left, glyph.right))
1280 .collect::<Vec<_>>();
1281 hits.sort_by(|a, b| {
1282 (a.0, a.1)
1283 .partial_cmp(&(b.0, b.1))
1284 .unwrap_or(std::cmp::Ordering::Equal)
1285 });
1286
1287 let mut boxes: Vec<(usize, Pixels, Pixels)> = Vec::with_capacity(hits.len());
1288 for (row, left, right) in hits {
1289 match boxes.last_mut() {
1290 Some(last) if last.0 == row && left <= last.2 => last.2 = last.2.max(right),
1291 _ => boxes.push((row, left, right)),
1292 }
1293 }
1294 boxes
1295}
1296
1297fn selection_for_multi_click(
1298 text: &str,
1299 text_layout: &TextLayout,
1300 bounds: Bounds<Pixels>,
1301 pos: Point<Pixels>,
1302 kind: TextViewMultiClickKind,
1303) -> Option<std::ops::Range<usize>> {
1304 if !bounds.contains(&pos) {
1305 return None;
1306 }
1307
1308 let offset = text_layout.index_for_position(pos).ok()?;
1309
1310 match kind {
1311 TextViewMultiClickKind::Word => word_range_at(text, offset),
1312 // Known limitation: a paragraph maps to a single Inline run here. When a
1313 // paragraph embeds an inline image it is split into multiple Inline runs,
1314 // so triple-click only selects the run on the clicked side of the image.
1315 TextViewMultiClickKind::Paragraph | TextViewMultiClickKind::Line => {
1316 (!text.is_empty()).then_some(0..text.len())
1317 }
1318 }
1319}
1320
1321/// Check if a `pos` is within a `bounds`, considering multi-line selections.
1322pub(super) fn point_in_text_selection(
1323 pos: Point<Pixels>,
1324 char_width: Pixels,
1325 selection_start: Point<Pixels>,
1326 selection_end: Point<Pixels>,
1327 line_height: Pixels,
1328) -> bool {
1329 let point_in_line = |point: Point<Pixels>| point.y >= pos.y && point.y < pos.y + line_height;
1330 let top = selection_start.y.min(selection_end.y);
1331 let bottom = selection_start.y.max(selection_end.y);
1332 let x = pos.x + char_width.half();
1333
1334 // Out of the vertical bounds
1335 if pos.y + line_height <= top || pos.y > bottom {
1336 return false;
1337 }
1338
1339 // Treat the selection as single-line when both drag points fall within the
1340 // same rendered line, even if their y coordinates differ inside that line.
1341 if point_in_line(selection_start) && point_in_line(selection_end) {
1342 let left = selection_start.x.min(selection_end.x);
1343 let right = selection_start.x.max(selection_end.x);
1344 return x >= left && x <= right;
1345 }
1346
1347 let (top_point, bottom_point) = if selection_start.y < selection_end.y {
1348 (selection_start, selection_end)
1349 } else {
1350 (selection_end, selection_start)
1351 };
1352 let is_top_line = point_in_line(top_point);
1353 let is_bottom_line = point_in_line(bottom_point);
1354
1355 if is_top_line {
1356 return x >= top_point.x;
1357 } else if is_bottom_line {
1358 return x <= bottom_point.x;
1359 } else {
1360 return true;
1361 }
1362}
1363
1364#[cfg(test)]
1365mod fade_highlights_tests {
1366 use super::*;
1367
1368 #[test]
1369 fn fades_text_and_background_only_inside_the_range() {
1370 let code = InlineHighlight::from(HighlightStyle {
1371 background_color: Some(gpui::red()),
1372 ..Default::default()
1373 });
1374 let combined = fade_highlights(vec![(0..4, code)], &[(2..6, 0.5)]);
1375
1376 let ranges: Vec<_> = combined.iter().map(|(range, _)| range.clone()).collect();
1377 assert_eq!(ranges, vec![0..2, 2..4, 4..6]);
1378
1379 let (_, untouched) = &combined[0];
1380 assert_eq!(untouched.style.fade_out, None);
1381 assert_eq!(untouched.style.background_color.unwrap().a, 1.0);
1382
1383 let (_, faded_code) = &combined[1];
1384 assert_eq!(faded_code.style.fade_out, Some(0.5));
1385 assert_eq!(faded_code.style.background_color.unwrap().a, 0.5);
1386
1387 let (_, faded_text) = &combined[2];
1388 assert_eq!(faded_text.style.fade_out, Some(0.5));
1389 assert!(faded_text.style.background_color.is_none());
1390 }
1391
1392 #[test]
1393 fn no_fades_leave_highlights_untouched() {
1394 let bold = InlineHighlight::from(HighlightStyle {
1395 font_weight: Some(gpui::FontWeight::BOLD),
1396 ..Default::default()
1397 });
1398 let highlights = vec![(1..3, bold)];
1399 assert_eq!(fade_highlights(highlights.clone(), &[]), highlights);
1400 }
1401}
1402
1403#[cfg(test)]
1404mod line_bounds_tests {
1405 use super::*;
1406 use super::{
1407 test_draw::in_prepaint,
1408 test_fonts::{BODY, WideMonoTextSystem},
1409 };
1410 use gpui::{AvailableSpace, TestApp, size};
1411
1412 /// The character walk this replaced, kept as the oracle: one box per
1413 /// character from `position_for_index`, unioned per row.
1414 fn by_character(
1415 text: &str,
1416 text_layout: &TextLayout,
1417 line_height: Pixels,
1418 mask_bounds: Bounds<Pixels>,
1419 ) -> Vec<Bounds<Pixels>> {
1420 let mut line_bounds = Vec::new();
1421 let mut current_line_y = None;
1422 let mut current_bounds: Option<Bounds<Pixels>> = None;
1423 let mut offset = 0;
1424 for c in text.chars() {
1425 let next_offset = offset + c.len_utf8();
1426 let Some(pos) = text_layout.position_for_index(offset) else {
1427 offset = next_offset;
1428 continue;
1429 };
1430 let mut char_width = line_height.half();
1431 if let Some(next_pos) = text_layout.position_for_index(next_offset)
1432 && next_pos.y == pos.y
1433 {
1434 char_width = next_pos.x - pos.x;
1435 }
1436 let bounds = Bounds::from_corners(pos, point(pos.x + char_width, pos.y + line_height))
1437 .intersect(&mask_bounds);
1438 if bounds.size.width > px(0.) && bounds.size.height > px(0.) {
1439 if current_line_y == Some(pos.y) {
1440 if let Some(current) = current_bounds.as_mut() {
1441 *current = current.union(&bounds);
1442 }
1443 } else {
1444 if let Some(current) = current_bounds.take() {
1445 line_bounds.push(current);
1446 }
1447 current_line_y = Some(pos.y);
1448 current_bounds = Some(bounds);
1449 }
1450 }
1451 offset = next_offset;
1452 }
1453 if let Some(current) = current_bounds {
1454 line_bounds.push(current);
1455 }
1456 line_bounds
1457 }
1458
1459 #[test]
1460 fn row_walk_matches_the_character_walk() {
1461 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
1462 in_prepaint(&mut app, |window, cx| {
1463 let style = TextStyle {
1464 font_family: BODY.into(),
1465 font_size: px(16.).into(),
1466 ..Default::default()
1467 };
1468 let origin = point(px(7.), px(11.));
1469 let mask = Bounds::new(point(px(0.), px(0.)), size(px(1000.), px(1000.)));
1470 let clipped = Bounds::new(point(px(20.), px(30.)), size(px(50.), px(60.)));
1471 for text in [
1472 "",
1473 "one row",
1474 "a long paragraph that wraps onto several rows of eight pixel glyphs",
1475 "first line\nsecond line that also wraps around\n\nfourth",
1476 "中文与 English 混排的一段文字也会换行",
1477 "trailing newline\n",
1478 ] {
1479 for wrap_width in [40., 100., 1000.] {
1480 let runs = text_runs(text.len(), &style, &[]);
1481 let styled =
1482 StyledText::new(SharedString::from(text.to_string())).with_runs(runs);
1483 let layout = styled.layout().clone();
1484 let mut element = styled.into_any_element();
1485 element.layout_as_root(
1486 size(
1487 AvailableSpace::Definite(px(wrap_width)),
1488 AvailableSpace::MinContent,
1489 ),
1490 window,
1491 cx,
1492 );
1493 element.prepaint_at(origin, window, cx);
1494 let line_height = layout.line_height();
1495 for mask in [mask, clipped] {
1496 let expected = by_character(text, &layout, line_height, mask);
1497 let actual = Inline::text_line_bounds(&layout, line_height, mask);
1498 let context = format!("{text:?} at {wrap_width}px in {mask:?}");
1499 // The character walk placed a wrapped row's first
1500 // character at the end of the row before it: that row's
1501 // box started one glyph in, and a row holding only that
1502 // one glyph had no box at all. The row walk covers every
1503 // row from its start, so it may see more rows, never
1504 // fewer, and agrees on every row the walk could see.
1505 assert!(
1506 actual.len() >= expected.len(),
1507 "rows of {context}: {} < {}",
1508 actual.len(),
1509 expected.len()
1510 );
1511 for (row, expected) in expected.iter().enumerate() {
1512 let actual = actual
1513 .iter()
1514 .find(|actual| actual.top() == expected.top())
1515 .unwrap_or_else(|| panic!("row {row} of {context} is missing"));
1516 assert_eq!(
1517 actual.bottom(),
1518 expected.bottom(),
1519 "row {row} of {context}"
1520 );
1521 assert_eq!(actual.right(), expected.right(), "row {row} of {context}");
1522 assert!(
1523 actual.left() <= expected.left(),
1524 "row {row} of {context} starts at {:?}, after {:?}",
1525 actual.left(),
1526 expected.left()
1527 );
1528 }
1529 for actual in &actual {
1530 assert_eq!(
1531 actual.left(),
1532 origin.x.max(mask.left()),
1533 "left of {context}"
1534 );
1535 }
1536 }
1537 }
1538 }
1539 });
1540 }
1541}
1542
1543#[cfg(test)]
1544mod range_highlight_tests {
1545 use super::*;
1546 use super::{
1547 test_draw::in_prepaint,
1548 test_fonts::{BODY, WideMonoTextSystem},
1549 };
1550 use gpui::{AvailableSpace, TestApp, size};
1551
1552 /// Lays `text` out at `wrap_width` and returns the highlight boxes of
1553 /// `range` with rows aligned by `align`: the left and right edges past
1554 /// the text's origin, and the row.
1555 fn boxes(
1556 text: &'static str,
1557 wrap_width: f32,
1558 align: TextAlign,
1559 range: Range<usize>,
1560 ) -> Vec<(Pixels, Pixels, usize)> {
1561 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
1562 in_prepaint(&mut app, move |window, cx| {
1563 let style = TextStyle {
1564 font_family: BODY.into(),
1565 font_size: px(16.).into(),
1566 ..Default::default()
1567 };
1568 let styled = StyledText::new(SharedString::from(text)).with_runs(text_runs(
1569 text.len(),
1570 &style,
1571 &[],
1572 ));
1573 let layout = styled.layout().clone();
1574 let mut element = styled.into_any_element();
1575 element.layout_as_root(
1576 size(
1577 AvailableSpace::Definite(px(wrap_width)),
1578 AvailableSpace::MinContent,
1579 ),
1580 window,
1581 cx,
1582 );
1583 let origin = point(px(7.), px(11.));
1584 element.prepaint_at(origin, window, cx);
1585 let glyphs = glyph_boxes(&layout, align, layout.bounds().size.width);
1586 range_boxes(&glyphs, range)
1587 .into_iter()
1588 .map(|(row, left, right)| (left, right, row))
1589 .collect()
1590 })
1591 }
1592
1593 /// The selection fast paths decide a whole inline from this extent, so it
1594 /// must start exactly at the first row the per-character walk tests and
1595 /// reach at least the bottom of the last one. It may reach further: a
1596 /// trailing empty line, or a last row whose only character the walk
1597 /// places at the end of the row before it, holds no row the walk tests.
1598 #[test]
1599 fn text_rows_extent_matches_the_character_walk() {
1600 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
1601 in_prepaint(&mut app, |window, cx| {
1602 let style = TextStyle {
1603 font_family: BODY.into(),
1604 font_size: px(16.).into(),
1605 ..Default::default()
1606 };
1607 let origin = point(px(7.), px(11.3));
1608 for text in [
1609 "one row",
1610 "a long paragraph that wraps onto several rows of eight pixel glyphs",
1611 "first line\nsecond line that also wraps around\n\nfourth",
1612 "中文与 English 混排的一段文字也会换行",
1613 "trailing newline\n",
1614 ] {
1615 for wrap_width in [40., 100., 1000.] {
1616 let runs = text_runs(text.len(), &style, &[]);
1617 let styled =
1618 StyledText::new(SharedString::from(text.to_string())).with_runs(runs);
1619 let layout = styled.layout().clone();
1620 let mut element = styled.into_any_element();
1621 element.layout_as_root(
1622 size(
1623 AvailableSpace::Definite(px(wrap_width)),
1624 AvailableSpace::MinContent,
1625 ),
1626 window,
1627 cx,
1628 );
1629 element.prepaint_at(origin, window, cx);
1630 // Taller than the layout's rows, as a window line height
1631 // may be.
1632 let line_height = layout.line_height() + px(3.);
1633 let rows_y = text
1634 .char_indices()
1635 .filter_map(|(offset, _)| layout.position_for_index(offset))
1636 .map(|position| position.y);
1637 let top = rows_y.clone().fold(Pixels::MAX, Pixels::min);
1638 let bottom = rows_y.fold(Pixels::MIN, Pixels::max) + line_height;
1639
1640 let (rows_top, rows_bottom) = text_rows_extent(&layout, line_height);
1641 let context = format!("{text:?} at {wrap_width}px");
1642 assert_eq!(rows_top, top, "top of {context}");
1643 assert!(rows_bottom >= bottom, "bottom of {context}");
1644 }
1645 }
1646 });
1647 }
1648
1649 #[test]
1650 fn a_highlight_starting_a_wrapped_row_paints_only_that_row() {
1651 // Three rows of "aaaa ", "bbbb ", "cccc".
1652 let text = "aaaa bbbb cccc";
1653 let rows = boxes(text, 45., TextAlign::Left, 0..text.len());
1654 assert_eq!(rows.len(), 3, "{rows:?}");
1655
1656 let bbbb = text.find("bbbb").unwrap();
1657 let highlight = boxes(text, 45., TextAlign::Left, bbbb..bbbb + 4);
1658 assert_eq!(highlight.len(), 1, "{highlight:?}");
1659 assert_eq!(highlight[0].0, px(0.));
1660 assert_eq!(highlight[0].2, 1);
1661
1662 // Across the wrap, each row only as far as its text.
1663 let across = boxes(text, 45., TextAlign::Left, 2..7);
1664 assert_eq!(across.len(), 2, "{across:?}");
1665 assert_eq!(across[0].1, rows[0].1);
1666 assert_eq!((across[1].0, across[1].2), (px(0.), 1));
1667 }
1668
1669 #[test]
1670 fn highlights_after_a_hard_line_break_start_on_its_row() {
1671 // Rows "aa", "bbb cc": the break is one byte of the text, not a glyph.
1672 let text = "aa\nbbb cc";
1673 let bbb = text.find("bbb").unwrap();
1674 let aa = boxes(text, 1000., TextAlign::Left, 0..2);
1675 let highlight = boxes(text, 1000., TextAlign::Left, bbb..bbb + 3);
1676 assert_eq!(highlight.len(), 1, "{highlight:?}");
1677 assert_eq!(highlight[0].0, px(0.));
1678 assert_eq!(highlight[0].2, 1);
1679 // Three glyphs as wide as the two of "aa" and a half.
1680 assert_eq!(highlight[0].1, (aa[0].1 - aa[0].0) * 1.5);
1681 }
1682
1683 #[test]
1684 fn highlights_follow_centered_and_right_aligned_rows() {
1685 // Rows "aaaa ", "bbbb ", "cc": the last is narrower than the text, so
1686 // alignment moves it.
1687 let text = "aaaa bbbb cc";
1688 let cc = text.find("cc").unwrap()..text.len();
1689 let widest = boxes(text, 45., TextAlign::Left, 0..5)[0].1;
1690 let left = boxes(text, 45., TextAlign::Left, cc.clone())[0];
1691 let center = boxes(text, 45., TextAlign::Center, cc.clone())[0];
1692 let right = boxes(text, 45., TextAlign::Right, cc)[0];
1693 let width = left.1 - left.0;
1694 assert!(width > px(0.) && width < widest, "{left:?} in {widest:?}");
1695 // GPUI aligns each row in the width of the laid-out text, the wrap
1696 // width here.
1697 let align_width = px(45.);
1698 assert_eq!(left.0, px(0.));
1699 assert_eq!(
1700 center,
1701 (
1702 (align_width - width) / 2.,
1703 (align_width + width) / 2.,
1704 left.2
1705 )
1706 );
1707 assert_eq!(right, (align_width - width, align_width, left.2));
1708 }
1709}
1710
1711/// A platform text system for tests where the `Mono` family shapes twice as
1712/// wide as every other family, so a measurement that ignores the family of a
1713/// run comes out visibly short.
1714#[cfg(test)]
1715pub(super) mod test_draw {
1716 use gpui::{App, Context, IntoElement, Render, Styled as _, TestApp, Window, canvas, px};
1717 use std::{cell::RefCell, rc::Rc};
1718
1719 struct Probe {
1720 body: Option<Box<dyn FnOnce(&mut Window, &mut App)>>,
1721 }
1722
1723 impl Render for Probe {
1724 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1725 let body = self.body.take();
1726 canvas(
1727 move |_, window, cx| {
1728 if let Some(body) = body {
1729 body(window, cx);
1730 }
1731 },
1732 |_, _, _, _| {},
1733 )
1734 .w(px(1000.))
1735 .h(px(1000.))
1736 }
1737 }
1738
1739 /// Runs `f` inside a real prepaint pass and returns its value.
1740 ///
1741 /// Measuring an inline object lays its GPUI element out through the
1742 /// window, which GPUI only permits while a frame is being drawn, so a test
1743 /// that builds a real element cannot call the measurement helpers straight
1744 /// from `TestAppWindow::update`.
1745 pub(crate) fn in_prepaint<R: 'static>(
1746 app: &mut TestApp,
1747 f: impl FnOnce(&mut Window, &mut App) -> R + 'static,
1748 ) -> R {
1749 let slot: Rc<RefCell<Option<R>>> = Rc::new(RefCell::new(None));
1750 let out = slot.clone();
1751 let mut window = app.open_window(|_, _| Probe {
1752 body: Some(Box::new(move |window, cx| {
1753 *out.borrow_mut() = Some(f(window, cx));
1754 })),
1755 });
1756 window.draw();
1757 let value = slot.borrow_mut().take();
1758 value.expect("prepaint probe did not run")
1759 }
1760}
1761
1762#[cfg(test)]
1763pub(super) mod test_fonts {
1764 use gpui::{
1765 Bounds, DevicePixels, Font, FontId, FontMetrics, FontRun, FontWeight, GlyphId, LineLayout,
1766 Pixels, PlatformTextSystem, RenderGlyphParams, ShapedGlyph, ShapedRun, Size,
1767 TextRenderingMode, point, px, size,
1768 };
1769 use std::{borrow::Cow, cell::RefCell};
1770
1771 pub(crate) const BODY: &str = "Body";
1772 pub(crate) const MONO: &str = "Mono";
1773 const BODY_ID: FontId = FontId(1);
1774 const MONO_ID: FontId = FontId(2);
1775 const BOLD_BODY_ID: FontId = FontId(3);
1776 const BOLD_MONO_ID: FontId = FontId(4);
1777 const UNITS_PER_EM: f32 = 1000.;
1778
1779 pub(crate) struct WideMonoTextSystem;
1780
1781 impl WideMonoTextSystem {
1782 /// Advance of one glyph in `font_id`, in em units.
1783 fn advance_units(font_id: FontId) -> f32 {
1784 match font_id {
1785 MONO_ID => 1000.,
1786 BOLD_MONO_ID => 1250.,
1787 BODY_ID => 500.,
1788 BOLD_BODY_ID => 750.,
1789 _ => 500.,
1790 }
1791 }
1792
1793 /// Width of `text` shaped entirely in `family` at `font_size`.
1794 pub(crate) fn width_of(text: &str, family: &str, font_size: Pixels) -> Pixels {
1795 let font_id = if family == MONO { MONO_ID } else { BODY_ID };
1796 font_size * (Self::advance_units(font_id) / UNITS_PER_EM) * text.chars().count() as f32
1797 }
1798 }
1799
1800 thread_local! {
1801 static SHAPED_LINE_RECORDER: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
1802 }
1803
1804 struct ShapeRecorderGuard;
1805
1806 impl Drop for ShapeRecorderGuard {
1807 fn drop(&mut self) {
1808 SHAPED_LINE_RECORDER.with(|recorder| recorder.borrow_mut().take());
1809 }
1810 }
1811
1812 /// Runs `f` while recording text submitted to [`PlatformTextSystem::layout_line`].
1813 pub(crate) fn record_shaped_lines<R>(f: impl FnOnce() -> R) -> (R, Vec<String>) {
1814 SHAPED_LINE_RECORDER.with(|recorder| *recorder.borrow_mut() = Some(Vec::new()));
1815 let _guard = ShapeRecorderGuard;
1816 let result = f();
1817 let shaped_lines =
1818 SHAPED_LINE_RECORDER.with(|recorder| recorder.borrow_mut().take().unwrap_or_default());
1819 (result, shaped_lines)
1820 }
1821
1822 impl PlatformTextSystem for WideMonoTextSystem {
1823 fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> anyhow::Result<()> {
1824 Ok(())
1825 }
1826
1827 fn all_font_names(&self) -> Vec<String> {
1828 vec![BODY.into(), MONO.into()]
1829 }
1830
1831 fn font_id(&self, descriptor: &Font) -> anyhow::Result<FontId> {
1832 Ok(
1833 match (
1834 descriptor.family.as_ref() == MONO,
1835 descriptor.weight == FontWeight::BOLD,
1836 ) {
1837 (true, true) => BOLD_MONO_ID,
1838 (true, false) => MONO_ID,
1839 (false, true) => BOLD_BODY_ID,
1840 (false, false) => BODY_ID,
1841 },
1842 )
1843 }
1844
1845 fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
1846 FontMetrics {
1847 units_per_em: UNITS_PER_EM as u32,
1848 ascent: 800.,
1849 descent: -200.,
1850 line_gap: 0.,
1851 underline_position: -100.,
1852 underline_thickness: 50.,
1853 cap_height: 700.,
1854 x_height: 500.,
1855 bounding_box: Bounds {
1856 origin: point(0., -200.),
1857 size: size(1000., 1000.),
1858 },
1859 }
1860 }
1861
1862 fn typographic_bounds(
1863 &self,
1864 font_id: FontId,
1865 _glyph_id: GlyphId,
1866 ) -> anyhow::Result<Bounds<f32>> {
1867 Ok(Bounds {
1868 origin: point(0., 0.),
1869 size: size(Self::advance_units(font_id), 700.),
1870 })
1871 }
1872
1873 fn advance(&self, font_id: FontId, _glyph_id: GlyphId) -> anyhow::Result<Size<f32>> {
1874 Ok(size(Self::advance_units(font_id), 0.))
1875 }
1876
1877 fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
1878 Some(GlyphId(ch as u32))
1879 }
1880
1881 fn glyph_raster_bounds(
1882 &self,
1883 _params: &RenderGlyphParams,
1884 ) -> anyhow::Result<Bounds<DevicePixels>> {
1885 Ok(Bounds::default())
1886 }
1887
1888 fn rasterize_glyph(
1889 &self,
1890 _params: &RenderGlyphParams,
1891 raster_bounds: Bounds<DevicePixels>,
1892 ) -> anyhow::Result<(Size<DevicePixels>, Vec<u8>)> {
1893 Ok((raster_bounds.size, Vec::new()))
1894 }
1895
1896 fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
1897 SHAPED_LINE_RECORDER.with(|recorder| {
1898 if let Some(lines) = recorder.borrow_mut().as_mut() {
1899 lines.push(text.to_string());
1900 }
1901 });
1902
1903 let mut position = px(0.);
1904 let mut shaped_runs = Vec::new();
1905 let mut run_start = 0;
1906 for run in runs {
1907 let run_text = &text[run_start..run_start + run.len];
1908 let advance = font_size * (Self::advance_units(run.font_id) / UNITS_PER_EM);
1909 let mut glyphs = Vec::new();
1910 for (ix, ch) in run_text.char_indices() {
1911 glyphs.push(ShapedGlyph {
1912 id: GlyphId(ch as u32),
1913 position: point(position, px(0.)),
1914 index: run_start + ix,
1915 is_emoji: false,
1916 });
1917 position += advance;
1918 }
1919 shaped_runs.push(ShapedRun {
1920 font_id: run.font_id,
1921 glyphs,
1922 });
1923 run_start += run.len;
1924 }
1925 let metrics = self.font_metrics(BODY_ID);
1926 LineLayout {
1927 font_size,
1928 width: position,
1929 ascent: font_size * (metrics.ascent / UNITS_PER_EM),
1930 // Native backends normalize the signed font metric for shaped lines.
1931 descent: font_size * (-metrics.descent / UNITS_PER_EM),
1932 runs: shaped_runs,
1933 len: text.len(),
1934 }
1935 }
1936
1937 fn recommended_rendering_mode(
1938 &self,
1939 _font_id: FontId,
1940 _font_size: Pixels,
1941 ) -> TextRenderingMode {
1942 TextRenderingMode::Grayscale
1943 }
1944 }
1945}
1946
1947#[cfg(test)]
1948mod tests {
1949 use super::{
1950 GlyphBox, InlineHighlight, aligned_row_left, combine_highlights, point_in_text_selection,
1951 range_boxes, text_runs,
1952 };
1953 use gpui::{FontWeight, HighlightStyle, SharedString, TextAlign, TextStyle, point, px};
1954 use std::ops::Range;
1955
1956 fn mono(style: HighlightStyle) -> InlineHighlight {
1957 InlineHighlight {
1958 style,
1959 font_family: Some(SharedString::from("Mono")),
1960 font_size_scale: None,
1961 }
1962 }
1963
1964 #[test]
1965 fn text_runs_shape_a_code_highlight_in_its_font_family() {
1966 let style = TextStyle {
1967 font_family: SharedString::from("Body"),
1968 ..Default::default()
1969 };
1970 let highlights = vec![(4..8, mono(HighlightStyle::default()))];
1971
1972 let runs = text_runs(12, &style, &highlights);
1973
1974 let families = runs
1975 .iter()
1976 .map(|run| (run.len, run.font.family.as_ref()))
1977 .collect::<Vec<_>>();
1978 assert_eq!(families, vec![(4, "Body"), (4, "Mono"), (4, "Body")]);
1979 }
1980
1981 #[test]
1982 fn rows_align_the_way_gpui_paints_them() {
1983 let width = px(100.);
1984 assert_eq!(aligned_row_left(TextAlign::Left, width, px(40.)), px(0.));
1985 assert_eq!(aligned_row_left(TextAlign::Center, width, px(40.)), px(30.));
1986 assert_eq!(aligned_row_left(TextAlign::Right, width, px(40.)), px(60.));
1987 }
1988
1989 fn glyph(text: Range<usize>, row: usize, left: f32, right: f32) -> GlyphBox {
1990 GlyphBox {
1991 text,
1992 row,
1993 left: px(left),
1994 right: px(right),
1995 }
1996 }
1997
1998 #[test]
1999 fn range_boxes_join_the_glyphs_of_a_range_on_each_row() {
2000 // "ab cd" wrapped after the space, glyphs 8px wide.
2001 let glyphs = [
2002 glyph(0..1, 0, 0., 8.),
2003 glyph(1..2, 0, 8., 16.),
2004 glyph(2..3, 0, 16., 24.),
2005 glyph(3..4, 1, 0., 8.),
2006 glyph(4..5, 1, 8., 16.),
2007 ];
2008 let boxes = |range| range_boxes(&glyphs, range);
2009 assert_eq!(boxes(1..2), [(0, px(8.), px(16.))]);
2010 assert_eq!(boxes(0..5), [(0, px(0.), px(24.)), (1, px(0.), px(16.))]);
2011 // Starting at the wrap paints the next row only.
2012 assert_eq!(boxes(3..5), [(1, px(0.), px(16.))]);
2013 assert!(boxes(2..2).is_empty());
2014 }
2015
2016 #[test]
2017 fn range_boxes_follow_right_to_left_glyphs() {
2018 // Three two-byte letters painted right to left: the first letter's
2019 // glyph is the rightmost.
2020 let glyphs = [
2021 glyph(0..2, 0, 16., 24.),
2022 glyph(2..4, 0, 8., 16.),
2023 glyph(4..6, 0, 0., 8.),
2024 ];
2025 assert_eq!(range_boxes(&glyphs, 0..2), [(0, px(16.), px(24.))]);
2026 assert_eq!(range_boxes(&glyphs, 2..6), [(0, px(0.), px(16.))]);
2027 }
2028
2029 #[test]
2030 fn range_boxes_cover_a_glyph_drawing_part_of_the_range() {
2031 // A ligature drawing "fi" in one glyph.
2032 let glyphs = [glyph(0..2, 0, 0., 10.), glyph(2..3, 0, 10., 15.)];
2033 assert_eq!(range_boxes(&glyphs, 1..2), [(0, px(0.), px(10.))]);
2034 }
2035
2036 #[test]
2037 fn combine_highlights_cuts_a_bold_span_at_the_code_boundary() {
2038 // `**bold `code`**`: the bold mark spans the code mark, so the
2039 // combined list carries the weight on both sides and the family on
2040 // the code side only.
2041 let bold = InlineHighlight::from(HighlightStyle {
2042 font_weight: Some(FontWeight::BOLD),
2043 ..Default::default()
2044 });
2045 let combined = combine_highlights(
2046 vec![(0..10, bold)],
2047 vec![(6..10, mono(HighlightStyle::default()))],
2048 );
2049
2050 assert_eq!(combined.len(), 2);
2051 assert_eq!(combined[0].0, 0..6);
2052 assert_eq!(combined[0].1.style.font_weight, Some(FontWeight::BOLD));
2053 assert_eq!(combined[0].1.font_family, None);
2054 assert_eq!(combined[1].0, 6..10);
2055 assert_eq!(combined[1].1.style.font_weight, Some(FontWeight::BOLD));
2056 assert_eq!(combined[1].1.font_family.as_deref(), Some("Mono"));
2057 }
2058
2059 #[test]
2060 fn test_point_in_text_selection() {
2061 let line_height = px(20.);
2062 let char_width = px(10.);
2063 let start = point(px(50.), px(50.));
2064 let end = point(px(150.), px(150.));
2065
2066 // First line but haft line height, true
2067 // | p --------|
2068 // | selection |
2069 // |-----------|
2070 assert!(point_in_text_selection(
2071 point(px(50.), px(40.)),
2072 char_width,
2073 start,
2074 end,
2075 line_height
2076 ));
2077
2078 // First line in selection, true
2079 // | p --------|
2080 // | selection |
2081 // |-----------|
2082 assert!(point_in_text_selection(
2083 point(px(50.), px(50.)),
2084 char_width,
2085 start,
2086 end,
2087 line_height
2088 ));
2089 // First line, but left out of selection, false
2090 // p |-----------|
2091 // | selection |
2092 // |-----------|
2093 assert!(!point_in_text_selection(
2094 point(px(40.), px(50.)),
2095 char_width,
2096 start,
2097 end,
2098 line_height
2099 ));
2100 // First line but right out of selection, true
2101 // |-----------| p
2102 // | selection |
2103 // |-----------|
2104 assert!(point_in_text_selection(
2105 point(px(160.), px(50.)),
2106 char_width,
2107 start,
2108 end,
2109 line_height
2110 ));
2111
2112 // Middle line in selection, true
2113 // |-----------|
2114 // | p |
2115 // |-----------|
2116 assert!(point_in_text_selection(
2117 point(px(100.), px(70.)),
2118 char_width,
2119 start,
2120 end,
2121 line_height
2122 ));
2123 // Middle line, but left out of selection, true
2124 // |-----------|
2125 // p | selection |
2126 // |-----------|
2127 assert!(point_in_text_selection(
2128 point(px(40.), px(70.)),
2129 char_width,
2130 start,
2131 end,
2132 line_height
2133 ));
2134 // Middle line, but right out of selection, true
2135 // |-----------|
2136 // | selection | p
2137 // |-----------|
2138 assert!(point_in_text_selection(
2139 point(px(160.), px(70.)),
2140 char_width,
2141 start,
2142 end,
2143 line_height
2144 ));
2145
2146 // Last line in selection, true
2147 // |-----------|
2148 // | selection |
2149 // |------- p -|
2150 assert!(point_in_text_selection(
2151 point(px(100.), px(140.)),
2152 char_width,
2153 start,
2154 end,
2155 line_height
2156 ));
2157 // Last line, but left out of selection, true
2158 //
2159 // |-----------|
2160 // | selection |
2161 // p |-----------|
2162 assert!(point_in_text_selection(
2163 point(px(40.), px(140.)),
2164 char_width,
2165 start,
2166 end,
2167 line_height
2168 ));
2169 // Last line, but right out of selection, false
2170 // |-----------|
2171 // | selection |
2172 // |-----------| p
2173 assert!(!point_in_text_selection(
2174 point(px(160.), px(140.)),
2175 char_width,
2176 start,
2177 end,
2178 line_height
2179 ));
2180
2181 // Out of vertical bounds (top), false
2182 // p
2183 // |-----------|
2184 // | selection |
2185 // |-----------|
2186 assert!(!point_in_text_selection(
2187 point(px(100.), px(20.)),
2188 char_width,
2189 start,
2190 end,
2191 line_height
2192 ));
2193 // Out of vertical bounds (bottom), false
2194 // |-----------|
2195 // | selection |
2196 // |-----------|
2197 // p
2198 assert!(!point_in_text_selection(
2199 point(px(100.), px(160.)),
2200 char_width,
2201 start,
2202 end,
2203 line_height
2204 ));
2205 }
2206
2207 #[test]
2208 fn test_point_in_text_selection_reversed_drag_direction() {
2209 let line_height = px(20.);
2210 let char_width = px(10.);
2211
2212 // Mouse down on lower line then drag upward to x=150.
2213 // Top line should follow current mouse x, bottom line should keep anchor x.
2214 let start = point(px(80.), px(150.));
2215 let end = point(px(150.), px(50.));
2216
2217 // On top line, selection starts from top cursor x (150), so x=140 should be excluded.
2218 assert!(!point_in_text_selection(
2219 point(px(140.), px(50.)),
2220 char_width,
2221 start,
2222 end,
2223 line_height
2224 ));
2225 assert!(point_in_text_selection(
2226 point(px(150.), px(50.)),
2227 char_width,
2228 start,
2229 end,
2230 line_height
2231 ));
2232
2233 // On bottom line, selection ends at anchor x (80), so x=90 should be excluded.
2234 assert!(point_in_text_selection(
2235 point(px(75.), px(140.)),
2236 char_width,
2237 start,
2238 end,
2239 line_height
2240 ));
2241 assert!(!point_in_text_selection(
2242 point(px(80.), px(140.)),
2243 char_width,
2244 start,
2245 end,
2246 line_height
2247 ));
2248 }
2249
2250 #[test]
2251 fn test_point_in_text_selection_same_visual_line_with_different_y() {
2252 let line_height = px(20.);
2253 let char_width = px(10.);
2254 let start = point(px(100.), px(55.));
2255 let end = point(px(60.), px(58.));
2256
2257 assert!(!point_in_text_selection(
2258 point(px(40.), px(50.)),
2259 char_width,
2260 start,
2261 end,
2262 line_height
2263 ));
2264 assert!(point_in_text_selection(
2265 point(px(70.), px(50.)),
2266 char_width,
2267 start,
2268 end,
2269 line_height
2270 ));
2271 assert!(!point_in_text_selection(
2272 point(px(110.), px(50.)),
2273 char_width,
2274 start,
2275 end,
2276 line_height
2277 ));
2278 }
2279
2280 #[test]
2281 fn test_point_in_text_selection_same_visual_line_with_reversed_y() {
2282 let line_height = px(20.);
2283 let char_width = px(10.);
2284 let start = point(px(60.), px(58.));
2285 let end = point(px(100.), px(55.));
2286
2287 assert!(!point_in_text_selection(
2288 point(px(40.), px(50.)),
2289 char_width,
2290 start,
2291 end,
2292 line_height
2293 ));
2294 assert!(point_in_text_selection(
2295 point(px(70.), px(50.)),
2296 char_width,
2297 start,
2298 end,
2299 line_height
2300 ));
2301 assert!(!point_in_text_selection(
2302 point(px(110.), px(50.)),
2303 char_width,
2304 start,
2305 end,
2306 line_height
2307 ));
2308 }
2309}
2310
2311#[cfg(test)]
2312mod retained_layout_tests {
2313 use gpui::{
2314 AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render, Styled as _,
2315 TestAppContext, Window, div, px,
2316 };
2317
2318 use super::RETAINED_LAYOUTS;
2319 use crate::text::{TextView, TextViewState};
2320
2321 /// The same document shown twice in one window, as a preview beside the
2322 /// text: both `Inline`s share every `InlineState`.
2323 struct Twice {
2324 state: Entity<TextViewState>,
2325 }
2326
2327 impl Render for Twice {
2328 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2329 div()
2330 .w(px(300.))
2331 .child(TextView::new(&self.state))
2332 .child(TextView::new(&self.state))
2333 }
2334 }
2335
2336 /// Without the hand-over rule the second copy's prepaint replaced the
2337 /// first copy's entry, and the first copy painted with the second's
2338 /// layout — at the second's bounds.
2339 #[gpui::test]
2340 fn the_same_paragraph_rendered_twice_in_a_frame_keeps_one_layout_and_paints_both(
2341 cx: &mut TestAppContext,
2342 ) {
2343 cx.update(crate::init);
2344 let (_, cx) = cx.add_window_view(|_, cx| Twice {
2345 state: cx
2346 .new(|cx| TextViewState::markdown("First paragraph.\n\nSecond **paragraph**.", cx)),
2347 });
2348 cx.run_until_parked();
2349
2350 // Frame 1 fills the table, frame 2 reuses it; neither may lose the
2351 // shaped text of either copy (painting an unmeasured placeholder
2352 // panics inside GPUI).
2353 for _ in 0..3 {
2354 cx.update(|window, cx| window.draw(cx).clear(cx));
2355 }
2356
2357 let retained = RETAINED_LAYOUTS.with(|layouts| layouts.borrow().len());
2358 assert_eq!(retained, 2, "one layout per paragraph state");
2359 }
2360
2361 struct Once {
2362 state: Entity<TextViewState>,
2363 }
2364
2365 impl Render for Once {
2366 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
2367 div().w(px(300.)).child(TextView::new(&self.state))
2368 }
2369 }
2370
2371 /// A paragraph with a code span is laid out by `InlineFlow`, as one
2372 /// `Inline` per wrapped fragment. The fragments' states have to outlive
2373 /// the frame, or every frame shapes the fragments again and leaves the
2374 /// table an entry nobody will take.
2375 #[gpui::test]
2376 fn inline_flow_fragments_keep_their_layouts_across_frames(cx: &mut TestAppContext) {
2377 cx.update(crate::init);
2378 let (_, cx) = cx.add_window_view(|_, cx| Once {
2379 state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)),
2380 });
2381 cx.run_until_parked();
2382
2383 for _ in 0..3 {
2384 cx.update(|window, cx| window.draw(cx).clear(cx));
2385 }
2386
2387 // "Call ", "foo" and " now.": three fragments on one line.
2388 let (retained, alive) = RETAINED_LAYOUTS.with(|layouts| {
2389 let layouts = layouts.borrow();
2390 (
2391 layouts.len(),
2392 layouts
2393 .values()
2394 .filter(|retained| retained.state.strong_count() > 0)
2395 .count(),
2396 )
2397 });
2398 assert_eq!(retained, 3, "one layout per fragment");
2399 assert_eq!(
2400 alive, 3,
2401 "every retained layout belongs to a live fragment state"
2402 );
2403 }
2404
2405 #[gpui::test]
2406 fn shortening_an_inline_flow_releases_obsolete_fragment_layouts(cx: &mut TestAppContext) {
2407 cx.update(crate::init);
2408 let source = "word `code` ".repeat(100);
2409 let (view, cx) = cx.add_window_view(|_, cx| Once {
2410 state: cx.new(|cx| TextViewState::markdown(&source, cx)),
2411 });
2412 cx.run_until_parked();
2413 for _ in 0..2 {
2414 cx.update(|window, cx| window.draw(cx).clear(cx));
2415 }
2416
2417 view.update(cx, |view, cx| {
2418 view.state.update(cx, |state, cx| {
2419 state.set_text("word `code` now", cx);
2420 });
2421 });
2422 cx.run_until_parked();
2423 for _ in 0..2 {
2424 cx.update(|window, cx| window.draw(cx).clear(cx));
2425 }
2426
2427 let alive = RETAINED_LAYOUTS.with(|layouts| {
2428 layouts
2429 .borrow()
2430 .values()
2431 .filter(|retained| retained.state.strong_count() > 0)
2432 .count()
2433 });
2434 assert_eq!(alive, 3, "one live layout per remaining fragment");
2435 }
2436}