BlueGit

ict rusty-teams

Files

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

element.rs

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