BlueGit

ict rusty-teams

Files

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

element.rs

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