BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-base / src / input / base / element.rs

element.rs

eef6c0a4 History
element.rs 175.9 KiB Download Raw
1use crate::input::{InputExtras as _, InputModeKind};
2use gpui::Corners;
3use gpui::Half;
4use gpui::{
5 AnyElement, App, Bounds, Edges, Element, ElementId, ElementInputHandler, Entity,
6 GlobalElementId,
7};
8use gpui::{
9 HighlightStyle, Hitbox, HitboxBehavior, Hsla, InteractiveElement, IntoElement, LayoutId,
10 LongPressEvent, MouseButton, MouseMoveEvent, MouseUpEvent, ParentElement as _, Path, Pixels,
11 Point, Position, ShapedLine, SharedString, Size, Style, Styled as _, TextAlign, TextRun,
12 TextStyle, TouchDragEvent, TouchPhase, UnderlineStyle, Window, fill, point, px, relative, size,
13};
14use ropey::Rope;
15use smallvec::SmallVec;
16use std::{ops::Range, rc::Rc};
17
18use crate::{
19 Scrollbar,
20 input::{RopeExt as _, blink_cursor::CURSOR_WIDTH, display_map::LineLayout},
21};
22
23use super::{
24 InputBaseState, RangeDecorationStyle, TextDecoration,
25 layout::{LastLayout, WhitespaceIndicators},
26 mode::LayoutMode,
27};
28
29fn diagnostic_highlight_style(
30 severity: crate::input::DiagnosticSeverity,
31 colors: crate::input::DiagnosticColors,
32) -> HighlightStyle {
33 let color = match severity {
34 crate::input::DiagnosticSeverity::Error => colors.error,
35 crate::input::DiagnosticSeverity::Warning => colors.warning,
36 crate::input::DiagnosticSeverity::Info => colors.info,
37 crate::input::DiagnosticSeverity::Hint => colors.hint,
38 };
39 HighlightStyle {
40 underline: Some(UnderlineStyle {
41 color: Some(color),
42 thickness: px(1.),
43 wavy: true,
44 }),
45 ..Default::default()
46 }
47}
48
49const BOTTOM_MARGIN_ROWS: usize = 3;
50pub(super) const RIGHT_MARGIN: Pixels = px(10.);
51pub(super) const LINE_NUMBER_RIGHT_MARGIN: Pixels = px(6.);
52const FOLD_ICON_WIDTH: Pixels = px(14.);
53const FOLD_ICON_HITBOX_WIDTH: Pixels = px(18.);
54const MAX_HIGHLIGHT_LINE_LENGTH: usize = 10_000;
55const MIN_LINE_NUMBER_DIGITS: usize = 3;
56const MAX_LINE_NUMBER_DIGITS: usize = 7;
57const MAX_DISPLAYED_LINE_NUMBER: usize = 9_999_999;
58
59fn line_number_len(total_lines: usize) -> usize {
60 (total_lines.max(1).ilog10() as usize + 1).clamp(MIN_LINE_NUMBER_DIGITS, MAX_LINE_NUMBER_DIGITS)
61}
62
63fn displayed_line_number(number: usize) -> usize {
64 number.min(MAX_DISPLAYED_LINE_NUMBER)
65}
66const FOLD_CHEVRON_RIGHT_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg>"#;
67const FOLD_CHEVRON_DOWN_SVG: &[u8] = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>"#;
68
69fn compose_decorations(
70 mut styles: Vec<(Range<usize>, HighlightStyle)>,
71 decorations: impl IntoIterator<Item = (Range<usize>, HighlightStyle)>,
72 visible_byte_range: Range<usize>,
73) -> Option<Vec<(Range<usize>, HighlightStyle)>> {
74 let mut visible_decorations = decorations
75 .into_iter()
76 .filter_map(|(range, style)| {
77 let range =
78 range.start.max(visible_byte_range.start)..range.end.min(visible_byte_range.end);
79 (!range.is_empty()).then_some((range, style))
80 })
81 .peekable();
82
83 if visible_decorations.peek().is_none() {
84 return (!styles.is_empty()).then_some(styles);
85 }
86 if styles.is_empty() {
87 styles.push((visible_byte_range.clone(), HighlightStyle::default()));
88 }
89
90 // Decorations are application-authored overrides and must win over syntax
91 // and semantic highlighting when both set the same style property.
92 Some(gpui::combine_highlights(styles, visible_decorations).collect())
93}
94
95fn compose_decoration_collections<'a>(
96 mut styles: Vec<(Range<usize>, HighlightStyle)>,
97 collections: impl IntoIterator<Item = &'a [TextDecoration]>,
98 visible_byte_range: Range<usize>,
99) -> Option<Vec<(Range<usize>, HighlightStyle)>> {
100 // Apply collections in reverse creation order so the first collection is
101 // composed last and retains its documented precedence.
102 let collections = collections.into_iter().collect::<Vec<_>>();
103 for decorations in collections.into_iter().rev() {
104 styles = compose_decorations(
105 styles,
106 decorations
107 .iter()
108 .map(|decoration| (decoration.range.clone(), decoration.style)),
109 visible_byte_range.clone(),
110 )
111 .unwrap_or_default();
112 }
113
114 (!styles.is_empty()).then_some(styles)
115}
116
117#[derive(Clone, Copy, Debug, PartialEq)]
118struct EditorScrollbarLayout {
119 bounds: Bounds<Pixels>,
120 scroll_size: Size<Pixels>,
121}
122
123/// What the unwrapped width of the longest line depends on. While it holds,
124/// prepaint reuses the stored width instead of copying the line and asking
125/// the text system for it again on every frame.
126#[derive(Clone, Debug, PartialEq)]
127pub(super) struct LongestLineKey {
128 document_revision: u64,
129 row: usize,
130 len: usize,
131 font: gpui::Font,
132 text_size: Pixels,
133 wrap_width: Option<Pixels>,
134}
135
136#[derive(Clone, Copy, Debug, PartialEq)]
137pub(super) struct EditorScrollbarSnapshot {
138 layout: EditorScrollbarLayout,
139 cursor_scroll_offset: Point<Pixels>,
140 soft_wrap: bool,
141}
142
143impl EditorScrollbarSnapshot {
144 fn new<M: InputModeKind>(
145 input_bounds: Bounds<Pixels>,
146 last_layout: &LastLayout,
147 scroll_size: Size<Pixels>,
148 cursor_scroll_offset: Point<Pixels>,
149 state: &InputBaseState<M>,
150 ) -> Self {
151 Self {
152 layout: EditorScrollbarLayout::new(
153 input_bounds,
154 last_layout.line_number_width,
155 scroll_size,
156 state.editor_paddings,
157 ),
158 cursor_scroll_offset,
159 soft_wrap: state.soft_wrap,
160 }
161 }
162}
163
164impl EditorScrollbarLayout {
165 fn new(
166 input_bounds: Bounds<Pixels>,
167 line_number_width: Pixels,
168 scroll_size: Size<Pixels>,
169 paddings: Edges<Pixels>,
170 ) -> Self {
171 let left = if line_number_width == px(0.) {
172 px(0.)
173 } else {
174 paddings.left + line_number_width - LINE_NUMBER_RIGHT_MARGIN
175 };
176
177 Self {
178 bounds: Bounds::new(
179 point(
180 input_bounds.origin.x + left,
181 input_bounds.origin.y - paddings.top,
182 ),
183 size(
184 input_bounds.size.width - left + paddings.right,
185 input_bounds.size.height + paddings.top + paddings.bottom,
186 ),
187 ),
188 scroll_size: size(
189 scroll_size.width - left + paddings.right + RIGHT_MARGIN,
190 scroll_size.height,
191 ),
192 }
193 }
194}
195
196pub(super) struct EditorScrollbar<M: InputModeKind> {
197 state: Entity<InputBaseState<M>>,
198}
199
200impl<M: InputModeKind> EditorScrollbar<M> {
201 pub(super) fn new(state: Entity<InputBaseState<M>>) -> Self {
202 Self { state }
203 }
204}
205
206impl<M: InputModeKind> IntoElement for EditorScrollbar<M> {
207 type Element = Self;
208
209 fn into_element(self) -> Self::Element {
210 self
211 }
212}
213
214impl<M: InputModeKind> Element for EditorScrollbar<M> {
215 type RequestLayoutState = ();
216 type PrepaintState = Option<AnyElement>;
217
218 fn id(&self) -> Option<ElementId> {
219 Some("editor-scrollbar".into())
220 }
221
222 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
223 None
224 }
225
226 fn request_layout(
227 &mut self,
228 _: Option<&GlobalElementId>,
229 _: Option<&gpui::InspectorElementId>,
230 window: &mut Window,
231 cx: &mut App,
232 ) -> (LayoutId, Self::RequestLayoutState) {
233 let mut style = Style::default();
234 style.position = Position::Absolute;
235 style.size.width = relative(1.).into();
236 style.size.height = relative(1.).into();
237
238 (window.request_layout(style, [], cx), ())
239 }
240
241 fn prepaint(
242 &mut self,
243 _: Option<&GlobalElementId>,
244 _: Option<&gpui::InspectorElementId>,
245 _: Bounds<Pixels>,
246 _: &mut Self::RequestLayoutState,
247 window: &mut Window,
248 cx: &mut App,
249 ) -> Self::PrepaintState {
250 let state = self.state.read(cx);
251 let Some(snapshot) = state.editor_scrollbar_snapshot.get() else {
252 return None;
253 };
254 let scroll_handle = state.scroll_handle.clone();
255
256 if scroll_handle.offset() != snapshot.cursor_scroll_offset {
257 scroll_handle.set_offset(snapshot.cursor_scroll_offset);
258 }
259
260 let mut scrollbar = if !snapshot.soft_wrap {
261 Scrollbar::new(&scroll_handle)
262 } else {
263 Scrollbar::vertical(&scroll_handle)
264 }
265 .viewport_bounds(snapshot.layout.bounds)
266 .scroll_size(snapshot.layout.scroll_size)
267 .into_any_element();
268
269 scrollbar.prepaint_as_root(
270 snapshot.layout.bounds.origin,
271 snapshot.layout.bounds.size.into(),
272 window,
273 cx,
274 );
275 Some(scrollbar)
276 }
277
278 fn paint(
279 &mut self,
280 _: Option<&GlobalElementId>,
281 _: Option<&gpui::InspectorElementId>,
282 _: Bounds<Pixels>,
283 _: &mut Self::RequestLayoutState,
284 prepaint: &mut Self::PrepaintState,
285 window: &mut Window,
286 cx: &mut App,
287 ) {
288 if let Some(scrollbar) = prepaint.as_mut() {
289 scrollbar.paint(window, cx);
290 }
291 }
292}
293
294// Prepaint and retained state must use the same range, including after content shrinks.
295pub(super) fn clamp_horizontal_scroll_offset(
296 offset: Pixels,
297 scroll_width: Pixels,
298 input_width: Pixels,
299 text_align: TextAlign,
300) -> Pixels {
301 let caret_clearance = if text_align == TextAlign::Left {
302 px(0.)
303 } else {
304 -CURSOR_WIDTH
305 };
306 let min_offset = (input_width - scroll_width + caret_clearance).min(caret_clearance);
307 offset.clamp(min_offset, px(0.))
308}
309
310fn clamp_auto_grow_vertical_scroll_offset(
311 mode: &LayoutMode,
312 scroll_top: Pixels,
313 scroll_height: Pixels,
314 input_height: Pixels,
315) -> Pixels {
316 if mode.is_auto_grow() {
317 scroll_top.clamp((input_height - scroll_height).min(px(0.)), px(0.))
318 } else {
319 scroll_top
320 }
321}
322
323fn editor_gutter_bounds(
324 input_bounds: Bounds<Pixels>,
325 line_number_width: Pixels,
326 ghost_lines_height: Pixels,
327 paddings: Edges<Pixels>,
328) -> Bounds<Pixels> {
329 Bounds {
330 origin: point(
331 input_bounds.origin.x - paddings.left,
332 input_bounds.origin.y - paddings.top,
333 ),
334 size: size(
335 line_number_width + paddings.left,
336 input_bounds.size.height + ghost_lines_height + paddings.top + paddings.bottom,
337 ),
338 }
339}
340
341use super::MASK_CHAR;
342
343/// Convert a byte offset in the original text to a byte offset in the masked display string.
344///
345/// The masked string consists of `MASK_CHAR` repeated once per character in the original text.
346/// Since `MASK_CHAR` may be multi-byte in UTF-8, the byte offset in the masked string is
347/// `char_index * MASK_CHAR.len_utf8()`.
348fn masked_display_offset(text: &Rope, original_offset: usize) -> usize {
349 text.offset_to_char_index(original_offset) * MASK_CHAR.len_utf8()
350}
351
352/// Move the IME marked range (tracked against the original text) into the display text
353/// coordinate space, so that a run boundary can't land inside a multi-byte `MASK_CHAR`
354/// and panic text shaping on a non-char-boundary slice.
355fn ime_marked_display_range(
356 text: &Rope,
357 marked_range: Option<Range<usize>>,
358 masked: bool,
359) -> Option<Range<usize>> {
360 let marked = marked_range?;
361 if masked {
362 Some(masked_display_offset(text, marked.start)..masked_display_offset(text, marked.end))
363 } else {
364 Some(marked)
365 }
366}
367
368/// Viewport capacity in display rows, independent of logical buffer lines.
369///
370/// Shared by both scroll-into-view paths (`layout_cursors` and
371/// `scroll_to_with_padding`) so they agree on the visible-line count even
372/// when soft-wrapped lines make logical and display rows diverge.
373pub(super) fn viewport_visible_lines(viewport_height: Pixels, line_height: Pixels) -> usize {
374 (viewport_height / line_height) as usize
375}
376
377/// Minimum pixel padding the cursor is kept clear of the viewport's
378/// top/bottom edges before auto-scroll engages. Backs
379/// [`InputBaseState::cursor_surrounding_lines`].
380///
381/// Auto-grow uses one line. Otherwise `None` falls back to the historical
382/// heuristic ([`BOTTOM_MARGIN_ROWS`] lines, or one line on small
383/// viewports); `Some(n)` uses `n` lines. The result is saturated against
384/// half the viewport so an oversized override can't invert the
385/// top/bottom thresholds into a scroll feedback loop. `visible_lines` is the
386/// viewport capacity in display rows, independent of logical buffer lines.
387pub(super) fn cursor_surrounding_padding(
388 is_auto_grow: bool,
389 override_lines: Option<usize>,
390 visible_lines: usize,
391 line_height: Pixels,
392) -> Pixels {
393 if is_auto_grow {
394 return line_height;
395 }
396 let raw = match override_lines {
397 Some(lines) => lines as f32 * line_height,
398 None => {
399 if visible_lines < BOTTOM_MARGIN_ROWS * 8 {
400 line_height
401 } else {
402 BOTTOM_MARGIN_ROWS * line_height
403 }
404 }
405 };
406 // Saturate against half the viewport so top + bottom margins can coexist.
407 let viewport_half = (visible_lines as f32 * line_height).half();
408 raw.min(viewport_half)
409}
410
411/// Pixel height of the empty area below the last line in the editor's
412/// scrollable region. Backs [`InputBaseState::scroll_beyond_last_line`].
413///
414/// `0` outside code-editor mode. Inside it, `None` is half the viewport
415/// (floored at [`BOTTOM_MARGIN_ROWS`] line-heights); `Some(n)` is exactly
416/// `n` line-heights.
417fn empty_bottom_height(
418 is_code_editor: bool,
419 override_rows: Option<usize>,
420 viewport_height: Pixels,
421 line_height: Pixels,
422) -> Pixels {
423 if !is_code_editor {
424 return px(0.);
425 }
426 match override_rows {
427 Some(rows) => rows as f32 * line_height,
428 None => viewport_height.half().max(BOTTOM_MARGIN_ROWS * line_height),
429 }
430}
431
432/// Layout information for fold icons.
433struct FoldIconLayout {
434 /// Hitbox for the line number area (used for hover detection)
435 line_number_hitbox: Hitbox,
436 /// List of (display_row, is_folded, icon_element) pairs for each fold candidate
437 icons: Vec<(usize, bool, gpui::AnyElement)>,
438}
439
440pub(super) struct TextElement<M: InputModeKind> {
441 pub(crate) state: Entity<InputBaseState<M>>,
442 placeholder: SharedString,
443}
444
445impl<M: InputModeKind> TextElement<M> {
446 pub(super) fn new(state: Entity<InputBaseState<M>>) -> Self {
447 Self {
448 state,
449 placeholder: SharedString::default(),
450 }
451 }
452
453 /// Set the placeholder text of the input field.
454 pub(super) fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
455 self.placeholder = placeholder.into();
456 self
457 }
458
459 fn paint_mouse_listeners(&mut self, hitbox: &Hitbox, window: &mut Window, _: &mut App) {
460 // Every touch is offered as a drag first; that is how a tap's mouse
461 // events are later told apart from a mouse's.
462 window.on_mouse_event(move |event: &TouchDragEvent, phase, _, cx| {
463 if phase.capture() && event.phase == TouchPhase::Started {
464 crate::GlobalState::note_touch(cx);
465 }
466 });
467
468 // A long press is touch's way to select: the word under the finger,
469 // then whatever the finger sweeps over. Claiming it keeps the moves
470 // out of the pan recognizer, so the input does not scroll instead.
471 window.on_mouse_event({
472 let state = self.state.clone();
473 let hitbox = hitbox.clone();
474 move |event: &LongPressEvent, phase, window, cx| {
475 if !phase.bubble() {
476 return;
477 }
478 if event.phase == TouchPhase::Started {
479 if window.default_prevented() || !hitbox.is_hovered(window) {
480 return;
481 }
482 if !state.update(cx, |state, cx| state.on_long_press(event, window, cx)) {
483 return;
484 }
485 window.capture_long_press(&state);
486 } else if !window.has_long_press_capture(&state) {
487 return;
488 } else {
489 state.update(cx, |state, cx| {
490 state.on_long_press(event, window, cx);
491 });
492 }
493 window.prevent_default();
494 cx.stop_propagation();
495 }
496 });
497
498 window.on_mouse_event({
499 let state = self.state.clone();
500
501 move |event: &MouseMoveEvent, _, window, cx| {
502 if event.pressed_button == Some(MouseButton::Left) {
503 state.update(cx, |state, cx| {
504 state.on_drag_move(event, window, cx);
505 });
506 }
507 }
508 });
509
510 window.on_mouse_event({
511 let state = self.state.clone();
512 move |_: &MouseUpEvent, phase, _, cx| {
513 if !phase.bubble() {
514 return;
515 }
516
517 // Stop auto-scroll when mouse up, and also stop selecting.
518 state.update(cx, |state, _| {
519 state.auto_scroll.stop();
520 state.selecting = false;
521 state.column_select_start = None;
522 });
523 }
524 });
525 }
526
527 /// Lays out the carets and updates the scroll position for the active one.
528 fn layout_cursors(
529 &self,
530 last_layout: &LastLayout,
531 bounds: &mut Bounds<Pixels>,
532 scroll_size: Size<Pixels>,
533 _: &mut Window,
534 cx: &mut App,
535 ) -> (Vec<CursorRenderInfo>, Point<Pixels>, Option<usize>) {
536 let state = self.state.read(cx);
537
538 let line_height = last_layout.line_height;
539 let visible_range = &last_layout.visible_range;
540 let lines = &last_layout.lines;
541 let line_number_width = last_layout.line_number_width;
542
543 let active_id = state.active_selection().id;
544 let mut scroll_offset = state.scroll_handle.offset();
545 let mut current_row = None;
546 let mut cursor_infos: Vec<CursorRenderInfo> = Vec::with_capacity(state.selections.len());
547
548 // Padding kept between the cursor and the viewport's top/bottom
549 // edges, used by the auto-scroll-into-view computation below.
550 let top_bottom_margin = cursor_surrounding_padding(
551 state.mode.is_auto_grow(),
552 state.cursor_surrounding_lines,
553 viewport_visible_lines(bounds.size.height, line_height),
554 line_height,
555 );
556
557 // Resolve a cursor or selection endpoint to a content-space position.
558 let visible_buffer_lines = &last_layout.visible_buffer_lines;
559 let caret_for = |row: usize, offset: usize, affinity: bool| -> Point<Pixels> {
560 // y of the top of buffer line `row` in content space.
561 let top = line_height * state.display_map.buffer_line_to_display_row(row);
562 let line_origin = point(px(0.), top);
563
564 if let Some(vi) = visible_buffer_lines.iter().position(|&bl| bl == row) {
565 let line = &lines[vi];
566 let line_start = last_layout.visible_line_byte_offsets[vi];
567 let local = offset.saturating_sub(line_start);
568 if let Some(pos) = line.position_for_index(local, last_layout, affinity) {
569 return line_origin + pos;
570 }
571 }
572 line_origin
573 };
574
575 let cursor_height = 0.85 * line_height;
576
577 for selection in state.selections.iter() {
578 let is_active = selection.id == active_id;
579
580 let mut selected_range = *selection;
581 let mut cursor = selection.cursor_offset();
582 if is_active {
583 if let Some(ime_marked_range) = &state.ime_marked_range {
584 selected_range = (ime_marked_range.end..ime_marked_range.end).into();
585 cursor = ime_marked_range.end;
586 }
587 }
588 let is_selected_all = selected_range.len() == state.text.len();
589
590 // Buffer rows from the raw (pre-mask) offsets, used to locate the cursor line.
591 let cursor_row = state.text.offset_to_point(cursor).row;
592
593 // Skip inactive cursors that are far outside the visible range. The
594 // active cursor is always processed so scroll tracking keeps working.
595 if !is_active
596 && (cursor_row + 2 < visible_range.start || cursor_row > visible_range.end + 2)
597 {
598 continue;
599 }
600
601 let sel_start_row = state.text.offset_to_point(selected_range.start).row;
602 let sel_end_row = state.text.offset_to_point(selected_range.end).row;
603 if state.masked {
604 selected_range.start = masked_display_offset(&state.text, selected_range.start);
605 selected_range.end = masked_display_offset(&state.text, selected_range.end);
606 cursor = masked_display_offset(&state.text, cursor);
607 }
608
609 let affinity = is_active && state.cursor_line_end_affinity;
610 let cursor_pos = caret_for(cursor_row, cursor, affinity);
611 let cursor_start = caret_for(sel_start_row, selected_range.start, false);
612 let cursor_end = caret_for(sel_end_row, selected_range.end, false);
613
614 if is_active {
615 current_row = Some(cursor_row);
616
617 let selection_changed = state.last_selected_range != Some(selected_range);
618 let auto_scrolling = state.auto_scroll.is_active();
619 if selection_changed && !is_selected_all {
620 // For Right alignment use 0 margin: cursor is clamped to bounds separately,
621 // so we never scroll the text for cursor-at-edge, avoiding a first-click jump.
622 let safety_margin = match last_layout.text_align {
623 TextAlign::Left => RIGHT_MARGIN,
624 TextAlign::Right => px(0.),
625 TextAlign::Center => CURSOR_WIDTH,
626 };
627
628 scroll_offset.x = if scroll_offset.x + cursor_pos.x
629 > (bounds.size.width - line_number_width - safety_margin)
630 {
631 // cursor is out of right
632 bounds.size.width - line_number_width - safety_margin - cursor_pos.x
633 } else if scroll_offset.x + cursor_pos.x < px(0.) {
634 // cursor is out of left
635 -cursor_pos.x
636 } else {
637 scroll_offset.x
638 };
639
640 // Vertical cursor-follow is suppressed while auto-scroll manages the y axis,
641 // to prevent fighting the background scroll task.
642 if !auto_scrolling {
643 // Scroll straight to the caret's line. This runs only on
644 // the frame the selection changed, so a one-line step
645 // would leave a far-off caret (e.g. after typing at the
646 // end of a long paste) outside the viewport.
647 scroll_offset.y = if scroll_offset.y + cursor_pos.y
648 > bounds.size.height - top_bottom_margin
649 {
650 // cursor is out of bottom
651 bounds.size.height - top_bottom_margin - cursor_pos.y
652 } else if scroll_offset.y + cursor_pos.y < top_bottom_margin {
653 // cursor is out of top
654 (top_bottom_margin - cursor_pos.y).min(px(0.))
655 } else {
656 scroll_offset.y
657 };
658 }
659
660 // For selection to move scroll
661 if selection.reversed {
662 if scroll_offset.x + cursor_start.x < px(0.) {
663 // selection start is out of left
664 scroll_offset.x = -cursor_start.x;
665 }
666 if !auto_scrolling && scroll_offset.y + cursor_start.y < px(0.) {
667 // selection start is out of top
668 scroll_offset.y = -cursor_start.y;
669 }
670 } else {
671 // TODO: Consider to remove this part,
672 // maybe is not necessary (But selection_reversed is needed).
673 if scroll_offset.x + cursor_end.x <= px(0.) {
674 // selection end is out of left
675 scroll_offset.x = -cursor_end.x;
676 }
677 if !auto_scrolling && scroll_offset.y + cursor_end.y <= px(0.) {
678 // selection end is out of top
679 scroll_offset.y = -cursor_end.y;
680 }
681 }
682 }
683 }
684
685 // Apply the final horizontal offset to every caret after cursor-follow and
686 // deferred scrolling have been resolved, regardless of selection order.
687 let cursor_x = bounds.left() + cursor_pos.x + line_number_width;
688 cursor_infos.push(CursorRenderInfo {
689 bounds: Bounds::new(
690 point(
691 cursor_x,
692 bounds.top() + cursor_pos.y + ((line_height - cursor_height) / 2.),
693 ),
694 size(CURSOR_WIDTH, cursor_height),
695 ),
696 is_active,
697 });
698 }
699
700 if let Some(deferred_scroll_offset) = state.deferred_scroll_offset {
701 scroll_offset = deferred_scroll_offset;
702 }
703 scroll_offset.x = clamp_horizontal_scroll_offset(
704 scroll_offset.x,
705 scroll_size.width,
706 bounds.size.width,
707 last_layout.text_align,
708 );
709 for info in &mut cursor_infos {
710 info.bounds.origin.x += scroll_offset.x;
711 // Right-aligned text keeps the caret inside the viewport edge.
712 if last_layout.text_align == TextAlign::Right {
713 info.bounds.origin.x = info.bounds.origin.x.min(bounds.right() - CURSOR_WIDTH);
714 }
715 }
716 scroll_offset.y = clamp_auto_grow_vertical_scroll_offset(
717 &state.mode,
718 scroll_offset.y,
719 scroll_size.height,
720 bounds.size.height,
721 );
722
723 bounds.origin = bounds.origin + scroll_offset;
724
725 (cursor_infos, scroll_offset, current_row)
726 }
727
728 /// Layout the match range to a Path.
729 pub(crate) fn layout_match_range(
730 range: Range<usize>,
731 last_layout: &LastLayout,
732 bounds: &Bounds<Pixels>,
733 ) -> Option<Path<Pixels>> {
734 let corners = Self::layout_range_corners(&range, last_layout)?;
735 let points = frame_outline_points(&corners);
736 let origin = bounds.origin + point(last_layout.line_number_width, px(0.));
737 let mut builder = gpui::PathBuilder::fill();
738 builder.move_to(origin + *points.first()?);
739 for point in points.iter().skip(1) {
740 builder.line_to(origin + *point);
741 }
742 builder.close();
743 builder.build().ok()
744 }
745
746 /// Project a buffer range through the visible (non-folded) shaped lines.
747 /// Half-open intersections give soft-wrap ends their trailing affinity and
748 /// prevent ranges on later lines from painting an earlier line's first glyph.
749 fn layout_range_corners(
750 range: &Range<usize>,
751 last_layout: &LastLayout,
752 ) -> Option<Vec<Corners<Point<Pixels>>>> {
753 let range = range.start.max(last_layout.visible_range_offset.start)
754 ..range.end.min(last_layout.visible_range_offset.end);
755 if range.is_empty() {
756 return None;
757 }
758
759 let mut y = last_layout.visible_top;
760 let mut corners = Vec::new();
761 for (&line_offset, line) in last_layout
762 .visible_line_byte_offsets
763 .iter()
764 .zip(last_layout.lines.iter())
765 {
766 let mut offset = line_offset;
767 let alignment = last_layout.alignment_offset(line.longest_width);
768 for (row, shaped) in line.wrapped_lines.iter().enumerate() {
769 let end = offset + shaped.len;
770 let start_ix = range.start.max(offset);
771 let end_ix = range.end.min(end);
772 let is_last = row + 1 == line.wrapped_lines.len();
773 // A selected newline has a one-space cell, including empty lines.
774 // A wrap boundary is not a newline and must not get such a cell.
775 let newline = is_last && range.start <= end && range.end > end;
776 if start_ix < end_ix || newline {
777 let indent = if row == 0 { px(0.) } else { line.wrap_indent };
778 let left = alignment + indent + shaped.x_for_index(start_ix.min(end) - offset);
779 let right = alignment
780 + indent
781 + if newline {
782 shaped.width + last_layout.space_width
783 } else {
784 shaped.x_for_index(end_ix - offset)
785 };
786 corners.push(Corners {
787 top_left: point(left, y),
788 top_right: point(right, y),
789 bottom_left: point(left, y + last_layout.line_height),
790 bottom_right: point(right, y + last_layout.line_height),
791 });
792 }
793 offset = end;
794 y += last_layout.line_height;
795 }
796 }
797 (!corners.is_empty()).then_some(corners)
798 }
799
800 fn layout_range_decorations(
801 &self,
802 last_layout: &LastLayout,
803 bounds: &Bounds<Pixels>,
804 window: &Window,
805 content_mask: Bounds<Pixels>,
806 cx: &App,
807 ) -> (Vec<(Path<Pixels>, Hsla)>, Vec<(Path<Pixels>, Hsla)>) {
808 let state = self.state.read(cx);
809 let mut fills = Vec::new();
810 let mut frames = Vec::new();
811 // Query separate buffer spans across folds instead of scanning annotations
812 // in the hidden text between the first and last visible buffer offsets.
813 let mut visible_spans: Vec<Range<usize>> = Vec::new();
814 for (&offset, line) in last_layout
815 .visible_line_byte_offsets
816 .iter()
817 .zip(last_layout.lines.iter())
818 {
819 let end = (offset + line.len() + 1).min(last_layout.visible_range_offset.end);
820 if let Some(previous) = visible_spans.last_mut().filter(|span| span.end == offset) {
821 previous.end = end;
822 } else if offset < end {
823 visible_spans.push(offset..end);
824 }
825 }
826 for decoration in state.extras.range_decorations(&visible_spans) {
827 match decoration.style() {
828 RangeDecorationStyle::Fill => {
829 let color = decoration
830 .color()
831 .unwrap_or(state.editor_style.foreground.opacity(0.12));
832 if let Some(path) =
833 Self::layout_match_range(decoration.range().clone(), last_layout, bounds)
834 {
835 fills.push((path, color));
836 }
837 }
838 RangeDecorationStyle::Frame => {
839 let color = decoration.color().unwrap_or(state.editor_style.foreground);
840 let Some(corners) = Self::layout_range_corners(decoration.range(), last_layout)
841 else {
842 continue;
843 };
844 let origin = bounds.origin + point(last_layout.line_number_width, px(0.));
845 let corners = pad_frame_corners(&corners, px(1.));
846 let points = frame_outline_points(&corners)
847 .into_iter()
848 .map(|point| origin + point)
849 .collect::<Vec<_>>();
850 let (stroke_width, points) =
851 snap_frame_outline(&points, px(1.), window.scale_factor());
852 let points = clamp_frame_to_content_mask(points, stroke_width, content_mask);
853 let Some(first) = points.first().copied() else {
854 continue;
855 };
856 let mut builder = gpui::PathBuilder::stroke(stroke_width);
857 builder.move_to(first);
858 for point in points.iter().skip(1) {
859 builder.line_to(*point);
860 }
861 builder.close();
862 if let Ok(path) = builder.build() {
863 frames.push((path, color));
864 }
865 }
866 }
867 }
868 (fills, frames)
869 }
870
871 fn layout_search_matches(
872 &self,
873 last_layout: &LastLayout,
874 bounds: &Bounds<Pixels>,
875 cx: &mut App,
876 ) -> Vec<(Path<Pixels>, bool)> {
877 let state = self.state.read(cx);
878 if !state.search_session.is_active() {
879 return vec![];
880 }
881 let ranges = state.search_session.matcher.matched_ranges();
882 let current_match_ix = state.search_session.matcher.current_match_index();
883
884 // Matches are sorted and do not overlap, so only the ones that reach
885 // into the visible range need a layout.
886 let visible_range = &last_layout.visible_range_offset;
887 let first = ranges.partition_point(|range| range.end <= visible_range.start);
888 let mut paths = Vec::new();
889 for (index, range) in ranges
890 .iter()
891 .enumerate()
892 .skip(first)
893 .take_while(|(_, range)| range.start < visible_range.end)
894 {
895 if let Some(path) = Self::layout_match_range(range.clone(), last_layout, bounds) {
896 paths.push((path, current_match_ix == index));
897 }
898 }
899
900 paths
901 }
902
903 fn layout_hover_highlight(
904 &self,
905 last_layout: &LastLayout,
906 bounds: &Bounds<Pixels>,
907 cx: &mut App,
908 ) -> Option<Path<Pixels>> {
909 let state = self.state.read(cx);
910 let Some(symbol_range) = state.extras.hover_symbol_range() else {
911 return None;
912 };
913
914 Self::layout_match_range(symbol_range, last_layout, bounds)
915 }
916
917 fn layout_document_colors(
918 &self,
919 document_colors: &[(Range<usize>, Hsla)],
920 last_layout: &LastLayout,
921 bounds: &Bounds<Pixels>,
922 _cx: &mut App,
923 ) -> Vec<(Path<Pixels>, Hsla)> {
924 let mut paths = vec![];
925 for (range, color) in document_colors.iter() {
926 if let Some(path) = Self::layout_match_range(range.clone(), last_layout, bounds) {
927 paths.push((path, *color));
928 }
929 }
930
931 paths
932 }
933
934 fn layout_selections(
935 &self,
936 last_layout: &LastLayout,
937 bounds: &mut Bounds<Pixels>,
938 window: &mut Window,
939 cx: &mut App,
940 ) -> Vec<Path<Pixels>> {
941 let state = self.state.read(cx);
942 if !state.focus_handle.is_focused(window) {
943 return vec![];
944 }
945
946 let active_id = state.active_selection().id;
947 let mut paths = Vec::new();
948
949 for selection in state.selections.iter() {
950 let is_active = selection.id == active_id;
951 let mut selected_range = *selection;
952
953 // IME composition replaces the active selection with a collapsed
954 // caret, so it never paints a selection highlight.
955 if is_active {
956 if let Some(ime_marked_range) = &state.ime_marked_range {
957 if !ime_marked_range.is_empty() {
958 selected_range = (ime_marked_range.end..ime_marked_range.end).into();
959 }
960 }
961 }
962 if selected_range.is_empty() {
963 continue;
964 }
965
966 if state.masked {
967 selected_range.start = masked_display_offset(&state.text, selected_range.start);
968 selected_range.end = masked_display_offset(&state.text, selected_range.end);
969 }
970
971 let (start_ix, end_ix) = if selected_range.start < selected_range.end {
972 (selected_range.start, selected_range.end)
973 } else {
974 (selected_range.end, selected_range.start)
975 };
976
977 let range = start_ix.max(last_layout.visible_range_offset.start)
978 ..end_ix.min(last_layout.visible_range_offset.end);
979
980 if range.is_empty() {
981 continue;
982 }
983
984 // A selected token shows its own selected state, so the text
985 // highlight stops at its edges instead of painting behind it.
986 let mut start = range.start;
987 if state.tokens_visible() {
988 let spans = state.token_spans();
989 let first = spans.partition_point(|s| s.range().end <= range.start);
990 for span in spans[first..]
991 .iter()
992 .take_while(|s| s.range().start < range.end)
993 {
994 if start < span.range().start {
995 paths.extend(Self::layout_match_range(
996 start..span.range().start,
997 last_layout,
998 bounds,
999 ));
1000 }
1001 start = span.range().end.max(start);
1002 }
1003 }
1004 if start < range.end {
1005 paths.extend(Self::layout_match_range(
1006 start..range.end,
1007 last_layout,
1008 bounds,
1009 ));
1010 }
1011 }
1012
1013 paths
1014 }
1015
1016 /// Calculate the visible range of lines in the viewport.
1017 ///
1018 /// Returns
1019 ///
1020 /// - visible_range: The visible range is based on unwrapped lines (Zero based).
1021 /// - visible_buffer_lines: Indices of non-hidden buffer lines within the visible range.
1022 /// - visible_top: The top position of the first visible line in the scroll viewport.
1023 fn calculate_visible_range(
1024 &self,
1025 state: &InputBaseState<M>,
1026 line_height: Pixels,
1027 input_height: Pixels,
1028 ) -> (Range<usize>, Vec<usize>, Pixels) {
1029 // Add extra rows to avoid showing empty space when scroll to bottom.
1030 let extra_rows = 1;
1031 if state.is_single_line() {
1032 return (0..1, vec![0], px(0.));
1033 }
1034
1035 let total_lines = state.display_map.wrap_row_count();
1036 let display_count = state.display_map.display_row_count();
1037 let buffer_line_count = state.display_map.buffer_line_count();
1038 if display_count == 0 || buffer_line_count == 0 {
1039 return (0..0, Vec::new(), px(0.));
1040 }
1041
1042 let mut scroll_top = if let Some(deferred_scroll_offset) = state.deferred_scroll_offset {
1043 deferred_scroll_offset.y
1044 } else {
1045 state.scroll_handle.offset().y
1046 };
1047 scroll_top = clamp_auto_grow_vertical_scroll_offset(
1048 &state.mode,
1049 scroll_top,
1050 line_height * total_lines,
1051 input_height,
1052 );
1053
1054 // Display rows are uniformly `line_height` tall, so the visible window maps
1055 // directly to a display-row range.
1056 let viewport_top = (-scroll_top).max(px(0.));
1057 let viewport_bottom = viewport_top + input_height;
1058 let line_height_f = f32::from(line_height);
1059 let first_display =
1060 ((f32::from(viewport_top) / line_height_f).floor() as usize).min(display_count - 1);
1061 let last_display =
1062 ((f32::from(viewport_bottom) / line_height_f).ceil() as usize).min(display_count - 1);
1063
1064 let start_line = state.display_map.display_row_to_buffer_line(first_display);
1065 let end_line = state.display_map.display_row_to_buffer_line(last_display);
1066
1067 // y of the top of the first visible buffer line (in content space).
1068 let visible_top = match state
1069 .display_map
1070 .buffer_line_to_display_row_range(start_line)
1071 {
1072 Some(range) => line_height * range.start,
1073 None => line_height * first_display,
1074 };
1075
1076 let visible_range = start_line..(end_line + 1 + extra_rows).min(buffer_line_count);
1077
1078 // Collect non-hidden buffer lines within the visible range
1079 let mut visible_buffer_lines = Vec::with_capacity(visible_range.len());
1080 for ix in visible_range.clone() {
1081 if state.display_map.visible_wrap_row_count_for_buffer_line(ix) > 0 {
1082 visible_buffer_lines.push(ix);
1083 }
1084 }
1085
1086 (visible_range, visible_buffer_lines, visible_top)
1087 }
1088
1089 /// Return (line_number_width, line_number_len)
1090 fn layout_line_numbers(
1091 state: &InputBaseState<M>,
1092 text: &Rope,
1093 font_size: Pixels,
1094 style: &TextStyle,
1095 window: &mut Window,
1096 ) -> (Pixels, usize) {
1097 let total_lines = text.lines_len();
1098 // Reserve three digits for small documents, then follow the actual
1099 // line count up to seven digits.
1100 let line_number_len = line_number_len(total_lines);
1101
1102 let mut line_number_width = if state.mode.line_number() {
1103 let empty_line_number = window.text_system().shape_line(
1104 "+".repeat(line_number_len).into(),
1105 font_size,
1106 &[TextRun {
1107 len: line_number_len,
1108 font: style.font(),
1109 color: gpui::black(),
1110 background_color: None,
1111 underline: None,
1112 strikethrough: None,
1113 }],
1114 None,
1115 );
1116
1117 empty_line_number.width + LINE_NUMBER_RIGHT_MARGIN
1118 } else if state.is_code_editor() {
1119 LINE_NUMBER_RIGHT_MARGIN
1120 } else {
1121 px(0.)
1122 };
1123
1124 if state.mode.is_folding() {
1125 // Add extra space for fold icons
1126 line_number_width += FOLD_ICON_HITBOX_WIDTH
1127 }
1128
1129 (line_number_width, line_number_len)
1130 }
1131
1132 /// Layout shaped lines for whitespace indicators (space and tab).
1133 ///
1134 /// Returns `WhitespaceIndicators` with shaped lines for space and tab characters.
1135 fn layout_whitespace_indicators(
1136 state: &InputBaseState<M>,
1137 text_size: Pixels,
1138 style: &TextStyle,
1139 window: &mut Window,
1140 _cx: &App,
1141 ) -> Option<WhitespaceIndicators> {
1142 if !state.show_whitespaces {
1143 return None;
1144 }
1145
1146 let invisible_color = state
1147 .editor_style
1148 .editor_invisible
1149 .unwrap_or(state.editor_style.muted_foreground);
1150
1151 let space_font_size = text_size.half();
1152 let tab_font_size = text_size;
1153
1154 let space_text = SharedString::new_static("•");
1155 let space = window.text_system().shape_line(
1156 space_text.clone(),
1157 space_font_size,
1158 &[TextRun {
1159 len: space_text.len(),
1160 font: style.font(),
1161 color: invisible_color,
1162 background_color: None,
1163 underline: None,
1164 strikethrough: None,
1165 }],
1166 None,
1167 );
1168
1169 let tab_text = SharedString::new_static("→");
1170 let tab = window.text_system().shape_line(
1171 tab_text.clone(),
1172 tab_font_size,
1173 &[TextRun {
1174 len: tab_text.len(),
1175 font: style.font(),
1176 color: invisible_color,
1177 background_color: None,
1178 underline: None,
1179 strikethrough: None,
1180 }],
1181 None,
1182 );
1183
1184 Some(WhitespaceIndicators { space, tab })
1185 }
1186
1187 /// Compute inline completion ghost lines for rendering.
1188 ///
1189 /// Returns (first_line, ghost_lines) where:
1190 /// - first_line: Shaped text for the first line (goes after cursor on same line)
1191 /// - ghost_lines: Shaped lines for subsequent lines (shift content down)
1192 fn layout_inline_completion(
1193 state: &InputBaseState<M>,
1194 visible_range: &Range<usize>,
1195 font_size: Pixels,
1196 window: &mut Window,
1197 _cx: &App,
1198 ) -> (Option<ShapedLine>, Vec<ShapedLine>) {
1199 // Must be focused to show inline completion
1200 if !state.focus_handle.is_focused(window) {
1201 return (None, vec![]);
1202 }
1203
1204 let Some(completion_item) = state.extras.inline_completion_item() else {
1205 return (None, vec![]);
1206 };
1207
1208 // Get cursor row from cursor position
1209 let cursor_row = state.cursor_position().line as usize;
1210
1211 // Only show if cursor row is visible
1212 if cursor_row < visible_range.start || cursor_row >= visible_range.end {
1213 return (None, vec![]);
1214 }
1215
1216 let completion_text = &completion_item.insert_text;
1217 let completion_color = state.editor_style.muted_foreground.opacity(0.5);
1218
1219 let text_style = window.text_style();
1220 let font = text_style.font();
1221
1222 let lines: Vec<&str> = completion_text.split('\n').collect();
1223 if lines.is_empty() {
1224 return (None, vec![]);
1225 }
1226
1227 // Shape first line (goes after cursor)
1228 let first_text: SharedString = lines[0].to_string().into();
1229 let first_line = if !first_text.is_empty() {
1230 let first_run = TextRun {
1231 len: first_text.len(),
1232 font: font.clone(),
1233 color: completion_color,
1234 background_color: None,
1235 underline: None,
1236 strikethrough: None,
1237 };
1238 Some(
1239 window
1240 .text_system()
1241 .shape_line(first_text, font_size, &[first_run], None),
1242 )
1243 } else {
1244 None
1245 };
1246
1247 // Shape ghost lines (lines 2+ that shift content down)
1248 let ghost_lines: Vec<ShapedLine> = lines[1..]
1249 .iter()
1250 .map(|line_text| {
1251 let text: SharedString = line_text.to_string().into();
1252 let len = text.len().max(1); // Ensure at least 1 for empty lines
1253 let run = TextRun {
1254 len,
1255 font: font.clone(),
1256 color: completion_color,
1257 background_color: None,
1258 underline: None,
1259 strikethrough: None,
1260 };
1261 // Use space for empty lines so they take up height
1262 let shaped_text = if text.is_empty() { " ".into() } else { text };
1263 window
1264 .text_system()
1265 .shape_line(shaped_text, font_size, &[run], None)
1266 })
1267 .collect();
1268
1269 (first_line, ghost_lines)
1270 }
1271
1272 /// Return (line_number_width, line_number_len)
1273 /// Layout fold icon hitboxes during prepaint phase.
1274 ///
1275 /// This creates hitboxes for the fold icon area, positioned to the right of line numbers.
1276 /// Icons are created and prepainted here to avoid panics.
1277 fn layout_fold_icons(
1278 &self,
1279 origin_x: Pixels,
1280 bounds: &Bounds<Pixels>,
1281 last_layout: &LastLayout,
1282 window: &mut Window,
1283 cx: &mut App,
1284 ) -> FoldIconLayout {
1285 // First pass: collect fold information from state
1286 struct FoldInfo {
1287 buffer_line: usize,
1288 is_folded: bool,
1289 display_row: usize,
1290 offset_y: Pixels,
1291 }
1292
1293 let line_number_hitbox = window.insert_hitbox(
1294 Bounds::new(
1295 point(origin_x, bounds.origin.y + last_layout.visible_top),
1296 size(last_layout.line_number_width, bounds.size.height),
1297 ),
1298 HitboxBehavior::Normal,
1299 );
1300
1301 let mut icon_layout = FoldIconLayout {
1302 line_number_hitbox,
1303 icons: vec![],
1304 };
1305
1306 let fold_infos: Vec<FoldInfo> = {
1307 let state = self.state.read(cx);
1308 if !state.mode.is_folding() {
1309 return icon_layout;
1310 }
1311
1312 let mut infos = Vec::with_capacity(last_layout.visible_buffer_lines.len());
1313 let mut offset_y = last_layout.visible_top;
1314
1315 for (line, &buffer_line) in last_layout
1316 .lines
1317 .iter()
1318 .zip(last_layout.visible_buffer_lines.iter())
1319 {
1320 if state.display_map.is_fold_candidate(buffer_line) {
1321 let is_folded = state.display_map.is_folded_at(buffer_line);
1322 infos.push(FoldInfo {
1323 buffer_line,
1324 is_folded,
1325 display_row: buffer_line,
1326 offset_y,
1327 });
1328 }
1329
1330 offset_y += line.wrapped_lines.len() * last_layout.line_height;
1331 }
1332
1333 infos
1334 }; // state is dropped here
1335
1336 // Second pass: create and prepaint icons
1337 let line_height = last_layout.line_height;
1338 let line_number_width =
1339 last_layout.line_number_width - LINE_NUMBER_RIGHT_MARGIN - FOLD_ICON_HITBOX_WIDTH;
1340 let icon_relative_pos = point(
1341 (FOLD_ICON_HITBOX_WIDTH - FOLD_ICON_WIDTH).half(),
1342 (line_height - FOLD_ICON_WIDTH).half(),
1343 );
1344
1345 for (ix, info) in fold_infos.iter().enumerate() {
1346 // Position fold icon to the right of line numbers.
1347 // Use origin_x (unscrolled) so icons stay fixed in the gutter during horizontal scroll.
1348 let fold_icon_bounds = Bounds::new(
1349 point(
1350 origin_x + icon_relative_pos.x + line_number_width,
1351 bounds.origin.y + icon_relative_pos.y + info.offset_y,
1352 ),
1353 size(FOLD_ICON_HITBOX_WIDTH, line_height),
1354 );
1355
1356 // Create and prepaint icon
1357 let child = self
1358 .state
1359 .read(cx)
1360 .editor_style
1361 .fold_icon_renderer
1362 .as_ref()
1363 .map(|render| render(ix, info.is_folded))
1364 .unwrap_or_else(|| {
1365 let (path, svg) = if info.is_folded {
1366 ("input-fold-chevron-right", FOLD_CHEVRON_RIGHT_SVG)
1367 } else {
1368 ("input-fold-chevron-down", FOLD_CHEVRON_DOWN_SVG)
1369 };
1370 gpui::canvas(
1371 |_, _, _| {},
1372 move |bounds, _, window, cx| {
1373 let color = window.text_style().color;
1374 let _ = window.paint_svg(
1375 bounds,
1376 path.into(),
1377 Some(svg),
1378 gpui::TransformationMatrix::default(),
1379 color,
1380 cx,
1381 );
1382 },
1383 )
1384 .size(FOLD_ICON_WIDTH)
1385 .into_any_element()
1386 });
1387 let mut icon = gpui::div()
1388 .id(("fold", ix))
1389 .size(FOLD_ICON_WIDTH)
1390 .child(child)
1391 .on_mouse_down(MouseButton::Left, {
1392 let state = self.state.clone();
1393 let buffer_line = info.buffer_line;
1394 move |_, _: &mut Window, cx: &mut App| {
1395 cx.stop_propagation();
1396
1397 state.update(cx, |state, cx| {
1398 state.display_map.toggle_fold(buffer_line);
1399 cx.notify();
1400 });
1401 }
1402 })
1403 .into_any_element();
1404
1405 icon.prepaint_as_root(
1406 fold_icon_bounds.origin,
1407 fold_icon_bounds.size.into(),
1408 window,
1409 cx,
1410 );
1411
1412 icon_layout
1413 .icons
1414 .push((info.display_row, info.is_folded, icon));
1415 }
1416
1417 icon_layout
1418 }
1419
1420 /// Paint fold icons using prepaint hitboxes.
1421 ///
1422 /// This handles:
1423 /// - Rendering fold icons (chevron-right for folded, chevron-down for expanded)
1424 /// - Mouse click handling to toggle fold state
1425 /// - Cursor style changes on hover
1426 /// - Only show icon on hover or for current line
1427 fn paint_fold_icons(
1428 &mut self,
1429 fold_icon_layout: &mut FoldIconLayout,
1430 current_row: Option<usize>,
1431 window: &mut Window,
1432 cx: &mut App,
1433 ) {
1434 let is_hovered = fold_icon_layout.line_number_hitbox.is_hovered(window);
1435 if !fold_icon_layout.icons.is_empty() {
1436 // Mouse moves do not repaint the editor, so repaint when the pointer
1437 // enters or leaves the gutter to show or hide the hover chevrons.
1438 let hitbox = fold_icon_layout.line_number_hitbox.clone();
1439 let entity_id = self.state.entity_id();
1440 window.on_mouse_event(move |_: &MouseMoveEvent, phase, window, cx| {
1441 if phase.bubble() && hitbox.is_hovered(window) != is_hovered {
1442 cx.notify(entity_id);
1443 }
1444 });
1445 }
1446 for (display_row, is_folded, icon) in fold_icon_layout.icons.iter_mut() {
1447 let is_current_line = current_row == Some(*display_row);
1448
1449 if !is_hovered && !is_current_line && !*is_folded {
1450 continue;
1451 }
1452
1453 icon.paint(window, cx);
1454 }
1455 }
1456
1457 fn token_element(
1458 &self,
1459 token: &super::InlineTokenContext,
1460 window: &mut Window,
1461 cx: &mut App,
1462 ) -> AnyElement {
1463 use gpui::{
1464 InteractiveElement as _, StatefulInteractiveElement as _, prelude::FluentBuilder as _,
1465 };
1466 let presentation = self.state.read(cx).token_presentation.clone();
1467 let child = presentation.render(token, window, cx);
1468 // Preserve interaction state only for the same token occurrence and
1469 // hover eligibility. Replacements and re-enabling start fresh.
1470 let start = token.range().start;
1471 let down_state = self.state.clone();
1472 let click_state = self.state.clone();
1473 let move_state = self.state.clone();
1474 let hover_state = self.state.clone();
1475 let hover_token = token.token().clone();
1476 let disabled = token.is_disabled();
1477 let hover_enabled = presentation.has_hover_listener() && !disabled;
1478 let id = gpui::ElementId::from(("inline-token", start));
1479 let id = gpui::ElementId::from((id, token.token().id().clone()));
1480 let id = gpui::ElementId::from((id, token.token().text().clone()));
1481 let id = gpui::ElementId::from((id, token.token().label().clone()));
1482 let id = gpui::ElementId::from((
1483 id,
1484 gpui::SharedString::from(if hover_enabled {
1485 "hover-enabled"
1486 } else {
1487 "hover-disabled"
1488 }),
1489 ));
1490 let accessible = presentation.has_listener() && !disabled;
1491 let accessible_state = self.state.clone();
1492 gpui::div()
1493 .id(id)
1494 .flex()
1495 .items_center()
1496 .h(token.line_height())
1497 .max_w(token.available_width())
1498 .overflow_hidden()
1499 // A token is an object, not text: the arrow, never the I-beam.
1500 .cursor_default()
1501 .when(accessible, |this| {
1502 this.role(gpui::Role::Button)
1503 .aria_label(token.token().label().clone())
1504 .on_a11y_action(gpui::AccessibleAction::Click, move |_, window, cx| {
1505 let state = accessible_state.read(cx);
1506 let activation = state
1507 .token_spans()
1508 .iter()
1509 .find(|s| s.range().start == start)
1510 .and_then(|span| {
1511 state.range_to_bounds(&span.range()).and_then(|bounds| {
1512 state.token_activation(
1513 start,
1514 bounds,
1515 gpui::ClickEvent::Keyboard(gpui::KeyboardClickEvent {
1516 bounds,
1517 ..Default::default()
1518 }),
1519 )
1520 })
1521 });
1522 if let Some((listener, event)) = activation {
1523 listener(&event, window, cx);
1524 }
1525 })
1526 })
1527 .capture_any_mouse_down(move |_, window, cx| {
1528 if disabled {
1529 window.prevent_default();
1530 cx.stop_propagation();
1531 }
1532 })
1533 .capture_any_mouse_up(move |_, window, cx| {
1534 if disabled {
1535 window.prevent_default();
1536 cx.stop_propagation();
1537 }
1538 })
1539 .capture_key_down(move |_, _, cx| {
1540 if disabled {
1541 cx.stop_propagation();
1542 }
1543 })
1544 .on_mouse_down(MouseButton::Left, move |event, window, cx| {
1545 if window.default_prevented() {
1546 return;
1547 }
1548 down_state.update(cx, |state, cx| {
1549 state.pressed_token = None;
1550 if event.click_count == 2 {
1551 if let Some(span) = state
1552 .token_spans()
1553 .iter()
1554 .find(|s| s.range().start == start)
1555 {
1556 state.set_selected_range(span.range(), cx);
1557 state.focus(window, cx);
1558 window.prevent_default();
1559 }
1560 } else if event.click_count == 1
1561 && !event.modifiers.shift
1562 && !event.modifiers.alt
1563 {
1564 state.pressed_token =
1565 Some((start, state.document_revision, event.position));
1566 }
1567 });
1568 })
1569 .on_mouse_move(move |event, _, cx| {
1570 move_state.update(cx, |state, _| {
1571 if state.pressed_token.as_ref().is_some_and(|(_, _, p)| {
1572 (event.position.x - p.x).abs() + (event.position.y - p.y).abs() > px(4.)
1573 }) {
1574 state.pressed_token = None;
1575 }
1576 });
1577 })
1578 .on_click(move |event, window, cx| {
1579 let activation = click_state.update(cx, |state, cx| {
1580 let (pressed, revision, _) = state.pressed_token.take()?;
1581 if pressed != start || revision != state.document_revision {
1582 return None;
1583 }
1584 if event.modifiers().shift || event.modifiers().alt {
1585 return None;
1586 }
1587 let span = state
1588 .token_spans()
1589 .iter()
1590 .find(|s| s.range().start == start)?
1591 .clone();
1592 // A click selects the whole token; opening it is the
1593 // listener's decision.
1594 state.set_selected_range(span.range(), cx);
1595 let bounds = state.range_to_bounds(&span.range())?;
1596 state.token_activation(start, bounds, event.clone())
1597 });
1598 if let Some((listener, event)) = activation {
1599 listener(&event, window, cx);
1600 }
1601 })
1602 .on_hover(move |hovered, window, cx| {
1603 // Hover never selects or edits; it only reports presence so the
1604 // application can show a tooltip or run custom logic.
1605 let hovered = *hovered;
1606 let activation = hover_state.update(cx, |state, _| {
1607 // Anchor to the real laid-out token rect, not the
1608 // range-to-bounds guess: a token at a soft-wrap boundary
1609 // would otherwise report a zero/negative width or a
1610 // two-row height.
1611 let bounds = if hovered {
1612 state.token_bounds.get(&start).copied()?
1613 } else {
1614 // Exits use entry geometry even if an earlier callback
1615 // removed the token and its current bounds.
1616 Bounds::default()
1617 };
1618 state.token_hover(start, bounds, hovered, Some(&hover_token))
1619 });
1620 if let Some((listener, event)) = activation {
1621 listener(&event, window, cx);
1622 }
1623 })
1624 .child(child)
1625 .into_any_element()
1626 }
1627
1628 fn measure_tokens(
1629 &self,
1630 width: Pixels,
1631 line_height: Pixels,
1632 viewport: Pixels,
1633 window: &mut Window,
1634 cx: &mut App,
1635 ) -> std::collections::HashMap<usize, (AnyElement, Size<Pixels>)> {
1636 let style = window.text_style();
1637 let state = self.state.read(cx);
1638 let key = (
1639 style.font(),
1640 style.font_size.to_pixels(window.rem_size()),
1641 width,
1642 line_height,
1643 state.is_single_line() || !state.soft_wrap,
1644 );
1645 if !state.tokens_visible() {
1646 if state.token_layout_cache.is_none() {
1647 let mut exit = self.state.update(cx, |state, _| {
1648 state.token_bounds.clear();
1649 state.reconcile_token_hover()
1650 });
1651 while let Some((listener, event)) = exit {
1652 listener(&event, window, cx);
1653 exit = self
1654 .state
1655 .update(cx, |state, _| state.reconcile_token_hover());
1656 }
1657 return Default::default();
1658 }
1659 self.state.update(cx, |state, cx| {
1660 state.display_map.set_inline_metrics(Rc::from([]), cx)
1661 });
1662 let mut exit = self.state.update(cx, |state, _| {
1663 state.token_bounds.clear();
1664 state.reconcile_token_hover()
1665 });
1666 while let Some((listener, event)) = exit {
1667 listener(&event, window, cx);
1668 exit = self
1669 .state
1670 .update(cx, |state, _| state.reconcile_token_hover());
1671 }
1672 return Default::default();
1673 }
1674 let revision = state.document_revision;
1675 let cache = state.token_layout_cache.as_ref();
1676 let all = cache.is_none_or(|cache| {
1677 cache.key.as_ref() != Some(&key)
1678 || cache.revision != revision
1679 || state
1680 .token_spans()
1681 .iter()
1682 .any(|span| !cache.widths.contains_key(span.token()))
1683 });
1684 let (visible, _, _) = self.calculate_visible_range(state, line_height, viewport);
1685 let start = state.text.line_start_offset(visible.start);
1686 let end = state.text.line_end_offset(visible.end.saturating_sub(1));
1687 let spans = state.token_spans();
1688 let first = if all {
1689 0
1690 } else {
1691 spans.partition_point(|s| s.range().end <= start)
1692 };
1693 let contexts: Vec<_> = spans[first..]
1694 .iter()
1695 .take_while(|s| all || s.range().start <= end)
1696 .filter(|span| {
1697 let range = span.range();
1698 (range.start <= end && range.end >= start)
1699 || cache.is_none_or(|cache| {
1700 cache.key.as_ref() != Some(&key) || !cache.widths.contains_key(span.token())
1701 })
1702 })
1703 .map(|span| state.token_context(span, line_height, width))
1704 .collect();
1705 let mut elements = std::collections::HashMap::new();
1706 let mut measured = Vec::new();
1707 for token in contexts {
1708 let mut element = self.token_element(&token, window, cx);
1709 let size = element.layout_as_root(
1710 size(
1711 gpui::AvailableSpace::MaxContent,
1712 gpui::AvailableSpace::Definite(line_height),
1713 ),
1714 window,
1715 cx,
1716 );
1717 measured.push((token.token().clone(), size.width.min(width).max(px(1.))));
1718 elements.insert(token.range().start, (element, size));
1719 }
1720 self.state.update(cx, |state, cx| {
1721 let mut cache = state.token_layout_cache.take().unwrap_or_default();
1722 let mut changed = cache.key.as_ref() != Some(&key) || cache.revision != revision;
1723 if cache.key.as_ref() != Some(&key) {
1724 cache.widths.clear();
1725 }
1726 for (token, width) in measured {
1727 changed |= cache.widths.get(&token) != Some(&width);
1728 cache.widths.insert(token, width);
1729 }
1730 cache.key = Some(key);
1731 if changed {
1732 let spans = state.token_spans();
1733 let tokens: std::collections::HashSet<_> =
1734 spans.iter().map(|s| s.token()).collect();
1735 cache.widths.retain(|token, _| tokens.contains(token));
1736 cache.metrics = spans
1737 .iter()
1738 .filter_map(|span| {
1739 cache
1740 .widths
1741 .get(span.token())
1742 .map(|width| (span.range(), *width))
1743 })
1744 .collect();
1745 cache.revision = revision;
1746 if state.is_single_line() || !state.soft_wrap {
1747 let mut rows: Vec<_> = spans
1748 .iter()
1749 .map(|s| state.text.offset_to_point(s.range().start).row)
1750 .collect();
1751 rows.push(state.display_map.longest_row());
1752 rows.sort_unstable();
1753 rows.dedup();
1754 cache.unwrapped_width = rows
1755 .into_iter()
1756 .map(|row| {
1757 let start = state.text.line_start_offset(row);
1758 let text = state.text.slice_line(row).to_string();
1759 let mut offset = 0;
1760 let mut width = px(0.);
1761 let first = spans.partition_point(|s| s.range().end <= start);
1762 for span in spans[first..]
1763 .iter()
1764 .take_while(|s| s.range().start < start + text.len())
1765 {
1766 let local = span.range().start - start..span.range().end - start;
1767 let part = &text[offset..local.start];
1768 width += window
1769 .text_system()
1770 .shape_line(
1771 part.to_owned().into(),
1772 style.font_size.to_pixels(window.rem_size()),
1773 &[style.to_run(part.len())],
1774 None,
1775 )
1776 .width;
1777 width +=
1778 cache.widths.get(span.token()).copied().unwrap_or_default();
1779 offset = local.end;
1780 }
1781 let part = &text[offset..];
1782 width
1783 + window
1784 .text_system()
1785 .shape_line(
1786 part.to_owned().into(),
1787 style.font_size.to_pixels(window.rem_size()),
1788 &[style.to_run(part.len())],
1789 None,
1790 )
1791 .width
1792 })
1793 .max()
1794 .unwrap_or_default();
1795 }
1796 }
1797 let metrics = cache.metrics.clone();
1798 state.token_layout_cache = Some(cache);
1799 state.display_map.set_inline_metrics(metrics, cx);
1800 if state.mode.is_auto_grow() {
1801 let rows = state.mode.rows();
1802 state.mode.update_auto_grow(&state.display_map);
1803 if state.mode.rows() != rows {
1804 cx.notify();
1805 }
1806 }
1807 });
1808 elements
1809 }
1810
1811 fn layout_token_lines(
1812 state: &InputBaseState<M>,
1813 last_layout: &LastLayout,
1814 font_size: Pixels,
1815 runs: &[TextRun],
1816 window: &mut Window,
1817 ) -> Vec<LineLayout> {
1818 use crate::input::display_map::{InlineFragment, InputLine};
1819 let spans = state.token_spans();
1820 let cache = state
1821 .token_layout_cache
1822 .as_ref()
1823 .expect("tokens measured before shaping");
1824 let mut run_offset = 0;
1825 last_layout
1826 .visible_buffer_lines
1827 .iter()
1828 .map(|&row| {
1829 let line_start = state.text.line_start_offset(row);
1830 let text: String = state.text.slice_line(row).into();
1831 let ranges = if state.is_single_line() {
1832 smallvec::smallvec![0..text.len()]
1833 } else {
1834 state
1835 .display_map
1836 .line(row)
1837 .expect("prepared line")
1838 .wrapped_lines
1839 .clone()
1840 };
1841 let mut lines: SmallVec<[InputLine; 1]> = SmallVec::new();
1842 for range in ranges {
1843 let mut fragments = Vec::new();
1844 let mut offset = range.start;
1845 let mut x = px(0.);
1846 let first =
1847 spans.partition_point(|s| s.range().end <= line_start + range.start);
1848 for span in spans[first..]
1849 .iter()
1850 .take_while(|s| s.range().start < line_start + range.end)
1851 {
1852 let local = span.range().start - line_start..span.range().end - line_start;
1853 if offset < local.start {
1854 let part = offset..local.start;
1855 let shaped = window.text_system().shape_line(
1856 text[part.clone()].to_owned().into(),
1857 font_size,
1858 &runs_for_range(runs, run_offset, &part),
1859 None,
1860 );
1861 let width = shaped.width;
1862 fragments.push(InlineFragment {
1863 range: part.start - range.start..part.end - range.start,
1864 x,
1865 width,
1866 text: Some(shaped),
1867 });
1868 x += width;
1869 }
1870 let width = cache.widths.get(span.token()).copied().unwrap_or_default();
1871 fragments.push(InlineFragment {
1872 range: local.start - range.start..local.end - range.start,
1873 x,
1874 width,
1875 text: None,
1876 });
1877 x += width;
1878 offset = local.end;
1879 }
1880 if offset < range.end {
1881 let part = offset..range.end;
1882 let shaped = window.text_system().shape_line(
1883 text[part.clone()].to_owned().into(),
1884 font_size,
1885 &runs_for_range(runs, run_offset, &part),
1886 None,
1887 );
1888 let width = shaped.width;
1889 fragments.push(InlineFragment {
1890 range: part.start - range.start..part.end - range.start,
1891 x,
1892 width,
1893 text: Some(shaped),
1894 });
1895 }
1896 lines.push(InputLine::inline(text[range].to_owned().into(), fragments));
1897 }
1898 let indent = state.display_map.line(row).map_or(0, |line| line.indent);
1899 let wrap_indent = if indent > 0 && lines.len() > 1 {
1900 let bytes = text
1901 .char_indices()
1902 .nth(indent as usize)
1903 .map_or(text.len(), |(ix, _)| ix);
1904 lines[0].x_for_index(bytes)
1905 } else {
1906 px(0.)
1907 };
1908 run_offset += text.len() + 1;
1909 LineLayout::new()
1910 .inline_lines(lines)
1911 .wrap_indent(wrap_indent)
1912 })
1913 .collect()
1914 }
1915
1916 fn prepaint_tokens(
1917 &self,
1918 layout: &LastLayout,
1919 bounds: Bounds<Pixels>,
1920 mut measured: std::collections::HashMap<usize, (AnyElement, Size<Pixels>)>,
1921 window: &mut Window,
1922 cx: &mut App,
1923 ) -> Vec<AnyElement> {
1924 let state = self.state.read(cx);
1925 if !state.tokens_visible() {
1926 let mut exit = self.state.update(cx, |state, _| {
1927 state.token_bounds.clear();
1928 state.reconcile_token_hover()
1929 });
1930 while let Some((listener, event)) = exit {
1931 listener(&event, window, cx);
1932 exit = self
1933 .state
1934 .update(cx, |state, _| state.reconcile_token_hover());
1935 }
1936 return vec![];
1937 }
1938 let width = state
1939 .token_layout_cache
1940 .as_ref()
1941 .and_then(|c| c.key.as_ref())
1942 .map_or(bounds.size.width, |k| k.2);
1943 let mut placements = Vec::new();
1944 let mut y = layout.visible_top;
1945 for (ix, &row) in layout.visible_buffer_lines.iter().enumerate() {
1946 let start = state.text.line_start_offset(row);
1947 let end = state.text.line_end_offset(row);
1948 let spans = state.token_spans();
1949 let first = spans.partition_point(|s| s.range().end <= start);
1950 for span in spans[first..].iter().take_while(|s| s.range().start < end) {
1951 if let Some(position) =
1952 layout.lines[ix].position_for_index(span.range().start - start, layout, false)
1953 {
1954 placements.push((
1955 state.token_context(span, layout.line_height, width),
1956 bounds.origin + position + point(layout.line_number_width, y),
1957 ));
1958 }
1959 }
1960 y += layout.lines[ix].size(layout.line_height).height;
1961 }
1962 let mut out = Vec::new();
1963 let mut token_bounds = std::collections::HashMap::new();
1964 for (token, origin) in placements {
1965 let (mut element, element_size) = match measured.remove(&token.range().start) {
1966 Some(found) => found,
1967 None => {
1968 let mut element = self.token_element(&token, window, cx);
1969 let element_size = element.layout_as_root(
1970 size(
1971 gpui::AvailableSpace::MaxContent,
1972 gpui::AvailableSpace::Definite(layout.line_height),
1973 ),
1974 window,
1975 cx,
1976 );
1977 (element, element_size)
1978 }
1979 };
1980 element.prepaint_at(origin, window, cx);
1981 token_bounds.insert(token.range().start, Bounds::new(origin, element_size));
1982 out.push(element);
1983 }
1984 let mut exit = self.state.update(cx, |state, _| {
1985 state.token_bounds = token_bounds;
1986 state.reconcile_token_hover()
1987 });
1988 while let Some((listener, event)) = exit {
1989 listener(&event, window, cx);
1990 exit = self
1991 .state
1992 .update(cx, |state, _| state.reconcile_token_hover());
1993 }
1994 out
1995 }
1996
1997 #[allow(clippy::too_many_arguments)]
1998 fn layout_lines(
1999 state: &InputBaseState<M>,
2000 display_text: &Rope,
2001 last_layout: &LastLayout,
2002 font_size: Pixels,
2003 runs: &[TextRun],
2004 bg_segments: &[(Range<usize>, Hsla)],
2005 whitespace_indicators: Option<WhitespaceIndicators>,
2006 window: &mut Window,
2007 ) -> Vec<LineLayout> {
2008 let is_single_line = state.is_single_line();
2009 if state.tokens_visible() {
2010 return Self::layout_token_lines(state, last_layout, font_size, runs, window);
2011 }
2012
2013 if is_single_line {
2014 let text: SharedString = display_text.to_string().into();
2015 let aligned_runs = align_runs_to_char_boundaries(&text, runs);
2016 let line_runs = aligned_runs.as_deref().unwrap_or(runs);
2017 let shaped_line = window
2018 .text_system()
2019 .shape_line(text, font_size, line_runs, None);
2020
2021 let line_layout = LineLayout::new()
2022 .lines(smallvec::smallvec![shaped_line])
2023 .with_background(has_background(line_runs))
2024 .with_whitespaces(whitespace_indicators);
2025 return vec![line_layout];
2026 }
2027
2028 // Empty to use placeholder, the placeholder is not in the wrapper map.
2029 if state.text.len() == 0 {
2030 let placeholder_text = display_text.to_string();
2031 let mut placeholder_lines = SmallVec::new();
2032 let mut line_has_background = false;
2033
2034 for (line, line_runs) in placeholder_line_runs(&placeholder_text, runs) {
2035 let shaped_line = window.text_system().shape_line(
2036 line.to_string().into(),
2037 font_size,
2038 &line_runs,
2039 None,
2040 );
2041 line_has_background |= has_background(&line_runs);
2042 placeholder_lines.push(shaped_line);
2043 }
2044
2045 // Keep placeholder lines in a single layout to stay parallel with visible_* metadata.
2046 let line_layout = LineLayout::new()
2047 .lines(placeholder_lines)
2048 .with_background(line_has_background)
2049 .with_whitespaces(whitespace_indicators);
2050 return vec![line_layout];
2051 }
2052
2053 let mut lines = Vec::with_capacity(last_layout.visible_buffer_lines.len());
2054 // run_offset tracks position in the runs vec coordinate space (only visible line bytes).
2055 // This is separate from the visible_text offset because runs from highlight_lines
2056 // only cover visible (non-folded) lines.
2057 let mut run_offset = 0;
2058
2059 for (vi, &buffer_line) in last_layout.visible_buffer_lines.iter().enumerate() {
2060 let line_text: String = display_text.slice_line(buffer_line).into();
2061 let line_item = state
2062 .display_map
2063 .line(buffer_line)
2064 .expect("line should exists in wrapper");
2065
2066 debug_assert_eq!(line_item.len(), line_text.len());
2067
2068 let mut wrapped_lines: SmallVec<[ShapedLine; 1]> = SmallVec::with_capacity(1);
2069 let mut line_has_background = false;
2070
2071 for range in &line_item.wrapped_lines {
2072 let line_runs = runs_for_range(runs, run_offset, &range);
2073 let line_runs = if bg_segments.is_empty() {
2074 line_runs
2075 } else {
2076 split_runs_by_bg_segments(
2077 last_layout.visible_line_byte_offsets[vi] + (range.start),
2078 &line_runs,
2079 bg_segments,
2080 )
2081 };
2082
2083 let sub_line: SharedString = line_text[range.clone()].to_string().into();
2084 let line_runs =
2085 align_runs_to_char_boundaries(&sub_line, &line_runs).unwrap_or(line_runs);
2086 let shaped_line = window
2087 .text_system()
2088 .shape_line(sub_line, font_size, &line_runs, None);
2089
2090 line_has_background |= has_background(&line_runs);
2091 wrapped_lines.push(shaped_line);
2092 }
2093
2094 // Use the first visual line's indentation width for continuation lines.
2095 let wrap_indent = if line_item.indent > 0 && wrapped_lines.len() > 1 {
2096 let indent_byte_len = line_text
2097 .char_indices()
2098 .nth(line_item.indent as usize)
2099 .map(|(ix, _)| ix)
2100 .unwrap_or(line_text.len());
2101 wrapped_lines[0].x_for_index(indent_byte_len)
2102 } else {
2103 px(0.)
2104 };
2105
2106 let line_layout = LineLayout::new()
2107 .lines(wrapped_lines)
2108 .wrap_indent(wrap_indent)
2109 .with_background(line_has_background)
2110 .with_whitespaces(whitespace_indicators.clone());
2111 lines.push(line_layout);
2112
2113 // +1 for the `\n`
2114 run_offset += line_text.len() + 1;
2115 }
2116
2117 lines
2118 }
2119
2120 /// First usize is the offset of skipped.
2121 fn highlight_lines(
2122 &mut self,
2123 visible_buffer_lines: &[usize],
2124 _visible_top: Pixels,
2125 visible_byte_range: Range<usize>,
2126 cx: &mut App,
2127 ) -> Option<Vec<(Range<usize>, HighlightStyle)>> {
2128 let state = self.state.read(cx);
2129 let text = &state.text;
2130 let is_multi_line = state.is_multi_line();
2131
2132 let (mut highlighter, diagnostics) = match &state.mode {
2133 LayoutMode::CodeEditor {
2134 highlighter,
2135 diagnostics,
2136 ..
2137 } => (highlighter.borrow_mut(), diagnostics),
2138 _ => {
2139 return (!state.masked)
2140 .then(|| {
2141 compose_decoration_collections(
2142 Vec::new(),
2143 state.extras.decoration_layers().into_iter(),
2144 visible_byte_range,
2145 )
2146 })
2147 .flatten();
2148 }
2149 };
2150 let Some(highlighter) = highlighter.as_mut() else {
2151 return (!state.masked)
2152 .then(|| {
2153 compose_decoration_collections(
2154 Vec::new(),
2155 state.extras.decoration_layers().into_iter(),
2156 visible_byte_range,
2157 )
2158 })
2159 .flatten();
2160 };
2161
2162 let mut styles = Vec::with_capacity(visible_buffer_lines.len());
2163 // Byte ranges of the flushed line groups; the composed styles are
2164 // clipped to these at the end so the resulting runs cover exactly the
2165 // visible (non-folded) lines' bytes.
2166 let mut group_ranges: Vec<Range<usize>> = Vec::new();
2167
2168 // Helper to flush a contiguous range of lines. These ranges are disjoint,
2169 // so appending avoids repeatedly cloning and recombining prior styles.
2170 let mut flush_range =
2171 |start_line: usize, end_line: usize, skip: bool, styles: &mut Vec<_>| {
2172 let byte_start = text.line_start_offset(start_line);
2173 let byte_end = if is_multi_line {
2174 // +1 for `\n`
2175 text.line_start_offset(end_line + 1)
2176 } else {
2177 text.line_end_offset(end_line)
2178 };
2179 let range_styles = if skip {
2180 vec![(byte_start..byte_end, HighlightStyle::default())]
2181 } else {
2182 highlighter.styles(
2183 &(byte_start..byte_end),
2184 state.editor_style.highlight_styles.as_ref(),
2185 )
2186 };
2187
2188 group_ranges.push(byte_start..byte_end);
2189 styles.extend(range_styles);
2190 };
2191
2192 // Group contiguous visible lines into ranges and call styles() once per range
2193 let mut visible_iter = visible_buffer_lines.iter().peekable();
2194 let mut range_start: Option<usize> = None;
2195
2196 while let Some(&line) = visible_iter.next() {
2197 // Check if this line is too long for highlighting
2198 let line_len = text.slice_line(line).len();
2199 if line_len > MAX_HIGHLIGHT_LINE_LENGTH {
2200 // Flush any accumulated range first
2201 if let Some(start) = range_start.take() {
2202 flush_range(start, line - 1, false, &mut styles);
2203 }
2204
2205 flush_range(line, line, true, &mut styles);
2206 continue;
2207 }
2208
2209 range_start.get_or_insert(line);
2210
2211 // Check if next line is contiguous, if so keep accumulating
2212 if visible_iter
2213 .peek()
2214 .map(|&&next| next == line + 1)
2215 .unwrap_or(false)
2216 {
2217 continue;
2218 }
2219
2220 // Flush the contiguous range
2221 let start_line = range_start.take().unwrap();
2222 flush_range(start_line, line, false, &mut styles);
2223 }
2224
2225 let diagnostic_styles: Vec<_> = diagnostics
2226 .range(visible_byte_range.clone())
2227 .map(|entry| {
2228 (
2229 entry.range.clone(),
2230 diagnostic_highlight_style(entry.severity, state.editor_style.diagnostics),
2231 )
2232 })
2233 .collect();
2234
2235 // Range semantic tokens, resolved from the LSP provider's cached
2236 // result through the active highlight theme so it shares the same
2237 // colour vocabulary as the tree-sitter path. Empty Vec when no
2238 // provider is set, so `combine_highlights` short-circuits.
2239 let custom_styles = state.extras.semantic_token_styles(
2240 text,
2241 &visible_byte_range,
2242 state.editor_style.highlight_styles.as_ref(),
2243 );
2244
2245 // hover definition style
2246 if let Some(hover_style) = M::hover_definition_style(self.state.read(cx), cx) {
2247 styles.push(hover_style);
2248 }
2249
2250 // Compose tree-sitter, semantic, application, then diagnostic styles.
2251 styles = gpui::combine_highlights(custom_styles, styles).collect();
2252 if !state.masked {
2253 styles = compose_decoration_collections(
2254 styles,
2255 state.extras.decoration_layers().into_iter(),
2256 visible_byte_range.clone(),
2257 )
2258 .unwrap_or_default();
2259 }
2260 styles = gpui::combine_highlights(diagnostic_styles, styles).collect();
2261
2262 // Some sources reach outside the flushed groups — a diagnostic
2263 // straddling the viewport edge, or any range inside a folded region —
2264 // which would inject extra bytes into the runs coordinate space and
2265 // shift every later run boundary (see `layout_lines`). Clip the
2266 // composed styles back to the groups.
2267 styles = clip_styles_to_ranges(styles, &group_ranges);
2268
2269 Some(styles)
2270 }
2271}
2272
2273/// Layout data for a single caret, produced by [`TextElement::layout_cursors`].
2274#[derive(Clone, Debug)]
2275struct CursorRenderInfo {
2276 bounds: Bounds<Pixels>,
2277 is_active: bool,
2278}
2279
2280pub(super) struct PrepaintState {
2281 /// The lines of entire lines.
2282 last_layout: LastLayout,
2283 token_elements: Vec<AnyElement>,
2284 /// The lines only contains the visible lines in the viewport, based on `visible_range`.
2285 ///
2286 /// The child is the soft lines.
2287 line_numbers: Option<Vec<SmallVec<[ShapedLine; 1]>>>,
2288 /// Size of the scrollable area by entire lines.
2289 scroll_size: Size<Pixels>,
2290 /// Caret bounds for every selection, active flagged.
2291 cursor_infos: Vec<CursorRenderInfo>,
2292 cursor_scroll_offset: Point<Pixels>,
2293 /// row index (zero based), no wrap, same line as the cursor.
2294 current_row: Option<usize>,
2295 selection_paths: Vec<Path<Pixels>>,
2296 hover_highlight_path: Option<Path<Pixels>>,
2297 search_match_paths: Vec<(Path<Pixels>, bool)>,
2298 document_color_paths: Vec<(Path<Pixels>, Hsla)>,
2299 range_decoration_fills: Vec<(Path<Pixels>, Hsla)>,
2300 range_decoration_frames: Vec<(Path<Pixels>, Hsla)>,
2301 hover_definition_hitbox: Option<Hitbox>,
2302 indent_guides_path: Option<Path<Pixels>>,
2303 /// The whole input, for deciding whether a long press started in it.
2304 hitbox: Hitbox,
2305 bounds: Bounds<Pixels>,
2306 /// Fold icon layout data
2307 fold_icon_layout: FoldIconLayout,
2308 // Inline completion rendering data
2309 /// Shaped ghost lines to paint after cursor row (completion lines 2+)
2310 ghost_lines: Vec<ShapedLine>,
2311 /// First line of inline completion (painted after cursor on same line)
2312 ghost_first_line: Option<ShapedLine>,
2313 ghost_lines_height: Pixels,
2314}
2315
2316impl PrepaintState {
2317 /// Returns all cursor infos adjusted for scroll offset.
2318 fn cursor_infos_with_scroll(&self) -> Vec<CursorRenderInfo> {
2319 self.cursor_infos
2320 .iter()
2321 .map(|info| {
2322 let mut bounds = info.bounds;
2323 bounds.origin.y += self.cursor_scroll_offset.y;
2324 CursorRenderInfo {
2325 bounds,
2326 is_active: info.is_active,
2327 }
2328 })
2329 .collect()
2330 }
2331}
2332
2333impl<M: InputModeKind> IntoElement for TextElement<M> {
2334 type Element = Self;
2335
2336 fn into_element(self) -> Self::Element {
2337 self
2338 }
2339}
2340
2341/// A debug function to print points as SVG path.
2342#[allow(unused)]
2343fn print_points_as_svg_path(
2344 line_corners: &Vec<gpui::Corners<Pixels>>,
2345 points: &Vec<Point<Pixels>>,
2346) {
2347 for corners in line_corners {
2348 println!(
2349 "tl: ({}, {}), tr: ({}, {}), bl: ({}, {}), br: ({}, {})",
2350 corners.top_left.as_f32() as i32,
2351 corners.top_left.as_f32() as i32,
2352 corners.top_right.as_f32() as i32,
2353 corners.top_right.as_f32() as i32,
2354 corners.bottom_left.as_f32() as i32,
2355 corners.bottom_left.as_f32() as i32,
2356 corners.bottom_right.as_f32() as i32,
2357 corners.bottom_right.as_f32() as i32,
2358 );
2359 }
2360
2361 if points.len() > 0 {
2362 println!(
2363 "M{},{}",
2364 points[0].x.as_f32() as i32,
2365 points[0].y.as_f32() as i32
2366 );
2367 for p in points.iter().skip(1) {
2368 println!("L{},{}", p.x.as_f32() as i32, p.y.as_f32() as i32);
2369 }
2370 }
2371}
2372
2373fn frame_outline_points(corners: &[Corners<Point<Pixels>>]) -> Vec<Point<Pixels>> {
2374 let rects = corners
2375 .iter()
2376 .map(|corners| (corners.top_left, corners.bottom_right))
2377 .collect::<Vec<_>>();
2378 let mut points = Vec::with_capacity(rects.len() * 4);
2379 let first = rects[0];
2380 let last = rects[rects.len() - 1];
2381 points.push(first.0);
2382 points.push(point(first.1.x, first.0.y));
2383 for pair in rects.windows(2) {
2384 let current = pair[0];
2385 let next = pair[1];
2386 points.push(current.1);
2387 points.push(point(next.1.x, current.1.y));
2388 points.push(point(next.1.x, next.1.y));
2389 }
2390 if points.last() != Some(&last.1) {
2391 points.push(last.1);
2392 }
2393 points.push(point(last.0.x, last.1.y));
2394 for pair in rects.windows(2).rev() {
2395 let current = pair[1];
2396 let next = pair[0];
2397 points.push(point(current.0.x, current.0.y));
2398 points.push(point(next.0.x, current.0.y));
2399 points.push(point(next.0.x, next.0.y));
2400 }
2401 if points.last() != points.first() {
2402 points.push(points[0]);
2403 }
2404 points
2405}
2406
2407fn pad_frame_corners(
2408 corners: &[Corners<Point<Pixels>>],
2409 horizontal_padding: Pixels,
2410) -> Vec<Corners<Point<Pixels>>> {
2411 corners
2412 .iter()
2413 .map(|corners| Corners {
2414 top_left: point(corners.top_left.x - horizontal_padding, corners.top_left.y),
2415 top_right: point(
2416 corners.top_right.x + horizontal_padding,
2417 corners.top_right.y,
2418 ),
2419 bottom_left: point(
2420 corners.bottom_left.x - horizontal_padding,
2421 corners.bottom_left.y,
2422 ),
2423 bottom_right: point(
2424 corners.bottom_right.x + horizontal_padding,
2425 corners.bottom_right.y,
2426 ),
2427 })
2428 .collect()
2429}
2430
2431fn snap_frame_outline(
2432 points: &[Point<Pixels>],
2433 stroke_width: Pixels,
2434 scale_factor: f32,
2435) -> (Pixels, Vec<Point<Pixels>>) {
2436 let physical_width = ((stroke_width.as_f32() * scale_factor).abs() - 0.5)
2437 .ceil()
2438 .max(1.);
2439 let stroke_width = px(physical_width / scale_factor);
2440 let center_offset = if physical_width % 2. == 0. { 0. } else { 0.5 };
2441 let snap = |value: Pixels| {
2442 px(
2443 ((value.as_f32() * scale_factor - center_offset).round() + center_offset)
2444 / scale_factor,
2445 )
2446 };
2447 (
2448 stroke_width,
2449 points
2450 .iter()
2451 .map(|point| point.map(snap))
2452 .collect::<Vec<_>>(),
2453 )
2454}
2455
2456fn clamp_frame_to_content_mask(
2457 points: Vec<Point<Pixels>>,
2458 stroke_width: Pixels,
2459 content_mask: Bounds<Pixels>,
2460) -> Vec<Point<Pixels>> {
2461 let half_width = stroke_width / 2.;
2462 let min_x = content_mask.left() + half_width;
2463 let max_x = (content_mask.right() - half_width).max(min_x);
2464 points
2465 .into_iter()
2466 .map(|p| point(p.x.max(min_x).min(max_x), p.y))
2467 .collect()
2468}
2469
2470impl<M: InputModeKind> Element for TextElement<M> {
2471 type RequestLayoutState = ();
2472 type PrepaintState = PrepaintState;
2473
2474 fn id(&self) -> Option<ElementId> {
2475 None
2476 }
2477
2478 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
2479 None
2480 }
2481
2482 fn request_layout(
2483 &mut self,
2484 _id: Option<&GlobalElementId>,
2485 _: Option<&gpui::InspectorElementId>,
2486 window: &mut Window,
2487 cx: &mut App,
2488 ) -> (LayoutId, Self::RequestLayoutState) {
2489 let state = self.state.read(cx);
2490 let line_height = window.line_height();
2491
2492 let mut style = Style::default();
2493 style.size.width = relative(1.).into();
2494 if state.is_multi_line() {
2495 style.flex_grow = 1.0;
2496 style.size.height = relative(1.).into();
2497 // At least `rows` tall (auto grow: the content's rows, capped at
2498 // `max_rows`); a taller parent still fills it.
2499 let rows = state.mode.max_rows().min(state.mode.rows());
2500 style.min_size.height = (rows * line_height).into();
2501 } else {
2502 // For single-line inputs, the minimum height should be the line height
2503 style.size.height = line_height.into();
2504 };
2505
2506 (window.request_layout(style, [], cx), ())
2507 }
2508
2509 fn prepaint(
2510 &mut self,
2511 _id: Option<&GlobalElementId>,
2512 _: Option<&gpui::InspectorElementId>,
2513 bounds: Bounds<Pixels>,
2514 _request_layout: &mut Self::RequestLayoutState,
2515 window: &mut Window,
2516 cx: &mut App,
2517 ) -> Self::PrepaintState {
2518 let style = window.text_style();
2519 let font = style.font();
2520 let text_size = style.font_size.to_pixels(window.rem_size());
2521 // Past the end of a line there are no glyphs to hit-test against, so a pointer
2522 // out there is measured in spaces instead.
2523 let space_width = {
2524 let font_id = window.text_system().resolve_font(&font);
2525 window.text_system().layout_width(font_id, text_size, ' ')
2526 };
2527
2528 self.state.update(cx, |state, cx| {
2529 state.display_map.set_font(font, text_size, cx);
2530 state.display_map.ensure_text_prepared(&state.text, cx);
2531 });
2532
2533 let state = self.state.read(cx);
2534 let multi_line = state.is_multi_line();
2535 let text = state.text.clone();
2536 let is_empty = text.len() == 0;
2537 let placeholder = self.placeholder.clone();
2538
2539 let text_style = window.text_style();
2540 let disabled = state.disabled;
2541 let dim = |color: Hsla| if disabled { color.opacity(0.5) } else { color };
2542 let fg = dim(text_style.color);
2543 let (display_text, text_color) = if is_empty {
2544 (
2545 &Rope::from(placeholder.as_str()),
2546 dim(state.editor_style.muted_foreground),
2547 )
2548 } else if state.masked {
2549 (
2550 &Rope::from(MASK_CHAR.to_string().repeat(text.chars().count())),
2551 fg,
2552 )
2553 } else {
2554 (&text, fg)
2555 };
2556
2557 // Calculate the width of the line numbers
2558 let (line_number_width, line_number_len) =
2559 Self::layout_line_numbers(&state, &text, text_size, &text_style, window);
2560
2561 let mut bounds = bounds;
2562 let wrap_width = if multi_line && state.soft_wrap {
2563 Some(bounds.size.width - line_number_width - RIGHT_MARGIN)
2564 } else {
2565 None
2566 };
2567
2568 let wrapping_indent = state.wrapping_indent;
2569 let wrap_width_changed = state
2570 .last_layout
2571 .as_ref()
2572 .map(|l| l.wrap_width != wrap_width)
2573 .unwrap_or(true);
2574
2575 let wrapping_indent_changed = state
2576 .last_layout
2577 .as_ref()
2578 .map(|l| l.wrapping_indent != wrapping_indent)
2579 .unwrap_or(true);
2580
2581 if wrap_width_changed || wrapping_indent_changed {
2582 self.state.update(cx, |state, cx| {
2583 state.display_map.on_layout_changed(wrap_width, cx);
2584 state.display_map.set_wrapping_indent(wrapping_indent, cx);
2585 });
2586 }
2587
2588 let line_height = window.line_height();
2589 let token_elements = self.measure_tokens(
2590 (bounds.size.width - line_number_width - RIGHT_MARGIN).max(px(1.)),
2591 line_height,
2592 bounds.size.height,
2593 window,
2594 cx,
2595 );
2596 let state = self.state.read(cx);
2597
2598 let (visible_range, visible_buffer_lines, visible_top) =
2599 self.calculate_visible_range(&state, line_height, bounds.size.height);
2600 let visible_start_offset = state.text.line_start_offset(visible_range.start);
2601 let visible_end_offset = state
2602 .text
2603 .line_end_offset(visible_range.end.saturating_sub(1));
2604
2605 let highlight_styles = self.highlight_lines(
2606 &visible_buffer_lines,
2607 visible_top,
2608 visible_start_offset..visible_end_offset,
2609 cx,
2610 );
2611
2612 let state = self.state.read(cx);
2613
2614 let visible_line_byte_offsets: Vec<usize> = visible_buffer_lines
2615 .iter()
2616 .map(|&bl| state.text.line_start_offset(bl))
2617 .collect();
2618
2619 // For password input (masked: true), convert byte offsets to masked display byte offsets so that
2620 // layout_match_range and position_for_index work in the correct coordinate space.
2621 let (visible_line_byte_offsets, visible_range_offset) = if state.masked {
2622 let offsets = visible_line_byte_offsets
2623 .iter()
2624 .map(|&o| masked_display_offset(&text, o))
2625 .collect();
2626 let range_offset = masked_display_offset(&text, visible_start_offset)
2627 ..masked_display_offset(&text, visible_end_offset);
2628 (offsets, range_offset)
2629 } else {
2630 (
2631 visible_line_byte_offsets,
2632 visible_start_offset..visible_end_offset,
2633 )
2634 };
2635
2636 let mut last_layout = LastLayout {
2637 visible_range,
2638 visible_buffer_lines,
2639 visible_line_byte_offsets,
2640 visible_top,
2641 visible_range_offset,
2642 line_height,
2643 wrap_width,
2644 wrapping_indent,
2645 line_number_width,
2646 space_width,
2647 lines: Rc::new(vec![]),
2648 cursor_bounds: None,
2649 text_align: state.text_align,
2650 content_width: bounds.size.width,
2651 };
2652
2653 let run = TextRun {
2654 len: display_text.len(),
2655 font: style.font(),
2656 color: text_color,
2657 background_color: None,
2658 underline: None,
2659 strikethrough: None,
2660 };
2661 let marked_run = TextRun {
2662 len: 0,
2663 font: style.font(),
2664 color: text_color,
2665 background_color: None,
2666 underline: Some(UnderlineStyle {
2667 thickness: px(1.),
2668 color: Some(text_color),
2669 wavy: false,
2670 }),
2671 strikethrough: None,
2672 };
2673
2674 let ime_marked_range = ime_marked_display_range(
2675 &text,
2676 state.ime_marked_range.as_ref().map(|m| m.start..m.end),
2677 state.masked,
2678 );
2679
2680 let runs = if let (false, Some(highlight_styles)) = (is_empty, highlight_styles) {
2681 let mut runs = Vec::with_capacity(highlight_styles.len() + 2);
2682
2683 for (range, style) in &highlight_styles {
2684 let mut run = text_style.clone().highlight(*style).to_run(range.len());
2685 if disabled {
2686 run.color = run.color.opacity(0.5);
2687 }
2688
2689 runs.extend(split_run_for_ime_underline(
2690 run,
2691 range.clone(),
2692 ime_marked_range.clone(),
2693 marked_run.underline,
2694 ));
2695 }
2696 runs
2697 } else {
2698 split_run_for_ime_underline(
2699 run,
2700 0..display_text.len(),
2701 ime_marked_range,
2702 marked_run.underline,
2703 )
2704 .into_vec()
2705 };
2706
2707 let document_colors = state
2708 .extras
2709 .document_color_swatches(&text, &last_layout.visible_range);
2710
2711 // Create shaped lines for whitespace indicators before layout
2712 let whitespace_indicators =
2713 Self::layout_whitespace_indicators(&state, text_size, &text_style, window, cx);
2714
2715 let lines = Self::layout_lines(
2716 &state,
2717 &display_text,
2718 &last_layout,
2719 text_size,
2720 &runs,
2721 &document_colors,
2722 whitespace_indicators,
2723 window,
2724 );
2725
2726 let mut longest_line_width = wrap_width.unwrap_or(px(0.));
2727 // 1. Single line
2728 // 2. Multi-line with soft wrap disabled.
2729 if state.is_single_line() || !state.soft_wrap {
2730 let longest_row = state.display_map.longest_row();
2731 let longest_line = state.text.slice_line(longest_row);
2732 let key = LongestLineKey {
2733 document_revision: state.document_revision,
2734 row: longest_row,
2735 len: longest_line.len(),
2736 font: style.font(),
2737 text_size,
2738 wrap_width,
2739 };
2740 let cached = state
2741 .longest_line_width
2742 .take()
2743 .filter(|(cached_key, _)| *cached_key == key);
2744 longest_line_width = match cached {
2745 Some((_, width)) => width,
2746 None => {
2747 let longest_line: SharedString = longest_line.to_string().into();
2748 window
2749 .text_system()
2750 .shape_line(
2751 longest_line.clone(),
2752 text_size,
2753 &[TextRun {
2754 len: longest_line.len(),
2755 font: key.font.clone(),
2756 color: gpui::black(),
2757 background_color: None,
2758 underline: None,
2759 strikethrough: None,
2760 }],
2761 wrap_width,
2762 )
2763 .width
2764 }
2765 };
2766 state
2767 .longest_line_width
2768 .set(Some((key, longest_line_width)));
2769 }
2770 if state.tokens_visible() {
2771 longest_line_width = if let Some(width) = wrap_width {
2772 width
2773 } else {
2774 state
2775 .token_layout_cache
2776 .as_ref()
2777 .map_or(px(0.), |cache| cache.unwrapped_width)
2778 };
2779 }
2780 last_layout.lines = Rc::new(lines);
2781
2782 let (ghost_first_line, ghost_lines) = Self::layout_inline_completion(
2783 state,
2784 &last_layout.visible_range,
2785 text_size,
2786 window,
2787 cx,
2788 );
2789 let ghost_line_count = ghost_lines.len();
2790 let ghost_lines_height = ghost_line_count as f32 * line_height;
2791
2792 let total_wrapped_lines = state.display_map.wrap_row_count();
2793 let empty_bottom_height = empty_bottom_height(
2794 state.is_code_editor(),
2795 state.scroll_beyond_last_line,
2796 bounds.size.height,
2797 line_height,
2798 );
2799
2800 // Empty bottom and ghost lines both describe extra height past the
2801 // last content row, so take the max rather than summing — summing
2802 // left a band of empty space the cursor could never reach.
2803 let mut scroll_size = size(
2804 if longest_line_width + line_number_width + RIGHT_MARGIN > bounds.size.width {
2805 longest_line_width + line_number_width + RIGHT_MARGIN
2806 } else {
2807 longest_line_width
2808 },
2809 (total_wrapped_lines as f32 * line_height
2810 + empty_bottom_height.max(ghost_lines_height))
2811 .max(bounds.size.height),
2812 );
2813
2814 // TODO: should be add some gap to right, to convenient to focus on boundary position
2815 if last_layout.text_align == TextAlign::Right || last_layout.text_align == TextAlign::Center
2816 {
2817 scroll_size.width = longest_line_width + line_number_width;
2818 }
2819
2820 // `position_for_index` for example
2821 //
2822 // #### text
2823 //
2824 // Hello 世界,this is GPUI component.
2825 // The GPUI Component is a collection of UI components for
2826 // GPUI framework, including Button, Input, Checkbox, Radio,
2827 // Dropdown, Tab, and more...
2828 //
2829 // wrap_width: 444px, line_height: 20px
2830 //
2831 // #### lines[0]
2832 //
2833 // | index | pos | line |
2834 // |-------|------------------|------|
2835 // | 5 | (37 px, 0.0) | 0 |
2836 // | 38 | (261.7 px, 20.0) | 0 |
2837 // | 40 | None | - |
2838 //
2839 // #### lines[1]
2840 //
2841 // | index | position | line |
2842 // |-------|-----------------------|------|
2843 // | 5 | (43.578125 px, 0.0) | 0 |
2844 // | 56 | (422.21094 px, 0.0) | 0 |
2845 // | 57 | (11.6328125 px, 20.0) | 1 |
2846 // | 114 | (429.85938 px, 20.0) | 1 |
2847 // | 115 | (11.3125 px, 40.0) | 2 |
2848
2849 // Calculate the scroll offset to keep the cursor in view
2850
2851 // Save the unscrolled x before layout_cursors modifies bounds.origin with scroll_offset.
2852 // Fold icons and their hitboxes must use this value so they stay fixed in the gutter
2853 // regardless of horizontal scroll position.
2854 let input_bounds = bounds;
2855 let original_x = bounds.origin.x;
2856
2857 let (cursor_infos, cursor_scroll_offset, current_row) =
2858 self.layout_cursors(&last_layout, &mut bounds, scroll_size, window, cx);
2859 // Completion/code-action menus position at the active caret.
2860 last_layout.cursor_bounds = cursor_infos
2861 .iter()
2862 .find(|info| info.is_active)
2863 .map(|info| info.bounds);
2864
2865 let search_match_paths = self.layout_search_matches(&last_layout, &mut bounds, cx);
2866 let selection_paths = self.layout_selections(&last_layout, &mut bounds, window, cx);
2867 let hover_highlight_path = self.layout_hover_highlight(&last_layout, &mut bounds, cx);
2868 let document_color_paths =
2869 self.layout_document_colors(&document_colors, &last_layout, &bounds, cx);
2870 let (range_decoration_fills, range_decoration_frames) = self.layout_range_decorations(
2871 &last_layout,
2872 &bounds,
2873 window,
2874 window.content_mask().bounds,
2875 cx,
2876 );
2877
2878 let state = self.state.read(cx);
2879 let line_numbers = if state.mode.line_number() {
2880 let mut line_numbers = Vec::with_capacity(last_layout.visible_buffer_lines.len());
2881 let other_line_runs = vec![TextRun {
2882 len: line_number_len,
2883 font: style.font(),
2884 color: state.editor_style.muted_foreground,
2885 background_color: None,
2886 underline: None,
2887 strikethrough: None,
2888 }];
2889 let current_line_runs = vec![TextRun {
2890 len: line_number_len,
2891 font: style.font(),
2892 color: state.editor_style.foreground,
2893 background_color: None,
2894 underline: None,
2895 strikethrough: None,
2896 }];
2897
2898 // build line numbers
2899 for (line, &buffer_line) in last_layout
2900 .lines
2901 .iter()
2902 .zip(last_layout.visible_buffer_lines.iter())
2903 {
2904 let line_no: SharedString = format!(
2905 "{:>width$}",
2906 displayed_line_number(buffer_line + 1),
2907 width = line_number_len
2908 )
2909 .into();
2910
2911 let runs = if current_row == Some(buffer_line) {
2912 &current_line_runs
2913 } else {
2914 &other_line_runs
2915 };
2916
2917 let mut sub_lines: SmallVec<[ShapedLine; 1]> = SmallVec::new();
2918 sub_lines.push(
2919 window
2920 .text_system()
2921 .shape_line(line_no, text_size, &runs, None),
2922 );
2923 for _ in 0..line.wrapped_lines.len().saturating_sub(1) {
2924 sub_lines.push(ShapedLine::default());
2925 }
2926 line_numbers.push(sub_lines);
2927 }
2928 Some(line_numbers)
2929 } else {
2930 None
2931 };
2932
2933 let hover_definition_hitbox = M::hover_definition_hitbox(state, window, cx);
2934 let indent_guides_path =
2935 self.layout_indent_guides(state, &bounds, &last_layout, &text_style, window);
2936 state
2937 .editor_scrollbar_snapshot
2938 .set(Some(EditorScrollbarSnapshot::new(
2939 input_bounds,
2940 &last_layout,
2941 scroll_size,
2942 cursor_scroll_offset,
2943 state,
2944 )));
2945 let fold_icon_layout =
2946 self.layout_fold_icons(original_x, &bounds, &last_layout, window, cx);
2947 let hitbox = window.insert_hitbox(input_bounds, HitboxBehavior::Normal);
2948
2949 let token_elements = self.prepaint_tokens(&last_layout, bounds, token_elements, window, cx);
2950 PrepaintState {
2951 token_elements,
2952 hitbox,
2953 bounds,
2954 last_layout,
2955 scroll_size,
2956 line_numbers,
2957 cursor_infos,
2958 cursor_scroll_offset,
2959 current_row,
2960 selection_paths,
2961 search_match_paths,
2962 hover_highlight_path,
2963 hover_definition_hitbox,
2964 document_color_paths,
2965 range_decoration_fills,
2966 range_decoration_frames,
2967 indent_guides_path,
2968 fold_icon_layout,
2969 ghost_first_line,
2970 ghost_lines,
2971 ghost_lines_height,
2972 }
2973 }
2974
2975 fn paint(
2976 &mut self,
2977 _id: Option<&GlobalElementId>,
2978 _: Option<&gpui::InspectorElementId>,
2979 input_bounds: Bounds<Pixels>,
2980 _request_layout: &mut Self::RequestLayoutState,
2981 prepaint: &mut Self::PrepaintState,
2982 window: &mut Window,
2983 cx: &mut App,
2984 ) {
2985 let (focus_handle, show_cursor, disabled, selected_range, editor_style, editor_paddings) = {
2986 let state = self.state.read(cx);
2987 (
2988 state.focus_handle.clone(),
2989 state.show_cursor(window, cx),
2990 state.disabled,
2991 *state.active_selection(),
2992 state.editor_style.clone(),
2993 state.editor_paddings,
2994 )
2995 };
2996 let focused = focus_handle.is_focused(window);
2997 let bounds = prepaint.bounds;
2998 let text_align = prepaint.last_layout.text_align;
2999
3000 window.handle_input(
3001 &focus_handle,
3002 ElementInputHandler::new(bounds, self.state.clone()),
3003 cx,
3004 );
3005
3006 // Paint multi line text
3007 let line_height = window.line_height();
3008 let origin = bounds.origin;
3009
3010 let invisible_top_padding = prepaint.last_layout.visible_top;
3011 let active_line_color = editor_style
3012 .editor_active_line
3013 .map(|color| if disabled { color.opacity(0.5) } else { color });
3014 let editor_background = if disabled {
3015 editor_style.background.opacity(0.5)
3016 } else {
3017 editor_style.background
3018 };
3019
3020 // Paint active line
3021 let mut offset_y = px(0.);
3022 if let Some(line_numbers) = prepaint.line_numbers.as_ref() {
3023 offset_y += invisible_top_padding;
3024
3025 // Each item is the normal lines.
3026 for (lines, &buffer_line) in line_numbers
3027 .iter()
3028 .zip(prepaint.last_layout.visible_buffer_lines.iter())
3029 {
3030 let is_active = prepaint.current_row == Some(buffer_line);
3031 let p = point(input_bounds.origin.x, origin.y + offset_y);
3032 let height = line_height * lines.len() as f32;
3033 // Paint the current line background
3034 if is_active {
3035 if let Some(bg_color) = active_line_color {
3036 window.paint_quad(fill(
3037 Bounds::new(p, size(bounds.size.width, height)),
3038 bg_color,
3039 ));
3040 }
3041 }
3042 offset_y += height;
3043 }
3044 }
3045
3046 // Keep scrollbar offset always be positive,Start from the left position
3047 let scroll_offset = if text_align == TextAlign::Right {
3048 (prepaint.scroll_size.width - prepaint.bounds.size.width).max(px(0.))
3049 } else if text_align == TextAlign::Center {
3050 (prepaint.scroll_size.width - prepaint.bounds.size.width)
3051 .half()
3052 .max(px(0.))
3053 } else {
3054 px(0.)
3055 };
3056
3057 // Paint glyph backgrounds
3058 //
3059 // gpui's `paint` only draws glyphs, underlines, and strikethroughs, so decoration
3060 // backgrounds need their own pass. It runs ahead of the indent guides, selections,
3061 // and text so a highlighted range sits under them instead of covering them.
3062 let mut offset_y = invisible_top_padding;
3063 for (line, &buffer_line) in prepaint
3064 .last_layout
3065 .lines
3066 .iter()
3067 .zip(prepaint.last_layout.visible_buffer_lines.iter())
3068 {
3069 let p = point(
3070 origin.x + prepaint.last_layout.line_number_width + scroll_offset,
3071 origin.y + offset_y,
3072 );
3073
3074 line.paint_background(
3075 p,
3076 line_height,
3077 text_align,
3078 Some(prepaint.last_layout.content_width),
3079 window,
3080 cx,
3081 );
3082
3083 offset_y += line.size(line_height).height;
3084
3085 // Ghost lines shift every later line down.
3086 if Some(buffer_line) == prepaint.current_row {
3087 offset_y += prepaint.ghost_lines_height;
3088 }
3089 }
3090
3091 // Paint indent guides
3092 if let Some(path) = prepaint.indent_guides_path.take() {
3093 window.paint_path(path, editor_style.border.opacity(0.85));
3094 }
3095
3096 // Application decorations sit below the user's selection.
3097 for (path, color) in &prepaint.range_decoration_fills {
3098 window.paint_path(path.clone(), *color);
3099 }
3100 for (path, color) in &prepaint.range_decoration_frames {
3101 window.paint_path(path.clone(), *color);
3102 }
3103
3104 // Paint selections
3105 if window.is_window_active() {
3106 let secondary_selection = Hsla {
3107 s: 0.1,
3108 ..editor_style.selection
3109 };
3110 for (path, is_active) in prepaint.search_match_paths.iter() {
3111 window.paint_path(path.clone(), secondary_selection);
3112
3113 if *is_active {
3114 window.paint_path(path.clone(), editor_style.selection);
3115 }
3116 }
3117
3118 for path in prepaint.selection_paths.drain(..) {
3119 window.paint_path(path, editor_style.selection);
3120 }
3121
3122 // Paint hover highlight
3123 if let Some(path) = prepaint.hover_highlight_path.take() {
3124 window.paint_path(path, secondary_selection);
3125 }
3126 }
3127
3128 // Paint document colors
3129 for (path, color) in prepaint.document_color_paths.iter() {
3130 let color = if disabled { color.opacity(0.5) } else { *color };
3131 window.paint_path(path.clone(), color);
3132 }
3133
3134 // Paint text with inline completion ghost line support
3135 let mut offset_y = invisible_top_padding;
3136 let ghost_lines = &prepaint.ghost_lines;
3137 let has_ghost_lines = !ghost_lines.is_empty();
3138
3139 // Track the y-position of the cursor row for positioning the first line suffix
3140 let mut cursor_row_y = None;
3141
3142 for (line, &buffer_line) in prepaint
3143 .last_layout
3144 .lines
3145 .iter()
3146 .zip(prepaint.last_layout.visible_buffer_lines.iter())
3147 {
3148 let row = buffer_line;
3149 let line_y = origin.y + offset_y;
3150 let p = point(
3151 origin.x + prepaint.last_layout.line_number_width + (scroll_offset),
3152 line_y,
3153 );
3154
3155 // Paint the actual line
3156 _ = line.paint(
3157 p,
3158 line_height,
3159 text_align,
3160 Some(prepaint.last_layout.content_width),
3161 window,
3162 cx,
3163 );
3164 offset_y += line.size(line_height).height;
3165
3166 if Some(row) == prepaint.current_row {
3167 cursor_row_y = Some(line_y);
3168 }
3169
3170 // After the cursor row, paint ghost lines (which shifts subsequent content down)
3171 if has_ghost_lines && Some(row) == prepaint.current_row {
3172 let ghost_x = origin.x + prepaint.last_layout.line_number_width;
3173
3174 for ghost_line in ghost_lines {
3175 let ghost_p = point(ghost_x, origin.y + offset_y);
3176
3177 // Paint semi-transparent background for ghost line
3178 let ghost_bounds = Bounds::new(
3179 ghost_p,
3180 size(
3181 bounds.size.width - prepaint.last_layout.line_number_width,
3182 line_height,
3183 ),
3184 );
3185 window.paint_quad(fill(ghost_bounds, editor_background));
3186
3187 // Paint ghost line text
3188 _ = ghost_line.paint(
3189 ghost_p,
3190 line_height,
3191 text_align,
3192 Some(prepaint.last_layout.content_width),
3193 window,
3194 cx,
3195 );
3196 offset_y += line_height;
3197 }
3198 }
3199 }
3200
3201 for element in &mut prepaint.token_elements {
3202 element.paint(window, cx);
3203 }
3204
3205 // Paint blinking cursors (shared blink state for all carets)
3206 if focused && show_cursor {
3207 for cursor_info in prepaint.cursor_infos_with_scroll() {
3208 window.paint_quad(fill(cursor_info.bounds, editor_style.caret));
3209 }
3210 }
3211
3212 // Paint line numbers
3213 let mut offset_y = px(0.);
3214 if let Some(line_numbers) = prepaint.line_numbers.as_ref() {
3215 offset_y += invisible_top_padding;
3216
3217 // The gutter is a fixed overlay above horizontally scrolling text.
3218 // Always give it an opaque editor background when the theme does not
3219 // provide a dedicated gutter color, and cover the complete gutter so
3220 // text cannot show through its right-side spacing/fold-icon area.
3221 let gutter_bg = editor_style
3222 .editor_gutter_background
3223 .unwrap_or(editor_background);
3224 let gutter_bounds = editor_gutter_bounds(
3225 input_bounds,
3226 prepaint.last_layout.line_number_width,
3227 prepaint.ghost_lines_height,
3228 editor_paddings,
3229 );
3230 window.paint_quad(fill(gutter_bounds, gutter_bg));
3231
3232 // Each item is the normal lines.
3233 for (lines, &buffer_line) in line_numbers
3234 .iter()
3235 .zip(prepaint.last_layout.visible_buffer_lines.iter())
3236 {
3237 let p = point(input_bounds.origin.x, origin.y + offset_y);
3238 let is_active = prepaint.current_row == Some(buffer_line);
3239
3240 let height = line_height * lines.len() as f32;
3241 // paint active line number background
3242 if is_active {
3243 if let Some(bg_color) = active_line_color {
3244 window.paint_quad(fill(
3245 Bounds::new(
3246 point(gutter_bounds.origin.x, p.y),
3247 size(gutter_bounds.size.width, height),
3248 ),
3249 bg_color,
3250 ));
3251 }
3252 }
3253
3254 for line in lines {
3255 _ = line.paint(p, line_height, TextAlign::Left, None, window, cx);
3256 offset_y += line_height;
3257 }
3258
3259 // Add ghost line height after cursor row for line numbers alignment
3260 if !prepaint.ghost_lines.is_empty() && prepaint.current_row == Some(buffer_line) {
3261 offset_y += prepaint.ghost_lines_height;
3262 }
3263 }
3264 }
3265
3266 // Paint fold icons (only visible on hover or for current line)
3267 self.paint_fold_icons(
3268 &mut prepaint.fold_icon_layout,
3269 prepaint.current_row,
3270 window,
3271 cx,
3272 );
3273
3274 self.state.update(cx, |state, cx| {
3275 let geometry_changed = state.last_bounds != Some(bounds)
3276 || state.input_bounds != input_bounds
3277 || state.scroll_size != prepaint.scroll_size
3278 || state.last_layout.as_ref().is_none_or(|layout| {
3279 layout.cursor_bounds != prepaint.last_layout.cursor_bounds
3280 || layout.line_height != prepaint.last_layout.line_height
3281 });
3282 state.last_layout = Some(prepaint.last_layout.clone());
3283 state.last_bounds = Some(bounds);
3284 state.last_cursor = Some(state.cursor());
3285 state.set_input_bounds(input_bounds, cx);
3286 state.last_selected_range = Some(selected_range);
3287 state.scroll_size = prepaint.scroll_size;
3288 state.update_scroll_offset(Some(prepaint.cursor_scroll_offset), cx);
3289 state.deferred_scroll_offset = None;
3290
3291 // Layout consumers need changed geometry, not another notification
3292 // for every paint of an unchanged input.
3293 if geometry_changed {
3294 cx.notify();
3295 }
3296 });
3297
3298 if let Some(hitbox) = prepaint.hover_definition_hitbox.as_ref()
3299 && !window.modifiers().alt
3300 {
3301 window.set_cursor_style(gpui::CursorStyle::PointingHand, &hitbox);
3302 }
3303
3304 // Paint inline completion first line suffix (after cursor on same line)
3305 if focused {
3306 if let Some(first_line) = &prepaint.ghost_first_line {
3307 let active_cursor = prepaint
3308 .cursor_infos_with_scroll()
3309 .into_iter()
3310 .find(|info| info.is_active);
3311 if let (Some(cursor_info), Some(cursor_row_y)) = (active_cursor, cursor_row_y) {
3312 let cursor_bounds = cursor_info.bounds;
3313 let first_line_x = cursor_bounds.origin.x + cursor_bounds.size.width;
3314 let p = point(first_line_x, cursor_row_y);
3315
3316 // Paint background to cover any existing text
3317 let bg_bounds = Bounds::new(p, size(first_line.width + px(4.), line_height));
3318 window.paint_quad(fill(bg_bounds, editor_background));
3319
3320 // Paint first line completion text
3321 _ = first_line.paint(p, line_height, text_align, None, window, cx);
3322 }
3323 }
3324 }
3325
3326 self.paint_mouse_listeners(&prepaint.hitbox, window, cx);
3327 }
3328}
3329
3330/// Split placeholder text into display lines and trim runs to each line.
3331fn placeholder_line_runs<'a>(
3332 display_text: &'a str,
3333 runs: &[TextRun],
3334) -> Vec<(&'a str, Vec<TextRun>)> {
3335 let mut result = Vec::new();
3336 let mut line_offset = 0;
3337
3338 for line in display_text.split('\n') {
3339 let line_runs = runs_for_range(runs, line_offset, &(0..line.len()));
3340 debug_assert_eq!(
3341 line_runs.iter().map(|run| run.len).sum::<usize>(),
3342 line.len()
3343 );
3344 result.push((line, line_runs));
3345 // Advance in the whole-placeholder coordinate space, including the separator.
3346 line_offset += line.len() + 1;
3347 }
3348
3349 result
3350}
3351
3352/// Get the runs for the given range.
3353///
3354/// The range is the byte range of the wrapped line.
3355pub(super) fn runs_for_range(
3356 runs: &[TextRun],
3357 line_offset: usize,
3358 range: &Range<usize>,
3359) -> Vec<TextRun> {
3360 let mut result = vec![];
3361 let range = (line_offset + range.start)..(line_offset + range.end);
3362 let mut cursor = 0;
3363
3364 for run in runs {
3365 let run_start = cursor;
3366 let run_end = cursor + run.len;
3367
3368 if run_end <= range.start {
3369 cursor = run_end;
3370 continue;
3371 }
3372
3373 if run_start >= range.end {
3374 break;
3375 }
3376
3377 let start = range.start.max(run_start) - run_start;
3378 let end = range.end.min(run_end) - run_start;
3379 let len = end - start;
3380
3381 if len > 0 {
3382 result.push(TextRun { len, ..run.clone() });
3383 }
3384
3385 cursor = run_end;
3386 }
3387
3388 result
3389}
3390
3391/// Clip sorted `styles` to the sorted, disjoint `ranges`, splitting styles
3392/// that span several ranges and dropping coverage in the gaps between them.
3393fn clip_styles_to_ranges(
3394 styles: Vec<(Range<usize>, HighlightStyle)>,
3395 ranges: &[Range<usize>],
3396) -> Vec<(Range<usize>, HighlightStyle)> {
3397 let mut result = Vec::with_capacity(styles.len());
3398 let mut range_ix = 0;
3399
3400 for (style_range, style) in styles {
3401 while range_ix < ranges.len() && ranges[range_ix].end <= style_range.start {
3402 range_ix += 1;
3403 }
3404
3405 let mut ix = range_ix;
3406 while ix < ranges.len() && ranges[ix].start < style_range.end {
3407 let start = style_range.start.max(ranges[ix].start);
3408 let end = style_range.end.min(ranges[ix].end);
3409 if start < end {
3410 result.push((start..end, style));
3411 }
3412 ix += 1;
3413 }
3414 }
3415
3416 result
3417}
3418
3419/// Snap run boundaries to char boundaries of `text` and cap them at its
3420/// length. Style ranges are byte offsets that can drift off char boundaries
3421/// (a stale syntax tree, a range in the wrong coordinate space) and the
3422/// platform text system panics when a run splits a multi-byte character.
3423///
3424/// Returns `None` when the runs are already aligned (the common case).
3425pub(super) fn align_runs_to_char_boundaries(text: &str, runs: &[TextRun]) -> Option<Vec<TextRun>> {
3426 let mut end = 0;
3427 let aligned = runs.iter().all(|run| {
3428 end += run.len;
3429 end <= text.len() && text.is_char_boundary(end)
3430 });
3431 if aligned {
3432 return None;
3433 }
3434
3435 let mut result = Vec::with_capacity(runs.len());
3436 let mut cursor = 0;
3437 let mut raw_end = 0;
3438 for run in runs {
3439 raw_end = (raw_end + run.len).min(text.len());
3440 let mut end = raw_end;
3441 while !text.is_char_boundary(end) {
3442 end += 1;
3443 }
3444 if end > cursor {
3445 result.push(TextRun {
3446 len: end - cursor,
3447 ..run.clone()
3448 });
3449 cursor = end;
3450 }
3451 }
3452
3453 Some(result)
3454}
3455
3456fn split_run_for_ime_underline(
3457 run: TextRun,
3458 run_range: Range<usize>,
3459 marked_range: Option<Range<usize>>,
3460 marked_underline: Option<UnderlineStyle>,
3461) -> SmallVec<[TextRun; 3]> {
3462 if run.len == 0 {
3463 return SmallVec::new();
3464 }
3465
3466 let Some(marked) = marked_range else {
3467 return [run].into_iter().collect();
3468 };
3469
3470 let intersection_start = run_range.start.max(marked.start);
3471 let intersection_end = run_range.end.min(marked.end);
3472 if intersection_start >= intersection_end {
3473 return [run].into_iter().collect();
3474 }
3475
3476 [
3477 TextRun {
3478 len: intersection_start - run_range.start,
3479 ..run.clone()
3480 },
3481 TextRun {
3482 len: intersection_end - intersection_start,
3483 underline: marked_underline,
3484 ..run.clone()
3485 },
3486 TextRun {
3487 len: run_range.end - intersection_end,
3488 ..run
3489 },
3490 ]
3491 .into_iter()
3492 .filter(|run| run.len > 0)
3493 .collect()
3494}
3495
3496/// Whether any of these runs paints a glyph background, used to skip the background
3497/// paint pass for lines without highlights.
3498fn has_background(runs: &[TextRun]) -> bool {
3499 runs.iter().any(|run| run.background_color.is_some())
3500}
3501
3502fn split_runs_by_bg_segments(
3503 start_offset: usize,
3504 runs: &[TextRun],
3505 bg_segments: &[(Range<usize>, Hsla)],
3506) -> Vec<TextRun> {
3507 let mut result = vec![];
3508
3509 let mut cursor = start_offset;
3510 for run in runs {
3511 let mut run_start = cursor;
3512 let run_end = cursor + run.len;
3513
3514 for (bg_range, bg_color) in bg_segments {
3515 if run_end <= bg_range.start || run_start >= bg_range.end {
3516 continue;
3517 }
3518
3519 // Overlap exists
3520 if run_start < bg_range.start {
3521 // Add the part before the background range
3522 result.push(TextRun {
3523 len: bg_range.start - run_start,
3524 ..run.clone()
3525 });
3526 }
3527
3528 // Add the overlapping part with background color
3529 let overlap_start = run_start.max(bg_range.start);
3530 let overlap_end = run_end.min(bg_range.end);
3531 let text_color = if bg_color.l >= 0.5 {
3532 gpui::black()
3533 } else {
3534 gpui::white()
3535 };
3536
3537 let run_len = overlap_end.saturating_sub(overlap_start);
3538 if run_len > 0 {
3539 result.push(TextRun {
3540 len: run_len,
3541 color: text_color,
3542 ..run.clone()
3543 });
3544
3545 cursor = bg_range.end;
3546 run_start = cursor;
3547 }
3548 }
3549
3550 if run_end > cursor {
3551 // Add the part after the background range
3552 result.push(TextRun {
3553 len: run_end - cursor,
3554 ..run.clone()
3555 });
3556 }
3557
3558 cursor = run_end;
3559 }
3560
3561 result
3562}
3563
3564#[cfg(test)]
3565mod tests {
3566 use super::*;
3567 use crate::input::{EditorMode, EditorState, FoldRange, RangeDecoration, Redo, Undo};
3568 use gpui::{
3569 AppContext as _, Context, EntityInputHandler as _, Render, TestAppContext,
3570 VisualTestContext, div,
3571 };
3572
3573 #[test]
3574 fn line_number_column_stays_at_three_digits_then_grows_up_to_seven() {
3575 assert_eq!(line_number_len(1), 3);
3576 assert_eq!(line_number_len(9), 3);
3577 assert_eq!(line_number_len(10), 3);
3578 assert_eq!(line_number_len(999), 3);
3579 assert_eq!(line_number_len(1_000), 4);
3580 assert_eq!(line_number_len(999_999), 6);
3581 assert_eq!(line_number_len(9_999_999), 7);
3582 assert_eq!(line_number_len(10_000_000), 7);
3583 }
3584
3585 #[test]
3586 fn displayed_line_number_stays_within_seven_digits() {
3587 assert_eq!(displayed_line_number(42), 42);
3588 assert_eq!(displayed_line_number(9_999_999), 9_999_999);
3589 assert_eq!(displayed_line_number(10_000_000), 9_999_999);
3590 }
3591
3592 struct DecorationHarness(Entity<EditorState>);
3593
3594 impl Render for DecorationHarness {
3595 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3596 div().size_full().child(self.0.clone())
3597 }
3598 }
3599
3600 fn decoration_editor(
3601 cx: &mut TestAppContext,
3602 text: &str,
3603 wrap: bool,
3604 ) -> (Entity<EditorState>, gpui::WindowHandle<DecorationHarness>) {
3605 cx.update(crate::init);
3606 let mut editor = None;
3607 let window = cx.open_window(size(px(240.), px(140.)), |window, cx| {
3608 let state = cx.new(|cx| {
3609 EditorState::new(window, cx)
3610 .soft_wrap(wrap)
3611 .folding(true)
3612 .default_value(text)
3613 });
3614 editor = Some(state.clone());
3615 DecorationHarness(state)
3616 });
3617 (editor.unwrap(), window)
3618 }
3619
3620 #[gpui::test]
3621 fn horizontal_scroll_is_clamped_before_text_and_caret_layout(cx: &mut TestAppContext) {
3622 let (editor, window) = decoration_editor(cx, "short text", false);
3623 let mut cx = VisualTestContext::from_window(window.into(), cx);
3624 cx.update(|window, cx| {
3625 window.draw(cx).clear(cx);
3626 let state = editor.read(cx);
3627 let layout = state.last_layout.clone().unwrap();
3628 let input_bounds = state.input_bounds;
3629 let scroll_size = input_bounds.size;
3630 let element = TextElement::new(editor.clone());
3631 let mut bounds = input_bounds;
3632 let (baseline, _, _) =
3633 element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx);
3634
3635 // Both a stale offset after deletion and a deferred scroll target must
3636 // be limited before either text or carets are positioned this frame.
3637 for deferred in [None, Some(point(px(-80.), px(0.)))] {
3638 editor.update(cx, |state, _| {
3639 state.scroll_handle.set_offset(point(px(-40.), px(0.)));
3640 state.deferred_scroll_offset = deferred;
3641 });
3642 let mut bounds = input_bounds;
3643 let (carets, offset, _) =
3644 element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx);
3645 assert_eq!(offset.x, px(0.));
3646 assert_eq!(bounds.origin.x, input_bounds.origin.x);
3647 assert_eq!(carets.len(), baseline.len());
3648 for (caret, original) in carets.iter().zip(&baseline) {
3649 assert_eq!(caret.bounds.origin.x, original.bounds.origin.x);
3650 }
3651 editor.update(cx, |state, cx| {
3652 state.scroll_size = scroll_size;
3653 state.update_scroll_offset(Some(offset), cx);
3654 assert_eq!(state.scroll_handle.offset().x, offset.x);
3655 });
3656 }
3657 });
3658 }
3659
3660 #[gpui::test]
3661 fn aligned_horizontal_scroll_clamps_deferred_targets(cx: &mut TestAppContext) {
3662 let (editor, window) = decoration_editor(cx, &"wide text ".repeat(80), false);
3663 let mut cx = VisualTestContext::from_window(window.into(), cx);
3664 cx.update(|window, cx| {
3665 window.draw(cx).clear(cx);
3666 let mut layout = editor.read(cx).last_layout.clone().unwrap();
3667 let input_bounds = editor.read(cx).input_bounds;
3668 let element = TextElement::new(editor.clone());
3669
3670 for alignment in [TextAlign::Left, TextAlign::Right, TextAlign::Center] {
3671 layout.text_align = alignment;
3672 for overflow in [px(0.), px(120.)] {
3673 let scroll_size =
3674 size(input_bounds.size.width + overflow, input_bounds.size.height);
3675 let minimum = if alignment == TextAlign::Left {
3676 -overflow
3677 } else {
3678 -overflow - CURSOR_WIDTH
3679 };
3680 editor.update(cx, |state, _| {
3681 state.text_align = alignment;
3682 state.last_selected_range = Some(*state.active_selection());
3683 state.deferred_scroll_offset = Some(point(minimum, px(0.)));
3684 });
3685 let mut bounds = input_bounds;
3686 let (expected, _, _) =
3687 element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx);
3688
3689 for target in [minimum - px(100.), px(100.)] {
3690 editor.update(cx, |state, _| {
3691 state.deferred_scroll_offset = Some(point(target, px(0.)));
3692 });
3693 let mut bounds = input_bounds;
3694 let (carets, offset, _) =
3695 element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx);
3696 let expected_offset = if target < minimum { minimum } else { px(0.) };
3697 assert_eq!(offset.x, expected_offset);
3698 assert_eq!(bounds.left(), input_bounds.left() + expected_offset);
3699 if target < minimum {
3700 assert_eq!(carets[0].bounds, expected[0].bounds);
3701 }
3702 if alignment == TextAlign::Right {
3703 assert!(carets[0].bounds.right() <= input_bounds.right());
3704 }
3705 editor.update(cx, |state, cx| {
3706 state.scroll_size = scroll_size;
3707 state.update_scroll_offset(Some(offset), cx);
3708 assert_eq!(state.scroll_handle.offset().x, expected_offset);
3709 });
3710 }
3711 }
3712 }
3713 });
3714 }
3715
3716 #[gpui::test]
3717 fn deferred_horizontal_scroll_moves_every_caret(cx: &mut TestAppContext) {
3718 use super::super::{cursor::CursorSelection, selection::CursorId};
3719
3720 let (editor, window) = decoration_editor(cx, &"wide text ".repeat(80), false);
3721 let mut cx = VisualTestContext::from_window(window.into(), cx);
3722 cx.update(|window, cx| {
3723 window.draw(cx).clear(cx);
3724 let layout = editor.read(cx).last_layout.clone().unwrap();
3725 let input_bounds = editor.read(cx).input_bounds;
3726 let scroll_size = size(input_bounds.size.width + px(120.), input_bounds.size.height);
3727 let element = TextElement::new(editor.clone());
3728
3729 for offsets in [[0, 2, 4], [0, 4, 2], [4, 0, 2]] {
3730 editor.update(cx, |state, _| {
3731 state.selections.replace_all(
3732 offsets
3733 .into_iter()
3734 .enumerate()
3735 .map(|(id, offset)| {
3736 CursorSelection::new(CursorId::new(id), offset, offset)
3737 })
3738 .collect(),
3739 );
3740 state.last_selected_range = Some(*state.active_selection());
3741 state.scroll_handle.set_offset(point(px(0.), px(0.)));
3742 state.deferred_scroll_offset = None;
3743 });
3744 let mut bounds = input_bounds;
3745 let (baseline, _, _) =
3746 element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx);
3747 editor.update(cx, |state, _| {
3748 state.deferred_scroll_offset = Some(point(px(-60.), px(0.)));
3749 });
3750 let mut bounds = input_bounds;
3751 let (carets, offset, _) =
3752 element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx);
3753 assert_eq!(offset.x, px(-60.));
3754 assert_eq!(carets.len(), 3);
3755 for (caret, original) in carets.iter().zip(baseline) {
3756 assert_eq!(caret.bounds.left(), original.bounds.left() - px(60.));
3757 }
3758 }
3759 });
3760 }
3761
3762 #[gpui::test]
3763 fn editor_line_number_gutter_resizes_with_document_lines(cx: &mut TestAppContext) {
3764 let (editor, window) = decoration_editor(cx, &"x\n".repeat(8), false);
3765 let mut cx = VisualTestContext::from_window(window.into(), cx);
3766 cx.update(|window, cx| {
3767 window.draw(cx).clear(cx);
3768 let narrow = editor
3769 .read(cx)
3770 .last_layout
3771 .as_ref()
3772 .unwrap()
3773 .line_number_width;
3774
3775 let longer_text = "x\n".repeat(99);
3776 editor.update(cx, |state, cx| {
3777 state.set_value(longer_text.as_str(), window, cx)
3778 });
3779 window.draw(cx).clear(cx);
3780 let middle = editor
3781 .read(cx)
3782 .last_layout
3783 .as_ref()
3784 .unwrap()
3785 .line_number_width;
3786 assert_eq!(middle, narrow, "one to three digits must share a width");
3787
3788 let longest_text = "x\n".repeat(999);
3789 editor.update(cx, |state, cx| {
3790 state.set_value(longest_text.as_str(), window, cx)
3791 });
3792 window.draw(cx).clear(cx);
3793 let wide = editor
3794 .read(cx)
3795 .last_layout
3796 .as_ref()
3797 .unwrap()
3798 .line_number_width;
3799
3800 assert!(
3801 wide > narrow,
3802 "more line-number digits must widen the gutter"
3803 );
3804 });
3805 }
3806
3807 #[gpui::test]
3808 fn geometric_decorations_clip_scrolled_viewport_and_cull_offscreen_ranges(
3809 cx: &mut TestAppContext,
3810 ) {
3811 let text = "abcdefghij\n".repeat(100);
3812 let (editor, window) = decoration_editor(cx, &text, false);
3813 let mut cx = VisualTestContext::from_window(window.into(), cx);
3814 cx.update(|window, cx| {
3815 editor.update(cx, |state, cx| {
3816 state.create_range_decorations_collection(
3817 vec![
3818 RangeDecoration::new(0..text.len()).with_style(RangeDecorationStyle::Fill),
3819 RangeDecoration::new(0..text.len()),
3820 RangeDecoration::new(0..3),
3821 RangeDecoration::new(text.len() - 3..text.len()),
3822 ],
3823 cx,
3824 );
3825 });
3826 window.draw(cx).clear(cx);
3827 editor.update(cx, |state, cx| {
3828 let height = state.last_layout.as_ref().unwrap().line_height;
3829 state.set_scroll_offset(point(px(0.), -height * 40.), cx);
3830 });
3831 // Deferred scroll is committed by prepaint and reflected next frame.
3832 window.draw(cx).clear(cx);
3833 window.draw(cx).clear(cx);
3834 let state = editor.read(cx);
3835 let layout = state.last_layout.as_ref().unwrap();
3836 assert!(layout.visible_range_offset.start > 0);
3837 assert!(layout.visible_range_offset.end < text.len());
3838 let all =
3839 TextElement::<EditorMode>::layout_range_corners(&(0..text.len()), layout).unwrap();
3840 let clipped = TextElement::<EditorMode>::layout_range_corners(
3841 &layout.visible_range_offset,
3842 layout,
3843 )
3844 .unwrap();
3845 assert_eq!(all, clipped);
3846 assert!(!all.is_empty());
3847 assert!(TextElement::<EditorMode>::layout_range_corners(&(0..3), layout).is_none());
3848 // Also execute the production path building seam, not just the corner helper.
3849 let (fills, frames) = TextElement::new(editor.clone()).layout_range_decorations(
3850 layout,
3851 &state.input_bounds,
3852 window,
3853 state.input_bounds,
3854 cx,
3855 );
3856 assert_eq!(fills.len(), 1);
3857 assert_eq!(frames.len(), 1);
3858 });
3859 }
3860
3861 #[gpui::test]
3862 fn geometric_decorations_use_shaped_wrap_boundaries_and_newline_cells(cx: &mut TestAppContext) {
3863 let text = " héllo world héllo world héllo world héllo world\n\nlast";
3864 let (editor, window) = decoration_editor(cx, text, true);
3865 let mut cx = VisualTestContext::from_window(window.into(), cx);
3866 cx.update(|window, cx| {
3867 window.draw(cx).clear(cx);
3868 let state = editor.read(cx);
3869 let layout = state.last_layout.as_ref().unwrap();
3870 let first = &layout.lines[0];
3871 assert!(first.wrapped_lines.len() > 1);
3872 assert!(first.wrap_indent > px(0.));
3873 let boundary = first.wrapped_lines[0].len;
3874 let first_row =
3875 TextElement::<EditorMode>::layout_range_corners(&(0..boundary), layout).unwrap();
3876 assert_eq!(
3877 first_row.len(),
3878 1,
3879 "a wrap end must not open the next visual row"
3880 );
3881 assert_eq!(first_row[0].top_right.x, first.wrapped_lines[0].width);
3882 let rest =
3883 TextElement::<EditorMode>::layout_range_corners(&(boundary..first.len()), layout)
3884 .unwrap();
3885 assert_eq!(rest.len(), first.wrapped_lines.len() - 1);
3886 assert_eq!(rest[0].top_left.y, layout.visible_top + layout.line_height);
3887 for (index, corners) in rest.iter().enumerate() {
3888 assert_eq!(
3889 corners.top_right.x,
3890 first.wrap_indent + first.wrapped_lines[index + 1].width
3891 );
3892 assert_eq!(
3893 corners.bottom_left.y - corners.top_left.y,
3894 layout.line_height
3895 );
3896 }
3897 let blank_offset = text.find("\n\n").unwrap() + 1;
3898 let blank = TextElement::<EditorMode>::layout_range_corners(
3899 &(blank_offset..blank_offset + 1),
3900 layout,
3901 )
3902 .unwrap();
3903 assert_eq!(blank.len(), 1);
3904 assert_eq!(
3905 blank[0].top_right.x - blank[0].top_left.x,
3906 layout.space_width
3907 );
3908 // A later-line decoration cannot paint the first row via saturating_sub.
3909 let last_offset = text.rfind("last").unwrap();
3910 let last =
3911 TextElement::<EditorMode>::layout_range_corners(&(last_offset..text.len()), layout)
3912 .unwrap();
3913 assert_eq!(last.len(), 1);
3914 assert!(last[0].top_left.y > rest.last().unwrap().top_left.y);
3915 });
3916 }
3917
3918 #[gpui::test]
3919 fn geometric_decorations_include_crlf_boundaries(cx: &mut TestAppContext) {
3920 let text = "one\r\ntwo\r\nthree";
3921 let (editor, window) = decoration_editor(cx, text, false);
3922 let mut cx = VisualTestContext::from_window(window.into(), cx);
3923 cx.update(|window, cx| {
3924 editor.update(cx, |state, cx| {
3925 state.create_range_decorations_collection(
3926 vec![
3927 RangeDecoration::new(0..8),
3928 RangeDecoration::new(3..5),
3929 RangeDecoration::new(4..5),
3930 RangeDecoration::new(5..8),
3931 RangeDecoration::new(9..10),
3932 ],
3933 cx,
3934 );
3935 });
3936 window.draw(cx).clear(cx);
3937 let state = editor.read(cx);
3938 let layout = state.last_layout.as_ref().unwrap();
3939 // Shaping retains '\r'; only '\n' needs an additional newline cell.
3940 assert_eq!(layout.lines[0].len(), "one\r".len());
3941 assert_eq!(layout.visible_line_byte_offsets, vec![0, 5, 10]);
3942 let spanning =
3943 TextElement::<EditorMode>::layout_range_corners(&(0..8), layout).unwrap();
3944 assert_eq!(spanning.len(), 2);
3945 for range in [3..5, 4..5, 9..10] {
3946 let corners =
3947 TextElement::<EditorMode>::layout_range_corners(&range, layout).unwrap();
3948 assert_eq!(corners.len(), 1);
3949 assert!(corners[0].top_right.x > corners[0].top_left.x);
3950 }
3951 let (fills, frames) = TextElement::new(editor.clone()).layout_range_decorations(
3952 layout,
3953 &state.input_bounds,
3954 window,
3955 state.input_bounds,
3956 cx,
3957 );
3958 assert!(fills.is_empty());
3959 assert_eq!(frames.len(), 5);
3960 });
3961 }
3962
3963 #[gpui::test]
3964 fn geometric_decorations_project_folds_without_changing_tracked_ranges(
3965 cx: &mut TestAppContext,
3966 ) {
3967 let text = "top\nhidden one\nhidden two\nend\nlast";
3968 let (editor, window) = decoration_editor(cx, text, false);
3969 let mut cx = VisualTestContext::from_window(window.into(), cx);
3970 cx.update(|window, cx| {
3971 let hidden = 4..text.find("end").unwrap();
3972 let collection = editor.update(cx, |state, cx| {
3973 state.apply_highlighter_fold_candidates(vec![FoldRange::new(0, 3)], cx);
3974 state.display_map.set_folded(0, true);
3975 state.create_range_decorations_collection(
3976 vec![RangeDecoration::new(hidden.clone())],
3977 cx,
3978 )
3979 });
3980 window.draw(cx).clear(cx);
3981 {
3982 let state = editor.read(cx);
3983 let layout = state.last_layout.as_ref().unwrap();
3984 assert_eq!(layout.visible_buffer_lines, vec![0, 3, 4]);
3985 assert!(TextElement::<EditorMode>::layout_range_corners(&hidden, layout).is_none());
3986 let (_, frames) = TextElement::new(editor.clone()).layout_range_decorations(
3987 layout,
3988 &state.input_bounds,
3989 window,
3990 state.input_bounds,
3991 cx,
3992 );
3993 assert!(frames.is_empty());
3994 let spanning =
3995 TextElement::<EditorMode>::layout_range_corners(&(0..text.len()), layout)
3996 .unwrap();
3997 assert_eq!(spanning.len(), 3);
3998 assert_eq!(spanning[1].top_left.y, spanning[0].bottom_left.y);
3999 }
4000 assert_eq!(collection.get_ranges(cx), vec![hidden.clone()]);
4001 editor.update(cx, |state, cx| {
4002 state.display_map.set_folded(0, false);
4003 cx.notify();
4004 });
4005 window.draw(cx).clear(cx);
4006 let state = editor.read(cx);
4007 let layout = state.last_layout.as_ref().unwrap();
4008 let revealed =
4009 TextElement::<EditorMode>::layout_range_corners(&hidden, layout).unwrap();
4010 assert_eq!(revealed.len(), 2);
4011 assert_eq!(collection.get_ranges(cx), vec![hidden]);
4012 });
4013 }
4014
4015 #[gpui::test]
4016 fn geometric_decorations_track_edits_history_replacement_and_owner_lifetime(
4017 cx: &mut TestAppContext,
4018 ) {
4019 let (editor, window) = decoration_editor(cx, "abc def", false);
4020 let mut cx = VisualTestContext::from_window(window.into(), cx);
4021 cx.update(|window, cx| {
4022 let (first, second) = editor.update(cx, |state, cx| {
4023 (
4024 state.create_range_decorations_collection(vec![RangeDecoration::new(4..7)], cx),
4025 state.create_range_decorations_collection(vec![RangeDecoration::new(0..3)], cx),
4026 )
4027 });
4028 editor.update(cx, |state, cx| {
4029 state.set_selected_range(0..0, cx);
4030 state.replace_text_in_range(None, "\n", window, cx);
4031 });
4032 assert_eq!(first.get_ranges(cx), vec![5..8]);
4033 editor.update(cx, |state, cx| state.undo(&Undo, window, cx));
4034 assert_eq!(first.get_ranges(cx), vec![4..7]);
4035 editor.update(cx, |state, cx| state.redo(&Redo, window, cx));
4036 assert_eq!(first.get_ranges(cx), vec![5..8]);
4037 first.clear(cx);
4038 assert_eq!(second.get_ranges(cx), vec![1..4]);
4039 first.append(vec![RangeDecoration::new(5..8)], cx);
4040 editor.update(cx, |state, cx| state.replace_all("formatted", window, cx));
4041 assert_eq!(first.get_ranges(cx), vec![0..9]);
4042 editor.update(cx, |state, cx| state.undo(&Undo, window, cx));
4043 // Annotations are transformed, not snapshotted in undo history.
4044 assert_eq!(first.get_ranges(cx), vec![0..8]);
4045 editor.update(cx, |state, cx| state.set_value("new", window, cx));
4046 assert_eq!(first.get_ranges(cx), vec![0..3]);
4047 let clone = first.clone();
4048 first.dispose(cx);
4049 clone.append(vec![RangeDecoration::new(0..1)], cx);
4050 assert!(clone.get_ranges(cx).is_empty());
4051 assert_eq!(second.get_ranges(cx), vec![0..3]);
4052 editor.update(cx, |state, cx| state.set_value("", window, cx));
4053 assert!(second.get_ranges(cx).is_empty());
4054 window.draw(cx).clear(cx);
4055 });
4056 }
4057
4058 #[test]
4059 fn frame_outline_is_continuous_across_different_line_widths() {
4060 let corners = [
4061 Corners {
4062 top_left: point(px(2.), px(0.)),
4063 top_right: point(px(20.), px(0.)),
4064 bottom_left: point(px(2.), px(10.)),
4065 bottom_right: point(px(20.), px(10.)),
4066 },
4067 Corners {
4068 top_left: point(px(0.), px(10.)),
4069 top_right: point(px(12.), px(10.)),
4070 bottom_left: point(px(0.), px(20.)),
4071 bottom_right: point(px(12.), px(20.)),
4072 },
4073 ];
4074
4075 assert_eq!(
4076 frame_outline_points(&corners),
4077 vec![
4078 point(px(2.), px(0.)),
4079 point(px(20.), px(0.)),
4080 point(px(20.), px(10.)),
4081 point(px(12.), px(10.)),
4082 point(px(12.), px(20.)),
4083 point(px(0.), px(20.)),
4084 point(px(0.), px(10.)),
4085 point(px(2.), px(10.)),
4086 point(px(2.), px(0.)),
4087 ]
4088 );
4089 }
4090
4091 #[test]
4092 fn frame_outline_keeps_horizontal_space_between_the_stroke_and_text() {
4093 let corners = [Corners {
4094 top_left: point(px(2.), px(0.)),
4095 top_right: point(px(20.), px(0.)),
4096 bottom_left: point(px(2.), px(10.)),
4097 bottom_right: point(px(20.), px(10.)),
4098 }];
4099
4100 assert_eq!(
4101 pad_frame_corners(&corners, px(1.)),
4102 vec![Corners {
4103 top_left: point(px(1.), px(0.)),
4104 top_right: point(px(21.), px(0.)),
4105 bottom_left: point(px(1.), px(10.)),
4106 bottom_right: point(px(21.), px(10.)),
4107 }]
4108 );
4109
4110 let points = frame_outline_points(&corners);
4111 assert_eq!(points.first(), points.last());
4112 }
4113
4114 #[test]
4115 fn frame_outline_stroke_is_aligned_to_physical_pixels_at_each_scale_factor() {
4116 let points = vec![point(px(0.2), px(1.8)), point(px(10.7), px(20.3))];
4117
4118 for (scale_factor, expected_width, expected_points) in [
4119 (
4120 1.,
4121 px(1.),
4122 vec![point(px(0.5), px(1.5)), point(px(10.5), px(20.5))],
4123 ),
4124 (
4125 1.5,
4126 px(2. / 3.),
4127 vec![
4128 point(px(1. / 3.), px(5. / 3.)),
4129 point(px(11.), px(61. / 3.)),
4130 ],
4131 ),
4132 (
4133 2.,
4134 px(1.),
4135 vec![point(px(0.), px(2.)), point(px(10.5), px(20.5))],
4136 ),
4137 ] {
4138 let (width, snapped) = snap_frame_outline(&points, px(1.), scale_factor);
4139 assert_eq!(width, expected_width);
4140 assert_eq!(snapped, expected_points);
4141 }
4142 }
4143
4144 #[test]
4145 fn frame_outline_keeps_its_vertical_edges_inside_the_content_mask() {
4146 let points = vec![
4147 point(px(9.5), px(2.5)),
4148 point(px(20.5), px(2.5)),
4149 point(px(20.5), px(10.5)),
4150 point(px(9.5), px(10.5)),
4151 point(px(9.5), px(2.5)),
4152 ];
4153 let mask = Bounds::new(point(px(10.), px(0.)), size(px(10.), px(20.)));
4154
4155 assert_eq!(
4156 clamp_frame_to_content_mask(points, px(1.), mask),
4157 vec![
4158 point(px(10.5), px(2.5)),
4159 point(px(19.5), px(2.5)),
4160 point(px(19.5), px(10.5)),
4161 point(px(10.5), px(10.5)),
4162 point(px(10.5), px(2.5)),
4163 ]
4164 );
4165 }
4166
4167 #[test]
4168 fn test_plain_text_decorations_include_unstyled_gaps() {
4169 let decoration = HighlightStyle {
4170 background_color: Some(gpui::red()),
4171 ..Default::default()
4172 };
4173 let styles = compose_decorations(Vec::new(), [(2..5, decoration)], 0..10).unwrap();
4174
4175 assert_eq!(
4176 styles
4177 .iter()
4178 .map(|(range, _)| range.clone())
4179 .collect::<Vec<_>>(),
4180 vec![0..2, 2..5, 5..10]
4181 );
4182 assert_eq!(styles[0].1, HighlightStyle::default());
4183 assert_eq!(styles[1].1.background_color, Some(gpui::red()));
4184 assert_eq!(styles[2].1, HighlightStyle::default());
4185 }
4186
4187 #[test]
4188 fn test_first_decoration_collection_has_precedence() {
4189 let first = [TextDecoration::new(
4190 0..4,
4191 HighlightStyle {
4192 background_color: Some(gpui::red()),
4193 ..Default::default()
4194 },
4195 )];
4196 let second = [TextDecoration::new(
4197 0..4,
4198 HighlightStyle {
4199 background_color: Some(gpui::blue()),
4200 ..Default::default()
4201 },
4202 )];
4203
4204 let styles =
4205 compose_decoration_collections(Vec::new(), [&first[..], &second[..]], 0..4).unwrap();
4206
4207 assert_eq!(styles.len(), 1);
4208 assert_eq!(styles[0].1.background_color, Some(gpui::red()));
4209 }
4210
4211 #[test]
4212 fn test_decorations_override_syntax_highlights() {
4213 let syntax = vec![(
4214 0..8,
4215 HighlightStyle {
4216 color: Some(gpui::blue()),
4217 ..Default::default()
4218 },
4219 )];
4220 let decoration = HighlightStyle {
4221 color: Some(gpui::red()),
4222 font_style: Some(gpui::FontStyle::Italic),
4223 ..Default::default()
4224 };
4225
4226 let styles = compose_decorations(syntax, [(2..6, decoration)], 0..8).unwrap();
4227
4228 assert_eq!(styles[1].0, 2..6);
4229 assert_eq!(styles[1].1.color, Some(gpui::red()));
4230 assert_eq!(styles[1].1.font_style, Some(gpui::FontStyle::Italic));
4231 }
4232
4233 #[test]
4234 fn test_editor_scrollbar_layout_uses_current_scroll_size() {
4235 let input_bounds = Bounds::new(point(px(10.), px(20.)), size(px(300.), px(80.)));
4236 let paddings = Edges {
4237 top: px(2.),
4238 right: px(3.),
4239 bottom: px(5.),
4240 left: px(7.),
4241 };
4242
4243 let layout =
4244 EditorScrollbarLayout::new(input_bounds, px(40.), size(px(1000.), px(200.)), paddings);
4245
4246 assert_eq!(
4247 layout.bounds,
4248 Bounds::new(point(px(51.), px(18.)), size(px(262.), px(87.)))
4249 );
4250 assert_eq!(layout.scroll_size, size(px(972.), px(200.)));
4251
4252 let layout_without_gutter =
4253 EditorScrollbarLayout::new(input_bounds, px(0.), size(px(500.), px(120.)), paddings);
4254
4255 assert_eq!(
4256 layout_without_gutter.bounds,
4257 Bounds::new(point(px(10.), px(18.)), size(px(303.), px(87.)))
4258 );
4259 assert_eq!(layout_without_gutter.scroll_size, size(px(513.), px(120.)));
4260 }
4261
4262 #[test]
4263 fn test_editor_gutter_covers_the_complete_fixed_column() {
4264 let input_bounds = Bounds::new(point(px(10.), px(20.)), size(px(300.), px(80.)));
4265
4266 assert_eq!(
4267 editor_gutter_bounds(
4268 input_bounds,
4269 px(48.),
4270 px(16.),
4271 Edges {
4272 top: px(2.),
4273 right: px(3.),
4274 bottom: px(5.),
4275 left: px(7.),
4276 },
4277 ),
4278 Bounds::new(point(px(3.), px(18.)), size(px(55.), px(103.)))
4279 );
4280 }
4281
4282 #[test]
4283 fn test_auto_grow_scroll_offset_is_clamped_to_current_viewport() {
4284 let mode = LayoutMode::auto_grow(3, 8);
4285
4286 assert_eq!(
4287 clamp_auto_grow_vertical_scroll_offset(&mode, px(-260.), px(340.), px(160.)),
4288 px(-180.)
4289 );
4290 assert_eq!(
4291 clamp_auto_grow_vertical_scroll_offset(&mode, px(-40.), px(340.), px(160.)),
4292 px(-40.)
4293 );
4294 assert_eq!(
4295 clamp_auto_grow_vertical_scroll_offset(&mode, px(20.), px(340.), px(160.)),
4296 px(0.)
4297 );
4298
4299 let plain_text = LayoutMode::plain_text();
4300 assert_eq!(
4301 clamp_auto_grow_vertical_scroll_offset(&plain_text, px(-260.), px(340.), px(160.)),
4302 px(-260.)
4303 );
4304 }
4305
4306 #[test]
4307 fn test_runs_for_range() {
4308 let run = TextRun {
4309 len: 0,
4310 font: gpui::font(".SystemUIFont"),
4311 color: gpui::black(),
4312 background_color: None,
4313 underline: None,
4314 strikethrough: None,
4315 };
4316
4317 // use hello this-is-test
4318 let runs = vec![
4319 // use
4320 TextRun {
4321 len: 3,
4322 ..run.clone()
4323 },
4324 // \s
4325 TextRun {
4326 len: 1,
4327 ..run.clone()
4328 },
4329 // hello
4330 TextRun {
4331 len: 5,
4332 ..run.clone()
4333 },
4334 // \s
4335 TextRun {
4336 len: 1,
4337 ..run.clone()
4338 },
4339 // this-is-test
4340 TextRun {
4341 len: 12,
4342 ..run.clone()
4343 },
4344 ];
4345
4346 #[track_caller]
4347 fn assert_runs(actual: Vec<TextRun>, expected: &[usize]) {
4348 let left = actual.iter().map(|run| run.len).collect::<Vec<_>>();
4349 assert_eq!(left, expected);
4350 }
4351
4352 assert_runs(runs_for_range(&runs, 0, &(0..0)), &[]);
4353 assert_runs(runs_for_range(&runs, 0, &(0..100)), &[3, 1, 5, 1, 12]);
4354
4355 assert_runs(runs_for_range(&runs, 0, &(0..6)), &[3, 1, 2]);
4356 assert_runs(runs_for_range(&runs, 0, &(1..6)), &[2, 1, 2]);
4357 assert_runs(runs_for_range(&runs, 0, &(3..10)), &[1, 5, 1]);
4358 assert_runs(runs_for_range(&runs, 0, &(5..8)), &[3]);
4359 assert_runs(runs_for_range(&runs, 3, &(0..3)), &[1, 2]);
4360 assert_runs(runs_for_range(&runs, 3, &(2..10)), &[4, 1, 3]);
4361 assert_runs(runs_for_range(&runs, 9, &(0..8)), &[1, 7]);
4362 }
4363
4364 #[test]
4365 fn test_split_runs_preserve_ime_underline_across_highlight_boundaries() {
4366 let underline = UnderlineStyle {
4367 thickness: px(1.),
4368 color: Some(gpui::black()),
4369 wavy: false,
4370 };
4371
4372 let runs = [0..4, 4..10]
4373 .into_iter()
4374 .flat_map(|range| {
4375 split_run_for_ime_underline(
4376 TextStyle::default().to_run(range.len()),
4377 range,
4378 Some(2..7),
4379 Some(underline),
4380 )
4381 })
4382 .collect::<Vec<_>>();
4383
4384 assert_eq!(
4385 runs.iter()
4386 .map(|run| (run.len, run.underline.is_some()))
4387 .collect::<Vec<_>>(),
4388 vec![(2, false), (2, true), (3, true), (3, false)]
4389 );
4390 }
4391
4392 #[test]
4393 fn test_split_run_applies_ime_underline_without_highlighting() {
4394 let underline = UnderlineStyle {
4395 thickness: px(1.),
4396 color: Some(gpui::black()),
4397 wavy: false,
4398 };
4399
4400 let runs = split_run_for_ime_underline(
4401 TextStyle::default().to_run(10),
4402 0..10,
4403 Some(2..7),
4404 Some(underline),
4405 );
4406
4407 assert_eq!(
4408 runs.iter()
4409 .map(|run| (run.len, run.underline.is_some()))
4410 .collect::<Vec<_>>(),
4411 vec![(2, false), (5, true), (3, false)]
4412 );
4413 assert!(
4414 split_run_for_ime_underline(TextStyle::default().to_run(0), 0..0, None, None)
4415 .is_empty()
4416 );
4417 }
4418
4419 #[test]
4420 fn test_masked_ime_underline_splits_on_mask_char_boundaries() {
4421 let underline = UnderlineStyle {
4422 thickness: px(1.),
4423 color: Some(gpui::black()),
4424 wavy: false,
4425 };
4426 let text = Rope::from("abcdef");
4427 let mask_len = MASK_CHAR.len_utf8();
4428
4429 assert_eq!(
4430 ime_marked_display_range(&text, Some(4..6), false),
4431 Some(4..6)
4432 );
4433 assert_eq!(ime_marked_display_range(&text, None, true), None);
4434 assert_eq!(
4435 ime_marked_display_range(&text, Some(4..6), true),
4436 Some(4 * mask_len..6 * mask_len)
4437 );
4438
4439 let display_text = MASK_CHAR.to_string().repeat(text.chars().count());
4440 let runs = split_run_for_ime_underline(
4441 TextStyle::default().to_run(display_text.len()),
4442 0..display_text.len(),
4443 ime_marked_display_range(&text, Some(4..6), true),
4444 Some(underline),
4445 );
4446
4447 let mut offset = 0;
4448 for run in &runs {
4449 assert!(display_text.is_char_boundary(offset));
4450 offset += run.len;
4451 }
4452 assert_eq!(offset, display_text.len());
4453 }
4454
4455 #[test]
4456 fn test_placeholder_line_runs() {
4457 let run = TextRun {
4458 len: 0,
4459 font: gpui::font(".SystemUIFont"),
4460 color: gpui::black(),
4461 background_color: None,
4462 underline: None,
4463 strikethrough: None,
4464 };
4465
4466 let runs = vec![
4467 TextRun {
4468 len: 2,
4469 ..run.clone()
4470 },
4471 TextRun {
4472 len: 2,
4473 ..run.clone()
4474 },
4475 TextRun { len: 1, ..run },
4476 ];
4477
4478 let placeholder_runs = placeholder_line_runs("ab\n\nc", &runs);
4479
4480 let lines = placeholder_runs
4481 .iter()
4482 .map(|(line, _)| *line)
4483 .collect::<Vec<_>>();
4484 assert_eq!(lines, vec!["ab", "", "c"]);
4485
4486 let run_lengths = placeholder_runs
4487 .iter()
4488 .map(|(_, line_runs)| line_runs.iter().map(|run| run.len).collect::<Vec<_>>())
4489 .collect::<Vec<_>>();
4490 assert_eq!(run_lengths, vec![vec![2], vec![], vec![1]]);
4491 }
4492
4493 #[test]
4494 fn test_align_runs_to_char_boundaries() {
4495 let run = TextRun {
4496 len: 0,
4497 font: gpui::font(".SystemUIFont"),
4498 color: gpui::blue(),
4499 background_color: None,
4500 underline: None,
4501 strikethrough: None,
4502 };
4503 let runs = |lens: &[usize]| {
4504 lens.iter()
4505 .map(|&len| TextRun { len, ..run.clone() })
4506 .collect::<Vec<_>>()
4507 };
4508 let lens = |runs: &[TextRun]| runs.iter().map(|run| run.len).collect::<Vec<_>>();
4509
4510 // "你好,世界" is 15 bytes; boundaries at 0, 3, 6, 9, 12, 15.
4511 let text = "你好,世界";
4512
4513 // Aligned runs pass through untouched.
4514 assert_eq!(align_runs_to_char_boundaries(text, &runs(&[3, 12])), None);
4515
4516 // A mid-char boundary (4) snaps up to the next boundary (6).
4517 let aligned = align_runs_to_char_boundaries(text, &runs(&[4, 11])).unwrap();
4518 assert_eq!(lens(&aligned), vec![6, 9]);
4519
4520 // Several boundaries inside the same char collapse into one run.
4521 let aligned = align_runs_to_char_boundaries(text, &runs(&[1, 1, 13])).unwrap();
4522 assert_eq!(lens(&aligned), vec![3, 12]);
4523
4524 // Overshooting runs are capped at the text length.
4525 let aligned = align_runs_to_char_boundaries(text, &runs(&[3, 20])).unwrap();
4526 assert_eq!(lens(&aligned), vec![3, 12]);
4527
4528 // Undershooting runs keep the shortfall (the tail is left unshaped,
4529 // matching `runs_for_range` clipping).
4530 assert_eq!(align_runs_to_char_boundaries(text, &runs(&[3, 3])), None);
4531 }
4532
4533 #[test]
4534 fn test_clip_styles_to_ranges() {
4535 let style = HighlightStyle::default();
4536 let styles = vec![(0..4, style), (4..10, style), (12..20, style)];
4537
4538 // Ranges with a gap (a folded region) drop the gap coverage and split
4539 // styles that span a range edge.
4540 let clipped = clip_styles_to_ranges(styles.clone(), &[2..6, 14..18]);
4541 assert_eq!(
4542 clipped
4543 .iter()
4544 .map(|(range, _)| range.clone())
4545 .collect::<Vec<_>>(),
4546 vec![2..4, 4..6, 14..18]
4547 );
4548
4549 // Styles fully inside the ranges are unchanged.
4550 let clipped = clip_styles_to_ranges(styles.clone(), &[0..20]);
4551 assert_eq!(
4552 clipped
4553 .iter()
4554 .map(|(range, _)| range.clone())
4555 .collect::<Vec<_>>(),
4556 vec![0..4, 4..10, 12..20]
4557 );
4558
4559 // A single style spanning several ranges splits into one piece per range.
4560 let clipped = clip_styles_to_ranges(vec![(0..30, style)], &[5..10, 20..25]);
4561 assert_eq!(
4562 clipped
4563 .iter()
4564 .map(|(range, _)| range.clone())
4565 .collect::<Vec<_>>(),
4566 vec![5..10, 20..25]
4567 );
4568
4569 assert!(clip_styles_to_ranges(styles, &[]).is_empty());
4570 }
4571
4572 #[test]
4573 fn test_split_runs_by_bg_segments() {
4574 let run = TextRun {
4575 len: 0,
4576 font: gpui::font(".SystemUIFont"),
4577 color: gpui::blue(),
4578 background_color: None,
4579 underline: None,
4580 strikethrough: None,
4581 };
4582
4583 let runs = vec![
4584 TextRun {
4585 len: 5,
4586 ..run.clone()
4587 },
4588 TextRun {
4589 len: 7,
4590 ..run.clone()
4591 },
4592 TextRun {
4593 len: 24,
4594 ..run.clone()
4595 },
4596 ];
4597
4598 let bg_segments = vec![(8..12, gpui::red()), (12..18, gpui::blue())];
4599 let result = split_runs_by_bg_segments(5, &runs, &bg_segments);
4600 assert_eq!(
4601 result.iter().map(|run| run.len).collect::<Vec<_>>(),
4602 vec![3, 2, 2, 5, 1, 23]
4603 );
4604 assert_eq!(result[0].color, gpui::blue());
4605 assert_eq!(result[1].color, gpui::black());
4606 assert_eq!(result[2].color, gpui::black());
4607 assert_eq!(result[3].color, gpui::black());
4608 assert_eq!(result[4].color, gpui::black());
4609 assert_eq!(result[5].color, gpui::blue());
4610 }
4611
4612 #[test]
4613 fn test_empty_bottom_height_outside_code_editor() {
4614 // Single-line / plain-text / auto-grow modes never reserve empty
4615 // bottom space, regardless of any override.
4616 for override_rows in [None, Some(0), Some(3), Some(99)] {
4617 assert_eq!(
4618 empty_bottom_height(false, override_rows, px(800.), px(20.)),
4619 px(0.),
4620 );
4621 }
4622 }
4623
4624 #[test]
4625 fn test_empty_bottom_height_code_editor_default() {
4626 // `None`: roughly half the viewport, floored at
4627 // `BOTTOM_MARGIN_ROWS * line_height` so the empty area never
4628 // collapses to "less than a few lines" on tiny viewports.
4629 let line_height = px(20.);
4630
4631 // Viewport much taller than the floor → half-viewport wins.
4632 assert_eq!(
4633 empty_bottom_height(true, None, px(800.), line_height),
4634 px(400.),
4635 );
4636
4637 // Viewport shorter than 2 × floor → floor wins.
4638 let floor = BOTTOM_MARGIN_ROWS * line_height;
4639 assert_eq!(empty_bottom_height(true, None, px(40.), line_height), floor);
4640 }
4641
4642 #[test]
4643 fn test_empty_bottom_height_explicit_row_count() {
4644 // `Some(n)`: exactly `n` line-heights. Caller fully controls
4645 // the trailing empty space; viewport size doesn't amplify it.
4646 let line_height = px(20.);
4647
4648 for rows in [0_usize, 1, 3, 8, 64] {
4649 let expected = rows as f32 * line_height;
4650 assert_eq!(
4651 empty_bottom_height(true, Some(rows), px(800.), line_height),
4652 expected,
4653 );
4654 // Tiny viewport: still exactly `n × line_height`, no floor
4655 // applied when caller supplied an explicit count.
4656 assert_eq!(
4657 empty_bottom_height(true, Some(rows), px(20.), line_height),
4658 expected,
4659 );
4660 }
4661 }
4662
4663 #[test]
4664 fn test_cursor_surrounding_padding_auto_grow() {
4665 // Auto-grow inputs always pad by one line, regardless of any
4666 // override or visible-lines count.
4667 let line_height = px(20.);
4668 for override_lines in [None, Some(0), Some(3), Some(99)] {
4669 for visible_lines in [0_usize, 1, 8, 64] {
4670 assert_eq!(
4671 cursor_surrounding_padding(true, override_lines, visible_lines, line_height,),
4672 line_height,
4673 );
4674 }
4675 }
4676 }
4677
4678 #[test]
4679 fn test_cursor_surrounding_padding_default() {
4680 // `None`: historical heuristic — `BOTTOM_MARGIN_ROWS` for normal
4681 // viewports, falls back to one line on small viewports (less
4682 // than `BOTTOM_MARGIN_ROWS × 8` rows tall).
4683 let line_height = px(20.);
4684
4685 // Small viewport → 1-line fallback.
4686 let small = BOTTOM_MARGIN_ROWS * 8 - 1;
4687 assert_eq!(
4688 cursor_surrounding_padding(false, None, small, line_height),
4689 line_height,
4690 );
4691
4692 // Boundary at `BOTTOM_MARGIN_ROWS × 8` flips to the full margin.
4693 let boundary = BOTTOM_MARGIN_ROWS * 8;
4694 assert_eq!(
4695 cursor_surrounding_padding(false, None, boundary, line_height),
4696 BOTTOM_MARGIN_ROWS * line_height,
4697 );
4698
4699 // Comfortably-large viewport.
4700 assert_eq!(
4701 cursor_surrounding_padding(false, None, 100, line_height),
4702 BOTTOM_MARGIN_ROWS * line_height,
4703 );
4704 }
4705
4706 #[test]
4707 fn test_cursor_surrounding_padding_explicit() {
4708 // `Some(n)`: exactly `n × line_height` when the viewport has
4709 // room for it; saturated against half the viewport when it
4710 // doesn't.
4711 let line_height = px(20.);
4712
4713 for lines in [0_usize, 1, 2, 5, 50] {
4714 let raw = lines as f32 * line_height;
4715 for visible_lines in [0_usize, 1, 8, 100] {
4716 let viewport_half = (visible_lines as f32 * line_height).half();
4717 assert_eq!(
4718 cursor_surrounding_padding(false, Some(lines), visible_lines, line_height,),
4719 raw.min(viewport_half),
4720 );
4721 }
4722 }
4723 }
4724
4725 #[test]
4726 fn test_cursor_surrounding_padding_saturates_against_viewport() {
4727 // An aggressive override on a small viewport must not produce a
4728 // padding larger than half the visible region — otherwise the
4729 // bottom-edge auto-scroll-into-view threshold sinks below the
4730 // top-edge threshold and the per-frame scroll adjustment loses
4731 // a stable fixed point.
4732 let line_height = px(20.);
4733
4734 // Override much larger than viewport → clamped to half.
4735 let visible_lines = 10;
4736 let viewport_half = (visible_lines as f32 * line_height).half();
4737 assert_eq!(
4738 cursor_surrounding_padding(false, Some(50), visible_lines, line_height),
4739 viewport_half,
4740 );
4741
4742 // Override that fits → returned unchanged.
4743 let visible_lines = 40;
4744 assert_eq!(
4745 cursor_surrounding_padding(false, Some(3), visible_lines, line_height),
4746 3.0 * line_height,
4747 );
4748
4749 // Default heuristic still saturates if BOTTOM_MARGIN_ROWS would
4750 // exceed the half-viewport bound (only possible at extreme
4751 // sizes — kept for defensive completeness).
4752 let visible_lines = BOTTOM_MARGIN_ROWS * 8;
4753 let half = (visible_lines as f32 * line_height).half();
4754 let raw = BOTTOM_MARGIN_ROWS * line_height;
4755 assert_eq!(
4756 cursor_surrounding_padding(false, None, visible_lines, line_height),
4757 raw.min(half),
4758 );
4759 }
4760}