BlueGit

ict rusty-teams

Files

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

element.rs

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