BlueGit

ict rusty-teams

Files

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

element.rs

element.rs 199.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 })
1867 })
1868 .collect();
1869 cache.revision = revision;
1870 if state.is_single_line() || !state.soft_wrap {
1871 let mut rows: Vec<_> = spans
1872 .iter()
1873 .map(|s| state.text.offset_to_point(s.range().start).row)
1874 .collect();
1875 rows.push(state.display_map.longest_row());
1876 rows.sort_unstable();
1877 rows.dedup();
1878 cache.unwrapped_width = rows
1879 .into_iter()
1880 .map(|row| {
1881 let start = state.text.line_start_offset(row);
1882 let text = state.text.slice_line(row).to_string();
1883 let mut offset = 0;
1884 let mut width = px(0.);
1885 let first = spans.partition_point(|s| s.range().end <= start);
1886 for span in spans[first..]
1887 .iter()
1888 .take_while(|s| s.range().start < start + text.len())
1889 {
1890 let local = span.range().start - start..span.range().end - start;
1891 let part = &text[offset..local.start];
1892 width += window
1893 .text_system()
1894 .shape_line(
1895 part.to_owned().into(),
1896 style.font_size.to_pixels(window.rem_size()),
1897 &[style.to_run(part.len())],
1898 None,
1899 )
1900 .width;
1901 width += cache
1902 .sizes
1903 .get(span.token())
1904 .map_or(px(0.), |token_size| token_size.width);
1905 offset = local.end;
1906 }
1907 let part = &text[offset..];
1908 width
1909 + window
1910 .text_system()
1911 .shape_line(
1912 part.to_owned().into(),
1913 style.font_size.to_pixels(window.rem_size()),
1914 &[style.to_run(part.len())],
1915 None,
1916 )
1917 .width
1918 })
1919 .max()
1920 .unwrap_or_default();
1921 }
1922 }
1923 let metrics = cache.metrics.clone();
1924 state.token_layout_cache = Some(cache);
1925 state.display_map.set_inline_metrics(metrics, cx);
1926 if state.mode.is_auto_grow() {
1927 let rows = state.mode.rows();
1928 state.mode.update_auto_grow(&state.display_map, line_height);
1929 if state.mode.rows() != rows {
1930 cx.notify();
1931 }
1932 }
1933 });
1934 elements
1935 }
1936
1937 fn layout_token_lines(
1938 state: &InputBaseState<M>,
1939 last_layout: &LastLayout,
1940 font_size: Pixels,
1941 runs: &[TextRun],
1942 font_overrides: &[(Range<usize>, FontOverride)],
1943 window: &mut Window,
1944 ) -> Vec<LineLayout> {
1945 let spans = state.token_spans();
1946 let cache = state
1947 .token_layout_cache
1948 .as_ref()
1949 .expect("tokens measured before shaping");
1950 let scale_font = scale_font(font_overrides, window);
1951 let mut run_offset = 0;
1952 last_layout
1953 .visible_buffer_lines
1954 .iter()
1955 .map(|&row| {
1956 let line_start = state.text.line_start_offset(row);
1957 let text: String = state.text.slice_line(row).into();
1958 let ranges = if state.is_single_line() {
1959 smallvec::smallvec![0..text.len()]
1960 } else {
1961 state
1962 .display_map
1963 .line(row)
1964 .expect("prepared line")
1965 .wrapped_lines
1966 .clone()
1967 };
1968 let mut lines: SmallVec<[InputLine; 1]> = SmallVec::new();
1969 for range in ranges {
1970 let scaled = scale_font.as_ref().and_then(|font| {
1971 scaled_row(
1972 window.text_system(),
1973 font,
1974 font_size,
1975 last_layout.line_height,
1976 line_start + range.start..line_start + range.end,
1977 font_overrides,
1978 )
1979 });
1980 let mut fragments = Vec::new();
1981 let mut block_height = None;
1982 let mut offset = range.start;
1983 let mut x = px(0.);
1984 let first =
1985 spans.partition_point(|s| s.range().end <= line_start + range.start);
1986 for span in spans[first..]
1987 .iter()
1988 .take_while(|s| s.range().start < line_start + range.end)
1989 {
1990 let local = span.range().start - line_start..span.range().end - line_start;
1991 if offset < local.start {
1992 push_text_fragments(
1993 window,
1994 &text,
1995 offset..local.start,
1996 range.start,
1997 line_start,
1998 scaled.as_ref(),
1999 font_size,
2000 |part| runs_for_range(runs, run_offset, part),
2001 &mut x,
2002 &mut fragments,
2003 );
2004 }
2005 let token_size = cache.sizes.get(span.token()).copied().unwrap_or_default();
2006 let width = token_size.width;
2007 if span.token().is_block() && local == range {
2008 block_height = Some(token_size.height);
2009 }
2010 fragments.push(InlineFragment {
2011 range: local.start - range.start..local.end - range.start,
2012 x,
2013 width,
2014 text: None,
2015 placement: None,
2016 });
2017 x += width;
2018 offset = local.end;
2019 }
2020 if offset < range.end {
2021 push_text_fragments(
2022 window,
2023 &text,
2024 offset..range.end,
2025 range.start,
2026 line_start,
2027 scaled.as_ref(),
2028 font_size,
2029 |part| runs_for_range(runs, run_offset, part),
2030 &mut x,
2031 &mut fragments,
2032 );
2033 }
2034 let mut line = InputLine::inline(text[range].to_owned().into(), fragments)
2035 .with_height(block_height);
2036 if let Some(scaled) = &scaled {
2037 let row_box = scaled.row_box;
2038 line = line
2039 .with_height(
2040 block_height.or(row_box.custom_height(last_layout.line_height)),
2041 )
2042 .with_inline_offset(row_box.baseline - row_box.base_baseline);
2043 }
2044 lines.push(line);
2045 }
2046 let indent = state.display_map.line(row).map_or(0, |line| line.indent);
2047 let wrap_indent = if indent > 0 && lines.len() > 1 {
2048 let bytes = text
2049 .char_indices()
2050 .nth(indent as usize)
2051 .map_or(text.len(), |(ix, _)| ix);
2052 lines[0].x_for_index(bytes)
2053 } else {
2054 px(0.)
2055 };
2056 run_offset += text.len() + 1;
2057 LineLayout::new()
2058 .inline_lines(lines)
2059 .wrap_indent(wrap_indent)
2060 .first_indent(state.display_map.line_indent(line_start))
2061 })
2062 .collect()
2063 }
2064
2065 fn prepaint_tokens(
2066 &self,
2067 layout: &LastLayout,
2068 bounds: Bounds<Pixels>,
2069 mut measured: std::collections::HashMap<usize, (AnyElement, Size<Pixels>)>,
2070 window: &mut Window,
2071 cx: &mut App,
2072 ) -> Vec<AnyElement> {
2073 let state = self.state.read(cx);
2074 if !state.tokens_visible() {
2075 let mut exit = self.state.update(cx, |state, _| {
2076 state.token_bounds.clear();
2077 state.reconcile_token_hover()
2078 });
2079 while let Some((listener, event)) = exit {
2080 listener(&event, window, cx);
2081 exit = self
2082 .state
2083 .update(cx, |state, _| state.reconcile_token_hover());
2084 }
2085 return vec![];
2086 }
2087 let width = state
2088 .token_layout_cache
2089 .as_ref()
2090 .and_then(|c| c.key.as_ref())
2091 .map_or(bounds.size.width, |k| k.2);
2092 let mut placements = Vec::new();
2093 let mut y = layout.visible_top;
2094 for (ix, &row) in layout.visible_buffer_lines.iter().enumerate() {
2095 let start = state.text.line_start_offset(row);
2096 let end = state.text.line_end_offset(row);
2097 let spans = state.token_spans();
2098 let first = spans.partition_point(|s| s.range().end <= start);
2099 for span in spans[first..].iter().take_while(|s| s.range().start < end) {
2100 if let Some(position) =
2101 layout.lines[ix].position_for_index(span.range().start - start, layout, false)
2102 {
2103 let baseline_offset =
2104 layout.lines[ix].inline_offset_at(position.y, layout.line_height);
2105 placements.push((
2106 state.token_context(span, layout.line_height, width),
2107 bounds.origin
2108 + position
2109 + point(layout.line_number_width, y + baseline_offset),
2110 ));
2111 }
2112 }
2113 y += layout.lines[ix].size(layout.line_height).height;
2114 }
2115 let mut out = Vec::new();
2116 let mut token_bounds = std::collections::HashMap::new();
2117 for (token, origin) in placements {
2118 let (mut element, element_size) = match measured.remove(&token.range().start) {
2119 Some(found) => found,
2120 None => {
2121 let mut element = self.token_element(&token, window, cx);
2122 let element_size = element.layout_as_root(
2123 Self::token_available_space(&token, layout.line_height),
2124 window,
2125 cx,
2126 );
2127 (element, element_size)
2128 }
2129 };
2130 element.prepaint_at(origin, window, cx);
2131 token_bounds.insert(token.range().start, Bounds::new(origin, element_size));
2132 out.push(element);
2133 }
2134 let mut exit = self.state.update(cx, |state, _| {
2135 state.token_bounds = token_bounds;
2136 state.reconcile_token_hover()
2137 });
2138 while let Some((listener, event)) = exit {
2139 listener(&event, window, cx);
2140 exit = self
2141 .state
2142 .update(cx, |state, _| state.reconcile_token_hover());
2143 }
2144 out
2145 }
2146
2147 #[allow(clippy::too_many_arguments)]
2148 fn layout_lines(
2149 state: &InputBaseState<M>,
2150 display_text: &Rope,
2151 last_layout: &LastLayout,
2152 font_size: Pixels,
2153 runs: &[TextRun],
2154 font_overrides: &[(Range<usize>, FontOverride)],
2155 bg_segments: &[(Range<usize>, Hsla)],
2156 whitespace_indicators: Option<WhitespaceIndicators>,
2157 window: &mut Window,
2158 ) -> Vec<LineLayout> {
2159 let is_single_line = state.is_single_line();
2160 if state.tokens_visible() {
2161 return Self::layout_token_lines(
2162 state,
2163 last_layout,
2164 font_size,
2165 runs,
2166 font_overrides,
2167 window,
2168 );
2169 }
2170
2171 if is_single_line {
2172 let text: SharedString = display_text.to_string().into();
2173 let aligned_runs = align_runs_to_char_boundaries(&text, runs);
2174 let line_runs = aligned_runs.as_deref().unwrap_or(runs);
2175 let shaped_line = window
2176 .text_system()
2177 .shape_line(text, font_size, line_runs, None);
2178
2179 let line_layout = LineLayout::new()
2180 .lines(smallvec::smallvec![shaped_line])
2181 .with_background(has_background(line_runs))
2182 .with_whitespaces(whitespace_indicators);
2183 return vec![line_layout];
2184 }
2185
2186 // Empty to use placeholder, the placeholder is not in the wrapper map.
2187 if state.text.len() == 0 {
2188 let placeholder_text = display_text.to_string();
2189 let mut placeholder_lines = SmallVec::new();
2190 let mut line_has_background = false;
2191
2192 for (line, line_runs) in placeholder_line_runs(&placeholder_text, runs) {
2193 let shaped_line = window.text_system().shape_line(
2194 line.to_string().into(),
2195 font_size,
2196 &line_runs,
2197 None,
2198 );
2199 line_has_background |= has_background(&line_runs);
2200 placeholder_lines.push(shaped_line);
2201 }
2202
2203 // Keep placeholder lines in a single layout to stay parallel with visible_* metadata.
2204 let line_layout = LineLayout::new()
2205 .lines(placeholder_lines)
2206 .with_background(line_has_background)
2207 .with_whitespaces(whitespace_indicators);
2208 return vec![line_layout];
2209 }
2210
2211 let scale_font = scale_font(font_overrides, window);
2212 let mut lines = Vec::with_capacity(last_layout.visible_buffer_lines.len());
2213 // run_offset tracks position in the runs vec coordinate space (only visible line bytes).
2214 // This is separate from the visible_text offset because runs from highlight_lines
2215 // only cover visible (non-folded) lines.
2216 let mut run_offset = 0;
2217
2218 for (vi, &buffer_line) in last_layout.visible_buffer_lines.iter().enumerate() {
2219 let line_text: String = display_text.slice_line(buffer_line).into();
2220 let line_item = state
2221 .display_map
2222 .line(buffer_line)
2223 .expect("line should exists in wrapper");
2224
2225 debug_assert_eq!(line_item.len(), line_text.len());
2226
2227 let mut wrapped_lines: SmallVec<[InputLine; 1]> = SmallVec::with_capacity(1);
2228 let mut line_has_background = false;
2229 let line_start = last_layout.visible_line_byte_offsets[vi];
2230
2231 for range in &line_item.wrapped_lines {
2232 let scaled = scale_font.as_ref().and_then(|font| {
2233 scaled_row(
2234 window.text_system(),
2235 font,
2236 font_size,
2237 last_layout.line_height,
2238 line_start + range.start..line_start + range.end,
2239 font_overrides,
2240 )
2241 });
2242 let part_runs = |part: &Range<usize>| {
2243 let line_runs = runs_for_range(runs, run_offset, part);
2244 let line_runs = if bg_segments.is_empty() {
2245 line_runs
2246 } else {
2247 split_runs_by_bg_segments(line_start + part.start, &line_runs, bg_segments)
2248 };
2249 align_runs_to_char_boundaries(&line_text[part.clone()], &line_runs)
2250 .unwrap_or(line_runs)
2251 };
2252
2253 if let Some(scaled) = scaled {
2254 let mut fragments = Vec::new();
2255 let mut x = px(0.);
2256 push_text_fragments(
2257 window,
2258 &line_text,
2259 range.clone(),
2260 range.start,
2261 line_start,
2262 Some(&scaled),
2263 font_size,
2264 |part| {
2265 let line_runs = part_runs(part);
2266 line_has_background |= has_background(&line_runs);
2267 line_runs
2268 },
2269 &mut x,
2270 &mut fragments,
2271 );
2272 let row_box = scaled.row_box;
2273 wrapped_lines.push(
2274 InputLine::inline(line_text[range.clone()].to_string().into(), fragments)
2275 .with_height(row_box.custom_height(last_layout.line_height))
2276 .with_inline_offset(row_box.baseline - row_box.base_baseline),
2277 );
2278 continue;
2279 }
2280
2281 let line_runs = part_runs(range);
2282 let sub_line: SharedString = line_text[range.clone()].to_string().into();
2283 let shaped_line = window
2284 .text_system()
2285 .shape_line(sub_line, font_size, &line_runs, None);
2286
2287 line_has_background |= has_background(&line_runs);
2288 wrapped_lines.push(shaped_line.into());
2289 }
2290
2291 // Use the first visual line's indentation width for continuation lines.
2292 let wrap_indent = if line_item.indent > 0 && wrapped_lines.len() > 1 {
2293 let indent_byte_len = line_text
2294 .char_indices()
2295 .nth(line_item.indent as usize)
2296 .map(|(ix, _)| ix)
2297 .unwrap_or(line_text.len());
2298 wrapped_lines[0].x_for_index(indent_byte_len)
2299 } else {
2300 px(0.)
2301 };
2302
2303 let line_layout = LineLayout::new()
2304 .inline_lines(wrapped_lines)
2305 .wrap_indent(wrap_indent)
2306 .first_indent(state.display_map.line_indent(line_start))
2307 .with_background(line_has_background)
2308 .with_whitespaces(whitespace_indicators.clone());
2309 lines.push(line_layout);
2310
2311 // +1 for the `\n`
2312 run_offset += line_text.len() + 1;
2313 }
2314
2315 lines
2316 }
2317
2318 /// First usize is the offset of skipped.
2319 fn highlight_lines(
2320 &mut self,
2321 visible_buffer_lines: &[usize],
2322 _visible_top: Pixels,
2323 visible_byte_range: Range<usize>,
2324 cx: &mut App,
2325 ) -> Option<Vec<(Range<usize>, HighlightStyle)>> {
2326 let state = self.state.read(cx);
2327 let text = &state.text;
2328 let is_multi_line = state.is_multi_line();
2329
2330 let (mut highlighter, diagnostics) = match &state.mode {
2331 LayoutMode::CodeEditor {
2332 highlighter,
2333 diagnostics,
2334 ..
2335 } => (highlighter.borrow_mut(), diagnostics),
2336 _ => {
2337 return (!state.masked)
2338 .then(|| {
2339 compose_decoration_collections(
2340 Vec::new(),
2341 state.extras.decoration_layers().into_iter(),
2342 visible_byte_range,
2343 )
2344 })
2345 .flatten();
2346 }
2347 };
2348 let Some(highlighter) = highlighter.as_mut() else {
2349 return (!state.masked)
2350 .then(|| {
2351 compose_decoration_collections(
2352 Vec::new(),
2353 state.extras.decoration_layers().into_iter(),
2354 visible_byte_range,
2355 )
2356 })
2357 .flatten();
2358 };
2359
2360 let mut styles = Vec::with_capacity(visible_buffer_lines.len());
2361 // Byte ranges of the flushed line groups; the composed styles are
2362 // clipped to these at the end so the resulting runs cover exactly the
2363 // visible (non-folded) lines' bytes.
2364 let mut group_ranges: Vec<Range<usize>> = Vec::new();
2365
2366 // Helper to flush a contiguous range of lines. These ranges are disjoint,
2367 // so appending avoids repeatedly cloning and recombining prior styles.
2368 let mut flush_range =
2369 |start_line: usize, end_line: usize, skip: bool, styles: &mut Vec<_>| {
2370 let byte_start = text.line_start_offset(start_line);
2371 let byte_end = if is_multi_line {
2372 // +1 for `\n`
2373 text.line_start_offset(end_line + 1)
2374 } else {
2375 text.line_end_offset(end_line)
2376 };
2377 let range_styles = if skip {
2378 vec![(byte_start..byte_end, HighlightStyle::default())]
2379 } else {
2380 highlighter.styles(
2381 &(byte_start..byte_end),
2382 state.editor_style.highlight_styles.as_ref(),
2383 )
2384 };
2385
2386 group_ranges.push(byte_start..byte_end);
2387 styles.extend(range_styles);
2388 };
2389
2390 // Group contiguous visible lines into ranges and call styles() once per range
2391 let mut visible_iter = visible_buffer_lines.iter().peekable();
2392 let mut range_start: Option<usize> = None;
2393
2394 while let Some(&line) = visible_iter.next() {
2395 // Check if this line is too long for highlighting
2396 let line_len = text.slice_line(line).len();
2397 if line_len > MAX_HIGHLIGHT_LINE_LENGTH {
2398 // Flush any accumulated range first
2399 if let Some(start) = range_start.take() {
2400 flush_range(start, line - 1, false, &mut styles);
2401 }
2402
2403 flush_range(line, line, true, &mut styles);
2404 continue;
2405 }
2406
2407 range_start.get_or_insert(line);
2408
2409 // Check if next line is contiguous, if so keep accumulating
2410 if visible_iter
2411 .peek()
2412 .map(|&&next| next == line + 1)
2413 .unwrap_or(false)
2414 {
2415 continue;
2416 }
2417
2418 // Flush the contiguous range
2419 let start_line = range_start.take().unwrap();
2420 flush_range(start_line, line, false, &mut styles);
2421 }
2422
2423 let diagnostic_styles: Vec<_> = diagnostics
2424 .range(visible_byte_range.clone())
2425 .map(|entry| {
2426 (
2427 entry.range.clone(),
2428 diagnostic_highlight_style(entry.severity, state.editor_style.diagnostics),
2429 )
2430 })
2431 .collect();
2432
2433 // Range semantic tokens, resolved from the LSP provider's cached
2434 // result through the active highlight theme so it shares the same
2435 // colour vocabulary as the tree-sitter path. Empty Vec when no
2436 // provider is set, so `combine_highlights` short-circuits.
2437 let custom_styles = state.extras.semantic_token_styles(
2438 text,
2439 &visible_byte_range,
2440 state.editor_style.highlight_styles.as_ref(),
2441 );
2442
2443 // hover definition style
2444 if let Some(hover_style) = M::hover_definition_style(self.state.read(cx), cx) {
2445 styles.push(hover_style);
2446 }
2447
2448 // Compose tree-sitter, semantic, application, then diagnostic styles.
2449 styles = gpui::combine_highlights(custom_styles, styles).collect();
2450 if !state.masked {
2451 styles = compose_decoration_collections(
2452 styles,
2453 state.extras.decoration_layers().into_iter(),
2454 visible_byte_range.clone(),
2455 )
2456 .unwrap_or_default();
2457 }
2458 styles = gpui::combine_highlights(diagnostic_styles, styles).collect();
2459
2460 // Some sources reach outside the flushed groups — a diagnostic
2461 // straddling the viewport edge, or any range inside a folded region —
2462 // which would inject extra bytes into the runs coordinate space and
2463 // shift every later run boundary (see `layout_lines`). Clip the
2464 // composed styles back to the groups.
2465 styles = clip_styles_to_ranges(styles, &group_ranges);
2466
2467 Some(styles)
2468 }
2469}
2470
2471/// Layout data for a single caret, produced by [`TextElement::layout_cursors`].
2472#[derive(Clone, Debug)]
2473struct CursorRenderInfo {
2474 bounds: Bounds<Pixels>,
2475 is_active: bool,
2476}
2477
2478pub(super) struct PrepaintState {
2479 /// The lines of entire lines.
2480 last_layout: LastLayout,
2481 token_elements: Vec<AnyElement>,
2482 /// The lines only contains the visible lines in the viewport, based on `visible_range`.
2483 ///
2484 /// The child is the soft lines.
2485 line_numbers: Option<Vec<SmallVec<[ShapedLine; 1]>>>,
2486 /// Size of the scrollable area by entire lines.
2487 scroll_size: Size<Pixels>,
2488 /// Caret bounds for every selection, active flagged.
2489 cursor_infos: Vec<CursorRenderInfo>,
2490 cursor_scroll_offset: Point<Pixels>,
2491 /// row index (zero based), no wrap, same line as the cursor.
2492 current_row: Option<usize>,
2493 selection_paths: Vec<Path<Pixels>>,
2494 hover_highlight_path: Option<Path<Pixels>>,
2495 search_match_paths: Vec<(Path<Pixels>, bool)>,
2496 document_color_paths: Vec<(Path<Pixels>, Hsla)>,
2497 range_decoration_fills: Vec<(Path<Pixels>, Hsla)>,
2498 range_decoration_frames: Vec<(Path<Pixels>, Hsla)>,
2499 range_decoration_quads: Vec<PaintQuad>,
2500 hover_definition_hitbox: Option<Hitbox>,
2501 indent_guides_path: Option<Path<Pixels>>,
2502 /// The whole input, for deciding whether a long press started in it.
2503 hitbox: Hitbox,
2504 bounds: Bounds<Pixels>,
2505 /// Fold icon layout data
2506 fold_icon_layout: FoldIconLayout,
2507 // Inline completion rendering data
2508 /// Shaped ghost lines to paint after cursor row (completion lines 2+)
2509 ghost_lines: Vec<ShapedLine>,
2510 /// First line of inline completion (painted after cursor on same line)
2511 ghost_first_line: Option<ShapedLine>,
2512 ghost_lines_height: Pixels,
2513}
2514
2515impl PrepaintState {
2516 /// Returns all cursor infos adjusted for scroll offset.
2517 fn cursor_infos_with_scroll(&self) -> Vec<CursorRenderInfo> {
2518 self.cursor_infos
2519 .iter()
2520 .map(|info| {
2521 let mut bounds = info.bounds;
2522 bounds.origin.y += self.cursor_scroll_offset.y;
2523 CursorRenderInfo {
2524 bounds,
2525 is_active: info.is_active,
2526 }
2527 })
2528 .collect()
2529 }
2530}
2531
2532impl<M: InputModeKind> IntoElement for TextElement<M> {
2533 type Element = Self;
2534
2535 fn into_element(self) -> Self::Element {
2536 self
2537 }
2538}
2539
2540/// A debug function to print points as SVG path.
2541#[allow(unused)]
2542fn print_points_as_svg_path(
2543 line_corners: &Vec<gpui::Corners<Pixels>>,
2544 points: &Vec<Point<Pixels>>,
2545) {
2546 for corners in line_corners {
2547 println!(
2548 "tl: ({}, {}), tr: ({}, {}), bl: ({}, {}), br: ({}, {})",
2549 corners.top_left.as_f32() as i32,
2550 corners.top_left.as_f32() as i32,
2551 corners.top_right.as_f32() as i32,
2552 corners.top_right.as_f32() as i32,
2553 corners.bottom_left.as_f32() as i32,
2554 corners.bottom_left.as_f32() as i32,
2555 corners.bottom_right.as_f32() as i32,
2556 corners.bottom_right.as_f32() as i32,
2557 );
2558 }
2559
2560 if points.len() > 0 {
2561 println!(
2562 "M{},{}",
2563 points[0].x.as_f32() as i32,
2564 points[0].y.as_f32() as i32
2565 );
2566 for p in points.iter().skip(1) {
2567 println!("L{},{}", p.x.as_f32() as i32, p.y.as_f32() as i32);
2568 }
2569 }
2570}
2571
2572const PILL_PADDING: Pixels = px(2.);
2573
2574fn rounded_quad(
2575 bounds: Bounds<Pixels>,
2576 radius: Pixels,
2577 color: Hsla,
2578 border: Option<Hsla>,
2579) -> PaintQuad {
2580 gpui::quad(
2581 bounds,
2582 radius,
2583 color,
2584 if border.is_some() { px(1.) } else { px(0.) },
2585 border.unwrap_or(gpui::transparent_black()),
2586 gpui::BorderStyle::default(),
2587 )
2588}
2589
2590fn frame_outline_points(corners: &[Corners<Point<Pixels>>]) -> Vec<Point<Pixels>> {
2591 let rects = corners
2592 .iter()
2593 .map(|corners| (corners.top_left, corners.bottom_right))
2594 .collect::<Vec<_>>();
2595 let mut points = Vec::with_capacity(rects.len() * 4);
2596 let first = rects[0];
2597 let last = rects[rects.len() - 1];
2598 points.push(first.0);
2599 points.push(point(first.1.x, first.0.y));
2600 for pair in rects.windows(2) {
2601 let current = pair[0];
2602 let next = pair[1];
2603 points.push(current.1);
2604 points.push(point(next.1.x, current.1.y));
2605 points.push(point(next.1.x, next.1.y));
2606 }
2607 if points.last() != Some(&last.1) {
2608 points.push(last.1);
2609 }
2610 points.push(point(last.0.x, last.1.y));
2611 for pair in rects.windows(2).rev() {
2612 let current = pair[1];
2613 let next = pair[0];
2614 points.push(point(current.0.x, current.0.y));
2615 points.push(point(next.0.x, current.0.y));
2616 points.push(point(next.0.x, next.0.y));
2617 }
2618 if points.last() != points.first() {
2619 points.push(points[0]);
2620 }
2621 points
2622}
2623
2624fn pad_frame_corners(
2625 corners: &[Corners<Point<Pixels>>],
2626 horizontal_padding: Pixels,
2627) -> Vec<Corners<Point<Pixels>>> {
2628 corners
2629 .iter()
2630 .map(|corners| Corners {
2631 top_left: point(corners.top_left.x - horizontal_padding, corners.top_left.y),
2632 top_right: point(
2633 corners.top_right.x + horizontal_padding,
2634 corners.top_right.y,
2635 ),
2636 bottom_left: point(
2637 corners.bottom_left.x - horizontal_padding,
2638 corners.bottom_left.y,
2639 ),
2640 bottom_right: point(
2641 corners.bottom_right.x + horizontal_padding,
2642 corners.bottom_right.y,
2643 ),
2644 })
2645 .collect()
2646}
2647
2648fn snap_frame_outline(
2649 points: &[Point<Pixels>],
2650 stroke_width: Pixels,
2651 scale_factor: f32,
2652) -> (Pixels, Vec<Point<Pixels>>) {
2653 let physical_width = ((stroke_width.as_f32() * scale_factor).abs() - 0.5)
2654 .ceil()
2655 .max(1.);
2656 let stroke_width = px(physical_width / scale_factor);
2657 let center_offset = if physical_width % 2. == 0. { 0. } else { 0.5 };
2658 let snap = |value: Pixels| {
2659 px(
2660 ((value.as_f32() * scale_factor - center_offset).round() + center_offset)
2661 / scale_factor,
2662 )
2663 };
2664 (
2665 stroke_width,
2666 points
2667 .iter()
2668 .map(|point| point.map(snap))
2669 .collect::<Vec<_>>(),
2670 )
2671}
2672
2673fn clamp_frame_to_content_mask(
2674 points: Vec<Point<Pixels>>,
2675 stroke_width: Pixels,
2676 content_mask: Bounds<Pixels>,
2677) -> Vec<Point<Pixels>> {
2678 let half_width = stroke_width / 2.;
2679 let min_x = content_mask.left() + half_width;
2680 let max_x = (content_mask.right() - half_width).max(min_x);
2681 points
2682 .into_iter()
2683 .map(|p| point(p.x.max(min_x).min(max_x), p.y))
2684 .collect()
2685}
2686
2687impl<M: InputModeKind> Element for TextElement<M> {
2688 type RequestLayoutState = ();
2689 type PrepaintState = PrepaintState;
2690
2691 fn id(&self) -> Option<ElementId> {
2692 None
2693 }
2694
2695 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
2696 None
2697 }
2698
2699 fn request_layout(
2700 &mut self,
2701 _id: Option<&GlobalElementId>,
2702 _: Option<&gpui::InspectorElementId>,
2703 window: &mut Window,
2704 cx: &mut App,
2705 ) -> (LayoutId, Self::RequestLayoutState) {
2706 let state = self.state.read(cx);
2707 let line_height = window.line_height();
2708
2709 let mut style = Style::default();
2710 style.size.width = relative(1.).into();
2711 if state.is_multi_line() {
2712 style.flex_grow = 1.0;
2713 style.size.height = relative(1.).into();
2714 // At least `rows` tall (auto grow: the content's rows, capped at
2715 // `max_rows` plus the rows of block tokens); a taller parent still fills it.
2716 let rows = state.mode.rows();
2717 style.min_size.height = (rows * line_height + state.mode.grow_extra()).into();
2718 } else {
2719 // For single-line inputs, the minimum height should be the line height
2720 style.size.height = line_height.into();
2721 };
2722
2723 (window.request_layout(style, [], cx), ())
2724 }
2725
2726 fn prepaint(
2727 &mut self,
2728 _id: Option<&GlobalElementId>,
2729 _: Option<&gpui::InspectorElementId>,
2730 bounds: Bounds<Pixels>,
2731 _request_layout: &mut Self::RequestLayoutState,
2732 window: &mut Window,
2733 cx: &mut App,
2734 ) -> Self::PrepaintState {
2735 let style = window.text_style();
2736 let font = style.font();
2737 let text_size = style.font_size.to_pixels(window.rem_size());
2738 // Past the end of a line there are no glyphs to hit-test against, so a pointer
2739 // out there is measured in spaces instead.
2740 let space_width = {
2741 let font_id = window.text_system().resolve_font(&font);
2742 window.text_system().layout_width(font_id, text_size, ' ')
2743 };
2744
2745 let font_overrides: Rc<[(Range<usize>, crate::input::decorations::FontOverride)]> = {
2746 let state = self.state.read(cx);
2747 if state.masked {
2748 Rc::from([])
2749 } else {
2750 font_override_spans(&state.extras.decoration_layers()).into()
2751 }
2752 };
2753 self.state.update(cx, |state, cx| {
2754 state.display_map.set_font(font, text_size, cx);
2755 state.display_map.set_line_height(window.line_height(), cx);
2756 state.display_map.ensure_text_prepared(&state.text, cx);
2757 state
2758 .display_map
2759 .set_font_overrides(font_overrides.clone(), cx);
2760 if state.mode.is_auto_grow() {
2761 let (rows, extra) = (state.mode.rows(), state.mode.grow_extra());
2762 state
2763 .mode
2764 .update_auto_grow(&state.display_map, window.line_height());
2765 if (state.mode.rows(), state.mode.grow_extra()) != (rows, extra) {
2766 cx.notify();
2767 }
2768 }
2769 });
2770
2771 let state = self.state.read(cx);
2772 let multi_line = state.is_multi_line();
2773 let text = state.text.clone();
2774 let is_empty = text.len() == 0;
2775 let placeholder = self.placeholder.clone();
2776
2777 let text_style = window.text_style();
2778 let disabled = state.disabled;
2779 let dim = |color: Hsla| if disabled { color.opacity(0.5) } else { color };
2780 let fg = dim(text_style.color);
2781 let (display_text, text_color) = if is_empty {
2782 (
2783 &Rope::from(placeholder.as_str()),
2784 dim(state.editor_style.muted_foreground),
2785 )
2786 } else if state.masked {
2787 (
2788 &Rope::from(MASK_CHAR.to_string().repeat(text.chars().count())),
2789 fg,
2790 )
2791 } else {
2792 (&text, fg)
2793 };
2794
2795 // Calculate the width of the line numbers
2796 let (line_number_width, line_number_len) =
2797 Self::layout_line_numbers(&state, &text, text_size, &text_style, window);
2798
2799 let mut bounds = bounds;
2800 let wrap_width = if multi_line && state.soft_wrap {
2801 Some(bounds.size.width - line_number_width - RIGHT_MARGIN)
2802 } else {
2803 None
2804 };
2805
2806 let wrapping_indent = state.wrapping_indent;
2807 let wrap_width_changed = state
2808 .last_layout
2809 .as_ref()
2810 .map(|l| l.wrap_width != wrap_width)
2811 .unwrap_or(true);
2812
2813 let wrapping_indent_changed = state
2814 .last_layout
2815 .as_ref()
2816 .map(|l| l.wrapping_indent != wrapping_indent)
2817 .unwrap_or(true);
2818
2819 if wrap_width_changed || wrapping_indent_changed {
2820 self.state.update(cx, |state, cx| {
2821 state.display_map.on_layout_changed(wrap_width, cx);
2822 state.display_map.set_wrapping_indent(wrapping_indent, cx);
2823 });
2824 }
2825
2826 let line_height = window.line_height();
2827 let token_elements = self.measure_tokens(
2828 (bounds.size.width - line_number_width - RIGHT_MARGIN).max(px(1.)),
2829 line_height,
2830 bounds.size.height,
2831 window,
2832 cx,
2833 );
2834 let state = self.state.read(cx);
2835
2836 let (visible_range, visible_buffer_lines, visible_top) =
2837 self.calculate_visible_range(&state, line_height, bounds.size.height);
2838 let visible_start_offset = state.text.line_start_offset(visible_range.start);
2839 let visible_end_offset = state
2840 .text
2841 .line_end_offset(visible_range.end.saturating_sub(1));
2842
2843 let highlight_styles = self.highlight_lines(
2844 &visible_buffer_lines,
2845 visible_top,
2846 visible_start_offset..visible_end_offset,
2847 cx,
2848 );
2849
2850 let state = self.state.read(cx);
2851
2852 let visible_line_byte_offsets: Vec<usize> = visible_buffer_lines
2853 .iter()
2854 .map(|&bl| state.text.line_start_offset(bl))
2855 .collect();
2856
2857 // For password input (masked: true), convert byte offsets to masked display byte offsets so that
2858 // layout_match_range and position_for_index work in the correct coordinate space.
2859 let (visible_line_byte_offsets, visible_range_offset) = if state.masked {
2860 let offsets = visible_line_byte_offsets
2861 .iter()
2862 .map(|&o| masked_display_offset(&text, o))
2863 .collect();
2864 let range_offset = masked_display_offset(&text, visible_start_offset)
2865 ..masked_display_offset(&text, visible_end_offset);
2866 (offsets, range_offset)
2867 } else {
2868 (
2869 visible_line_byte_offsets,
2870 visible_start_offset..visible_end_offset,
2871 )
2872 };
2873
2874 let mut last_layout = LastLayout {
2875 visible_range,
2876 visible_buffer_lines,
2877 visible_line_byte_offsets,
2878 visible_top,
2879 visible_range_offset,
2880 line_height,
2881 wrap_width,
2882 wrapping_indent,
2883 line_number_width,
2884 space_width,
2885 lines: Rc::new(vec![]),
2886 cursor_bounds: None,
2887 text_align: state.text_align,
2888 content_width: bounds.size.width,
2889 };
2890
2891 let run = TextRun {
2892 len: display_text.len(),
2893 font: style.font(),
2894 color: text_color,
2895 background_color: None,
2896 underline: None,
2897 strikethrough: None,
2898 };
2899 let marked_run = TextRun {
2900 len: 0,
2901 font: style.font(),
2902 color: text_color,
2903 background_color: None,
2904 underline: Some(UnderlineStyle {
2905 thickness: px(1.),
2906 color: Some(text_color),
2907 wavy: false,
2908 }),
2909 strikethrough: None,
2910 };
2911
2912 let ime_marked_range = ime_marked_display_range(
2913 &text,
2914 state.ime_marked_range.as_ref().map(|m| m.start..m.end),
2915 state.masked,
2916 );
2917
2918 let runs = if let (false, Some(highlight_styles)) = (is_empty, highlight_styles) {
2919 let mut runs = Vec::with_capacity(highlight_styles.len() + 2);
2920
2921 for (range, style) in &highlight_styles {
2922 let mut run = text_style.clone().highlight(*style).to_run(range.len());
2923 if disabled {
2924 run.color = run.color.opacity(0.5);
2925 }
2926
2927 let mut start = range.start;
2928 for run in split_run_by_font_overrides(run, range.clone(), &font_overrides) {
2929 let run_range = start..start + run.len;
2930 start = run_range.end;
2931 runs.extend(split_run_for_ime_underline(
2932 run,
2933 run_range,
2934 ime_marked_range.clone(),
2935 marked_run.underline,
2936 ));
2937 }
2938 }
2939 runs
2940 } else {
2941 split_run_for_ime_underline(
2942 run,
2943 0..display_text.len(),
2944 ime_marked_range,
2945 marked_run.underline,
2946 )
2947 .into_vec()
2948 };
2949
2950 let document_colors = state
2951 .extras
2952 .document_color_swatches(&text, &last_layout.visible_range);
2953
2954 // Create shaped lines for whitespace indicators before layout
2955 let whitespace_indicators =
2956 Self::layout_whitespace_indicators(&state, text_size, &text_style, window, cx);
2957
2958 let lines = Self::layout_lines(
2959 &state,
2960 &display_text,
2961 &last_layout,
2962 text_size,
2963 &runs,
2964 &font_overrides,
2965 &document_colors,
2966 whitespace_indicators,
2967 window,
2968 );
2969
2970 let mut longest_line_width = wrap_width.unwrap_or(px(0.));
2971 // 1. Single line
2972 // 2. Multi-line with soft wrap disabled.
2973 if state.is_single_line() || !state.soft_wrap {
2974 let longest_row = state.display_map.longest_row();
2975 let longest_line = state.text.slice_line(longest_row);
2976 let key = LongestLineKey {
2977 document_revision: state.document_revision,
2978 row: longest_row,
2979 len: longest_line.len(),
2980 font: style.font(),
2981 text_size,
2982 wrap_width,
2983 };
2984 let cached = state
2985 .longest_line_width
2986 .take()
2987 .filter(|(cached_key, _)| *cached_key == key);
2988 longest_line_width = match cached {
2989 Some((_, width)) => width,
2990 None => {
2991 let longest_line: SharedString = longest_line.to_string().into();
2992 window
2993 .text_system()
2994 .shape_line(
2995 longest_line.clone(),
2996 text_size,
2997 &[TextRun {
2998 len: longest_line.len(),
2999 font: key.font.clone(),
3000 color: gpui::black(),
3001 background_color: None,
3002 underline: None,
3003 strikethrough: None,
3004 }],
3005 wrap_width,
3006 )
3007 .width
3008 }
3009 };
3010 state
3011 .longest_line_width
3012 .set(Some((key, longest_line_width)));
3013 }
3014 if state.tokens_visible() {
3015 longest_line_width = if let Some(width) = wrap_width {
3016 width
3017 } else {
3018 state
3019 .token_layout_cache
3020 .as_ref()
3021 .map_or(px(0.), |cache| cache.unwrapped_width)
3022 };
3023 }
3024 last_layout.lines = Rc::new(lines);
3025
3026 let (ghost_first_line, ghost_lines) = Self::layout_inline_completion(
3027 state,
3028 &last_layout.visible_range,
3029 text_size,
3030 window,
3031 cx,
3032 );
3033 let ghost_line_count = ghost_lines.len();
3034 let ghost_lines_height = ghost_line_count as f32 * line_height;
3035
3036 let empty_bottom_height = empty_bottom_height(
3037 state.is_code_editor(),
3038 state.scroll_beyond_last_line,
3039 bounds.size.height,
3040 line_height,
3041 );
3042
3043 // Empty bottom and ghost lines both describe extra height past the
3044 // last content row, so take the max rather than summing — summing
3045 // left a band of empty space the cursor could never reach.
3046 let mut scroll_size = size(
3047 if longest_line_width + line_number_width + RIGHT_MARGIN > bounds.size.width {
3048 longest_line_width + line_number_width + RIGHT_MARGIN
3049 } else {
3050 longest_line_width
3051 },
3052 (state.display_map.content_height(line_height)
3053 + empty_bottom_height.max(ghost_lines_height))
3054 .max(bounds.size.height),
3055 );
3056
3057 // TODO: should be add some gap to right, to convenient to focus on boundary position
3058 if last_layout.text_align == TextAlign::Right || last_layout.text_align == TextAlign::Center
3059 {
3060 scroll_size.width = longest_line_width + line_number_width;
3061 }
3062
3063 // `position_for_index` for example
3064 //
3065 // #### text
3066 //
3067 // Hello 世界,this is GPUI component.
3068 // The GPUI Component is a collection of UI components for
3069 // GPUI framework, including Button, Input, Checkbox, Radio,
3070 // Dropdown, Tab, and more...
3071 //
3072 // wrap_width: 444px, line_height: 20px
3073 //
3074 // #### lines[0]
3075 //
3076 // | index | pos | line |
3077 // |-------|------------------|------|
3078 // | 5 | (37 px, 0.0) | 0 |
3079 // | 38 | (261.7 px, 20.0) | 0 |
3080 // | 40 | None | - |
3081 //
3082 // #### lines[1]
3083 //
3084 // | index | position | line |
3085 // |-------|-----------------------|------|
3086 // | 5 | (43.578125 px, 0.0) | 0 |
3087 // | 56 | (422.21094 px, 0.0) | 0 |
3088 // | 57 | (11.6328125 px, 20.0) | 1 |
3089 // | 114 | (429.85938 px, 20.0) | 1 |
3090 // | 115 | (11.3125 px, 40.0) | 2 |
3091
3092 // Calculate the scroll offset to keep the cursor in view
3093
3094 // Save the unscrolled x before layout_cursors modifies bounds.origin with scroll_offset.
3095 // Fold icons and their hitboxes must use this value so they stay fixed in the gutter
3096 // regardless of horizontal scroll position.
3097 let input_bounds = bounds;
3098 let original_x = bounds.origin.x;
3099
3100 let (cursor_infos, cursor_scroll_offset, current_row) =
3101 self.layout_cursors(&last_layout, &mut bounds, scroll_size, window, cx);
3102 // Completion/code-action menus position at the active caret.
3103 last_layout.cursor_bounds = cursor_infos
3104 .iter()
3105 .find(|info| info.is_active)
3106 .map(|info| info.bounds);
3107
3108 let search_match_paths = self.layout_search_matches(&last_layout, &mut bounds, cx);
3109 let selection_paths = self.layout_selections(&last_layout, &mut bounds, window, cx);
3110 let hover_highlight_path = self.layout_hover_highlight(&last_layout, &mut bounds, cx);
3111 let document_color_paths =
3112 self.layout_document_colors(&document_colors, &last_layout, &bounds, cx);
3113 let (range_decoration_fills, range_decoration_frames) = self.layout_range_decorations(
3114 &last_layout,
3115 &bounds,
3116 window,
3117 window.content_mask().bounds,
3118 cx,
3119 );
3120 let range_decoration_quads = self.layout_range_decoration_quads(&last_layout, &bounds, cx);
3121
3122 let state = self.state.read(cx);
3123 let line_numbers = if state.mode.line_number() {
3124 let mut line_numbers = Vec::with_capacity(last_layout.visible_buffer_lines.len());
3125 let other_line_runs = vec![TextRun {
3126 len: line_number_len,
3127 font: style.font(),
3128 color: state.editor_style.muted_foreground,
3129 background_color: None,
3130 underline: None,
3131 strikethrough: None,
3132 }];
3133 let current_line_runs = vec![TextRun {
3134 len: line_number_len,
3135 font: style.font(),
3136 color: state.editor_style.foreground,
3137 background_color: None,
3138 underline: None,
3139 strikethrough: None,
3140 }];
3141
3142 // build line numbers
3143 for (line, &buffer_line) in last_layout
3144 .lines
3145 .iter()
3146 .zip(last_layout.visible_buffer_lines.iter())
3147 {
3148 let line_no: SharedString = format!(
3149 "{:>width$}",
3150 displayed_line_number(buffer_line + 1),
3151 width = line_number_len
3152 )
3153 .into();
3154
3155 let runs = if current_row == Some(buffer_line) {
3156 &current_line_runs
3157 } else {
3158 &other_line_runs
3159 };
3160
3161 let mut sub_lines: SmallVec<[ShapedLine; 1]> = SmallVec::new();
3162 sub_lines.push(
3163 window
3164 .text_system()
3165 .shape_line(line_no, text_size, &runs, None),
3166 );
3167 for _ in 0..line.wrapped_lines.len().saturating_sub(1) {
3168 sub_lines.push(ShapedLine::default());
3169 }
3170 line_numbers.push(sub_lines);
3171 }
3172 Some(line_numbers)
3173 } else {
3174 None
3175 };
3176
3177 let hover_definition_hitbox = M::hover_definition_hitbox(state, window, cx);
3178 let indent_guides_path =
3179 self.layout_indent_guides(state, &bounds, &last_layout, &text_style, window);
3180 state
3181 .editor_scrollbar_snapshot
3182 .set(Some(EditorScrollbarSnapshot::new(
3183 input_bounds,
3184 &last_layout,
3185 scroll_size,
3186 cursor_scroll_offset,
3187 state,
3188 )));
3189 let fold_icon_layout =
3190 self.layout_fold_icons(original_x, &bounds, &last_layout, window, cx);
3191 let hitbox = window.insert_hitbox(input_bounds, HitboxBehavior::Normal);
3192
3193 let token_elements = self.prepaint_tokens(&last_layout, bounds, token_elements, window, cx);
3194 PrepaintState {
3195 token_elements,
3196 hitbox,
3197 bounds,
3198 last_layout,
3199 scroll_size,
3200 line_numbers,
3201 cursor_infos,
3202 cursor_scroll_offset,
3203 current_row,
3204 selection_paths,
3205 search_match_paths,
3206 hover_highlight_path,
3207 hover_definition_hitbox,
3208 document_color_paths,
3209 range_decoration_fills,
3210 range_decoration_frames,
3211 range_decoration_quads,
3212 indent_guides_path,
3213 fold_icon_layout,
3214 ghost_first_line,
3215 ghost_lines,
3216 ghost_lines_height,
3217 }
3218 }
3219
3220 fn paint(
3221 &mut self,
3222 _id: Option<&GlobalElementId>,
3223 _: Option<&gpui::InspectorElementId>,
3224 input_bounds: Bounds<Pixels>,
3225 _request_layout: &mut Self::RequestLayoutState,
3226 prepaint: &mut Self::PrepaintState,
3227 window: &mut Window,
3228 cx: &mut App,
3229 ) {
3230 let (focus_handle, show_cursor, disabled, selected_range, editor_style, editor_paddings) = {
3231 let state = self.state.read(cx);
3232 (
3233 state.focus_handle.clone(),
3234 state.show_cursor(window, cx),
3235 state.disabled,
3236 *state.active_selection(),
3237 state.editor_style.clone(),
3238 state.editor_paddings,
3239 )
3240 };
3241 let focused = focus_handle.is_focused(window);
3242 let bounds = prepaint.bounds;
3243 let text_align = prepaint.last_layout.text_align;
3244
3245 window.handle_input(
3246 &focus_handle,
3247 ElementInputHandler::new(bounds, self.state.clone()),
3248 cx,
3249 );
3250
3251 // Paint multi line text
3252 let line_height = window.line_height();
3253 let origin = bounds.origin;
3254
3255 let invisible_top_padding = prepaint.last_layout.visible_top;
3256 let active_line_color = editor_style
3257 .editor_active_line
3258 .map(|color| if disabled { color.opacity(0.5) } else { color });
3259 let editor_background = if disabled {
3260 editor_style.background.opacity(0.5)
3261 } else {
3262 editor_style.background
3263 };
3264
3265 // Paint active line
3266 let mut offset_y = px(0.);
3267 if let Some(line_numbers) = prepaint.line_numbers.as_ref() {
3268 offset_y += invisible_top_padding;
3269
3270 // Each item is the normal lines.
3271 for (lines, &buffer_line) in line_numbers
3272 .iter()
3273 .zip(prepaint.last_layout.visible_buffer_lines.iter())
3274 {
3275 let is_active = prepaint.current_row == Some(buffer_line);
3276 let p = point(input_bounds.origin.x, origin.y + offset_y);
3277 let height = line_height * lines.len() as f32;
3278 // Paint the current line background
3279 if is_active {
3280 if let Some(bg_color) = active_line_color {
3281 window.paint_quad(fill(
3282 Bounds::new(p, size(bounds.size.width, height)),
3283 bg_color,
3284 ));
3285 }
3286 }
3287 offset_y += height;
3288 }
3289 }
3290
3291 // Keep scrollbar offset always be positive,Start from the left position
3292 let scroll_offset = if text_align == TextAlign::Right {
3293 (prepaint.scroll_size.width - prepaint.bounds.size.width).max(px(0.))
3294 } else if text_align == TextAlign::Center {
3295 (prepaint.scroll_size.width - prepaint.bounds.size.width)
3296 .half()
3297 .max(px(0.))
3298 } else {
3299 px(0.)
3300 };
3301
3302 // Paint glyph backgrounds
3303 //
3304 // gpui's `paint` only draws glyphs, underlines, and strikethroughs, so decoration
3305 // backgrounds need their own pass. It runs ahead of the indent guides, selections,
3306 // and text so a highlighted range sits under them instead of covering them.
3307 let mut offset_y = invisible_top_padding;
3308 for (line, &buffer_line) in prepaint
3309 .last_layout
3310 .lines
3311 .iter()
3312 .zip(prepaint.last_layout.visible_buffer_lines.iter())
3313 {
3314 let p = point(
3315 origin.x + prepaint.last_layout.line_number_width + scroll_offset,
3316 origin.y + offset_y,
3317 );
3318
3319 line.paint_background(
3320 p,
3321 line_height,
3322 text_align,
3323 Some(prepaint.last_layout.content_width),
3324 window,
3325 cx,
3326 );
3327
3328 offset_y += line.size(line_height).height;
3329
3330 // Ghost lines shift every later line down.
3331 if Some(buffer_line) == prepaint.current_row {
3332 offset_y += prepaint.ghost_lines_height;
3333 }
3334 }
3335
3336 // Paint indent guides
3337 if let Some(path) = prepaint.indent_guides_path.take() {
3338 window.paint_path(path, editor_style.border.opacity(0.85));
3339 }
3340
3341 // Application decorations sit below the user's selection.
3342 for quad in &prepaint.range_decoration_quads {
3343 window.paint_quad(quad.clone());
3344 }
3345 for (path, color) in &prepaint.range_decoration_fills {
3346 window.paint_path(path.clone(), *color);
3347 }
3348 for (path, color) in &prepaint.range_decoration_frames {
3349 window.paint_path(path.clone(), *color);
3350 }
3351
3352 // Paint selections
3353 if window.is_window_active() {
3354 let secondary_selection = Hsla {
3355 s: 0.1,
3356 ..editor_style.selection
3357 };
3358 for (path, is_active) in prepaint.search_match_paths.iter() {
3359 window.paint_path(path.clone(), secondary_selection);
3360
3361 if *is_active {
3362 window.paint_path(path.clone(), editor_style.selection);
3363 }
3364 }
3365
3366 for path in prepaint.selection_paths.drain(..) {
3367 window.paint_path(path, editor_style.selection);
3368 }
3369
3370 // Paint hover highlight
3371 if let Some(path) = prepaint.hover_highlight_path.take() {
3372 window.paint_path(path, secondary_selection);
3373 }
3374 }
3375
3376 // Paint document colors
3377 for (path, color) in prepaint.document_color_paths.iter() {
3378 let color = if disabled { color.opacity(0.5) } else { *color };
3379 window.paint_path(path.clone(), color);
3380 }
3381
3382 // Paint text with inline completion ghost line support
3383 let mut offset_y = invisible_top_padding;
3384 let ghost_lines = &prepaint.ghost_lines;
3385 let has_ghost_lines = !ghost_lines.is_empty();
3386
3387 // Track the y-position of the cursor row for positioning the first line suffix
3388 let mut cursor_row_y = None;
3389
3390 for (line, &buffer_line) in prepaint
3391 .last_layout
3392 .lines
3393 .iter()
3394 .zip(prepaint.last_layout.visible_buffer_lines.iter())
3395 {
3396 let row = buffer_line;
3397 let line_y = origin.y + offset_y;
3398 let p = point(
3399 origin.x + prepaint.last_layout.line_number_width + (scroll_offset),
3400 line_y,
3401 );
3402
3403 // Paint the actual line
3404 _ = line.paint(
3405 p,
3406 line_height,
3407 text_align,
3408 Some(prepaint.last_layout.content_width),
3409 window,
3410 cx,
3411 );
3412 offset_y += line.size(line_height).height;
3413
3414 if Some(row) == prepaint.current_row {
3415 cursor_row_y = Some(line_y);
3416 }
3417
3418 // After the cursor row, paint ghost lines (which shifts subsequent content down)
3419 if has_ghost_lines && Some(row) == prepaint.current_row {
3420 let ghost_x = origin.x + prepaint.last_layout.line_number_width;
3421
3422 for ghost_line in ghost_lines {
3423 let ghost_p = point(ghost_x, origin.y + offset_y);
3424
3425 // Paint semi-transparent background for ghost line
3426 let ghost_bounds = Bounds::new(
3427 ghost_p,
3428 size(
3429 bounds.size.width - prepaint.last_layout.line_number_width,
3430 line_height,
3431 ),
3432 );
3433 window.paint_quad(fill(ghost_bounds, editor_background));
3434
3435 // Paint ghost line text
3436 _ = ghost_line.paint(
3437 ghost_p,
3438 line_height,
3439 text_align,
3440 Some(prepaint.last_layout.content_width),
3441 window,
3442 cx,
3443 );
3444 offset_y += line_height;
3445 }
3446 }
3447 }
3448
3449 for element in &mut prepaint.token_elements {
3450 element.paint(window, cx);
3451 }
3452
3453 // Paint blinking cursors (shared blink state for all carets)
3454 if focused && show_cursor {
3455 for cursor_info in prepaint.cursor_infos_with_scroll() {
3456 window.paint_quad(fill(cursor_info.bounds, editor_style.caret));
3457 }
3458 }
3459
3460 // Paint line numbers
3461 let mut offset_y = px(0.);
3462 if let Some(line_numbers) = prepaint.line_numbers.as_ref() {
3463 offset_y += invisible_top_padding;
3464
3465 // The gutter is a fixed overlay above horizontally scrolling text.
3466 // Always give it an opaque editor background when the theme does not
3467 // provide a dedicated gutter color, and cover the complete gutter so
3468 // text cannot show through its right-side spacing/fold-icon area.
3469 let gutter_bg = editor_style
3470 .editor_gutter_background
3471 .unwrap_or(editor_background);
3472 let gutter_bounds = editor_gutter_bounds(
3473 input_bounds,
3474 prepaint.last_layout.line_number_width,
3475 prepaint.ghost_lines_height,
3476 editor_paddings,
3477 );
3478 window.paint_quad(fill(gutter_bounds, gutter_bg));
3479
3480 // Each item is the normal lines.
3481 for (lines, &buffer_line) in line_numbers
3482 .iter()
3483 .zip(prepaint.last_layout.visible_buffer_lines.iter())
3484 {
3485 let p = point(input_bounds.origin.x, origin.y + offset_y);
3486 let is_active = prepaint.current_row == Some(buffer_line);
3487
3488 let height = line_height * lines.len() as f32;
3489 // paint active line number background
3490 if is_active {
3491 if let Some(bg_color) = active_line_color {
3492 window.paint_quad(fill(
3493 Bounds::new(
3494 point(gutter_bounds.origin.x, p.y),
3495 size(gutter_bounds.size.width, height),
3496 ),
3497 bg_color,
3498 ));
3499 }
3500 }
3501
3502 for line in lines {
3503 _ = line.paint(p, line_height, TextAlign::Left, None, window, cx);
3504 offset_y += line_height;
3505 }
3506
3507 // Add ghost line height after cursor row for line numbers alignment
3508 if !prepaint.ghost_lines.is_empty() && prepaint.current_row == Some(buffer_line) {
3509 offset_y += prepaint.ghost_lines_height;
3510 }
3511 }
3512 }
3513
3514 // Paint fold icons (only visible on hover or for current line)
3515 self.paint_fold_icons(
3516 &mut prepaint.fold_icon_layout,
3517 prepaint.current_row,
3518 window,
3519 cx,
3520 );
3521
3522 self.state.update(cx, |state, cx| {
3523 let geometry_changed = state.last_bounds != Some(bounds)
3524 || state.input_bounds != input_bounds
3525 || state.scroll_size != prepaint.scroll_size
3526 || state.last_layout.as_ref().is_none_or(|layout| {
3527 layout.cursor_bounds != prepaint.last_layout.cursor_bounds
3528 || layout.line_height != prepaint.last_layout.line_height
3529 });
3530 state.last_layout = Some(prepaint.last_layout.clone());
3531 state.last_bounds = Some(bounds);
3532 state.last_cursor = Some(state.cursor());
3533 state.set_input_bounds(input_bounds, cx);
3534 state.last_selected_range = Some(selected_range);
3535 state.scroll_size = prepaint.scroll_size;
3536 state.update_scroll_offset(Some(prepaint.cursor_scroll_offset), cx);
3537 state.deferred_scroll_offset = None;
3538
3539 // Layout consumers need changed geometry, not another notification
3540 // for every paint of an unchanged input.
3541 if geometry_changed {
3542 cx.notify();
3543 }
3544 });
3545
3546 if let Some(hitbox) = prepaint.hover_definition_hitbox.as_ref()
3547 && !window.modifiers().alt
3548 {
3549 window.set_cursor_style(gpui::CursorStyle::PointingHand, &hitbox);
3550 }
3551
3552 // Paint inline completion first line suffix (after cursor on same line)
3553 if focused {
3554 if let Some(first_line) = &prepaint.ghost_first_line {
3555 let active_cursor = prepaint
3556 .cursor_infos_with_scroll()
3557 .into_iter()
3558 .find(|info| info.is_active);
3559 if let (Some(cursor_info), Some(cursor_row_y)) = (active_cursor, cursor_row_y) {
3560 let cursor_bounds = cursor_info.bounds;
3561 let first_line_x = cursor_bounds.origin.x + cursor_bounds.size.width;
3562 let p = point(first_line_x, cursor_row_y);
3563
3564 // Paint background to cover any existing text
3565 let bg_bounds = Bounds::new(p, size(first_line.width + px(4.), line_height));
3566 window.paint_quad(fill(bg_bounds, editor_background));
3567
3568 // Paint first line completion text
3569 _ = first_line.paint(p, line_height, text_align, None, window, cx);
3570 }
3571 }
3572 }
3573
3574 self.paint_mouse_listeners(&prepaint.hitbox, window, cx);
3575 }
3576}
3577
3578/// Split placeholder text into display lines and trim runs to each line.
3579fn placeholder_line_runs<'a>(
3580 display_text: &'a str,
3581 runs: &[TextRun],
3582) -> Vec<(&'a str, Vec<TextRun>)> {
3583 let mut result = Vec::new();
3584 let mut line_offset = 0;
3585
3586 for line in display_text.split('\n') {
3587 let line_runs = runs_for_range(runs, line_offset, &(0..line.len()));
3588 debug_assert_eq!(
3589 line_runs.iter().map(|run| run.len).sum::<usize>(),
3590 line.len()
3591 );
3592 result.push((line, line_runs));
3593 // Advance in the whole-placeholder coordinate space, including the separator.
3594 line_offset += line.len() + 1;
3595 }
3596
3597 result
3598}
3599
3600fn scale_font(
3601 font_overrides: &[(Range<usize>, FontOverride)],
3602 window: &Window,
3603) -> Option<gpui::Font> {
3604 font_overrides
3605 .iter()
3606 .any(|(_, font_override)| font_override.scale.is_some() || font_override.raise.is_some())
3607 .then(|| window.text_style().font())
3608}
3609
3610#[allow(clippy::too_many_arguments)]
3611fn push_text_fragments(
3612 window: &Window,
3613 line_text: &str,
3614 part: Range<usize>,
3615 row_start: usize,
3616 line_start: usize,
3617 scaled: Option<&ScaledRow>,
3618 font_size: Pixels,
3619 mut part_runs: impl FnMut(&Range<usize>) -> Vec<TextRun>,
3620 x: &mut Pixels,
3621 fragments: &mut Vec<InlineFragment>,
3622) {
3623 let mut push =
3624 |local: Range<usize>, size: Pixels, placement_of: Option<(&ScaledRow, Pixels)>| {
3625 let shaped = window.text_system().shape_line(
3626 line_text[local.clone()].to_owned().into(),
3627 size,
3628 &part_runs(&local),
3629 None,
3630 );
3631 let width = shaped.width;
3632 let placement = placement_of.map(|(scaled, raise)| {
3633 (
3634 scaled.row_box.baseline - raise - shaped.ascent,
3635 shaped.ascent + shaped.descent,
3636 )
3637 });
3638 fragments.push(InlineFragment {
3639 range: local.start - row_start..local.end - row_start,
3640 x: *x,
3641 width,
3642 text: Some(shaped),
3643 placement,
3644 });
3645 *x += width;
3646 };
3647 match scaled {
3648 None => push(part, font_size, None),
3649 Some(scaled) => {
3650 for (range, row_piece) in
3651 scaled.pieces_in(line_start + part.start..line_start + part.end)
3652 {
3653 push(
3654 range.start - line_start..range.end - line_start,
3655 font_size * row_piece.piece.scale,
3656 Some((scaled, scaled.raise_pixels(row_piece))),
3657 );
3658 }
3659 }
3660 }
3661}
3662
3663/// Get the runs for the given range.
3664///
3665/// The range is the byte range of the wrapped line.
3666pub(super) fn runs_for_range(
3667 runs: &[TextRun],
3668 line_offset: usize,
3669 range: &Range<usize>,
3670) -> Vec<TextRun> {
3671 let mut result = vec![];
3672 let range = (line_offset + range.start)..(line_offset + range.end);
3673 let mut cursor = 0;
3674
3675 for run in runs {
3676 let run_start = cursor;
3677 let run_end = cursor + run.len;
3678
3679 if run_end <= range.start {
3680 cursor = run_end;
3681 continue;
3682 }
3683
3684 if run_start >= range.end {
3685 break;
3686 }
3687
3688 let start = range.start.max(run_start) - run_start;
3689 let end = range.end.min(run_end) - run_start;
3690 let len = end - start;
3691
3692 if len > 0 {
3693 result.push(TextRun { len, ..run.clone() });
3694 }
3695
3696 cursor = run_end;
3697 }
3698
3699 result
3700}
3701
3702/// Clip sorted `styles` to the sorted, disjoint `ranges`, splitting styles
3703/// that span several ranges and dropping coverage in the gaps between them.
3704fn clip_styles_to_ranges(
3705 styles: Vec<(Range<usize>, HighlightStyle)>,
3706 ranges: &[Range<usize>],
3707) -> Vec<(Range<usize>, HighlightStyle)> {
3708 let mut result = Vec::with_capacity(styles.len());
3709 let mut range_ix = 0;
3710
3711 for (style_range, style) in styles {
3712 while range_ix < ranges.len() && ranges[range_ix].end <= style_range.start {
3713 range_ix += 1;
3714 }
3715
3716 let mut ix = range_ix;
3717 while ix < ranges.len() && ranges[ix].start < style_range.end {
3718 let start = style_range.start.max(ranges[ix].start);
3719 let end = style_range.end.min(ranges[ix].end);
3720 if start < end {
3721 result.push((start..end, style));
3722 }
3723 ix += 1;
3724 }
3725 }
3726
3727 result
3728}
3729
3730/// Snap run boundaries to char boundaries of `text` and cap them at its
3731/// length. Style ranges are byte offsets that can drift off char boundaries
3732/// (a stale syntax tree, a range in the wrong coordinate space) and the
3733/// platform text system panics when a run splits a multi-byte character.
3734///
3735/// Returns `None` when the runs are already aligned (the common case).
3736pub(super) fn align_runs_to_char_boundaries(text: &str, runs: &[TextRun]) -> Option<Vec<TextRun>> {
3737 let mut end = 0;
3738 let aligned = runs.iter().all(|run| {
3739 end += run.len;
3740 end <= text.len() && text.is_char_boundary(end)
3741 });
3742 if aligned {
3743 return None;
3744 }
3745
3746 let mut result = Vec::with_capacity(runs.len());
3747 let mut cursor = 0;
3748 let mut raw_end = 0;
3749 for run in runs {
3750 raw_end = (raw_end + run.len).min(text.len());
3751 let mut end = raw_end;
3752 while !text.is_char_boundary(end) {
3753 end += 1;
3754 }
3755 if end > cursor {
3756 result.push(TextRun {
3757 len: end - cursor,
3758 ..run.clone()
3759 });
3760 cursor = end;
3761 }
3762 }
3763
3764 Some(result)
3765}
3766
3767fn split_run_for_ime_underline(
3768 run: TextRun,
3769 run_range: Range<usize>,
3770 marked_range: Option<Range<usize>>,
3771 marked_underline: Option<UnderlineStyle>,
3772) -> SmallVec<[TextRun; 3]> {
3773 if run.len == 0 {
3774 return SmallVec::new();
3775 }
3776
3777 let Some(marked) = marked_range else {
3778 return [run].into_iter().collect();
3779 };
3780
3781 let intersection_start = run_range.start.max(marked.start);
3782 let intersection_end = run_range.end.min(marked.end);
3783 if intersection_start >= intersection_end {
3784 return [run].into_iter().collect();
3785 }
3786
3787 [
3788 TextRun {
3789 len: intersection_start - run_range.start,
3790 ..run.clone()
3791 },
3792 TextRun {
3793 len: intersection_end - intersection_start,
3794 underline: marked_underline,
3795 ..run.clone()
3796 },
3797 TextRun {
3798 len: run_range.end - intersection_end,
3799 ..run
3800 },
3801 ]
3802 .into_iter()
3803 .filter(|run| run.len > 0)
3804 .collect()
3805}
3806
3807/// Whether any of these runs paints a glyph background, used to skip the background
3808/// paint pass for lines without highlights.
3809fn has_background(runs: &[TextRun]) -> bool {
3810 runs.iter().any(|run| run.background_color.is_some())
3811}
3812
3813fn split_runs_by_bg_segments(
3814 start_offset: usize,
3815 runs: &[TextRun],
3816 bg_segments: &[(Range<usize>, Hsla)],
3817) -> Vec<TextRun> {
3818 let mut result = vec![];
3819
3820 let mut cursor = start_offset;
3821 for run in runs {
3822 let mut run_start = cursor;
3823 let run_end = cursor + run.len;
3824
3825 for (bg_range, bg_color) in bg_segments {
3826 if run_end <= bg_range.start || run_start >= bg_range.end {
3827 continue;
3828 }
3829
3830 // Overlap exists
3831 if run_start < bg_range.start {
3832 // Add the part before the background range
3833 result.push(TextRun {
3834 len: bg_range.start - run_start,
3835 ..run.clone()
3836 });
3837 }
3838
3839 // Add the overlapping part with background color
3840 let overlap_start = run_start.max(bg_range.start);
3841 let overlap_end = run_end.min(bg_range.end);
3842 let text_color = if bg_color.l >= 0.5 {
3843 gpui::black()
3844 } else {
3845 gpui::white()
3846 };
3847
3848 let run_len = overlap_end.saturating_sub(overlap_start);
3849 if run_len > 0 {
3850 result.push(TextRun {
3851 len: run_len,
3852 color: text_color,
3853 ..run.clone()
3854 });
3855
3856 cursor = bg_range.end;
3857 run_start = cursor;
3858 }
3859 }
3860
3861 if run_end > cursor {
3862 // Add the part after the background range
3863 result.push(TextRun {
3864 len: run_end - cursor,
3865 ..run.clone()
3866 });
3867 }
3868
3869 cursor = run_end;
3870 }
3871
3872 result
3873}
3874
3875#[cfg(test)]
3876mod tests {
3877 use super::*;
3878 use crate::input::{EditorMode, EditorState, FoldRange, RangeDecoration, Redo, Undo};
3879 use gpui::{
3880 AppContext as _, Context, EntityInputHandler as _, Render, TestAppContext,
3881 VisualTestContext, div,
3882 };
3883
3884 #[test]
3885 fn line_number_column_stays_at_three_digits_then_grows_up_to_seven() {
3886 assert_eq!(line_number_len(1), 3);
3887 assert_eq!(line_number_len(9), 3);
3888 assert_eq!(line_number_len(10), 3);
3889 assert_eq!(line_number_len(999), 3);
3890 assert_eq!(line_number_len(1_000), 4);
3891 assert_eq!(line_number_len(999_999), 6);
3892 assert_eq!(line_number_len(9_999_999), 7);
3893 assert_eq!(line_number_len(10_000_000), 7);
3894 }
3895
3896 #[test]
3897 fn displayed_line_number_stays_within_seven_digits() {
3898 assert_eq!(displayed_line_number(42), 42);
3899 assert_eq!(displayed_line_number(9_999_999), 9_999_999);
3900 assert_eq!(displayed_line_number(10_000_000), 9_999_999);
3901 }
3902
3903 struct DecorationHarness(Entity<EditorState>);
3904
3905 impl Render for DecorationHarness {
3906 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3907 div().size_full().child(self.0.clone())
3908 }
3909 }
3910
3911 fn decoration_editor(
3912 cx: &mut TestAppContext,
3913 text: &str,
3914 wrap: bool,
3915 ) -> (Entity<EditorState>, gpui::WindowHandle<DecorationHarness>) {
3916 cx.update(crate::init);
3917 let mut editor = None;
3918 let window = cx.open_window(size(px(240.), px(140.)), |window, cx| {
3919 let state = cx.new(|cx| {
3920 EditorState::new(window, cx)
3921 .soft_wrap(wrap)
3922 .folding(true)
3923 .default_value(text)
3924 });
3925 editor = Some(state.clone());
3926 DecorationHarness(state)
3927 });
3928 (editor.unwrap(), window)
3929 }
3930
3931 #[cfg(target_os = "linux")]
3932 #[test]
3933 fn font_family_decorations_shape_wrap_and_hit_test_in_that_font() {
3934 let platform = gpui_platform::current_platform(true);
3935 let mut cx = TestAppContext::build_with_text_system(
3936 gpui::TestDispatcher::new(0),
3937 None,
3938 platform.text_system(),
3939 );
3940 let text = "iiiiiiii ".repeat(8);
3941 let mono_range = 9..35;
3942 let (editor, window) = decoration_editor(&mut cx, &text, true);
3943 let mut cx = VisualTestContext::from_window(window.into(), &mut cx);
3944 cx.update(|window, cx| {
3945 window.draw(cx).clear(cx);
3946 let plain_rows = editor.read(cx).last_layout.as_ref().unwrap().lines[0]
3947 .wrapped_lines
3948 .len();
3949 editor.update(cx, |state, cx| {
3950 state.create_decorations_collection(
3951 vec![
3952 TextDecoration::new(mono_range.clone(), HighlightStyle::default())
3953 .with_font_family("DejaVu Sans Mono"),
3954 ],
3955 cx,
3956 );
3957 });
3958 window.draw(cx).clear(cx);
3959 let state = editor.read(cx);
3960 let layout = state.last_layout.as_ref().unwrap();
3961 let line = &layout.lines[0];
3962 assert!(line.wrapped_lines.len() > plain_rows);
3963 for row in line.wrapped_lines.iter() {
3964 assert!(row.width <= layout.wrap_width.unwrap());
3965 }
3966
3967 let mono_offset = mono_range.start + 4;
3968 let position = line.position_for_index(mono_offset, layout, false).unwrap();
3969 let next = line
3970 .position_for_index(mono_offset + 1, layout, false)
3971 .unwrap();
3972 let mono_glyph_width = window
3973 .text_system()
3974 .shape_line(
3975 "i".into(),
3976 window.text_style().font_size.to_pixels(window.rem_size()),
3977 &[TextRun {
3978 len: 1,
3979 font: gpui::font("DejaVu Sans Mono"),
3980 color: gpui::black(),
3981 background_color: None,
3982 underline: None,
3983 strikethrough: None,
3984 }],
3985 None,
3986 )
3987 .width;
3988 assert_eq!(next.x - position.x, mono_glyph_width);
3989 let (hit, _) = line
3990 .closest_index_for_position(
3991 point(position.x + mono_glyph_width / 4., position.y),
3992 layout,
3993 )
3994 .unwrap();
3995 assert_eq!(hit, mono_offset);
3996 });
3997 }
3998
3999 struct TextareaHarness(Entity<crate::input::TextareaState>);
4000
4001 impl Render for TextareaHarness {
4002 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4003 div().size_full().child(self.0.clone())
4004 }
4005 }
4006
4007 #[cfg(target_os = "linux")]
4008 #[test]
4009 fn pills_blocks_and_bars_paint_as_quads_only() {
4010 let platform = gpui_platform::current_platform(true);
4011 let mut cx = TestAppContext::build_with_text_system(
4012 gpui::TestDispatcher::new(0),
4013 None,
4014 platform.text_system(),
4015 );
4016 cx.update(crate::init);
4017 let mut textarea = None;
4018 let window = cx.open_window(size(px(240.), px(140.)), |window, cx| {
4019 let state = cx.new(|cx| {
4020 crate::input::TextareaState::new(window, cx)
4021 .rows(4)
4022 .default_value("ab\ncd\nef\n")
4023 });
4024 textarea = Some(state.clone());
4025 TextareaHarness(state)
4026 });
4027 let textarea = textarea.unwrap();
4028 let mut cx = VisualTestContext::from_window(window.into(), &mut cx);
4029 cx.update(|window, cx| {
4030 textarea.update(cx, |state, cx| {
4031 state.create_range_decorations_collection(
4032 vec![
4033 RangeDecoration::new(0..1)
4034 .with_style(RangeDecorationStyle::Pill)
4035 .with_radius(px(4.)),
4036 RangeDecoration::new(3..8).with_style(RangeDecorationStyle::Block),
4037 RangeDecoration::new(9..9)
4038 .with_style(RangeDecorationStyle::Bar)
4039 .with_radius(px(3.)),
4040 ],
4041 cx,
4042 );
4043 });
4044 window.draw(cx).clear(cx);
4045 let state = textarea.read(cx);
4046 let layout = state.last_layout.as_ref().unwrap();
4047 let element = TextElement::new(textarea.clone());
4048 let (fills, frames) = element.layout_range_decorations(
4049 layout,
4050 &state.input_bounds,
4051 window,
4052 state.input_bounds,
4053 cx,
4054 );
4055 assert!(fills.is_empty() && frames.is_empty());
4056 let quads = element.layout_range_decoration_quads(layout, &state.input_bounds, cx);
4057 assert_eq!(quads.len(), 3);
4058 let line_height = layout.line_height;
4059 assert_eq!(quads[1].bounds.size.height, line_height * 2.);
4060 assert_eq!(quads[2].bounds.size.width, px(3.));
4061 assert_eq!(quads[2].bounds.size.height, line_height);
4062 });
4063 }
4064
4065 #[cfg(target_os = "linux")]
4066 #[test]
4067 fn block_token_selection_and_block_decoration_span_the_row_height() {
4068 use crate::input::{InlineToken, InlineTokenPresentation};
4069 let platform = gpui_platform::current_platform(true);
4070 let mut cx = TestAppContext::build_with_text_system(
4071 gpui::TestDispatcher::new(0),
4072 None,
4073 platform.text_system(),
4074 );
4075 cx.update(crate::init);
4076 let mut textarea = None;
4077 let window = cx.open_window(size(px(400.), px(300.)), |window, cx| {
4078 let state = cx.new(|cx| {
4079 crate::input::TextareaState::new(window, cx)
4080 .rows(4)
4081 .default_value("ab[img]cd")
4082 });
4083 textarea = Some(state.clone());
4084 TextareaHarness(state)
4085 });
4086 let textarea = textarea.unwrap();
4087 let mut cx = VisualTestContext::from_window(window.into(), &mut cx);
4088 cx.update(|window, cx| {
4089 textarea.update(cx, |state, cx| {
4090 state.set_token_presentation(
4091 InlineTokenPresentation::default()
4092 .token(|_, _, _| div().w(px(200.)).h(px(120.))),
4093 );
4094 state
4095 .replace_range_with_token(
4096 2..7,
4097 InlineToken::new("img", "[img]").block(),
4098 window,
4099 cx,
4100 )
4101 .unwrap();
4102 state.create_range_decorations_collection(
4103 vec![RangeDecoration::new(0..0).with_style(RangeDecorationStyle::Block)],
4104 cx,
4105 );
4106 });
4107 window.draw(cx).clear(cx);
4108 window.draw(cx).clear(cx);
4109 let state = textarea.read(cx);
4110 let layout = state.last_layout.as_ref().unwrap();
4111 let line_height = layout.line_height;
4112 let corners =
4113 TextElement::<crate::input::TextareaMode>::layout_range_corners(&(2..7), layout)
4114 .unwrap();
4115 assert_eq!(corners.len(), 1);
4116 assert_eq!(corners[0].top_left.y, layout.visible_top + line_height);
4117 assert_eq!(corners[0].bottom_left.y - corners[0].top_left.y, px(120.));
4118 assert_eq!(
4119 (corners[0].top_left.x, corners[0].top_right.x),
4120 (px(0.), px(200.))
4121 );
4122 let element = TextElement::new(textarea.clone());
4123 let quads = element.layout_range_decoration_quads(layout, &state.input_bounds, cx);
4124 assert_eq!(quads[0].bounds.size.height, line_height * 2. + px(120.));
4125 });
4126 }
4127
4128 #[cfg(target_os = "linux")]
4129 #[test]
4130 fn textarea_decorations_render_fill_and_wrap_like_the_editor() {
4131 let platform = gpui_platform::current_platform(true);
4132 let mut cx = TestAppContext::build_with_text_system(
4133 gpui::TestDispatcher::new(0),
4134 None,
4135 platform.text_system(),
4136 );
4137 cx.update(crate::init);
4138 let text = "iiiiiiii ".repeat(8);
4139 let mono_range = 9..35;
4140 let mut textarea = None;
4141 let window = cx.open_window(size(px(240.), px(140.)), |window, cx| {
4142 let state = cx.new(|cx| {
4143 crate::input::TextareaState::new(window, cx)
4144 .rows(4)
4145 .default_value(text.clone())
4146 });
4147 textarea = Some(state.clone());
4148 TextareaHarness(state)
4149 });
4150 let textarea = textarea.unwrap();
4151 let mut cx = VisualTestContext::from_window(window.into(), &mut cx);
4152 cx.update(|window, cx| {
4153 window.draw(cx).clear(cx);
4154 let plain_rows: Vec<_> = textarea.read(cx).last_layout.as_ref().unwrap().lines[0]
4155 .wrapped_lines
4156 .iter()
4157 .map(|row| row.len)
4158 .collect();
4159 let collection = textarea.update(cx, |state, cx| {
4160 state.create_range_decorations_collection(
4161 vec![
4162 RangeDecoration::new(mono_range.clone())
4163 .with_style(RangeDecorationStyle::Fill),
4164 ],
4165 cx,
4166 );
4167 state.create_decorations_collection(Vec::new(), cx)
4168 });
4169 collection.set(
4170 vec![
4171 TextDecoration::new(mono_range.clone(), HighlightStyle::default())
4172 .with_font_family("DejaVu Sans Mono"),
4173 ],
4174 cx,
4175 );
4176 window.draw(cx).clear(cx);
4177 let state = textarea.read(cx);
4178 let layout = state.last_layout.as_ref().unwrap();
4179 let line = &layout.lines[0];
4180 let rows: Vec<_> = line.wrapped_lines.iter().map(|row| row.len).collect();
4181 assert!(rows[0] < plain_rows[0], "{rows:?} vs {plain_rows:?}");
4182 for row in line.wrapped_lines.iter() {
4183 assert!(row.width <= layout.wrap_width.unwrap());
4184 }
4185 let (fills, frames) = TextElement::new(textarea.clone()).layout_range_decorations(
4186 layout,
4187 &state.input_bounds,
4188 window,
4189 state.input_bounds,
4190 cx,
4191 );
4192 assert_eq!(fills.len(), 1);
4193 assert!(frames.is_empty());
4194 assert_eq!(collection.get_ranges(cx), vec![mono_range.clone()]);
4195 });
4196 cx.update(|window, cx| {
4197 textarea.update(cx, |state, cx| {
4198 state.set_selected_range(0..0, cx);
4199 state.replace_text_in_range(None, "X", window, cx);
4200 let layers = state.extras.decoration_layers();
4201 assert_eq!(layers.into_iter().flatten().next().unwrap().range, 10..36);
4202 });
4203 });
4204 }
4205
4206 #[gpui::test]
4207 fn horizontal_scroll_is_clamped_before_text_and_caret_layout(cx: &mut TestAppContext) {
4208 let (editor, window) = decoration_editor(cx, "short text", false);
4209 let mut cx = VisualTestContext::from_window(window.into(), cx);
4210 cx.update(|window, cx| {
4211 window.draw(cx).clear(cx);
4212 let state = editor.read(cx);
4213 let layout = state.last_layout.clone().unwrap();
4214 let input_bounds = state.input_bounds;
4215 let scroll_size = input_bounds.size;
4216 let element = TextElement::new(editor.clone());
4217 let mut bounds = input_bounds;
4218 let (baseline, _, _) =
4219 element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx);
4220
4221 // Both a stale offset after deletion and a deferred scroll target must
4222 // be limited before either text or carets are positioned this frame.
4223 for deferred in [None, Some(point(px(-80.), px(0.)))] {
4224 editor.update(cx, |state, _| {
4225 state.scroll_handle.set_offset(point(px(-40.), px(0.)));
4226 state.deferred_scroll_offset = deferred;
4227 });
4228 let mut bounds = input_bounds;
4229 let (carets, offset, _) =
4230 element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx);
4231 assert_eq!(offset.x, px(0.));
4232 assert_eq!(bounds.origin.x, input_bounds.origin.x);
4233 assert_eq!(carets.len(), baseline.len());
4234 for (caret, original) in carets.iter().zip(&baseline) {
4235 assert_eq!(caret.bounds.origin.x, original.bounds.origin.x);
4236 }
4237 editor.update(cx, |state, cx| {
4238 state.scroll_size = scroll_size;
4239 state.update_scroll_offset(Some(offset), cx);
4240 assert_eq!(state.scroll_handle.offset().x, offset.x);
4241 });
4242 }
4243 });
4244 }
4245
4246 #[gpui::test]
4247 fn aligned_horizontal_scroll_clamps_deferred_targets(cx: &mut TestAppContext) {
4248 let (editor, window) = decoration_editor(cx, &"wide text ".repeat(80), false);
4249 let mut cx = VisualTestContext::from_window(window.into(), cx);
4250 cx.update(|window, cx| {
4251 window.draw(cx).clear(cx);
4252 let mut layout = editor.read(cx).last_layout.clone().unwrap();
4253 let input_bounds = editor.read(cx).input_bounds;
4254 let element = TextElement::new(editor.clone());
4255
4256 for alignment in [TextAlign::Left, TextAlign::Right, TextAlign::Center] {
4257 layout.text_align = alignment;
4258 for overflow in [px(0.), px(120.)] {
4259 let scroll_size =
4260 size(input_bounds.size.width + overflow, input_bounds.size.height);
4261 let minimum = if alignment == TextAlign::Left {
4262 -overflow
4263 } else {
4264 -overflow - CURSOR_WIDTH
4265 };
4266 editor.update(cx, |state, _| {
4267 state.text_align = alignment;
4268 state.last_selected_range = Some(*state.active_selection());
4269 state.deferred_scroll_offset = Some(point(minimum, px(0.)));
4270 });
4271 let mut bounds = input_bounds;
4272 let (expected, _, _) =
4273 element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx);
4274
4275 for target in [minimum - px(100.), px(100.)] {
4276 editor.update(cx, |state, _| {
4277 state.deferred_scroll_offset = Some(point(target, px(0.)));
4278 });
4279 let mut bounds = input_bounds;
4280 let (carets, offset, _) =
4281 element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx);
4282 let expected_offset = if target < minimum { minimum } else { px(0.) };
4283 assert_eq!(offset.x, expected_offset);
4284 assert_eq!(bounds.left(), input_bounds.left() + expected_offset);
4285 if target < minimum {
4286 assert_eq!(carets[0].bounds, expected[0].bounds);
4287 }
4288 if alignment == TextAlign::Right {
4289 assert!(carets[0].bounds.right() <= input_bounds.right());
4290 }
4291 editor.update(cx, |state, cx| {
4292 state.scroll_size = scroll_size;
4293 state.update_scroll_offset(Some(offset), cx);
4294 assert_eq!(state.scroll_handle.offset().x, expected_offset);
4295 });
4296 }
4297 }
4298 }
4299 });
4300 }
4301
4302 #[gpui::test]
4303 fn deferred_horizontal_scroll_moves_every_caret(cx: &mut TestAppContext) {
4304 use super::super::{cursor::CursorSelection, selection::CursorId};
4305
4306 let (editor, window) = decoration_editor(cx, &"wide text ".repeat(80), false);
4307 let mut cx = VisualTestContext::from_window(window.into(), cx);
4308 cx.update(|window, cx| {
4309 window.draw(cx).clear(cx);
4310 let layout = editor.read(cx).last_layout.clone().unwrap();
4311 let input_bounds = editor.read(cx).input_bounds;
4312 let scroll_size = size(input_bounds.size.width + px(120.), input_bounds.size.height);
4313 let element = TextElement::new(editor.clone());
4314
4315 for offsets in [[0, 2, 4], [0, 4, 2], [4, 0, 2]] {
4316 editor.update(cx, |state, _| {
4317 state.selections.replace_all(
4318 offsets
4319 .into_iter()
4320 .enumerate()
4321 .map(|(id, offset)| {
4322 CursorSelection::new(CursorId::new(id), offset, offset)
4323 })
4324 .collect(),
4325 );
4326 state.last_selected_range = Some(*state.active_selection());
4327 state.scroll_handle.set_offset(point(px(0.), px(0.)));
4328 state.deferred_scroll_offset = None;
4329 });
4330 let mut bounds = input_bounds;
4331 let (baseline, _, _) =
4332 element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx);
4333 editor.update(cx, |state, _| {
4334 state.deferred_scroll_offset = Some(point(px(-60.), px(0.)));
4335 });
4336 let mut bounds = input_bounds;
4337 let (carets, offset, _) =
4338 element.layout_cursors(&layout, &mut bounds, scroll_size, window, cx);
4339 assert_eq!(offset.x, px(-60.));
4340 assert_eq!(carets.len(), 3);
4341 for (caret, original) in carets.iter().zip(baseline) {
4342 assert_eq!(caret.bounds.left(), original.bounds.left() - px(60.));
4343 }
4344 }
4345 });
4346 }
4347
4348 #[gpui::test]
4349 fn editor_line_number_gutter_resizes_with_document_lines(cx: &mut TestAppContext) {
4350 let (editor, window) = decoration_editor(cx, &"x\n".repeat(8), false);
4351 let mut cx = VisualTestContext::from_window(window.into(), cx);
4352 cx.update(|window, cx| {
4353 window.draw(cx).clear(cx);
4354 let narrow = editor
4355 .read(cx)
4356 .last_layout
4357 .as_ref()
4358 .unwrap()
4359 .line_number_width;
4360
4361 let longer_text = "x\n".repeat(99);
4362 editor.update(cx, |state, cx| {
4363 state.set_value(longer_text.as_str(), window, cx)
4364 });
4365 window.draw(cx).clear(cx);
4366 let middle = editor
4367 .read(cx)
4368 .last_layout
4369 .as_ref()
4370 .unwrap()
4371 .line_number_width;
4372 assert_eq!(middle, narrow, "one to three digits must share a width");
4373
4374 let longest_text = "x\n".repeat(999);
4375 editor.update(cx, |state, cx| {
4376 state.set_value(longest_text.as_str(), window, cx)
4377 });
4378 window.draw(cx).clear(cx);
4379 let wide = editor
4380 .read(cx)
4381 .last_layout
4382 .as_ref()
4383 .unwrap()
4384 .line_number_width;
4385
4386 assert!(
4387 wide > narrow,
4388 "more line-number digits must widen the gutter"
4389 );
4390 });
4391 }
4392
4393 #[gpui::test]
4394 fn geometric_decorations_clip_scrolled_viewport_and_cull_offscreen_ranges(
4395 cx: &mut TestAppContext,
4396 ) {
4397 let text = "abcdefghij\n".repeat(100);
4398 let (editor, window) = decoration_editor(cx, &text, false);
4399 let mut cx = VisualTestContext::from_window(window.into(), cx);
4400 cx.update(|window, cx| {
4401 editor.update(cx, |state, cx| {
4402 state.create_range_decorations_collection(
4403 vec![
4404 RangeDecoration::new(0..text.len()).with_style(RangeDecorationStyle::Fill),
4405 RangeDecoration::new(0..text.len()),
4406 RangeDecoration::new(0..3),
4407 RangeDecoration::new(text.len() - 3..text.len()),
4408 ],
4409 cx,
4410 );
4411 });
4412 window.draw(cx).clear(cx);
4413 editor.update(cx, |state, cx| {
4414 let height = state.last_layout.as_ref().unwrap().line_height;
4415 state.set_scroll_offset(point(px(0.), -height * 40.), cx);
4416 });
4417 // Deferred scroll is committed by prepaint and reflected next frame.
4418 window.draw(cx).clear(cx);
4419 window.draw(cx).clear(cx);
4420 let state = editor.read(cx);
4421 let layout = state.last_layout.as_ref().unwrap();
4422 assert!(layout.visible_range_offset.start > 0);
4423 assert!(layout.visible_range_offset.end < text.len());
4424 let all =
4425 TextElement::<EditorMode>::layout_range_corners(&(0..text.len()), layout).unwrap();
4426 let clipped = TextElement::<EditorMode>::layout_range_corners(
4427 &layout.visible_range_offset,
4428 layout,
4429 )
4430 .unwrap();
4431 assert_eq!(all, clipped);
4432 assert!(!all.is_empty());
4433 assert!(TextElement::<EditorMode>::layout_range_corners(&(0..3), layout).is_none());
4434 // Also execute the production path building seam, not just the corner helper.
4435 let (fills, frames) = TextElement::new(editor.clone()).layout_range_decorations(
4436 layout,
4437 &state.input_bounds,
4438 window,
4439 state.input_bounds,
4440 cx,
4441 );
4442 assert_eq!(fills.len(), 1);
4443 assert_eq!(frames.len(), 1);
4444 });
4445 }
4446
4447 #[gpui::test]
4448 fn geometric_decorations_use_shaped_wrap_boundaries_and_newline_cells(cx: &mut TestAppContext) {
4449 let text = " héllo world héllo world héllo world héllo world\n\nlast";
4450 let (editor, window) = decoration_editor(cx, text, true);
4451 let mut cx = VisualTestContext::from_window(window.into(), cx);
4452 cx.update(|window, cx| {
4453 window.draw(cx).clear(cx);
4454 let state = editor.read(cx);
4455 let layout = state.last_layout.as_ref().unwrap();
4456 let first = &layout.lines[0];
4457 assert!(first.wrapped_lines.len() > 1);
4458 assert!(first.wrap_indent > px(0.));
4459 let boundary = first.wrapped_lines[0].len;
4460 let first_row =
4461 TextElement::<EditorMode>::layout_range_corners(&(0..boundary), layout).unwrap();
4462 assert_eq!(
4463 first_row.len(),
4464 1,
4465 "a wrap end must not open the next visual row"
4466 );
4467 assert_eq!(first_row[0].top_right.x, first.wrapped_lines[0].width);
4468 let rest =
4469 TextElement::<EditorMode>::layout_range_corners(&(boundary..first.len()), layout)
4470 .unwrap();
4471 assert_eq!(rest.len(), first.wrapped_lines.len() - 1);
4472 assert_eq!(rest[0].top_left.y, layout.visible_top + layout.line_height);
4473 for (index, corners) in rest.iter().enumerate() {
4474 assert_eq!(
4475 corners.top_right.x,
4476 first.wrap_indent + first.wrapped_lines[index + 1].width
4477 );
4478 assert_eq!(
4479 corners.bottom_left.y - corners.top_left.y,
4480 layout.line_height
4481 );
4482 }
4483 let blank_offset = text.find("\n\n").unwrap() + 1;
4484 let blank = TextElement::<EditorMode>::layout_range_corners(
4485 &(blank_offset..blank_offset + 1),
4486 layout,
4487 )
4488 .unwrap();
4489 assert_eq!(blank.len(), 1);
4490 assert_eq!(
4491 blank[0].top_right.x - blank[0].top_left.x,
4492 layout.space_width
4493 );
4494 // A later-line decoration cannot paint the first row via saturating_sub.
4495 let last_offset = text.rfind("last").unwrap();
4496 let last =
4497 TextElement::<EditorMode>::layout_range_corners(&(last_offset..text.len()), layout)
4498 .unwrap();
4499 assert_eq!(last.len(), 1);
4500 assert!(last[0].top_left.y > rest.last().unwrap().top_left.y);
4501 });
4502 }
4503
4504 #[gpui::test]
4505 fn geometric_decorations_include_crlf_boundaries(cx: &mut TestAppContext) {
4506 let text = "one\r\ntwo\r\nthree";
4507 let (editor, window) = decoration_editor(cx, text, false);
4508 let mut cx = VisualTestContext::from_window(window.into(), cx);
4509 cx.update(|window, cx| {
4510 editor.update(cx, |state, cx| {
4511 state.create_range_decorations_collection(
4512 vec![
4513 RangeDecoration::new(0..8),
4514 RangeDecoration::new(3..5),
4515 RangeDecoration::new(4..5),
4516 RangeDecoration::new(5..8),
4517 RangeDecoration::new(9..10),
4518 ],
4519 cx,
4520 );
4521 });
4522 window.draw(cx).clear(cx);
4523 let state = editor.read(cx);
4524 let layout = state.last_layout.as_ref().unwrap();
4525 // Shaping retains '\r'; only '\n' needs an additional newline cell.
4526 assert_eq!(layout.lines[0].len(), "one\r".len());
4527 assert_eq!(layout.visible_line_byte_offsets, vec![0, 5, 10]);
4528 let spanning =
4529 TextElement::<EditorMode>::layout_range_corners(&(0..8), layout).unwrap();
4530 assert_eq!(spanning.len(), 2);
4531 for range in [3..5, 4..5, 9..10] {
4532 let corners =
4533 TextElement::<EditorMode>::layout_range_corners(&range, layout).unwrap();
4534 assert_eq!(corners.len(), 1);
4535 assert!(corners[0].top_right.x > corners[0].top_left.x);
4536 }
4537 let (fills, frames) = TextElement::new(editor.clone()).layout_range_decorations(
4538 layout,
4539 &state.input_bounds,
4540 window,
4541 state.input_bounds,
4542 cx,
4543 );
4544 assert!(fills.is_empty());
4545 assert_eq!(frames.len(), 5);
4546 });
4547 }
4548
4549 #[gpui::test]
4550 fn geometric_decorations_project_folds_without_changing_tracked_ranges(
4551 cx: &mut TestAppContext,
4552 ) {
4553 let text = "top\nhidden one\nhidden two\nend\nlast";
4554 let (editor, window) = decoration_editor(cx, text, false);
4555 let mut cx = VisualTestContext::from_window(window.into(), cx);
4556 cx.update(|window, cx| {
4557 let hidden = 4..text.find("end").unwrap();
4558 let collection = editor.update(cx, |state, cx| {
4559 state.apply_highlighter_fold_candidates(vec![FoldRange::new(0, 3)], cx);
4560 state.display_map.set_folded(0, true);
4561 state.create_range_decorations_collection(
4562 vec![RangeDecoration::new(hidden.clone())],
4563 cx,
4564 )
4565 });
4566 window.draw(cx).clear(cx);
4567 {
4568 let state = editor.read(cx);
4569 let layout = state.last_layout.as_ref().unwrap();
4570 assert_eq!(layout.visible_buffer_lines, vec![0, 3, 4]);
4571 assert!(TextElement::<EditorMode>::layout_range_corners(&hidden, layout).is_none());
4572 let (_, frames) = TextElement::new(editor.clone()).layout_range_decorations(
4573 layout,
4574 &state.input_bounds,
4575 window,
4576 state.input_bounds,
4577 cx,
4578 );
4579 assert!(frames.is_empty());
4580 let spanning =
4581 TextElement::<EditorMode>::layout_range_corners(&(0..text.len()), layout)
4582 .unwrap();
4583 assert_eq!(spanning.len(), 3);
4584 assert_eq!(spanning[1].top_left.y, spanning[0].bottom_left.y);
4585 }
4586 assert_eq!(collection.get_ranges(cx), vec![hidden.clone()]);
4587 editor.update(cx, |state, cx| {
4588 state.display_map.set_folded(0, false);
4589 cx.notify();
4590 });
4591 window.draw(cx).clear(cx);
4592 let state = editor.read(cx);
4593 let layout = state.last_layout.as_ref().unwrap();
4594 let revealed =
4595 TextElement::<EditorMode>::layout_range_corners(&hidden, layout).unwrap();
4596 assert_eq!(revealed.len(), 2);
4597 assert_eq!(collection.get_ranges(cx), vec![hidden]);
4598 });
4599 }
4600
4601 #[gpui::test]
4602 fn geometric_decorations_track_edits_history_replacement_and_owner_lifetime(
4603 cx: &mut TestAppContext,
4604 ) {
4605 let (editor, window) = decoration_editor(cx, "abc def", false);
4606 let mut cx = VisualTestContext::from_window(window.into(), cx);
4607 cx.update(|window, cx| {
4608 let (first, second) = editor.update(cx, |state, cx| {
4609 (
4610 state.create_range_decorations_collection(vec![RangeDecoration::new(4..7)], cx),
4611 state.create_range_decorations_collection(vec![RangeDecoration::new(0..3)], cx),
4612 )
4613 });
4614 editor.update(cx, |state, cx| {
4615 state.set_selected_range(0..0, cx);
4616 state.replace_text_in_range(None, "\n", window, cx);
4617 });
4618 assert_eq!(first.get_ranges(cx), vec![5..8]);
4619 editor.update(cx, |state, cx| state.undo(&Undo, window, cx));
4620 assert_eq!(first.get_ranges(cx), vec![4..7]);
4621 editor.update(cx, |state, cx| state.redo(&Redo, window, cx));
4622 assert_eq!(first.get_ranges(cx), vec![5..8]);
4623 first.clear(cx);
4624 assert_eq!(second.get_ranges(cx), vec![1..4]);
4625 first.append(vec![RangeDecoration::new(5..8)], cx);
4626 editor.update(cx, |state, cx| state.replace_all("formatted", window, cx));
4627 assert_eq!(first.get_ranges(cx), vec![0..9]);
4628 editor.update(cx, |state, cx| state.undo(&Undo, window, cx));
4629 // Annotations are transformed, not snapshotted in undo history.
4630 assert_eq!(first.get_ranges(cx), vec![0..8]);
4631 editor.update(cx, |state, cx| state.set_value("new", window, cx));
4632 assert_eq!(first.get_ranges(cx), vec![0..3]);
4633 let clone = first.clone();
4634 first.dispose(cx);
4635 clone.append(vec![RangeDecoration::new(0..1)], cx);
4636 assert!(clone.get_ranges(cx).is_empty());
4637 assert_eq!(second.get_ranges(cx), vec![0..3]);
4638 editor.update(cx, |state, cx| state.set_value("", window, cx));
4639 assert!(second.get_ranges(cx).is_empty());
4640 window.draw(cx).clear(cx);
4641 });
4642 }
4643
4644 #[test]
4645 fn frame_outline_is_continuous_across_different_line_widths() {
4646 let corners = [
4647 Corners {
4648 top_left: point(px(2.), px(0.)),
4649 top_right: point(px(20.), px(0.)),
4650 bottom_left: point(px(2.), px(10.)),
4651 bottom_right: point(px(20.), px(10.)),
4652 },
4653 Corners {
4654 top_left: point(px(0.), px(10.)),
4655 top_right: point(px(12.), px(10.)),
4656 bottom_left: point(px(0.), px(20.)),
4657 bottom_right: point(px(12.), px(20.)),
4658 },
4659 ];
4660
4661 assert_eq!(
4662 frame_outline_points(&corners),
4663 vec![
4664 point(px(2.), px(0.)),
4665 point(px(20.), px(0.)),
4666 point(px(20.), px(10.)),
4667 point(px(12.), px(10.)),
4668 point(px(12.), px(20.)),
4669 point(px(0.), px(20.)),
4670 point(px(0.), px(10.)),
4671 point(px(2.), px(10.)),
4672 point(px(2.), px(0.)),
4673 ]
4674 );
4675 }
4676
4677 #[test]
4678 fn frame_outline_keeps_horizontal_space_between_the_stroke_and_text() {
4679 let corners = [Corners {
4680 top_left: point(px(2.), px(0.)),
4681 top_right: point(px(20.), px(0.)),
4682 bottom_left: point(px(2.), px(10.)),
4683 bottom_right: point(px(20.), px(10.)),
4684 }];
4685
4686 assert_eq!(
4687 pad_frame_corners(&corners, px(1.)),
4688 vec![Corners {
4689 top_left: point(px(1.), px(0.)),
4690 top_right: point(px(21.), px(0.)),
4691 bottom_left: point(px(1.), px(10.)),
4692 bottom_right: point(px(21.), px(10.)),
4693 }]
4694 );
4695
4696 let points = frame_outline_points(&corners);
4697 assert_eq!(points.first(), points.last());
4698 }
4699
4700 #[test]
4701 fn frame_outline_stroke_is_aligned_to_physical_pixels_at_each_scale_factor() {
4702 let points = vec![point(px(0.2), px(1.8)), point(px(10.7), px(20.3))];
4703
4704 for (scale_factor, expected_width, expected_points) in [
4705 (
4706 1.,
4707 px(1.),
4708 vec![point(px(0.5), px(1.5)), point(px(10.5), px(20.5))],
4709 ),
4710 (
4711 1.5,
4712 px(2. / 3.),
4713 vec![
4714 point(px(1. / 3.), px(5. / 3.)),
4715 point(px(11.), px(61. / 3.)),
4716 ],
4717 ),
4718 (
4719 2.,
4720 px(1.),
4721 vec![point(px(0.), px(2.)), point(px(10.5), px(20.5))],
4722 ),
4723 ] {
4724 let (width, snapped) = snap_frame_outline(&points, px(1.), scale_factor);
4725 assert_eq!(width, expected_width);
4726 assert_eq!(snapped, expected_points);
4727 }
4728 }
4729
4730 #[test]
4731 fn frame_outline_keeps_its_vertical_edges_inside_the_content_mask() {
4732 let points = vec![
4733 point(px(9.5), px(2.5)),
4734 point(px(20.5), px(2.5)),
4735 point(px(20.5), px(10.5)),
4736 point(px(9.5), px(10.5)),
4737 point(px(9.5), px(2.5)),
4738 ];
4739 let mask = Bounds::new(point(px(10.), px(0.)), size(px(10.), px(20.)));
4740
4741 assert_eq!(
4742 clamp_frame_to_content_mask(points, px(1.), mask),
4743 vec![
4744 point(px(10.5), px(2.5)),
4745 point(px(19.5), px(2.5)),
4746 point(px(19.5), px(10.5)),
4747 point(px(10.5), px(10.5)),
4748 point(px(10.5), px(2.5)),
4749 ]
4750 );
4751 }
4752
4753 #[test]
4754 fn test_plain_text_decorations_include_unstyled_gaps() {
4755 let decoration = HighlightStyle {
4756 background_color: Some(gpui::red()),
4757 ..Default::default()
4758 };
4759 let styles = compose_decorations(Vec::new(), [(2..5, decoration)], 0..10).unwrap();
4760
4761 assert_eq!(
4762 styles
4763 .iter()
4764 .map(|(range, _)| range.clone())
4765 .collect::<Vec<_>>(),
4766 vec![0..2, 2..5, 5..10]
4767 );
4768 assert_eq!(styles[0].1, HighlightStyle::default());
4769 assert_eq!(styles[1].1.background_color, Some(gpui::red()));
4770 assert_eq!(styles[2].1, HighlightStyle::default());
4771 }
4772
4773 #[test]
4774 fn test_first_decoration_collection_has_precedence() {
4775 let first = [TextDecoration::new(
4776 0..4,
4777 HighlightStyle {
4778 background_color: Some(gpui::red()),
4779 ..Default::default()
4780 },
4781 )];
4782 let second = [TextDecoration::new(
4783 0..4,
4784 HighlightStyle {
4785 background_color: Some(gpui::blue()),
4786 ..Default::default()
4787 },
4788 )];
4789
4790 let styles =
4791 compose_decoration_collections(Vec::new(), [&first[..], &second[..]], 0..4).unwrap();
4792
4793 assert_eq!(styles.len(), 1);
4794 assert_eq!(styles[0].1.background_color, Some(gpui::red()));
4795 }
4796
4797 #[test]
4798 fn test_decorations_override_syntax_highlights() {
4799 let syntax = vec![(
4800 0..8,
4801 HighlightStyle {
4802 color: Some(gpui::blue()),
4803 ..Default::default()
4804 },
4805 )];
4806 let decoration = HighlightStyle {
4807 color: Some(gpui::red()),
4808 font_style: Some(gpui::FontStyle::Italic),
4809 ..Default::default()
4810 };
4811
4812 let styles = compose_decorations(syntax, [(2..6, decoration)], 0..8).unwrap();
4813
4814 assert_eq!(styles[1].0, 2..6);
4815 assert_eq!(styles[1].1.color, Some(gpui::red()));
4816 assert_eq!(styles[1].1.font_style, Some(gpui::FontStyle::Italic));
4817 }
4818
4819 #[test]
4820 fn test_editor_scrollbar_layout_uses_current_scroll_size() {
4821 let input_bounds = Bounds::new(point(px(10.), px(20.)), size(px(300.), px(80.)));
4822 let paddings = Edges {
4823 top: px(2.),
4824 right: px(3.),
4825 bottom: px(5.),
4826 left: px(7.),
4827 };
4828
4829 let layout =
4830 EditorScrollbarLayout::new(input_bounds, px(40.), size(px(1000.), px(200.)), paddings);
4831
4832 assert_eq!(
4833 layout.bounds,
4834 Bounds::new(point(px(51.), px(18.)), size(px(262.), px(87.)))
4835 );
4836 assert_eq!(layout.scroll_size, size(px(972.), px(200.)));
4837
4838 let layout_without_gutter =
4839 EditorScrollbarLayout::new(input_bounds, px(0.), size(px(500.), px(120.)), paddings);
4840
4841 assert_eq!(
4842 layout_without_gutter.bounds,
4843 Bounds::new(point(px(10.), px(18.)), size(px(303.), px(87.)))
4844 );
4845 assert_eq!(layout_without_gutter.scroll_size, size(px(513.), px(120.)));
4846 }
4847
4848 #[test]
4849 fn test_editor_gutter_covers_the_complete_fixed_column() {
4850 let input_bounds = Bounds::new(point(px(10.), px(20.)), size(px(300.), px(80.)));
4851
4852 assert_eq!(
4853 editor_gutter_bounds(
4854 input_bounds,
4855 px(48.),
4856 px(16.),
4857 Edges {
4858 top: px(2.),
4859 right: px(3.),
4860 bottom: px(5.),
4861 left: px(7.),
4862 },
4863 ),
4864 Bounds::new(point(px(3.), px(18.)), size(px(55.), px(103.)))
4865 );
4866 }
4867
4868 #[test]
4869 fn test_auto_grow_scroll_offset_is_clamped_to_current_viewport() {
4870 let mode = LayoutMode::auto_grow(3, 8);
4871
4872 assert_eq!(
4873 clamp_auto_grow_vertical_scroll_offset(&mode, px(-260.), px(340.), px(160.)),
4874 px(-180.)
4875 );
4876 assert_eq!(
4877 clamp_auto_grow_vertical_scroll_offset(&mode, px(-40.), px(340.), px(160.)),
4878 px(-40.)
4879 );
4880 assert_eq!(
4881 clamp_auto_grow_vertical_scroll_offset(&mode, px(20.), px(340.), px(160.)),
4882 px(0.)
4883 );
4884
4885 let plain_text = LayoutMode::plain_text();
4886 assert_eq!(
4887 clamp_auto_grow_vertical_scroll_offset(&plain_text, px(-260.), px(340.), px(160.)),
4888 px(-260.)
4889 );
4890 }
4891
4892 #[test]
4893 fn test_runs_for_range() {
4894 let run = TextRun {
4895 len: 0,
4896 font: gpui::font(".SystemUIFont"),
4897 color: gpui::black(),
4898 background_color: None,
4899 underline: None,
4900 strikethrough: None,
4901 };
4902
4903 // use hello this-is-test
4904 let runs = vec![
4905 // use
4906 TextRun {
4907 len: 3,
4908 ..run.clone()
4909 },
4910 // \s
4911 TextRun {
4912 len: 1,
4913 ..run.clone()
4914 },
4915 // hello
4916 TextRun {
4917 len: 5,
4918 ..run.clone()
4919 },
4920 // \s
4921 TextRun {
4922 len: 1,
4923 ..run.clone()
4924 },
4925 // this-is-test
4926 TextRun {
4927 len: 12,
4928 ..run.clone()
4929 },
4930 ];
4931
4932 #[track_caller]
4933 fn assert_runs(actual: Vec<TextRun>, expected: &[usize]) {
4934 let left = actual.iter().map(|run| run.len).collect::<Vec<_>>();
4935 assert_eq!(left, expected);
4936 }
4937
4938 assert_runs(runs_for_range(&runs, 0, &(0..0)), &[]);
4939 assert_runs(runs_for_range(&runs, 0, &(0..100)), &[3, 1, 5, 1, 12]);
4940
4941 assert_runs(runs_for_range(&runs, 0, &(0..6)), &[3, 1, 2]);
4942 assert_runs(runs_for_range(&runs, 0, &(1..6)), &[2, 1, 2]);
4943 assert_runs(runs_for_range(&runs, 0, &(3..10)), &[1, 5, 1]);
4944 assert_runs(runs_for_range(&runs, 0, &(5..8)), &[3]);
4945 assert_runs(runs_for_range(&runs, 3, &(0..3)), &[1, 2]);
4946 assert_runs(runs_for_range(&runs, 3, &(2..10)), &[4, 1, 3]);
4947 assert_runs(runs_for_range(&runs, 9, &(0..8)), &[1, 7]);
4948 }
4949
4950 #[test]
4951 fn test_split_runs_preserve_ime_underline_across_highlight_boundaries() {
4952 let underline = UnderlineStyle {
4953 thickness: px(1.),
4954 color: Some(gpui::black()),
4955 wavy: false,
4956 };
4957
4958 let runs = [0..4, 4..10]
4959 .into_iter()
4960 .flat_map(|range| {
4961 split_run_for_ime_underline(
4962 TextStyle::default().to_run(range.len()),
4963 range,
4964 Some(2..7),
4965 Some(underline),
4966 )
4967 })
4968 .collect::<Vec<_>>();
4969
4970 assert_eq!(
4971 runs.iter()
4972 .map(|run| (run.len, run.underline.is_some()))
4973 .collect::<Vec<_>>(),
4974 vec![(2, false), (2, true), (3, true), (3, false)]
4975 );
4976 }
4977
4978 #[test]
4979 fn test_split_run_applies_ime_underline_without_highlighting() {
4980 let underline = UnderlineStyle {
4981 thickness: px(1.),
4982 color: Some(gpui::black()),
4983 wavy: false,
4984 };
4985
4986 let runs = split_run_for_ime_underline(
4987 TextStyle::default().to_run(10),
4988 0..10,
4989 Some(2..7),
4990 Some(underline),
4991 );
4992
4993 assert_eq!(
4994 runs.iter()
4995 .map(|run| (run.len, run.underline.is_some()))
4996 .collect::<Vec<_>>(),
4997 vec![(2, false), (5, true), (3, false)]
4998 );
4999 assert!(
5000 split_run_for_ime_underline(TextStyle::default().to_run(0), 0..0, None, None)
5001 .is_empty()
5002 );
5003 }
5004
5005 #[test]
5006 fn test_masked_ime_underline_splits_on_mask_char_boundaries() {
5007 let underline = UnderlineStyle {
5008 thickness: px(1.),
5009 color: Some(gpui::black()),
5010 wavy: false,
5011 };
5012 let text = Rope::from("abcdef");
5013 let mask_len = MASK_CHAR.len_utf8();
5014
5015 assert_eq!(
5016 ime_marked_display_range(&text, Some(4..6), false),
5017 Some(4..6)
5018 );
5019 assert_eq!(ime_marked_display_range(&text, None, true), None);
5020 assert_eq!(
5021 ime_marked_display_range(&text, Some(4..6), true),
5022 Some(4 * mask_len..6 * mask_len)
5023 );
5024
5025 let display_text = MASK_CHAR.to_string().repeat(text.chars().count());
5026 let runs = split_run_for_ime_underline(
5027 TextStyle::default().to_run(display_text.len()),
5028 0..display_text.len(),
5029 ime_marked_display_range(&text, Some(4..6), true),
5030 Some(underline),
5031 );
5032
5033 let mut offset = 0;
5034 for run in &runs {
5035 assert!(display_text.is_char_boundary(offset));
5036 offset += run.len;
5037 }
5038 assert_eq!(offset, display_text.len());
5039 }
5040
5041 #[test]
5042 fn test_placeholder_line_runs() {
5043 let run = TextRun {
5044 len: 0,
5045 font: gpui::font(".SystemUIFont"),
5046 color: gpui::black(),
5047 background_color: None,
5048 underline: None,
5049 strikethrough: None,
5050 };
5051
5052 let runs = vec![
5053 TextRun {
5054 len: 2,
5055 ..run.clone()
5056 },
5057 TextRun {
5058 len: 2,
5059 ..run.clone()
5060 },
5061 TextRun { len: 1, ..run },
5062 ];
5063
5064 let placeholder_runs = placeholder_line_runs("ab\n\nc", &runs);
5065
5066 let lines = placeholder_runs
5067 .iter()
5068 .map(|(line, _)| *line)
5069 .collect::<Vec<_>>();
5070 assert_eq!(lines, vec!["ab", "", "c"]);
5071
5072 let run_lengths = placeholder_runs
5073 .iter()
5074 .map(|(_, line_runs)| line_runs.iter().map(|run| run.len).collect::<Vec<_>>())
5075 .collect::<Vec<_>>();
5076 assert_eq!(run_lengths, vec![vec![2], vec![], vec![1]]);
5077 }
5078
5079 #[test]
5080 fn test_align_runs_to_char_boundaries() {
5081 let run = TextRun {
5082 len: 0,
5083 font: gpui::font(".SystemUIFont"),
5084 color: gpui::blue(),
5085 background_color: None,
5086 underline: None,
5087 strikethrough: None,
5088 };
5089 let runs = |lens: &[usize]| {
5090 lens.iter()
5091 .map(|&len| TextRun { len, ..run.clone() })
5092 .collect::<Vec<_>>()
5093 };
5094 let lens = |runs: &[TextRun]| runs.iter().map(|run| run.len).collect::<Vec<_>>();
5095
5096 // "你好,世界" is 15 bytes; boundaries at 0, 3, 6, 9, 12, 15.
5097 let text = "你好,世界";
5098
5099 // Aligned runs pass through untouched.
5100 assert_eq!(align_runs_to_char_boundaries(text, &runs(&[3, 12])), None);
5101
5102 // A mid-char boundary (4) snaps up to the next boundary (6).
5103 let aligned = align_runs_to_char_boundaries(text, &runs(&[4, 11])).unwrap();
5104 assert_eq!(lens(&aligned), vec![6, 9]);
5105
5106 // Several boundaries inside the same char collapse into one run.
5107 let aligned = align_runs_to_char_boundaries(text, &runs(&[1, 1, 13])).unwrap();
5108 assert_eq!(lens(&aligned), vec![3, 12]);
5109
5110 // Overshooting runs are capped at the text length.
5111 let aligned = align_runs_to_char_boundaries(text, &runs(&[3, 20])).unwrap();
5112 assert_eq!(lens(&aligned), vec![3, 12]);
5113
5114 // Undershooting runs keep the shortfall (the tail is left unshaped,
5115 // matching `runs_for_range` clipping).
5116 assert_eq!(align_runs_to_char_boundaries(text, &runs(&[3, 3])), None);
5117 }
5118
5119 #[test]
5120 fn test_clip_styles_to_ranges() {
5121 let style = HighlightStyle::default();
5122 let styles = vec![(0..4, style), (4..10, style), (12..20, style)];
5123
5124 // Ranges with a gap (a folded region) drop the gap coverage and split
5125 // styles that span a range edge.
5126 let clipped = clip_styles_to_ranges(styles.clone(), &[2..6, 14..18]);
5127 assert_eq!(
5128 clipped
5129 .iter()
5130 .map(|(range, _)| range.clone())
5131 .collect::<Vec<_>>(),
5132 vec![2..4, 4..6, 14..18]
5133 );
5134
5135 // Styles fully inside the ranges are unchanged.
5136 let clipped = clip_styles_to_ranges(styles.clone(), &[0..20]);
5137 assert_eq!(
5138 clipped
5139 .iter()
5140 .map(|(range, _)| range.clone())
5141 .collect::<Vec<_>>(),
5142 vec![0..4, 4..10, 12..20]
5143 );
5144
5145 // A single style spanning several ranges splits into one piece per range.
5146 let clipped = clip_styles_to_ranges(vec![(0..30, style)], &[5..10, 20..25]);
5147 assert_eq!(
5148 clipped
5149 .iter()
5150 .map(|(range, _)| range.clone())
5151 .collect::<Vec<_>>(),
5152 vec![5..10, 20..25]
5153 );
5154
5155 assert!(clip_styles_to_ranges(styles, &[]).is_empty());
5156 }
5157
5158 #[test]
5159 fn test_split_runs_by_bg_segments() {
5160 let run = TextRun {
5161 len: 0,
5162 font: gpui::font(".SystemUIFont"),
5163 color: gpui::blue(),
5164 background_color: None,
5165 underline: None,
5166 strikethrough: None,
5167 };
5168
5169 let runs = vec![
5170 TextRun {
5171 len: 5,
5172 ..run.clone()
5173 },
5174 TextRun {
5175 len: 7,
5176 ..run.clone()
5177 },
5178 TextRun {
5179 len: 24,
5180 ..run.clone()
5181 },
5182 ];
5183
5184 let bg_segments = vec![(8..12, gpui::red()), (12..18, gpui::blue())];
5185 let result = split_runs_by_bg_segments(5, &runs, &bg_segments);
5186 assert_eq!(
5187 result.iter().map(|run| run.len).collect::<Vec<_>>(),
5188 vec![3, 2, 2, 5, 1, 23]
5189 );
5190 assert_eq!(result[0].color, gpui::blue());
5191 assert_eq!(result[1].color, gpui::black());
5192 assert_eq!(result[2].color, gpui::black());
5193 assert_eq!(result[3].color, gpui::black());
5194 assert_eq!(result[4].color, gpui::black());
5195 assert_eq!(result[5].color, gpui::blue());
5196 }
5197
5198 #[test]
5199 fn test_empty_bottom_height_outside_code_editor() {
5200 // Single-line / plain-text / auto-grow modes never reserve empty
5201 // bottom space, regardless of any override.
5202 for override_rows in [None, Some(0), Some(3), Some(99)] {
5203 assert_eq!(
5204 empty_bottom_height(false, override_rows, px(800.), px(20.)),
5205 px(0.),
5206 );
5207 }
5208 }
5209
5210 #[test]
5211 fn test_empty_bottom_height_code_editor_default() {
5212 // `None`: roughly half the viewport, floored at
5213 // `BOTTOM_MARGIN_ROWS * line_height` so the empty area never
5214 // collapses to "less than a few lines" on tiny viewports.
5215 let line_height = px(20.);
5216
5217 // Viewport much taller than the floor → half-viewport wins.
5218 assert_eq!(
5219 empty_bottom_height(true, None, px(800.), line_height),
5220 px(400.),
5221 );
5222
5223 // Viewport shorter than 2 × floor → floor wins.
5224 let floor = BOTTOM_MARGIN_ROWS * line_height;
5225 assert_eq!(empty_bottom_height(true, None, px(40.), line_height), floor);
5226 }
5227
5228 #[test]
5229 fn test_empty_bottom_height_explicit_row_count() {
5230 // `Some(n)`: exactly `n` line-heights. Caller fully controls
5231 // the trailing empty space; viewport size doesn't amplify it.
5232 let line_height = px(20.);
5233
5234 for rows in [0_usize, 1, 3, 8, 64] {
5235 let expected = rows as f32 * line_height;
5236 assert_eq!(
5237 empty_bottom_height(true, Some(rows), px(800.), line_height),
5238 expected,
5239 );
5240 // Tiny viewport: still exactly `n × line_height`, no floor
5241 // applied when caller supplied an explicit count.
5242 assert_eq!(
5243
5244… afgekapt