1use crate::{
2 blame_entry_tooltip::{blame_entry_relative_timestamp, BlameEntryTooltip},
3 display_map::{
4 BlockContext, BlockStyle, DisplaySnapshot, HighlightedChunk, ToDisplayPoint, TransformBlock,
5 },
6 editor_settings::{
7 CurrentLineHighlight, DoubleClickInMultibuffer, MultiCursorModifier, ShowScrollbar,
8 },
9 git::{
10 blame::{CommitDetails, GitBlame},
11 diff_hunk_to_display, DisplayDiffHunk,
12 },
13 hover_popover::{
14 self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
15 },
16 hunk_status,
17 items::BufferSearchHighlights,
18 mouse_context_menu::{self, MouseContextMenu},
19 scroll::scroll_amount::ScrollAmount,
20 CodeActionsMenu, CursorShape, DisplayPoint, DisplayRow, DocumentHighlightRead,
21 DocumentHighlightWrite, Editor, EditorMode, EditorSettings, EditorSnapshot, EditorStyle,
22 ExpandExcerpts, GutterDimensions, HalfPageDown, HalfPageUp, HoveredCursor, HunkToExpand,
23 LineDown, LineUp, OpenExcerpts, PageDown, PageUp, Point, RowExt, RowRangeExt, SelectPhase,
24 Selection, SoftWrap, ToPoint, CURSORS_VISIBLE_FOR, MAX_LINE_LEN,
25};
26use client::ParticipantIndex;
27use collections::{BTreeMap, HashMap};
28use git::{blame::BlameEntry, diff::DiffHunkStatus, Oid};
29use gpui::{
30 anchored, deferred, div, fill, outline, point, px, quad, relative, size, svg,
31 transparent_black, Action, AnchorCorner, AnyElement, AvailableSpace, Bounds, ClipboardItem,
32 ContentMask, Corners, CursorStyle, DispatchPhase, Edges, Element, ElementInputHandler, Entity,
33 FontId, GlobalElementId, Hitbox, Hsla, InteractiveElement, IntoElement, Length,
34 ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
35 ParentElement, Pixels, ScrollDelta, ScrollWheelEvent, ShapedLine, SharedString, Size,
36 StatefulInteractiveElement, Style, Styled, TextRun, TextStyle, TextStyleRefinement, View,
37 ViewContext, WeakView, WindowContext,
38};
39use itertools::Itertools;
40use language::language_settings::{
41 IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings, ShowWhitespaceSetting,
42};
43use lsp::DiagnosticSeverity;
44use multi_buffer::{Anchor, MultiBufferPoint, MultiBufferRow};
45use project::{
46 project_settings::{GitGutterSetting, ProjectSettings},
47 ProjectPath,
48};
49use settings::Settings;
50use smallvec::{smallvec, SmallVec};
51use std::{
52 any::TypeId,
53 borrow::Cow,
54 cmp::{self, Ordering},
55 fmt::{self, Write},
56 iter, mem,
57 ops::{Deref, Range},
58 sync::Arc,
59};
60use sum_tree::Bias;
61use theme::{ActiveTheme, PlayerColor};
62use ui::prelude::*;
63use ui::{h_flex, ButtonLike, ButtonStyle, ContextMenu, Tooltip};
64use util::ResultExt;
65use workspace::{item::Item, Workspace};
66
67struct SelectionLayout {
68 head: DisplayPoint,
69 cursor_shape: CursorShape,
70 is_newest: bool,
71 is_local: bool,
72 range: Range<DisplayPoint>,
73 active_rows: Range<DisplayRow>,
74 user_name: Option<SharedString>,
75}
76
77impl SelectionLayout {
78 fn new<T: ToPoint + ToDisplayPoint + Clone>(
79 selection: Selection<T>,
80 line_mode: bool,
81 cursor_shape: CursorShape,
82 map: &DisplaySnapshot,
83 is_newest: bool,
84 is_local: bool,
85 user_name: Option<SharedString>,
86 ) -> Self {
87 let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
88 let display_selection = point_selection.map(|p| p.to_display_point(map));
89 let mut range = display_selection.range();
90 let mut head = display_selection.head();
91 let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
92 ..map.next_line_boundary(point_selection.end).1.row();
93
94 // vim visual line mode
95 if line_mode {
96 let point_range = map.expand_to_line(point_selection.range());
97 range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
98 }
99
100 // any vim visual mode (including line mode)
101 if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
102 && !range.is_empty()
103 && !selection.reversed
104 {
105 if head.column() > 0 {
106 head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
107 } else if head.row().0 > 0 && head != map.max_point() {
108 head = map.clip_point(
109 DisplayPoint::new(
110 head.row().previous_row(),
111 map.line_len(head.row().previous_row()),
112 ),
113 Bias::Left,
114 );
115 // updating range.end is a no-op unless you're cursor is
116 // on the newline containing a multi-buffer divider
117 // in which case the clip_point may have moved the head up
118 // an additional row.
119 range.end = DisplayPoint::new(head.row().next_row(), 0);
120 active_rows.end = head.row();
121 }
122 }
123
124 Self {
125 head,
126 cursor_shape,
127 is_newest,
128 is_local,
129 range,
130 active_rows,
131 user_name,
132 }
133 }
134}
135
136pub struct EditorElement {
137 editor: View<Editor>,
138 style: EditorStyle,
139}
140
141type DisplayRowDelta = u32;
142
143impl EditorElement {
144 pub(crate) const SCROLLBAR_WIDTH: Pixels = px(13.);
145
146 pub fn new(editor: &View<Editor>, style: EditorStyle) -> Self {
147 Self {
148 editor: editor.clone(),
149 style,
150 }
151 }
152
153 fn register_actions(&self, cx: &mut WindowContext) {
154 let view = &self.editor;
155 view.update(cx, |editor, cx| {
156 for action in editor.editor_actions.iter() {
157 (action)(cx)
158 }
159 });
160
161 crate::rust_analyzer_ext::apply_related_actions(view, cx);
162 register_action(view, cx, Editor::move_left);
163 register_action(view, cx, Editor::move_right);
164 register_action(view, cx, Editor::move_down);
165 register_action(view, cx, Editor::move_down_by_lines);
166 register_action(view, cx, Editor::select_down_by_lines);
167 register_action(view, cx, Editor::move_up);
168 register_action(view, cx, Editor::move_up_by_lines);
169 register_action(view, cx, Editor::select_up_by_lines);
170 register_action(view, cx, Editor::cancel);
171 register_action(view, cx, Editor::newline);
172 register_action(view, cx, Editor::newline_above);
173 register_action(view, cx, Editor::newline_below);
174 register_action(view, cx, Editor::backspace);
175 register_action(view, cx, Editor::delete);
176 register_action(view, cx, Editor::tab);
177 register_action(view, cx, Editor::tab_prev);
178 register_action(view, cx, Editor::indent);
179 register_action(view, cx, Editor::outdent);
180 register_action(view, cx, Editor::delete_line);
181 register_action(view, cx, Editor::join_lines);
182 register_action(view, cx, Editor::sort_lines_case_sensitive);
183 register_action(view, cx, Editor::sort_lines_case_insensitive);
184 register_action(view, cx, Editor::reverse_lines);
185 register_action(view, cx, Editor::shuffle_lines);
186 register_action(view, cx, Editor::convert_to_upper_case);
187 register_action(view, cx, Editor::convert_to_lower_case);
188 register_action(view, cx, Editor::convert_to_title_case);
189 register_action(view, cx, Editor::convert_to_snake_case);
190 register_action(view, cx, Editor::convert_to_kebab_case);
191 register_action(view, cx, Editor::convert_to_upper_camel_case);
192 register_action(view, cx, Editor::convert_to_lower_camel_case);
193 register_action(view, cx, Editor::convert_to_opposite_case);
194 register_action(view, cx, Editor::delete_to_previous_word_start);
195 register_action(view, cx, Editor::delete_to_previous_subword_start);
196 register_action(view, cx, Editor::delete_to_next_word_end);
197 register_action(view, cx, Editor::delete_to_next_subword_end);
198 register_action(view, cx, Editor::delete_to_beginning_of_line);
199 register_action(view, cx, Editor::delete_to_end_of_line);
200 register_action(view, cx, Editor::cut_to_end_of_line);
201 register_action(view, cx, Editor::duplicate_line_up);
202 register_action(view, cx, Editor::duplicate_line_down);
203 register_action(view, cx, Editor::move_line_up);
204 register_action(view, cx, Editor::move_line_down);
205 register_action(view, cx, Editor::transpose);
206 register_action(view, cx, Editor::cut);
207 register_action(view, cx, Editor::copy);
208 register_action(view, cx, Editor::paste);
209 register_action(view, cx, Editor::undo);
210 register_action(view, cx, Editor::redo);
211 register_action(view, cx, Editor::move_page_up);
212 register_action(view, cx, Editor::move_page_down);
213 register_action(view, cx, Editor::next_screen);
214 register_action(view, cx, Editor::scroll_cursor_top);
215 register_action(view, cx, Editor::scroll_cursor_center);
216 register_action(view, cx, Editor::scroll_cursor_bottom);
217 register_action(view, cx, |editor, _: &LineDown, cx| {
218 editor.scroll_screen(&ScrollAmount::Line(1.), cx)
219 });
220 register_action(view, cx, |editor, _: &LineUp, cx| {
221 editor.scroll_screen(&ScrollAmount::Line(-1.), cx)
222 });
223 register_action(view, cx, |editor, _: &HalfPageDown, cx| {
224 editor.scroll_screen(&ScrollAmount::Page(0.5), cx)
225 });
226 register_action(view, cx, |editor, _: &HalfPageUp, cx| {
227 editor.scroll_screen(&ScrollAmount::Page(-0.5), cx)
228 });
229 register_action(view, cx, |editor, _: &PageDown, cx| {
230 editor.scroll_screen(&ScrollAmount::Page(1.), cx)
231 });
232 register_action(view, cx, |editor, _: &PageUp, cx| {
233 editor.scroll_screen(&ScrollAmount::Page(-1.), cx)
234 });
235 register_action(view, cx, Editor::move_to_previous_word_start);
236 register_action(view, cx, Editor::move_to_previous_subword_start);
237 register_action(view, cx, Editor::move_to_next_word_end);
238 register_action(view, cx, Editor::move_to_next_subword_end);
239 register_action(view, cx, Editor::move_to_beginning_of_line);
240 register_action(view, cx, Editor::move_to_end_of_line);
241 register_action(view, cx, Editor::move_to_start_of_paragraph);
242 register_action(view, cx, Editor::move_to_end_of_paragraph);
243 register_action(view, cx, Editor::move_to_beginning);
244 register_action(view, cx, Editor::move_to_end);
245 register_action(view, cx, Editor::select_up);
246 register_action(view, cx, Editor::select_down);
247 register_action(view, cx, Editor::select_left);
248 register_action(view, cx, Editor::select_right);
249 register_action(view, cx, Editor::select_to_previous_word_start);
250 register_action(view, cx, Editor::select_to_previous_subword_start);
251 register_action(view, cx, Editor::select_to_next_word_end);
252 register_action(view, cx, Editor::select_to_next_subword_end);
253 register_action(view, cx, Editor::select_to_beginning_of_line);
254 register_action(view, cx, Editor::select_to_end_of_line);
255 register_action(view, cx, Editor::select_to_start_of_paragraph);
256 register_action(view, cx, Editor::select_to_end_of_paragraph);
257 register_action(view, cx, Editor::select_to_beginning);
258 register_action(view, cx, Editor::select_to_end);
259 register_action(view, cx, Editor::select_all);
260 register_action(view, cx, |editor, action, cx| {
261 editor.select_all_matches(action, cx).log_err();
262 });
263 register_action(view, cx, Editor::select_line);
264 register_action(view, cx, Editor::split_selection_into_lines);
265 register_action(view, cx, Editor::add_selection_above);
266 register_action(view, cx, Editor::add_selection_below);
267 register_action(view, cx, |editor, action, cx| {
268 editor.select_next(action, cx).log_err();
269 });
270 register_action(view, cx, |editor, action, cx| {
271 editor.select_previous(action, cx).log_err();
272 });
273 register_action(view, cx, Editor::toggle_comments);
274 register_action(view, cx, Editor::select_larger_syntax_node);
275 register_action(view, cx, Editor::select_smaller_syntax_node);
276 register_action(view, cx, Editor::move_to_enclosing_bracket);
277 register_action(view, cx, Editor::undo_selection);
278 register_action(view, cx, Editor::redo_selection);
279 if !view.read(cx).is_singleton(cx) {
280 register_action(view, cx, Editor::expand_excerpts);
281 register_action(view, cx, Editor::expand_excerpts_up);
282 register_action(view, cx, Editor::expand_excerpts_down);
283 }
284 register_action(view, cx, Editor::go_to_diagnostic);
285 register_action(view, cx, Editor::go_to_prev_diagnostic);
286 register_action(view, cx, Editor::go_to_hunk);
287 register_action(view, cx, Editor::go_to_prev_hunk);
288 register_action(view, cx, |editor, a, cx| {
289 editor.go_to_definition(a, cx).detach_and_log_err(cx);
290 });
291 register_action(view, cx, |editor, a, cx| {
292 editor.go_to_definition_split(a, cx).detach_and_log_err(cx);
293 });
294 register_action(view, cx, |editor, a, cx| {
295 editor.go_to_implementation(a, cx).detach_and_log_err(cx);
296 });
297 register_action(view, cx, |editor, a, cx| {
298 editor
299 .go_to_implementation_split(a, cx)
300 .detach_and_log_err(cx);
301 });
302 register_action(view, cx, |editor, a, cx| {
303 editor.go_to_type_definition(a, cx).detach_and_log_err(cx);
304 });
305 register_action(view, cx, |editor, a, cx| {
306 editor
307 .go_to_type_definition_split(a, cx)
308 .detach_and_log_err(cx);
309 });
310 register_action(view, cx, Editor::open_url);
311 register_action(view, cx, Editor::fold);
312 register_action(view, cx, Editor::fold_at);
313 register_action(view, cx, Editor::unfold_lines);
314 register_action(view, cx, Editor::unfold_at);
315 register_action(view, cx, Editor::fold_selected_ranges);
316 register_action(view, cx, Editor::show_completions);
317 register_action(view, cx, Editor::toggle_code_actions);
318 register_action(view, cx, Editor::open_excerpts);
319 register_action(view, cx, Editor::open_excerpts_in_split);
320 register_action(view, cx, Editor::toggle_soft_wrap);
321 register_action(view, cx, Editor::toggle_line_numbers);
322 register_action(view, cx, Editor::toggle_indent_guides);
323 register_action(view, cx, Editor::toggle_inlay_hints);
324 register_action(view, cx, hover_popover::hover);
325 register_action(view, cx, Editor::reveal_in_finder);
326 register_action(view, cx, Editor::copy_path);
327 register_action(view, cx, Editor::copy_relative_path);
328 register_action(view, cx, Editor::copy_highlight_json);
329 register_action(view, cx, Editor::copy_permalink_to_line);
330 register_action(view, cx, Editor::open_permalink_to_line);
331 register_action(view, cx, Editor::toggle_git_blame);
332 register_action(view, cx, Editor::toggle_git_blame_inline);
333 register_action(view, cx, Editor::toggle_hunk_diff);
334 register_action(view, cx, Editor::expand_all_hunk_diffs);
335 register_action(view, cx, |editor, action, cx| {
336 if let Some(task) = editor.format(action, cx) {
337 task.detach_and_log_err(cx);
338 } else {
339 cx.propagate();
340 }
341 });
342 register_action(view, cx, Editor::restart_language_server);
343 register_action(view, cx, Editor::show_character_palette);
344 register_action(view, cx, |editor, action, cx| {
345 if let Some(task) = editor.confirm_completion(action, cx) {
346 task.detach_and_log_err(cx);
347 } else {
348 cx.propagate();
349 }
350 });
351 register_action(view, cx, |editor, action, cx| {
352 if let Some(task) = editor.confirm_code_action(action, cx) {
353 task.detach_and_log_err(cx);
354 } else {
355 cx.propagate();
356 }
357 });
358 register_action(view, cx, |editor, action, cx| {
359 if let Some(task) = editor.rename(action, cx) {
360 task.detach_and_log_err(cx);
361 } else {
362 cx.propagate();
363 }
364 });
365 register_action(view, cx, |editor, action, cx| {
366 if let Some(task) = editor.confirm_rename(action, cx) {
367 task.detach_and_log_err(cx);
368 } else {
369 cx.propagate();
370 }
371 });
372 register_action(view, cx, |editor, action, cx| {
373 if let Some(task) = editor.find_all_references(action, cx) {
374 task.detach_and_log_err(cx);
375 } else {
376 cx.propagate();
377 }
378 });
379 register_action(view, cx, Editor::next_inline_completion);
380 register_action(view, cx, Editor::previous_inline_completion);
381 register_action(view, cx, Editor::show_inline_completion);
382 register_action(view, cx, Editor::context_menu_first);
383 register_action(view, cx, Editor::context_menu_prev);
384 register_action(view, cx, Editor::context_menu_next);
385 register_action(view, cx, Editor::context_menu_last);
386 register_action(view, cx, Editor::display_cursor_names);
387 register_action(view, cx, Editor::unique_lines_case_insensitive);
388 register_action(view, cx, Editor::unique_lines_case_sensitive);
389 register_action(view, cx, Editor::accept_partial_inline_completion);
390 register_action(view, cx, Editor::accept_inline_completion);
391 register_action(view, cx, Editor::revert_selected_hunks);
392 register_action(view, cx, Editor::open_active_item_in_terminal)
393 }
394
395 fn register_key_listeners(&self, cx: &mut WindowContext, layout: &EditorLayout) {
396 let position_map = layout.position_map.clone();
397 cx.on_key_event({
398 let editor = self.editor.clone();
399 let text_hitbox = layout.text_hitbox.clone();
400 move |event: &ModifiersChangedEvent, phase, cx| {
401 if phase != DispatchPhase::Bubble {
402 return;
403 }
404
405 editor.update(cx, |editor, cx| {
406 Self::modifiers_changed(editor, event, &position_map, &text_hitbox, cx)
407 })
408 }
409 });
410 }
411
412 fn modifiers_changed(
413 editor: &mut Editor,
414 event: &ModifiersChangedEvent,
415 position_map: &PositionMap,
416 text_hitbox: &Hitbox,
417 cx: &mut ViewContext<Editor>,
418 ) {
419 let mouse_position = cx.mouse_position();
420 if !text_hitbox.is_hovered(cx) {
421 return;
422 }
423
424 editor.update_hovered_link(
425 position_map.point_for_position(text_hitbox.bounds, mouse_position),
426 &position_map.snapshot,
427 event.modifiers,
428 cx,
429 )
430 }
431
432 fn mouse_left_down(
433 editor: &mut Editor,
434 event: &MouseDownEvent,
435 hovered_hunk: Option<&HunkToExpand>,
436 position_map: &PositionMap,
437 text_hitbox: &Hitbox,
438 gutter_hitbox: &Hitbox,
439 cx: &mut ViewContext<Editor>,
440 ) {
441 if cx.default_prevented() {
442 return;
443 }
444
445 let mut click_count = event.click_count;
446 let mut modifiers = event.modifiers;
447
448 if let Some(hovered_hunk) = hovered_hunk {
449 editor.expand_diff_hunk(None, hovered_hunk, cx);
450 cx.notify();
451 return;
452 } else if gutter_hitbox.is_hovered(cx) {
453 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
454 } else if !text_hitbox.is_hovered(cx) {
455 return;
456 }
457
458 if click_count == 2 && !editor.buffer().read(cx).is_singleton() {
459 match EditorSettings::get_global(cx).double_click_in_multibuffer {
460 DoubleClickInMultibuffer::Select => {
461 // do nothing special on double click, all selection logic is below
462 }
463 DoubleClickInMultibuffer::Open => {
464 if modifiers.alt {
465 // if double click is made with alt, pretend it's a regular double click without opening and alt,
466 // and run the selection logic.
467 modifiers.alt = false;
468 } else {
469 // if double click is made without alt, open the corresponding excerp
470 editor.open_excerpts(&OpenExcerpts, cx);
471 return;
472 }
473 }
474 }
475 }
476
477 let point_for_position =
478 position_map.point_for_position(text_hitbox.bounds, event.position);
479 let position = point_for_position.previous_valid;
480 if modifiers.shift && modifiers.alt {
481 editor.select(
482 SelectPhase::BeginColumnar {
483 position,
484 reset: false,
485 goal_column: point_for_position.exact_unclipped.column(),
486 },
487 cx,
488 );
489 } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
490 {
491 editor.select(
492 SelectPhase::Extend {
493 position,
494 click_count,
495 },
496 cx,
497 );
498 } else {
499 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
500 let multi_cursor_modifier = match multi_cursor_setting {
501 MultiCursorModifier::Alt => modifiers.alt,
502 MultiCursorModifier::CmdOrCtrl => modifiers.secondary(),
503 };
504 editor.select(
505 SelectPhase::Begin {
506 position,
507 add: multi_cursor_modifier,
508 click_count,
509 },
510 cx,
511 );
512 }
513
514 cx.stop_propagation();
515 }
516
517 fn mouse_right_down(
518 editor: &mut Editor,
519 event: &MouseDownEvent,
520 position_map: &PositionMap,
521 text_hitbox: &Hitbox,
522 cx: &mut ViewContext<Editor>,
523 ) {
524 if !text_hitbox.is_hovered(cx) {
525 return;
526 }
527 let point_for_position =
528 position_map.point_for_position(text_hitbox.bounds, event.position);
529 mouse_context_menu::deploy_context_menu(
530 editor,
531 event.position,
532 point_for_position.previous_valid,
533 cx,
534 );
535 cx.stop_propagation();
536 }
537
538 fn mouse_middle_down(
539 editor: &mut Editor,
540 event: &MouseDownEvent,
541 position_map: &PositionMap,
542 text_hitbox: &Hitbox,
543 cx: &mut ViewContext<Editor>,
544 ) {
545 if !text_hitbox.is_hovered(cx) || cx.default_prevented() {
546 return;
547 }
548
549 let point_for_position =
550 position_map.point_for_position(text_hitbox.bounds, event.position);
551 let position = point_for_position.previous_valid;
552
553 editor.select(
554 SelectPhase::BeginColumnar {
555 position,
556 reset: true,
557 goal_column: point_for_position.exact_unclipped.column(),
558 },
559 cx,
560 );
561 }
562
563 fn mouse_up(
564 editor: &mut Editor,
565 event: &MouseUpEvent,
566 position_map: &PositionMap,
567 text_hitbox: &Hitbox,
568 cx: &mut ViewContext<Editor>,
569 ) {
570 let end_selection = editor.has_pending_selection();
571 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
572
573 if end_selection {
574 editor.select(SelectPhase::End, cx);
575 }
576
577 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
578 let multi_cursor_modifier = match multi_cursor_setting {
579 MultiCursorModifier::Alt => event.modifiers.secondary(),
580 MultiCursorModifier::CmdOrCtrl => event.modifiers.alt,
581 };
582
583 if !pending_nonempty_selections && multi_cursor_modifier && text_hitbox.is_hovered(cx) {
584 let point = position_map.point_for_position(text_hitbox.bounds, event.position);
585 editor.handle_click_hovered_link(point, event.modifiers, cx);
586
587 cx.stop_propagation();
588 } else if end_selection {
589 cx.stop_propagation();
590 } else if cfg!(target_os = "linux") && event.button == MouseButton::Middle {
591 if !text_hitbox.is_hovered(cx) || editor.read_only(cx) {
592 return;
593 }
594
595 #[cfg(target_os = "linux")]
596 if let Some(item) = cx.read_from_clipboard() {
597 let point_for_position =
598 position_map.point_for_position(text_hitbox.bounds, event.position);
599 let position = point_for_position.previous_valid;
600
601 editor.select(
602 SelectPhase::Begin {
603 position,
604 add: false,
605 click_count: 1,
606 },
607 cx,
608 );
609 editor.insert(item.text(), cx);
610 }
611 cx.stop_propagation()
612 }
613 }
614
615 fn mouse_dragged(
616 editor: &mut Editor,
617 event: &MouseMoveEvent,
618 position_map: &PositionMap,
619 text_bounds: Bounds<Pixels>,
620 cx: &mut ViewContext<Editor>,
621 ) {
622 if !editor.has_pending_selection() {
623 return;
624 }
625
626 let point_for_position = position_map.point_for_position(text_bounds, event.position);
627 let mut scroll_delta = gpui::Point::<f32>::default();
628 let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
629 let top = text_bounds.origin.y + vertical_margin;
630 let bottom = text_bounds.lower_left().y - vertical_margin;
631 if event.position.y < top {
632 scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
633 }
634 if event.position.y > bottom {
635 scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
636 }
637
638 let horizontal_margin = position_map.line_height.min(text_bounds.size.width / 3.0);
639 let left = text_bounds.origin.x + horizontal_margin;
640 let right = text_bounds.upper_right().x - horizontal_margin;
641 if event.position.x < left {
642 scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
643 }
644 if event.position.x > right {
645 scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
646 }
647
648 editor.select(
649 SelectPhase::Update {
650 position: point_for_position.previous_valid,
651 goal_column: point_for_position.exact_unclipped.column(),
652 scroll_delta,
653 },
654 cx,
655 );
656 }
657
658 fn mouse_moved(
659 editor: &mut Editor,
660 event: &MouseMoveEvent,
661 position_map: &PositionMap,
662 text_hitbox: &Hitbox,
663 gutter_hitbox: &Hitbox,
664 cx: &mut ViewContext<Editor>,
665 ) {
666 let modifiers = event.modifiers;
667 let gutter_hovered = gutter_hitbox.is_hovered(cx);
668 editor.set_gutter_hovered(gutter_hovered, cx);
669
670 // Don't trigger hover popover if mouse is hovering over context menu
671 if text_hitbox.is_hovered(cx) {
672 let point_for_position =
673 position_map.point_for_position(text_hitbox.bounds, event.position);
674
675 editor.update_hovered_link(point_for_position, &position_map.snapshot, modifiers, cx);
676
677 if let Some(point) = point_for_position.as_valid() {
678 let anchor = position_map
679 .snapshot
680 .buffer_snapshot
681 .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
682 hover_at(editor, Some(anchor), cx);
683 Self::update_visible_cursor(editor, point, position_map, cx);
684 } else {
685 hover_at(editor, None, cx);
686 }
687 } else {
688 editor.hide_hovered_link(cx);
689 hover_at(editor, None, cx);
690 if gutter_hovered {
691 cx.stop_propagation();
692 }
693 }
694 }
695
696 fn update_visible_cursor(
697 editor: &mut Editor,
698 point: DisplayPoint,
699 position_map: &PositionMap,
700 cx: &mut ViewContext<Editor>,
701 ) {
702 let snapshot = &position_map.snapshot;
703 let Some(hub) = editor.collaboration_hub() else {
704 return;
705 };
706 let range = DisplayPoint::new(point.row(), point.column().saturating_sub(1))
707 ..DisplayPoint::new(
708 point.row(),
709 (point.column() + 1).min(snapshot.line_len(point.row())),
710 );
711
712 let range = snapshot
713 .buffer_snapshot
714 .anchor_at(range.start.to_point(&snapshot.display_snapshot), Bias::Left)
715 ..snapshot
716 .buffer_snapshot
717 .anchor_at(range.end.to_point(&snapshot.display_snapshot), Bias::Right);
718
719 let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
720 return;
721 };
722 let key = crate::HoveredCursor {
723 replica_id: selection.replica_id,
724 selection_id: selection.selection.id,
725 };
726 editor.hovered_cursors.insert(
727 key.clone(),
728 cx.spawn(|editor, mut cx| async move {
729 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
730 editor
731 .update(&mut cx, |editor, cx| {
732 editor.hovered_cursors.remove(&key);
733 cx.notify();
734 })
735 .ok();
736 }),
737 );
738 cx.notify()
739 }
740
741 fn layout_selections(
742 &self,
743 start_anchor: Anchor,
744 end_anchor: Anchor,
745 snapshot: &EditorSnapshot,
746 start_row: DisplayRow,
747 end_row: DisplayRow,
748 cx: &mut WindowContext,
749 ) -> (
750 Vec<(PlayerColor, Vec<SelectionLayout>)>,
751 BTreeMap<DisplayRow, bool>,
752 Option<DisplayPoint>,
753 ) {
754 let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
755 let mut active_rows = BTreeMap::new();
756 let mut newest_selection_head = None;
757 let editor = self.editor.read(cx);
758
759 if editor.show_local_selections {
760 let mut local_selections: Vec<Selection<Point>> = editor
761 .selections
762 .disjoint_in_range(start_anchor..end_anchor, cx);
763 local_selections.extend(editor.selections.pending(cx));
764 let mut layouts = Vec::new();
765 let newest = editor.selections.newest(cx);
766 for selection in local_selections.drain(..) {
767 let is_empty = selection.start == selection.end;
768 let is_newest = selection == newest;
769
770 let layout = SelectionLayout::new(
771 selection,
772 editor.selections.line_mode,
773 editor.cursor_shape,
774 &snapshot.display_snapshot,
775 is_newest,
776 editor.leader_peer_id.is_none(),
777 None,
778 );
779 if is_newest {
780 newest_selection_head = Some(layout.head);
781 }
782
783 for row in cmp::max(layout.active_rows.start.0, start_row.0)
784 ..=cmp::min(layout.active_rows.end.0, end_row.0)
785 {
786 let contains_non_empty_selection =
787 active_rows.entry(DisplayRow(row)).or_insert(!is_empty);
788 *contains_non_empty_selection |= !is_empty;
789 }
790 layouts.push(layout);
791 }
792
793 let player = if editor.read_only(cx) {
794 cx.theme().players().read_only()
795 } else {
796 self.style.local_player
797 };
798
799 selections.push((player, layouts));
800 }
801
802 if let Some(collaboration_hub) = &editor.collaboration_hub {
803 // When following someone, render the local selections in their color.
804 if let Some(leader_id) = editor.leader_peer_id {
805 if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id) {
806 if let Some(participant_index) = collaboration_hub
807 .user_participant_indices(cx)
808 .get(&collaborator.user_id)
809 {
810 if let Some((local_selection_style, _)) = selections.first_mut() {
811 *local_selection_style = cx
812 .theme()
813 .players()
814 .color_for_participant(participant_index.0);
815 }
816 }
817 }
818 }
819
820 let mut remote_selections = HashMap::default();
821 for selection in snapshot.remote_selections_in_range(
822 &(start_anchor..end_anchor),
823 collaboration_hub.as_ref(),
824 cx,
825 ) {
826 let selection_style = Self::get_participant_color(selection.participant_index, cx);
827
828 // Don't re-render the leader's selections, since the local selections
829 // match theirs.
830 if Some(selection.peer_id) == editor.leader_peer_id {
831 continue;
832 }
833 let key = HoveredCursor {
834 replica_id: selection.replica_id,
835 selection_id: selection.selection.id,
836 };
837
838 let is_shown =
839 editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
840
841 remote_selections
842 .entry(selection.replica_id)
843 .or_insert((selection_style, Vec::new()))
844 .1
845 .push(SelectionLayout::new(
846 selection.selection,
847 selection.line_mode,
848 selection.cursor_shape,
849 &snapshot.display_snapshot,
850 false,
851 false,
852 if is_shown { selection.user_name } else { None },
853 ));
854 }
855
856 selections.extend(remote_selections.into_values());
857 }
858 (selections, active_rows, newest_selection_head)
859 }
860
861 fn collect_cursors(
862 &self,
863 snapshot: &EditorSnapshot,
864 cx: &mut WindowContext,
865 ) -> Vec<(DisplayPoint, Hsla)> {
866 let editor = self.editor.read(cx);
867 let mut cursors = Vec::new();
868 let mut skip_local = false;
869 let mut add_cursor = |anchor: Anchor, color| {
870 cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
871 };
872 // Remote cursors
873 if let Some(collaboration_hub) = &editor.collaboration_hub {
874 for remote_selection in snapshot.remote_selections_in_range(
875 &(Anchor::min()..Anchor::max()),
876 collaboration_hub.deref(),
877 cx,
878 ) {
879 let color = Self::get_participant_color(remote_selection.participant_index, cx);
880 add_cursor(remote_selection.selection.head(), color.cursor);
881 if Some(remote_selection.peer_id) == editor.leader_peer_id {
882 skip_local = true;
883 }
884 }
885 }
886 // Local cursors
887 if !skip_local {
888 let color = cx.theme().players().local().cursor;
889 editor.selections.disjoint.iter().for_each(|selection| {
890 add_cursor(selection.head(), color);
891 });
892 if let Some(ref selection) = editor.selections.pending_anchor() {
893 add_cursor(selection.head(), color);
894 }
895 }
896 cursors
897 }
898
899 #[allow(clippy::too_many_arguments)]
900 fn layout_visible_cursors(
901 &self,
902 snapshot: &EditorSnapshot,
903 selections: &[(PlayerColor, Vec<SelectionLayout>)],
904 visible_display_row_range: Range<DisplayRow>,
905 line_layouts: &[LineWithInvisibles],
906 text_hitbox: &Hitbox,
907 content_origin: gpui::Point<Pixels>,
908 scroll_position: gpui::Point<f32>,
909 scroll_pixel_position: gpui::Point<Pixels>,
910 line_height: Pixels,
911 em_width: Pixels,
912 autoscroll_containing_element: bool,
913 cx: &mut WindowContext,
914 ) -> Vec<CursorLayout> {
915 let mut autoscroll_bounds = None;
916 let cursor_layouts = self.editor.update(cx, |editor, cx| {
917 let mut cursors = Vec::new();
918 for (player_color, selections) in selections {
919 for selection in selections {
920 let cursor_position = selection.head;
921
922 let in_range = visible_display_row_range.contains(&cursor_position.row());
923 if (selection.is_local && !editor.show_local_cursors(cx)) || !in_range {
924 continue;
925 }
926
927 let cursor_row_layout = &line_layouts
928 [cursor_position.row().minus(visible_display_row_range.start) as usize];
929 let cursor_column = cursor_position.column() as usize;
930
931 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
932 let mut block_width =
933 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
934 if block_width == Pixels::ZERO {
935 block_width = em_width;
936 }
937 let block_text = if let CursorShape::Block = selection.cursor_shape {
938 snapshot.display_chars_at(cursor_position).next().and_then(
939 |(character, _)| {
940 let text = if character == '\n' {
941 SharedString::from(" ")
942 } else {
943 SharedString::from(character.to_string())
944 };
945 let len = text.len();
946
947 let font = cursor_row_layout
948 .font_id_for_index(cursor_column)
949 .and_then(|cursor_font_id| {
950 cx.text_system().get_font_for_id(cursor_font_id)
951 })
952 .unwrap_or(self.style.text.font());
953
954 cx.text_system()
955 .shape_line(
956 text,
957 cursor_row_layout.font_size,
958 &[TextRun {
959 len,
960 font,
961 color: self.style.background,
962 background_color: None,
963 strikethrough: None,
964 underline: None,
965 }],
966 )
967 .log_err()
968 },
969 )
970 } else {
971 None
972 };
973
974 let x = cursor_character_x - scroll_pixel_position.x;
975 let y = (cursor_position.row().as_f32()
976 - scroll_pixel_position.y / line_height)
977 * line_height;
978 if selection.is_newest {
979 editor.pixel_position_of_newest_cursor = Some(point(
980 text_hitbox.origin.x + x + block_width / 2.,
981 text_hitbox.origin.y + y + line_height / 2.,
982 ));
983
984 if autoscroll_containing_element {
985 let top = text_hitbox.origin.y
986 + (cursor_position.row().as_f32() - scroll_position.y - 3.).max(0.)
987 * line_height;
988 let left = text_hitbox.origin.x
989 + (cursor_position.column() as f32 - scroll_position.x - 3.)
990 .max(0.)
991 * em_width;
992
993 let bottom = text_hitbox.origin.y
994 + (cursor_position.row().as_f32() - scroll_position.y + 4.)
995 * line_height;
996 let right = text_hitbox.origin.x
997 + (cursor_position.column() as f32 - scroll_position.x + 4.)
998 * em_width;
999
1000 autoscroll_bounds =
1001 Some(Bounds::from_corners(point(left, top), point(right, bottom)))
1002 }
1003 }
1004
1005 let mut cursor = CursorLayout {
1006 color: player_color.cursor,
1007 block_width,
1008 origin: point(x, y),
1009 line_height,
1010 shape: selection.cursor_shape,
1011 block_text,
1012 cursor_name: None,
1013 };
1014 let cursor_name = selection.user_name.clone().map(|name| CursorName {
1015 string: name,
1016 color: self.style.background,
1017 is_top_row: cursor_position.row().0 == 0,
1018 });
1019 cursor.layout(content_origin, cursor_name, cx);
1020 cursors.push(cursor);
1021 }
1022 }
1023 cursors
1024 });
1025
1026 if let Some(bounds) = autoscroll_bounds {
1027 cx.request_autoscroll(bounds);
1028 }
1029
1030 cursor_layouts
1031 }
1032
1033 fn layout_scrollbar(
1034 &self,
1035 snapshot: &EditorSnapshot,
1036 bounds: Bounds<Pixels>,
1037 scroll_position: gpui::Point<f32>,
1038 rows_per_page: f32,
1039 non_visible_cursors: bool,
1040 cx: &mut WindowContext,
1041 ) -> Option<ScrollbarLayout> {
1042 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1043 let show_scrollbars = match scrollbar_settings.show {
1044 ShowScrollbar::Auto => {
1045 let editor = self.editor.read(cx);
1046 let is_singleton = editor.is_singleton(cx);
1047 // Git
1048 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_git_diffs())
1049 ||
1050 // Buffer Search Results
1051 (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
1052 ||
1053 // Selected Symbol Occurrences
1054 (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
1055 ||
1056 // Diagnostics
1057 (is_singleton && scrollbar_settings.diagnostics && snapshot.buffer_snapshot.has_diagnostics())
1058 ||
1059 // Cursors out of sight
1060 non_visible_cursors
1061 ||
1062 // Scrollmanager
1063 editor.scroll_manager.scrollbars_visible()
1064 }
1065 ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
1066 ShowScrollbar::Always => true,
1067 ShowScrollbar::Never => false,
1068 };
1069 if snapshot.mode != EditorMode::Full {
1070 return None;
1071 }
1072
1073 let visible_row_range = scroll_position.y..scroll_position.y + rows_per_page;
1074
1075 // If a drag took place after we started dragging the scrollbar,
1076 // cancel the scrollbar drag.
1077 if cx.has_active_drag() {
1078 self.editor.update(cx, |editor, cx| {
1079 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
1080 });
1081 }
1082
1083 let track_bounds = Bounds::from_corners(
1084 point(self.scrollbar_left(&bounds), bounds.origin.y),
1085 point(bounds.lower_right().x, bounds.lower_left().y),
1086 );
1087
1088 let height = bounds.size.height;
1089 let total_rows = snapshot.max_point().row().as_f32() + rows_per_page;
1090 let px_per_row = height / total_rows;
1091 let thumb_height = (rows_per_page * px_per_row).max(ScrollbarLayout::MIN_THUMB_HEIGHT);
1092 let row_height = (height - thumb_height) / snapshot.max_point().row().as_f32();
1093
1094 Some(ScrollbarLayout {
1095 hitbox: cx.insert_hitbox(track_bounds, false),
1096 visible_row_range,
1097 row_height,
1098 visible: show_scrollbars,
1099 thumb_height,
1100 })
1101 }
1102
1103 #[allow(clippy::too_many_arguments)]
1104 fn prepaint_gutter_fold_toggles(
1105 &self,
1106 toggles: &mut [Option<AnyElement>],
1107 line_height: Pixels,
1108 gutter_dimensions: &GutterDimensions,
1109 gutter_settings: crate::editor_settings::Gutter,
1110 scroll_pixel_position: gpui::Point<Pixels>,
1111 gutter_hitbox: &Hitbox,
1112 cx: &mut WindowContext,
1113 ) {
1114 for (ix, fold_indicator) in toggles.iter_mut().enumerate() {
1115 if let Some(fold_indicator) = fold_indicator {
1116 debug_assert!(gutter_settings.folds);
1117 let available_space = size(
1118 AvailableSpace::MinContent,
1119 AvailableSpace::Definite(line_height * 0.55),
1120 );
1121 let fold_indicator_size = fold_indicator.layout_as_root(available_space, cx);
1122
1123 let position = point(
1124 gutter_dimensions.width - gutter_dimensions.right_padding,
1125 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1126 );
1127 let centering_offset = point(
1128 (gutter_dimensions.fold_area_width() - fold_indicator_size.width) / 2.,
1129 (line_height - fold_indicator_size.height) / 2.,
1130 );
1131 let origin = gutter_hitbox.origin + position + centering_offset;
1132 fold_indicator.prepaint_as_root(origin, available_space, cx);
1133 }
1134 }
1135 }
1136
1137 #[allow(clippy::too_many_arguments)]
1138 fn prepaint_flap_trailers(
1139 &self,
1140 trailers: Vec<Option<AnyElement>>,
1141 lines: &[LineWithInvisibles],
1142 line_height: Pixels,
1143 content_origin: gpui::Point<Pixels>,
1144 scroll_pixel_position: gpui::Point<Pixels>,
1145 em_width: Pixels,
1146 cx: &mut WindowContext,
1147 ) -> Vec<Option<FlapTrailerLayout>> {
1148 trailers
1149 .into_iter()
1150 .enumerate()
1151 .map(|(ix, element)| {
1152 let mut element = element?;
1153 let available_space = size(
1154 AvailableSpace::MinContent,
1155 AvailableSpace::Definite(line_height),
1156 );
1157 let size = element.layout_as_root(available_space, cx);
1158
1159 let line = &lines[ix];
1160 let padding = if line.width == Pixels::ZERO {
1161 Pixels::ZERO
1162 } else {
1163 4. * em_width
1164 };
1165 let position = point(
1166 scroll_pixel_position.x + line.width + padding,
1167 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1168 );
1169 let centering_offset = point(px(0.), (line_height - size.height) / 2.);
1170 let origin = content_origin + position + centering_offset;
1171 element.prepaint_as_root(origin, available_space, cx);
1172 Some(FlapTrailerLayout {
1173 element,
1174 bounds: Bounds::new(origin, size),
1175 })
1176 })
1177 .collect()
1178 }
1179
1180 // Folds contained in a hunk are ignored apart from shrinking visual size
1181 // If a fold contains any hunks then that fold line is marked as modified
1182 fn layout_git_gutters(
1183 &self,
1184 line_height: Pixels,
1185 gutter_hitbox: &Hitbox,
1186 display_rows: Range<DisplayRow>,
1187 snapshot: &EditorSnapshot,
1188 cx: &mut WindowContext,
1189 ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
1190 let buffer_snapshot = &snapshot.buffer_snapshot;
1191
1192 let buffer_start_row = MultiBufferRow(
1193 DisplayPoint::new(display_rows.start, 0)
1194 .to_point(snapshot)
1195 .row,
1196 );
1197 let buffer_end_row = MultiBufferRow(
1198 DisplayPoint::new(display_rows.end, 0)
1199 .to_point(snapshot)
1200 .row,
1201 );
1202
1203 let expanded_hunk_display_rows = self.editor.update(cx, |editor, _| {
1204 editor
1205 .expanded_hunks
1206 .hunks(false)
1207 .map(|expanded_hunk| {
1208 let start_row = expanded_hunk
1209 .hunk_range
1210 .start
1211 .to_display_point(snapshot)
1212 .row();
1213 let end_row = expanded_hunk
1214 .hunk_range
1215 .end
1216 .to_display_point(snapshot)
1217 .row();
1218 (start_row, end_row)
1219 })
1220 .collect::<HashMap<_, _>>()
1221 });
1222
1223 buffer_snapshot
1224 .git_diff_hunks_in_range(buffer_start_row..buffer_end_row)
1225 .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
1226 .dedup()
1227 .map(|hunk| {
1228 let hitbox = if let DisplayDiffHunk::Unfolded {
1229 display_row_range, ..
1230 } = &hunk
1231 {
1232 let was_expanded = expanded_hunk_display_rows
1233 .get(&display_row_range.start)
1234 .map(|expanded_end_row| expanded_end_row == &display_row_range.end)
1235 .unwrap_or(false);
1236 if was_expanded {
1237 None
1238 } else {
1239 let hunk_bounds = Self::diff_hunk_bounds(
1240 &snapshot,
1241 line_height,
1242 gutter_hitbox.bounds,
1243 &hunk,
1244 );
1245 Some(cx.insert_hitbox(hunk_bounds, true))
1246 }
1247 } else {
1248 None
1249 };
1250 (hunk, hitbox)
1251 })
1252 .collect()
1253 }
1254
1255 #[allow(clippy::too_many_arguments)]
1256 fn layout_inline_blame(
1257 &self,
1258 display_row: DisplayRow,
1259 display_snapshot: &DisplaySnapshot,
1260 line_layout: &LineWithInvisibles,
1261 flap_trailer: Option<&FlapTrailerLayout>,
1262 em_width: Pixels,
1263 content_origin: gpui::Point<Pixels>,
1264 scroll_pixel_position: gpui::Point<Pixels>,
1265 line_height: Pixels,
1266 cx: &mut WindowContext,
1267 ) -> Option<AnyElement> {
1268 if !self
1269 .editor
1270 .update(cx, |editor, cx| editor.render_git_blame_inline(cx))
1271 {
1272 return None;
1273 }
1274
1275 let workspace = self
1276 .editor
1277 .read(cx)
1278 .workspace
1279 .as_ref()
1280 .map(|(w, _)| w.clone());
1281
1282 let display_point = DisplayPoint::new(display_row, 0);
1283 let buffer_row = MultiBufferRow(display_point.to_point(display_snapshot).row);
1284
1285 let blame = self.editor.read(cx).blame.clone()?;
1286 let blame_entry = blame
1287 .update(cx, |blame, cx| {
1288 blame.blame_for_rows([Some(buffer_row)], cx).next()
1289 })
1290 .flatten()?;
1291
1292 let mut element =
1293 render_inline_blame_entry(&blame, blame_entry, &self.style, workspace, cx);
1294
1295 let start_y = content_origin.y
1296 + line_height * (display_row.as_f32() - scroll_pixel_position.y / line_height);
1297
1298 let start_x = {
1299 const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 6.;
1300
1301 let line_end = if let Some(flap_trailer) = flap_trailer {
1302 flap_trailer.bounds.right()
1303 } else {
1304 content_origin.x - scroll_pixel_position.x + line_layout.width
1305 };
1306 let padded_line_end = line_end + em_width * INLINE_BLAME_PADDING_EM_WIDTHS;
1307
1308 let min_column_in_pixels = ProjectSettings::get_global(cx)
1309 .git
1310 .inline_blame
1311 .and_then(|settings| settings.min_column)
1312 .map(|col| self.column_pixels(col as usize, cx))
1313 .unwrap_or(px(0.));
1314 let min_start = content_origin.x - scroll_pixel_position.x + min_column_in_pixels;
1315
1316 cmp::max(padded_line_end, min_start)
1317 };
1318
1319 let absolute_offset = point(start_x, start_y);
1320 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1321
1322 element.prepaint_as_root(absolute_offset, available_space, cx);
1323
1324 Some(element)
1325 }
1326
1327 #[allow(clippy::too_many_arguments)]
1328 fn layout_blame_entries(
1329 &self,
1330 buffer_rows: impl Iterator<Item = Option<MultiBufferRow>>,
1331 em_width: Pixels,
1332 scroll_position: gpui::Point<f32>,
1333 line_height: Pixels,
1334 gutter_hitbox: &Hitbox,
1335 max_width: Option<Pixels>,
1336 cx: &mut WindowContext,
1337 ) -> Option<Vec<AnyElement>> {
1338 if !self
1339 .editor
1340 .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1341 {
1342 return None;
1343 }
1344
1345 let blame = self.editor.read(cx).blame.clone()?;
1346 let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1347 blame.blame_for_rows(buffer_rows, cx).collect()
1348 });
1349
1350 let width = if let Some(max_width) = max_width {
1351 AvailableSpace::Definite(max_width)
1352 } else {
1353 AvailableSpace::MaxContent
1354 };
1355 let scroll_top = scroll_position.y * line_height;
1356 let start_x = em_width * 1;
1357
1358 let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1359
1360 let shaped_lines = blamed_rows
1361 .into_iter()
1362 .enumerate()
1363 .flat_map(|(ix, blame_entry)| {
1364 if let Some(blame_entry) = blame_entry {
1365 let mut element = render_blame_entry(
1366 ix,
1367 &blame,
1368 blame_entry,
1369 &self.style,
1370 &mut last_used_color,
1371 self.editor.clone(),
1372 cx,
1373 );
1374
1375 let start_y = ix as f32 * line_height - (scroll_top % line_height);
1376 let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1377
1378 element.prepaint_as_root(
1379 absolute_offset,
1380 size(width, AvailableSpace::MinContent),
1381 cx,
1382 );
1383
1384 Some(element)
1385 } else {
1386 None
1387 }
1388 })
1389 .collect();
1390
1391 Some(shaped_lines)
1392 }
1393
1394 #[allow(clippy::too_many_arguments)]
1395 fn layout_indent_guides(
1396 &self,
1397 content_origin: gpui::Point<Pixels>,
1398 text_origin: gpui::Point<Pixels>,
1399 visible_buffer_range: Range<MultiBufferRow>,
1400 scroll_pixel_position: gpui::Point<Pixels>,
1401 line_height: Pixels,
1402 snapshot: &DisplaySnapshot,
1403 cx: &mut WindowContext,
1404 ) -> Option<Vec<IndentGuideLayout>> {
1405 let indent_guides = self.editor.update(cx, |editor, cx| {
1406 editor.indent_guides(visible_buffer_range, snapshot, cx)
1407 })?;
1408
1409 let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
1410 editor
1411 .find_active_indent_guide_indices(&indent_guides, snapshot, cx)
1412 .unwrap_or_default()
1413 });
1414
1415 Some(
1416 indent_guides
1417 .into_iter()
1418 .enumerate()
1419 .filter_map(|(i, indent_guide)| {
1420 let single_indent_width =
1421 self.column_pixels(indent_guide.tab_size as usize, cx);
1422 let total_width = single_indent_width * indent_guide.depth as f32;
1423 let start_x = content_origin.x + total_width - scroll_pixel_position.x;
1424 if start_x >= text_origin.x {
1425 let (offset_y, length) = Self::calculate_indent_guide_bounds(
1426 indent_guide.multibuffer_row_range.clone(),
1427 line_height,
1428 snapshot,
1429 );
1430
1431 let start_y = content_origin.y + offset_y - scroll_pixel_position.y;
1432
1433 Some(IndentGuideLayout {
1434 origin: point(start_x, start_y),
1435 length,
1436 single_indent_width,
1437 depth: indent_guide.depth,
1438 active: active_indent_guide_indices.contains(&i),
1439 settings: indent_guide.settings,
1440 })
1441 } else {
1442 None
1443 }
1444 })
1445 .collect(),
1446 )
1447 }
1448
1449 fn calculate_indent_guide_bounds(
1450 row_range: Range<MultiBufferRow>,
1451 line_height: Pixels,
1452 snapshot: &DisplaySnapshot,
1453 ) -> (gpui::Pixels, gpui::Pixels) {
1454 let start_point = Point::new(row_range.start.0, 0);
1455 let end_point = Point::new(row_range.end.0, 0);
1456
1457 let row_range = start_point.to_display_point(snapshot).row()
1458 ..end_point.to_display_point(snapshot).row();
1459
1460 let mut prev_line = start_point;
1461 prev_line.row = prev_line.row.saturating_sub(1);
1462 let prev_line = prev_line.to_display_point(snapshot).row();
1463
1464 let mut cons_line = end_point;
1465 cons_line.row += 1;
1466 let cons_line = cons_line.to_display_point(snapshot).row();
1467
1468 let mut offset_y = row_range.start.0 as f32 * line_height;
1469 let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
1470
1471 // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
1472 if row_range.end == cons_line {
1473 length += line_height;
1474 }
1475
1476 // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
1477 // we want to extend the indent guide to the start of the block.
1478 let mut block_height = 0;
1479 let mut block_offset = 0;
1480 let mut found_excerpt_header = false;
1481 for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
1482 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
1483 found_excerpt_header = true;
1484 break;
1485 }
1486 block_offset += block.height();
1487 block_height += block.height();
1488 }
1489 if !found_excerpt_header {
1490 offset_y -= block_offset as f32 * line_height;
1491 length += block_height as f32 * line_height;
1492 }
1493
1494 // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
1495 // we want to ensure that the indent guide stops before the excerpt header.
1496 let mut block_height = 0;
1497 let mut found_excerpt_header = false;
1498 for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
1499 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
1500 found_excerpt_header = true;
1501 }
1502 block_height += block.height();
1503 }
1504 if found_excerpt_header {
1505 length -= block_height as f32 * line_height;
1506 }
1507
1508 (offset_y, length)
1509 }
1510
1511 fn layout_run_indicators(
1512 &self,
1513 line_height: Pixels,
1514 scroll_pixel_position: gpui::Point<Pixels>,
1515 gutter_dimensions: &GutterDimensions,
1516 gutter_hitbox: &Hitbox,
1517 snapshot: &EditorSnapshot,
1518 cx: &mut WindowContext,
1519 ) -> Vec<AnyElement> {
1520 self.editor.update(cx, |editor, cx| {
1521 let active_task_indicator_row =
1522 if let Some(crate::ContextMenu::CodeActions(CodeActionsMenu {
1523 deployed_from_indicator,
1524 actions,
1525 ..
1526 })) = editor.context_menu.read().as_ref()
1527 {
1528 actions
1529 .tasks
1530 .as_ref()
1531 .map(|tasks| tasks.position.to_display_point(snapshot).row())
1532 .or_else(|| *deployed_from_indicator)
1533 } else {
1534 None
1535 };
1536 editor
1537 .tasks
1538 .iter()
1539 .filter_map(|(_, tasks)| {
1540 let multibuffer_point = tasks.offset.0.to_point(&snapshot.buffer_snapshot);
1541 let multibuffer_row = MultiBufferRow(multibuffer_point.row);
1542 if snapshot.is_line_folded(multibuffer_row) {
1543 return None;
1544 }
1545 let display_row = multibuffer_point.to_display_point(snapshot).row();
1546 let button = editor.render_run_indicator(
1547 &self.style,
1548 Some(display_row) == active_task_indicator_row,
1549 display_row,
1550 cx,
1551 );
1552
1553 let button = prepaint_gutter_button(
1554 button,
1555 display_row,
1556 line_height,
1557 gutter_dimensions,
1558 scroll_pixel_position,
1559 gutter_hitbox,
1560 cx,
1561 );
1562 Some(button)
1563 })
1564 .collect_vec()
1565 })
1566 }
1567
1568 fn layout_code_actions_indicator(
1569 &self,
1570 line_height: Pixels,
1571 newest_selection_head: DisplayPoint,
1572 scroll_pixel_position: gpui::Point<Pixels>,
1573 gutter_dimensions: &GutterDimensions,
1574 gutter_hitbox: &Hitbox,
1575 cx: &mut WindowContext,
1576 ) -> Option<AnyElement> {
1577 let mut active = false;
1578 let mut button = None;
1579 let row = newest_selection_head.row();
1580 self.editor.update(cx, |editor, cx| {
1581 if let Some(crate::ContextMenu::CodeActions(CodeActionsMenu {
1582 deployed_from_indicator,
1583 ..
1584 })) = editor.context_menu.read().as_ref()
1585 {
1586 active = deployed_from_indicator.map_or(true, |indicator_row| indicator_row == row);
1587 };
1588 button = editor.render_code_actions_indicator(&self.style, row, active, cx);
1589 });
1590
1591 let button = prepaint_gutter_button(
1592 button?,
1593 row,
1594 line_height,
1595 gutter_dimensions,
1596 scroll_pixel_position,
1597 gutter_hitbox,
1598 cx,
1599 );
1600
1601 Some(button)
1602 }
1603
1604 fn get_participant_color(
1605 participant_index: Option<ParticipantIndex>,
1606 cx: &WindowContext,
1607 ) -> PlayerColor {
1608 if let Some(index) = participant_index {
1609 cx.theme().players().color_for_participant(index.0)
1610 } else {
1611 cx.theme().players().absent()
1612 }
1613 }
1614
1615 fn calculate_relative_line_numbers(
1616 &self,
1617 snapshot: &EditorSnapshot,
1618 rows: &Range<DisplayRow>,
1619 relative_to: Option<DisplayRow>,
1620 ) -> HashMap<DisplayRow, DisplayRowDelta> {
1621 let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
1622 let Some(relative_to) = relative_to else {
1623 return relative_rows;
1624 };
1625
1626 let start = rows.start.min(relative_to);
1627 let end = rows.end.max(relative_to);
1628
1629 let buffer_rows = snapshot
1630 .buffer_rows(start)
1631 .take(1 + end.minus(start) as usize)
1632 .collect::<Vec<_>>();
1633
1634 let head_idx = relative_to.minus(start);
1635 let mut delta = 1;
1636 let mut i = head_idx + 1;
1637 while i < buffer_rows.len() as u32 {
1638 if buffer_rows[i as usize].is_some() {
1639 if rows.contains(&DisplayRow(i + start.0)) {
1640 relative_rows.insert(DisplayRow(i + start.0), delta);
1641 }
1642 delta += 1;
1643 }
1644 i += 1;
1645 }
1646 delta = 1;
1647 i = head_idx.min(buffer_rows.len() as u32 - 1);
1648 while i > 0 && buffer_rows[i as usize].is_none() {
1649 i -= 1;
1650 }
1651
1652 while i > 0 {
1653 i -= 1;
1654 if buffer_rows[i as usize].is_some() {
1655 if rows.contains(&DisplayRow(i + start.0)) {
1656 relative_rows.insert(DisplayRow(i + start.0), delta);
1657 }
1658 delta += 1;
1659 }
1660 }
1661
1662 relative_rows
1663 }
1664
1665 fn layout_line_numbers(
1666 &self,
1667 rows: Range<DisplayRow>,
1668 buffer_rows: impl Iterator<Item = Option<MultiBufferRow>>,
1669 active_rows: &BTreeMap<DisplayRow, bool>,
1670 newest_selection_head: Option<DisplayPoint>,
1671 snapshot: &EditorSnapshot,
1672 cx: &mut WindowContext,
1673 ) -> Vec<Option<ShapedLine>> {
1674 let include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
1675 EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full
1676 });
1677 if !include_line_numbers {
1678 return Vec::new();
1679 }
1680
1681 let editor = self.editor.read(cx);
1682 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1683 let newest = editor.selections.newest::<Point>(cx);
1684 SelectionLayout::new(
1685 newest,
1686 editor.selections.line_mode,
1687 editor.cursor_shape,
1688 &snapshot.display_snapshot,
1689 true,
1690 true,
1691 None,
1692 )
1693 .head
1694 });
1695 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1696
1697 let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1698 let relative_to = if is_relative {
1699 Some(newest_selection_head.row())
1700 } else {
1701 None
1702 };
1703 let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
1704 let mut line_number = String::new();
1705 buffer_rows
1706 .into_iter()
1707 .enumerate()
1708 .map(|(ix, multibuffer_row)| {
1709 let multibuffer_row = multibuffer_row?;
1710 let display_row = DisplayRow(rows.start.0 + ix as u32);
1711 let color = if active_rows.contains_key(&display_row) {
1712 cx.theme().colors().editor_active_line_number
1713 } else {
1714 cx.theme().colors().editor_line_number
1715 };
1716 line_number.clear();
1717 let default_number = multibuffer_row.0 + 1;
1718 let number = relative_rows
1719 .get(&DisplayRow(ix as u32 + rows.start.0))
1720 .unwrap_or(&default_number);
1721 write!(&mut line_number, "{number}").unwrap();
1722 let run = TextRun {
1723 len: line_number.len(),
1724 font: self.style.text.font(),
1725 color,
1726 background_color: None,
1727 underline: None,
1728 strikethrough: None,
1729 };
1730 let shaped_line = cx
1731 .text_system()
1732 .shape_line(line_number.clone().into(), font_size, &[run])
1733 .unwrap();
1734 Some(shaped_line)
1735 })
1736 .collect()
1737 }
1738
1739 fn layout_gutter_fold_toggles(
1740 &self,
1741 rows: Range<DisplayRow>,
1742 buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1743 active_rows: &BTreeMap<DisplayRow, bool>,
1744 snapshot: &EditorSnapshot,
1745 cx: &mut WindowContext,
1746 ) -> Vec<Option<AnyElement>> {
1747 let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
1748 && snapshot.mode == EditorMode::Full
1749 && self.editor.read(cx).is_singleton(cx);
1750 if include_fold_statuses {
1751 buffer_rows
1752 .into_iter()
1753 .enumerate()
1754 .map(|(ix, row)| {
1755 if let Some(multibuffer_row) = row {
1756 let display_row = DisplayRow(rows.start.0 + ix as u32);
1757 let active = active_rows.contains_key(&display_row);
1758 snapshot.render_fold_toggle(
1759 multibuffer_row,
1760 active,
1761 self.editor.clone(),
1762 cx,
1763 )
1764 } else {
1765 None
1766 }
1767 })
1768 .collect()
1769 } else {
1770 Vec::new()
1771 }
1772 }
1773
1774 fn layout_flap_trailers(
1775 &self,
1776 buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1777 snapshot: &EditorSnapshot,
1778 cx: &mut WindowContext,
1779 ) -> Vec<Option<AnyElement>> {
1780 buffer_rows
1781 .into_iter()
1782 .map(|row| {
1783 if let Some(multibuffer_row) = row {
1784 snapshot.render_flap_trailer(multibuffer_row, cx)
1785 } else {
1786 None
1787 }
1788 })
1789 .collect()
1790 }
1791
1792 fn layout_lines(
1793 &self,
1794 rows: Range<DisplayRow>,
1795 line_number_layouts: &[Option<ShapedLine>],
1796 snapshot: &EditorSnapshot,
1797 cx: &mut WindowContext,
1798 ) -> Vec<LineWithInvisibles> {
1799 if rows.start >= rows.end {
1800 return Vec::new();
1801 }
1802
1803 // Show the placeholder when the editor is empty
1804 if snapshot.is_empty() {
1805 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1806 let placeholder_color = cx.theme().colors().text_placeholder;
1807 let placeholder_text = snapshot.placeholder_text();
1808
1809 let placeholder_lines = placeholder_text
1810 .as_ref()
1811 .map_or("", AsRef::as_ref)
1812 .split('\n')
1813 .skip(rows.start.0 as usize)
1814 .chain(iter::repeat(""))
1815 .take(rows.len());
1816 placeholder_lines
1817 .filter_map(move |line| {
1818 let run = TextRun {
1819 len: line.len(),
1820 font: self.style.text.font(),
1821 color: placeholder_color,
1822 background_color: None,
1823 underline: Default::default(),
1824 strikethrough: None,
1825 };
1826 cx.text_system()
1827 .shape_line(line.to_string().into(), font_size, &[run])
1828 .log_err()
1829 })
1830 .map(|line| LineWithInvisibles {
1831 width: line.width,
1832 len: line.len,
1833 fragments: smallvec![LineFragment::Text(line)],
1834 invisibles: Vec::new(),
1835 font_size,
1836 })
1837 .collect()
1838 } else {
1839 let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1840 LineWithInvisibles::from_chunks(
1841 chunks,
1842 &self.style.text,
1843 MAX_LINE_LEN,
1844 rows.len(),
1845 line_number_layouts,
1846 snapshot.mode,
1847 cx,
1848 )
1849 }
1850 }
1851
1852 fn prepaint_lines(
1853 &self,
1854 start_row: DisplayRow,
1855 line_layouts: &mut [LineWithInvisibles],
1856 line_height: Pixels,
1857 scroll_pixel_position: gpui::Point<Pixels>,
1858 content_origin: gpui::Point<Pixels>,
1859 cx: &mut WindowContext,
1860 ) -> SmallVec<[AnyElement; 1]> {
1861 let mut line_elements = SmallVec::new();
1862 for (ix, line) in line_layouts.iter_mut().enumerate() {
1863 let row = start_row + DisplayRow(ix as u32);
1864 line.prepaint(
1865 line_height,
1866 scroll_pixel_position,
1867 row,
1868 content_origin,
1869 &mut line_elements,
1870 cx,
1871 );
1872 }
1873 line_elements
1874 }
1875
1876 #[allow(clippy::too_many_arguments)]
1877 fn build_blocks(
1878 &self,
1879 rows: Range<DisplayRow>,
1880 snapshot: &EditorSnapshot,
1881 hitbox: &Hitbox,
1882 text_hitbox: &Hitbox,
1883 scroll_width: &mut Pixels,
1884 gutter_dimensions: &GutterDimensions,
1885 em_width: Pixels,
1886 text_x: Pixels,
1887 line_height: Pixels,
1888 line_layouts: &[LineWithInvisibles],
1889 cx: &mut WindowContext,
1890 ) -> Vec<BlockLayout> {
1891 let mut block_id = 0;
1892 let (fixed_blocks, non_fixed_blocks) = snapshot
1893 .blocks_in_range(rows.clone())
1894 .partition::<Vec<_>, _>(|(_, block)| match block {
1895 TransformBlock::ExcerptHeader { .. } => false,
1896 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1897 TransformBlock::ExcerptFooter { .. } => false,
1898 });
1899
1900 let render_block = |block: &TransformBlock,
1901 available_space: Size<AvailableSpace>,
1902 block_id: usize,
1903 block_row_start: DisplayRow,
1904 cx: &mut WindowContext| {
1905 let mut element = match block {
1906 TransformBlock::Custom(block) => {
1907 let align_to = block
1908 .position()
1909 .to_point(&snapshot.buffer_snapshot)
1910 .to_display_point(snapshot);
1911 let anchor_x = text_x
1912 + if rows.contains(&align_to.row()) {
1913 line_layouts[align_to.row().minus(rows.start) as usize]
1914 .x_for_index(align_to.column() as usize)
1915 } else {
1916 layout_line(align_to.row(), snapshot, &self.style, cx)
1917 .x_for_index(align_to.column() as usize)
1918 };
1919
1920 block.render(&mut BlockContext {
1921 context: cx,
1922 anchor_x,
1923 gutter_dimensions,
1924 line_height,
1925 em_width,
1926 block_id,
1927 max_width: text_hitbox.size.width.max(*scroll_width),
1928 editor_style: &self.style,
1929 })
1930 }
1931
1932 TransformBlock::ExcerptHeader {
1933 buffer,
1934 range,
1935 starts_new_buffer,
1936 height,
1937 id,
1938 show_excerpt_controls,
1939 ..
1940 } => {
1941 let include_root = self
1942 .editor
1943 .read(cx)
1944 .project
1945 .as_ref()
1946 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1947 .unwrap_or_default();
1948
1949 #[derive(Clone)]
1950 struct JumpData {
1951 position: Point,
1952 anchor: text::Anchor,
1953 path: ProjectPath,
1954 line_offset_from_top: u32,
1955 }
1956
1957 let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
1958 let jump_path = ProjectPath {
1959 worktree_id: file.worktree_id(cx),
1960 path: file.path.clone(),
1961 };
1962 let jump_anchor = range
1963 .primary
1964 .as_ref()
1965 .map_or(range.context.start, |primary| primary.start);
1966
1967 let excerpt_start = range.context.start;
1968 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1969 let offset_from_excerpt_start = if jump_anchor == excerpt_start {
1970 0
1971 } else {
1972 let excerpt_start_row =
1973 language::ToPoint::to_point(&jump_anchor, buffer).row;
1974 jump_position.row - excerpt_start_row
1975 };
1976
1977 let line_offset_from_top =
1978 block_row_start.0 + *height as u32 + offset_from_excerpt_start
1979 - snapshot
1980 .scroll_anchor
1981 .scroll_position(&snapshot.display_snapshot)
1982 .y as u32;
1983
1984 JumpData {
1985 position: jump_position,
1986 anchor: jump_anchor,
1987 path: jump_path,
1988 line_offset_from_top,
1989 }
1990 });
1991
1992 let icon_offset = gutter_dimensions.width
1993 - (gutter_dimensions.left_padding + gutter_dimensions.margin);
1994
1995 let element = if *starts_new_buffer {
1996 let path = buffer.resolve_file_path(cx, include_root);
1997 let mut filename = None;
1998 let mut parent_path = None;
1999 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2000 if let Some(path) = path {
2001 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
2002 parent_path = path
2003 .parent()
2004 .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
2005 }
2006
2007 let header_padding = px(6.0);
2008
2009 v_flex()
2010 .id(("path excerpt header", block_id))
2011 .size_full()
2012 .p(header_padding)
2013 .child(
2014 h_flex()
2015 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
2016 .id("path header block")
2017 .pl(gpui::px(12.))
2018 .pr(gpui::px(8.))
2019 .rounded_md()
2020 .shadow_md()
2021 .border_1()
2022 .border_color(cx.theme().colors().border)
2023 .bg(cx.theme().colors().editor_subheader_background)
2024 .justify_between()
2025 .hover(|style| style.bg(cx.theme().colors().element_hover))
2026 .child(
2027 h_flex().gap_3().child(
2028 h_flex()
2029 .gap_2()
2030 .child(
2031 filename
2032 .map(SharedString::from)
2033 .unwrap_or_else(|| "untitled".into()),
2034 )
2035 .when_some(parent_path, |then, path| {
2036 then.child(
2037 div().child(path).text_color(
2038 cx.theme().colors().text_muted,
2039 ),
2040 )
2041 }),
2042 ),
2043 )
2044 .when_some(jump_data.clone(), |this, jump_data| {
2045 this.cursor_pointer()
2046 .tooltip(|cx| {
2047 Tooltip::for_action(
2048 "Jump to File",
2049 &OpenExcerpts,
2050 cx,
2051 )
2052 })
2053 .on_mouse_down(MouseButton::Left, |_, cx| {
2054 cx.stop_propagation()
2055 })
2056 .on_click(cx.listener_for(&self.editor, {
2057 move |editor, _, cx| {
2058 editor.jump(
2059 jump_data.path.clone(),
2060 jump_data.position,
2061 jump_data.anchor,
2062 jump_data.line_offset_from_top,
2063 cx,
2064 );
2065 }
2066 }))
2067 }),
2068 )
2069 .children(show_excerpt_controls.then(|| {
2070 h_flex()
2071 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.333)))
2072 .pt_1()
2073 .justify_end()
2074 .flex_none()
2075 .w(icon_offset - header_padding)
2076 .child(
2077 ButtonLike::new("expand-icon")
2078 .style(ButtonStyle::Transparent)
2079 .child(
2080 svg()
2081 .path(IconName::ArrowUpFromLine.path())
2082 .size(IconSize::XSmall.rems())
2083 .text_color(
2084 cx.theme().colors().editor_line_number,
2085 )
2086 .group("")
2087 .hover(|style| {
2088 style.text_color(
2089 cx.theme()
2090 .colors()
2091 .editor_active_line_number,
2092 )
2093 }),
2094 )
2095 .on_click(cx.listener_for(&self.editor, {
2096 let id = *id;
2097 move |editor, _, cx| {
2098 editor.expand_excerpt(
2099 id,
2100 multi_buffer::ExpandExcerptDirection::Up,
2101 cx,
2102 );
2103 }
2104 }))
2105 .tooltip({
2106 move |cx| {
2107 Tooltip::for_action(
2108 "Expand Excerpt",
2109 &ExpandExcerpts { lines: 0 },
2110 cx,
2111 )
2112 }
2113 }),
2114 )
2115 }))
2116 } else {
2117 v_flex()
2118 .id(("excerpt header", block_id))
2119 .size_full()
2120 .child(
2121 div()
2122 .flex()
2123 .v_flex()
2124 .justify_start()
2125 .id("jump to collapsed context")
2126 .w(relative(1.0))
2127 .h_full()
2128 .child(
2129 div()
2130 .h_px()
2131 .w_full()
2132 .bg(cx.theme().colors().border_variant)
2133 .group_hover("excerpt-jump-action", |style| {
2134 style.bg(cx.theme().colors().border)
2135 }),
2136 ),
2137 )
2138 .child(
2139 h_flex()
2140 .justify_end()
2141 .flex_none()
2142 .w(icon_offset)
2143 .h_full()
2144 .child(
2145 show_excerpt_controls.then(|| {
2146 ButtonLike::new("expand-icon")
2147 .style(ButtonStyle::Transparent)
2148 .child(
2149 svg()
2150 .path(IconName::ArrowUpFromLine.path())
2151 .size(IconSize::XSmall.rems())
2152 .text_color(
2153 cx.theme().colors().editor_line_number,
2154 )
2155 .group("")
2156 .hover(|style| {
2157 style.text_color(
2158 cx.theme()
2159 .colors()
2160 .editor_active_line_number,
2161 )
2162 }),
2163 )
2164 .on_click(cx.listener_for(&self.editor, {
2165 let id = *id;
2166 move |editor, _, cx| {
2167 editor.expand_excerpt(
2168 id,
2169 multi_buffer::ExpandExcerptDirection::Up,
2170 cx,
2171 );
2172 }
2173 }))
2174 .tooltip({
2175 move |cx| {
2176 Tooltip::for_action(
2177 "Expand Excerpt",
2178 &ExpandExcerpts { lines: 0 },
2179 cx,
2180 )
2181 }
2182 })
2183 }).unwrap_or_else(|| {
2184 ButtonLike::new("jump-icon")
2185 .style(ButtonStyle::Transparent)
2186 .child(
2187 svg()
2188 .path(IconName::ArrowUpRight.path())
2189 .size(IconSize::XSmall.rems())
2190 .text_color(
2191 cx.theme().colors().border_variant,
2192 )
2193 .group("excerpt-jump-action")
2194 .group_hover("excerpt-jump-action", |style| {
2195 style.text_color(
2196 cx.theme().colors().border
2197
2198 )
2199 })
2200 )
2201 .when_some(jump_data.clone(), |this, jump_data| {
2202 this.on_click(cx.listener_for(&self.editor, {
2203 let path = jump_data.path.clone();
2204 move |editor, _, cx| {
2205 cx.stop_propagation();
2206
2207 editor.jump(
2208 path.clone(),
2209 jump_data.position,
2210 jump_data.anchor,
2211 jump_data.line_offset_from_top,
2212 cx,
2213 );
2214 }
2215 }))
2216 .tooltip(move |cx| {
2217 Tooltip::for_action(
2218 format!(
2219 "Jump to {}:L{}",
2220 jump_data.path.path.display(),
2221 jump_data.position.row + 1
2222 ),
2223 &OpenExcerpts,
2224 cx,
2225 )
2226 })
2227 })
2228 })
2229
2230 ),
2231 )
2232 .group("excerpt-jump-action")
2233 .cursor_pointer()
2234 .when_some(jump_data.clone(), |this, jump_data| {
2235 this.on_click(cx.listener_for(&self.editor, {
2236 let path = jump_data.path.clone();
2237 move |editor, _, cx| {
2238 cx.stop_propagation();
2239
2240 editor.jump(
2241 path.clone(),
2242 jump_data.position,
2243 jump_data.anchor,
2244 jump_data.line_offset_from_top,
2245 cx,
2246 );
2247 }
2248 }))
2249 .tooltip(move |cx| {
2250 Tooltip::for_action(
2251 format!(
2252 "Jump to {}:L{}",
2253 jump_data.path.path.display(),
2254 jump_data.position.row + 1
2255 ),
2256 &OpenExcerpts,
2257 cx,
2258 )
2259 })
2260 })
2261 };
2262 element.into_any()
2263 }
2264
2265 TransformBlock::ExcerptFooter { id, .. } => {
2266 let element = v_flex().id(("excerpt footer", block_id)).size_full().child(
2267 h_flex()
2268 .justify_end()
2269 .flex_none()
2270 .w(gutter_dimensions.width
2271 - (gutter_dimensions.left_padding + gutter_dimensions.margin))
2272 .h_full()
2273 .child(
2274 ButtonLike::new("expand-icon")
2275 .style(ButtonStyle::Transparent)
2276 .child(
2277 svg()
2278 .path(IconName::ArrowDownFromLine.path())
2279 .size(IconSize::XSmall.rems())
2280 .text_color(cx.theme().colors().editor_line_number)
2281 .group("")
2282 .hover(|style| {
2283 style.text_color(
2284 cx.theme().colors().editor_active_line_number,
2285 )
2286 }),
2287 )
2288 .on_click(cx.listener_for(&self.editor, {
2289 let id = *id;
2290 move |editor, _, cx| {
2291 editor.expand_excerpt(
2292 id,
2293 multi_buffer::ExpandExcerptDirection::Down,
2294 cx,
2295 );
2296 }
2297 }))
2298 .tooltip({
2299 move |cx| {
2300 Tooltip::for_action(
2301 "Expand Excerpt",
2302 &ExpandExcerpts { lines: 0 },
2303 cx,
2304 )
2305 }
2306 }),
2307 ),
2308 );
2309 element.into_any()
2310 }
2311 };
2312
2313 let size = element.layout_as_root(available_space, cx);
2314 (element, size)
2315 };
2316
2317 let mut fixed_block_max_width = Pixels::ZERO;
2318 let mut blocks = Vec::new();
2319 for (row, block) in fixed_blocks {
2320 let available_space = size(
2321 AvailableSpace::MinContent,
2322 AvailableSpace::Definite(block.height() as f32 * line_height),
2323 );
2324 let (element, element_size) = render_block(block, available_space, block_id, row, cx);
2325 block_id += 1;
2326 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2327 blocks.push(BlockLayout {
2328 row,
2329 element,
2330 available_space,
2331 style: BlockStyle::Fixed,
2332 });
2333 }
2334 for (row, block) in non_fixed_blocks {
2335 let style = match block {
2336 TransformBlock::Custom(block) => block.style(),
2337 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
2338 TransformBlock::ExcerptFooter { .. } => BlockStyle::Sticky,
2339 };
2340 let width = match style {
2341 BlockStyle::Sticky => hitbox.size.width,
2342 BlockStyle::Flex => hitbox
2343 .size
2344 .width
2345 .max(fixed_block_max_width)
2346 .max(gutter_dimensions.width + *scroll_width),
2347 BlockStyle::Fixed => unreachable!(),
2348 };
2349 let available_space = size(
2350 AvailableSpace::Definite(width),
2351 AvailableSpace::Definite(block.height() as f32 * line_height),
2352 );
2353 let (element, _) = render_block(block, available_space, block_id, row, cx);
2354 block_id += 1;
2355 blocks.push(BlockLayout {
2356 row,
2357 element,
2358 available_space,
2359 style,
2360 });
2361 }
2362
2363 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2364 blocks
2365 }
2366
2367 fn layout_blocks(
2368 &self,
2369 blocks: &mut Vec<BlockLayout>,
2370 hitbox: &Hitbox,
2371 line_height: Pixels,
2372 scroll_pixel_position: gpui::Point<Pixels>,
2373 cx: &mut WindowContext,
2374 ) {
2375 for block in blocks {
2376 let mut origin = hitbox.origin
2377 + point(
2378 Pixels::ZERO,
2379 block.row.as_f32() * line_height - scroll_pixel_position.y,
2380 );
2381 if !matches!(block.style, BlockStyle::Sticky) {
2382 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2383 }
2384 block
2385 .element
2386 .prepaint_as_root(origin, block.available_space, cx);
2387 }
2388 }
2389
2390 #[allow(clippy::too_many_arguments)]
2391 fn layout_context_menu(
2392 &self,
2393 line_height: Pixels,
2394 hitbox: &Hitbox,
2395 text_hitbox: &Hitbox,
2396 content_origin: gpui::Point<Pixels>,
2397 start_row: DisplayRow,
2398 scroll_pixel_position: gpui::Point<Pixels>,
2399 line_layouts: &[LineWithInvisibles],
2400 newest_selection_head: DisplayPoint,
2401 gutter_overshoot: Pixels,
2402 cx: &mut WindowContext,
2403 ) -> bool {
2404 let max_height = cmp::min(
2405 12. * line_height,
2406 cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
2407 );
2408 let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
2409 if editor.context_menu_visible() {
2410 editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
2411 } else {
2412 None
2413 }
2414 }) else {
2415 return false;
2416 };
2417
2418 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2419 let context_menu_size = context_menu.layout_as_root(available_space, cx);
2420
2421 let (x, y) = match position {
2422 crate::ContextMenuOrigin::EditorPoint(point) => {
2423 let cursor_row_layout = &line_layouts[point.row().minus(start_row) as usize];
2424 let x = cursor_row_layout.x_for_index(point.column() as usize)
2425 - scroll_pixel_position.x;
2426 let y = point.row().next_row().as_f32() * line_height - scroll_pixel_position.y;
2427 (x, y)
2428 }
2429 crate::ContextMenuOrigin::GutterIndicator(row) => {
2430 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the indicator than just a plain first column of the
2431 // text field.
2432 let x = -gutter_overshoot;
2433 let y = row.next_row().as_f32() * line_height - scroll_pixel_position.y;
2434 (x, y)
2435 }
2436 };
2437
2438 let mut list_origin = content_origin + point(x, y);
2439 let list_width = context_menu_size.width;
2440 let list_height = context_menu_size.height;
2441
2442 // Snap the right edge of the list to the right edge of the window if
2443 // its horizontal bounds overflow.
2444 if list_origin.x + list_width > cx.viewport_size().width {
2445 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
2446 }
2447
2448 if list_origin.y + list_height > text_hitbox.lower_right().y {
2449 list_origin.y -= line_height + list_height;
2450 }
2451
2452 cx.defer_draw(context_menu, list_origin, 1);
2453 true
2454 }
2455
2456 fn layout_mouse_context_menu(&self, cx: &mut WindowContext) -> Option<AnyElement> {
2457 let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
2458 let mut element = deferred(
2459 anchored()
2460 .position(mouse_context_menu.position)
2461 .child(mouse_context_menu.context_menu.clone())
2462 .anchor(AnchorCorner::TopLeft)
2463 .snap_to_window(),
2464 )
2465 .with_priority(1)
2466 .into_any();
2467
2468 element.prepaint_as_root(gpui::Point::default(), AvailableSpace::min_size(), cx);
2469 Some(element)
2470 }
2471
2472 #[allow(clippy::too_many_arguments)]
2473 fn layout_hover_popovers(
2474 &self,
2475 snapshot: &EditorSnapshot,
2476 hitbox: &Hitbox,
2477 text_hitbox: &Hitbox,
2478 visible_display_row_range: Range<DisplayRow>,
2479 content_origin: gpui::Point<Pixels>,
2480 scroll_pixel_position: gpui::Point<Pixels>,
2481 line_layouts: &[LineWithInvisibles],
2482 line_height: Pixels,
2483 em_width: Pixels,
2484 cx: &mut WindowContext,
2485 ) {
2486 struct MeasuredHoverPopover {
2487 element: AnyElement,
2488 size: Size<Pixels>,
2489 horizontal_offset: Pixels,
2490 }
2491
2492 let max_size = size(
2493 (120. * em_width) // Default size
2494 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2495 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2496 (16. * line_height) // Default size
2497 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2498 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2499 );
2500
2501 let hover_popovers = self.editor.update(cx, |editor, cx| {
2502 editor.hover_state.render(
2503 &snapshot,
2504 &self.style,
2505 visible_display_row_range.clone(),
2506 max_size,
2507 editor.workspace.as_ref().map(|(w, _)| w.clone()),
2508 cx,
2509 )
2510 });
2511 let Some((position, hover_popovers)) = hover_popovers else {
2512 return;
2513 };
2514
2515 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2516
2517 // This is safe because we check on layout whether the required row is available
2518 let hovered_row_layout =
2519 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
2520
2521 // Compute Hovered Point
2522 let x =
2523 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
2524 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
2525 let hovered_point = content_origin + point(x, y);
2526
2527 let mut overall_height = Pixels::ZERO;
2528 let mut measured_hover_popovers = Vec::new();
2529 for mut hover_popover in hover_popovers {
2530 let size = hover_popover.layout_as_root(available_space, cx);
2531 let horizontal_offset =
2532 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
2533
2534 overall_height += HOVER_POPOVER_GAP + size.height;
2535
2536 measured_hover_popovers.push(MeasuredHoverPopover {
2537 element: hover_popover,
2538 size,
2539 horizontal_offset,
2540 });
2541 }
2542 overall_height += HOVER_POPOVER_GAP;
2543
2544 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
2545 let mut occlusion = div()
2546 .size_full()
2547 .occlude()
2548 .on_mouse_move(|_, cx| cx.stop_propagation())
2549 .into_any_element();
2550 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
2551 cx.defer_draw(occlusion, origin, 2);
2552 }
2553
2554 if hovered_point.y > overall_height {
2555 // There is enough space above. Render popovers above the hovered point
2556 let mut current_y = hovered_point.y;
2557 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2558 let size = popover.size;
2559 let popover_origin = point(
2560 hovered_point.x + popover.horizontal_offset,
2561 current_y - size.height,
2562 );
2563
2564 cx.defer_draw(popover.element, popover_origin, 2);
2565 if position != itertools::Position::Last {
2566 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
2567 draw_occluder(size.width, origin, cx);
2568 }
2569
2570 current_y = popover_origin.y - HOVER_POPOVER_GAP;
2571 }
2572 } else {
2573 // There is not enough space above. Render popovers below the hovered point
2574 let mut current_y = hovered_point.y + line_height;
2575 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2576 let size = popover.size;
2577 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2578
2579 cx.defer_draw(popover.element, popover_origin, 2);
2580 if position != itertools::Position::Last {
2581 let origin = point(popover_origin.x, popover_origin.y + size.height);
2582 draw_occluder(size.width, origin, cx);
2583 }
2584
2585 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2586 }
2587 }
2588 }
2589
2590 fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2591 cx.paint_layer(layout.hitbox.bounds, |cx| {
2592 let scroll_top = layout.position_map.snapshot.scroll_position().y;
2593 let gutter_bg = cx.theme().colors().editor_gutter_background;
2594 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2595 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2596
2597 if let EditorMode::Full = layout.mode {
2598 let mut active_rows = layout.active_rows.iter().peekable();
2599 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2600 let mut end_row = start_row.0;
2601 while active_rows
2602 .peek()
2603 .map_or(false, |(active_row, has_selection)| {
2604 active_row.0 == end_row + 1
2605 && *has_selection == contains_non_empty_selection
2606 })
2607 {
2608 active_rows.next().unwrap();
2609 end_row += 1;
2610 }
2611
2612 if !contains_non_empty_selection {
2613 let highlight_h_range =
2614 match layout.position_map.snapshot.current_line_highlight {
2615 CurrentLineHighlight::Gutter => Some(Range {
2616 start: layout.hitbox.left(),
2617 end: layout.gutter_hitbox.right(),
2618 }),
2619 CurrentLineHighlight::Line => Some(Range {
2620 start: layout.text_hitbox.bounds.left(),
2621 end: layout.text_hitbox.bounds.right(),
2622 }),
2623 CurrentLineHighlight::All => Some(Range {
2624 start: layout.hitbox.left(),
2625 end: layout.hitbox.right(),
2626 }),
2627 CurrentLineHighlight::None => None,
2628 };
2629 if let Some(range) = highlight_h_range {
2630 let active_line_bg = cx.theme().colors().editor_active_line_background;
2631 let bounds = Bounds {
2632 origin: point(
2633 range.start,
2634 layout.hitbox.origin.y
2635 + (start_row.as_f32() - scroll_top)
2636 * layout.position_map.line_height,
2637 ),
2638 size: size(
2639 range.end - range.start,
2640 layout.position_map.line_height
2641 * (end_row - start_row.0 + 1) as f32,
2642 ),
2643 };
2644 cx.paint_quad(fill(bounds, active_line_bg));
2645 }
2646 }
2647 }
2648
2649 let mut paint_highlight =
2650 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
2651 let origin = point(
2652 layout.hitbox.origin.x,
2653 layout.hitbox.origin.y
2654 + (highlight_row_start.as_f32() - scroll_top)
2655 * layout.position_map.line_height,
2656 );
2657 let size = size(
2658 layout.hitbox.size.width,
2659 layout.position_map.line_height
2660 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
2661 );
2662 cx.paint_quad(fill(Bounds { origin, size }, color));
2663 };
2664
2665 let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
2666 for (&new_row, &new_color) in &layout.highlighted_rows {
2667 match &mut current_paint {
2668 Some((current_color, current_range)) => {
2669 let current_color = *current_color;
2670 let new_range_started = current_color != new_color
2671 || current_range.end.next_row() != new_row;
2672 if new_range_started {
2673 paint_highlight(
2674 current_range.start,
2675 current_range.end,
2676 current_color,
2677 );
2678 current_paint = Some((new_color, new_row..new_row));
2679 continue;
2680 } else {
2681 current_range.end = current_range.end.next_row();
2682 }
2683 }
2684 None => current_paint = Some((new_color, new_row..new_row)),
2685 };
2686 }
2687 if let Some((color, range)) = current_paint {
2688 paint_highlight(range.start, range.end, color);
2689 }
2690
2691 let scroll_left =
2692 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2693
2694 for (wrap_position, active) in layout.wrap_guides.iter() {
2695 let x = (layout.text_hitbox.origin.x
2696 + *wrap_position
2697 + layout.position_map.em_width / 2.)
2698 - scroll_left;
2699
2700 let show_scrollbars = layout
2701 .scrollbar_layout
2702 .as_ref()
2703 .map_or(false, |scrollbar| scrollbar.visible);
2704 if x < layout.text_hitbox.origin.x
2705 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2706 {
2707 continue;
2708 }
2709
2710 let color = if *active {
2711 cx.theme().colors().editor_active_wrap_guide
2712 } else {
2713 cx.theme().colors().editor_wrap_guide
2714 };
2715 cx.paint_quad(fill(
2716 Bounds {
2717 origin: point(x, layout.text_hitbox.origin.y),
2718 size: size(px(1.), layout.text_hitbox.size.height),
2719 },
2720 color,
2721 ));
2722 }
2723 }
2724 })
2725 }
2726
2727 fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2728 let Some(indent_guides) = &layout.indent_guides else {
2729 return;
2730 };
2731
2732 let faded_color = |color: Hsla, alpha: f32| {
2733 let mut faded = color;
2734 faded.a = alpha;
2735 faded
2736 };
2737
2738 for indent_guide in indent_guides {
2739 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
2740 let settings = indent_guide.settings;
2741
2742 // TODO fixed for now, expose them through themes later
2743 const INDENT_AWARE_ALPHA: f32 = 0.2;
2744 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
2745 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
2746 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
2747
2748 let line_color = match (settings.coloring, indent_guide.active) {
2749 (IndentGuideColoring::Disabled, _) => None,
2750 (IndentGuideColoring::Fixed, false) => {
2751 Some(cx.theme().colors().editor_indent_guide)
2752 }
2753 (IndentGuideColoring::Fixed, true) => {
2754 Some(cx.theme().colors().editor_indent_guide_active)
2755 }
2756 (IndentGuideColoring::IndentAware, false) => {
2757 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
2758 }
2759 (IndentGuideColoring::IndentAware, true) => {
2760 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
2761 }
2762 };
2763
2764 let background_color = match (settings.background_coloring, indent_guide.active) {
2765 (IndentGuideBackgroundColoring::Disabled, _) => None,
2766 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
2767 indent_accent_colors,
2768 INDENT_AWARE_BACKGROUND_ALPHA,
2769 )),
2770 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
2771 indent_accent_colors,
2772 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
2773 )),
2774 };
2775
2776 let requested_line_width = settings.line_width.clamp(1, 10);
2777 let mut line_indicator_width = 0.;
2778 if let Some(color) = line_color {
2779 cx.paint_quad(fill(
2780 Bounds {
2781 origin: indent_guide.origin,
2782 size: size(px(requested_line_width as f32), indent_guide.length),
2783 },
2784 color,
2785 ));
2786 line_indicator_width = requested_line_width as f32;
2787 }
2788
2789 if let Some(color) = background_color {
2790 let width = indent_guide.single_indent_width - px(line_indicator_width);
2791 cx.paint_quad(fill(
2792 Bounds {
2793 origin: point(
2794 indent_guide.origin.x + px(line_indicator_width),
2795 indent_guide.origin.y,
2796 ),
2797 size: size(width, indent_guide.length),
2798 },
2799 color,
2800 ));
2801 }
2802 }
2803 }
2804
2805 fn paint_gutter(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2806 let line_height = layout.position_map.line_height;
2807
2808 let scroll_position = layout.position_map.snapshot.scroll_position();
2809 let scroll_top = scroll_position.y * line_height;
2810
2811 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2812 for (_, hunk_hitbox) in &layout.display_hunks {
2813 if let Some(hunk_hitbox) = hunk_hitbox {
2814 cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
2815 }
2816 }
2817
2818 let show_git_gutter = layout
2819 .position_map
2820 .snapshot
2821 .show_git_diff_gutter
2822 .unwrap_or_else(|| {
2823 matches!(
2824 ProjectSettings::get_global(cx).git.git_gutter,
2825 Some(GitGutterSetting::TrackedFiles)
2826 )
2827 });
2828 if show_git_gutter {
2829 Self::paint_diff_hunks(layout.gutter_hitbox.bounds, layout, cx)
2830 }
2831
2832 if layout.blamed_display_rows.is_some() {
2833 self.paint_blamed_display_rows(layout, cx);
2834 }
2835
2836 for (ix, line) in layout.line_numbers.iter().enumerate() {
2837 if let Some(line) = line {
2838 let line_origin = layout.gutter_hitbox.origin
2839 + point(
2840 layout.gutter_hitbox.size.width
2841 - line.width
2842 - layout.gutter_dimensions.right_padding,
2843 ix as f32 * line_height - (scroll_top % line_height),
2844 );
2845
2846 line.paint(line_origin, line_height, cx).log_err();
2847 }
2848 }
2849
2850 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2851 cx.with_element_namespace("gutter_fold_toggles", |cx| {
2852 for fold_indicator in layout.gutter_fold_toggles.iter_mut().flatten() {
2853 fold_indicator.paint(cx);
2854 }
2855 });
2856
2857 for test_indicators in layout.test_indicators.iter_mut() {
2858 test_indicators.paint(cx);
2859 }
2860
2861 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2862 indicator.paint(cx);
2863 }
2864 });
2865 }
2866
2867 fn paint_diff_hunks(
2868 gutter_bounds: Bounds<Pixels>,
2869 layout: &EditorLayout,
2870 cx: &mut WindowContext,
2871 ) {
2872 if layout.display_hunks.is_empty() {
2873 return;
2874 }
2875
2876 let line_height = layout.position_map.line_height;
2877 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2878 for (hunk, hitbox) in &layout.display_hunks {
2879 let hunk_to_paint = match hunk {
2880 DisplayDiffHunk::Folded { .. } => {
2881 let hunk_bounds = Self::diff_hunk_bounds(
2882 &layout.position_map.snapshot,
2883 line_height,
2884 gutter_bounds,
2885 &hunk,
2886 );
2887 Some((
2888 hunk_bounds,
2889 cx.theme().status().modified,
2890 Corners::all(1. * line_height),
2891 ))
2892 }
2893 DisplayDiffHunk::Unfolded { status, .. } => {
2894 hitbox.as_ref().map(|hunk_hitbox| match status {
2895 DiffHunkStatus::Added => (
2896 hunk_hitbox.bounds,
2897 cx.theme().status().created,
2898 Corners::all(0.05 * line_height),
2899 ),
2900 DiffHunkStatus::Modified => (
2901 hunk_hitbox.bounds,
2902 cx.theme().status().modified,
2903 Corners::all(0.05 * line_height),
2904 ),
2905 DiffHunkStatus::Removed => (
2906 Bounds::new(
2907 point(
2908 hunk_hitbox.origin.x - hunk_hitbox.size.width,
2909 hunk_hitbox.origin.y,
2910 ),
2911 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
2912 ),
2913 cx.theme().status().deleted,
2914 Corners::all(1. * line_height),
2915 ),
2916 })
2917 }
2918 };
2919
2920 if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
2921 cx.paint_quad(quad(
2922 hunk_bounds,
2923 corner_radii,
2924 background_color,
2925 Edges::default(),
2926 transparent_black(),
2927 ));
2928 }
2929 }
2930 });
2931 }
2932
2933 fn diff_hunk_bounds(
2934 snapshot: &EditorSnapshot,
2935 line_height: Pixels,
2936 bounds: Bounds<Pixels>,
2937 hunk: &DisplayDiffHunk,
2938 ) -> Bounds<Pixels> {
2939 let scroll_position = snapshot.scroll_position();
2940 let scroll_top = scroll_position.y * line_height;
2941
2942 match hunk {
2943 DisplayDiffHunk::Folded { display_row, .. } => {
2944 let start_y = display_row.as_f32() * line_height - scroll_top;
2945 let end_y = start_y + line_height;
2946
2947 let width = 0.275 * line_height;
2948 let highlight_origin = bounds.origin + point(px(0.), start_y);
2949 let highlight_size = size(width, end_y - start_y);
2950 Bounds::new(highlight_origin, highlight_size)
2951 }
2952 DisplayDiffHunk::Unfolded {
2953 display_row_range,
2954 status,
2955 ..
2956 } => match status {
2957 DiffHunkStatus::Added | DiffHunkStatus::Modified => {
2958 let start_row = display_row_range.start;
2959 let end_row = display_row_range.end;
2960 // If we're in a multibuffer, row range span might include an
2961 // excerpt header, so if we were to draw the marker straight away,
2962 // the hunk might include the rows of that header.
2963 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2964 // Instead, we simply check whether the range we're dealing with includes
2965 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2966 let end_row_in_current_excerpt = snapshot
2967 .blocks_in_range(start_row..end_row)
2968 .find_map(|(start_row, block)| {
2969 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2970 Some(start_row)
2971 } else {
2972 None
2973 }
2974 })
2975 .unwrap_or(end_row);
2976
2977 let start_y = start_row.as_f32() * line_height - scroll_top;
2978 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
2979
2980 let width = 0.275 * line_height;
2981 let highlight_origin = bounds.origin + point(px(0.), start_y);
2982 let highlight_size = size(width, end_y - start_y);
2983 Bounds::new(highlight_origin, highlight_size)
2984 }
2985 DiffHunkStatus::Removed => {
2986 let row = display_row_range.start;
2987
2988 let offset = line_height / 2.;
2989 let start_y = row.as_f32() * line_height - offset - scroll_top;
2990 let end_y = start_y + line_height;
2991
2992 let width = 0.35 * line_height;
2993 let highlight_origin = bounds.origin + point(px(0.), start_y);
2994 let highlight_size = size(width, end_y - start_y);
2995 Bounds::new(highlight_origin, highlight_size)
2996 }
2997 },
2998 }
2999 }
3000
3001 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3002 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3003 return;
3004 };
3005
3006 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3007 for mut blame_element in blamed_display_rows.into_iter() {
3008 blame_element.paint(cx);
3009 }
3010 })
3011 }
3012
3013 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3014 cx.with_content_mask(
3015 Some(ContentMask {
3016 bounds: layout.text_hitbox.bounds,
3017 }),
3018 |cx| {
3019 let cursor_style = if self
3020 .editor
3021 .read(cx)
3022 .hovered_link_state
3023 .as_ref()
3024 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3025 {
3026 CursorStyle::PointingHand
3027 } else {
3028 CursorStyle::IBeam
3029 };
3030 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3031
3032 let invisible_display_ranges = self.paint_highlights(layout, cx);
3033 self.paint_lines(&invisible_display_ranges, layout, cx);
3034 self.paint_redactions(layout, cx);
3035 self.paint_cursors(layout, cx);
3036 self.paint_inline_blame(layout, cx);
3037 cx.with_element_namespace("flap_trailers", |cx| {
3038 for trailer in layout.flap_trailers.iter_mut().flatten() {
3039 trailer.element.paint(cx);
3040 }
3041 });
3042 },
3043 )
3044 }
3045
3046 fn paint_highlights(
3047 &mut self,
3048 layout: &mut EditorLayout,
3049 cx: &mut WindowContext,
3050 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3051 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3052 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3053 let line_end_overshoot = 0.15 * layout.position_map.line_height;
3054 for (range, color) in &layout.highlighted_ranges {
3055 self.paint_highlighted_range(
3056 range.clone(),
3057 *color,
3058 Pixels::ZERO,
3059 line_end_overshoot,
3060 layout,
3061 cx,
3062 );
3063 }
3064
3065 let corner_radius = 0.15 * layout.position_map.line_height;
3066
3067 for (player_color, selections) in &layout.selections {
3068 for selection in selections.into_iter() {
3069 self.paint_highlighted_range(
3070 selection.range.clone(),
3071 player_color.selection,
3072 corner_radius,
3073 corner_radius * 2.,
3074 layout,
3075 cx,
3076 );
3077
3078 if selection.is_local && !selection.range.is_empty() {
3079 invisible_display_ranges.push(selection.range.clone());
3080 }
3081 }
3082 }
3083 invisible_display_ranges
3084 })
3085 }
3086
3087 fn paint_lines(
3088 &mut self,
3089 invisible_display_ranges: &[Range<DisplayPoint>],
3090 layout: &mut EditorLayout,
3091 cx: &mut WindowContext,
3092 ) {
3093 let whitespace_setting = self
3094 .editor
3095 .read(cx)
3096 .buffer
3097 .read(cx)
3098 .settings_at(0, cx)
3099 .show_whitespaces;
3100
3101 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3102 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3103 line_with_invisibles.draw(
3104 layout,
3105 row,
3106 layout.content_origin,
3107 whitespace_setting,
3108 invisible_display_ranges,
3109 cx,
3110 )
3111 }
3112
3113 for line_element in &mut layout.line_elements {
3114 line_element.paint(cx);
3115 }
3116 }
3117
3118 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3119 if layout.redacted_ranges.is_empty() {
3120 return;
3121 }
3122
3123 let line_end_overshoot = layout.line_end_overshoot();
3124
3125 // A softer than perfect black
3126 let redaction_color = gpui::rgb(0x0e1111);
3127
3128 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3129 for range in layout.redacted_ranges.iter() {
3130 self.paint_highlighted_range(
3131 range.clone(),
3132 redaction_color.into(),
3133 Pixels::ZERO,
3134 line_end_overshoot,
3135 layout,
3136 cx,
3137 );
3138 }
3139 });
3140 }
3141
3142 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3143 for cursor in &mut layout.visible_cursors {
3144 cursor.paint(layout.content_origin, cx);
3145 }
3146 }
3147
3148 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3149 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3150 return;
3151 };
3152
3153 let thumb_bounds = scrollbar_layout.thumb_bounds();
3154 if scrollbar_layout.visible {
3155 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3156 cx.paint_quad(quad(
3157 scrollbar_layout.hitbox.bounds,
3158 Corners::default(),
3159 cx.theme().colors().scrollbar_track_background,
3160 Edges {
3161 top: Pixels::ZERO,
3162 right: Pixels::ZERO,
3163 bottom: Pixels::ZERO,
3164 left: ScrollbarLayout::BORDER_WIDTH,
3165 },
3166 cx.theme().colors().scrollbar_track_border,
3167 ));
3168
3169 let fast_markers =
3170 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3171 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3172 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3173
3174 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3175 for marker in markers.iter().chain(&fast_markers) {
3176 let mut marker = marker.clone();
3177 marker.bounds.origin += scrollbar_layout.hitbox.origin;
3178 cx.paint_quad(marker);
3179 }
3180
3181 cx.paint_quad(quad(
3182 thumb_bounds,
3183 Corners::default(),
3184 cx.theme().colors().scrollbar_thumb_background,
3185 Edges {
3186 top: Pixels::ZERO,
3187 right: Pixels::ZERO,
3188 bottom: Pixels::ZERO,
3189 left: ScrollbarLayout::BORDER_WIDTH,
3190 },
3191 cx.theme().colors().scrollbar_thumb_border,
3192 ));
3193 });
3194 }
3195
3196 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3197
3198 let row_height = scrollbar_layout.row_height;
3199 let row_range = scrollbar_layout.visible_row_range.clone();
3200
3201 cx.on_mouse_event({
3202 let editor = self.editor.clone();
3203 let hitbox = scrollbar_layout.hitbox.clone();
3204 let mut mouse_position = cx.mouse_position();
3205 move |event: &MouseMoveEvent, phase, cx| {
3206 if phase == DispatchPhase::Capture {
3207 return;
3208 }
3209
3210 editor.update(cx, |editor, cx| {
3211 if event.pressed_button == Some(MouseButton::Left)
3212 && editor.scroll_manager.is_dragging_scrollbar()
3213 {
3214 let y = mouse_position.y;
3215 let new_y = event.position.y;
3216 if (hitbox.top()..hitbox.bottom()).contains(&y) {
3217 let mut position = editor.scroll_position(cx);
3218 position.y += (new_y - y) / row_height;
3219 if position.y < 0.0 {
3220 position.y = 0.0;
3221 }
3222 editor.set_scroll_position(position, cx);
3223 }
3224
3225 cx.stop_propagation();
3226 } else {
3227 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3228 if hitbox.is_hovered(cx) {
3229 editor.scroll_manager.show_scrollbar(cx);
3230 }
3231 }
3232 mouse_position = event.position;
3233 })
3234 }
3235 });
3236
3237 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3238 cx.on_mouse_event({
3239 let editor = self.editor.clone();
3240 move |_: &MouseUpEvent, phase, cx| {
3241 if phase == DispatchPhase::Capture {
3242 return;
3243 }
3244
3245 editor.update(cx, |editor, cx| {
3246 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3247 cx.stop_propagation();
3248 });
3249 }
3250 });
3251 } else {
3252 cx.on_mouse_event({
3253 let editor = self.editor.clone();
3254 let hitbox = scrollbar_layout.hitbox.clone();
3255 move |event: &MouseDownEvent, phase, cx| {
3256 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3257 return;
3258 }
3259
3260 editor.update(cx, |editor, cx| {
3261 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3262
3263 let y = event.position.y;
3264 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3265 let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3266 let top_row = center_row
3267 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3268 let mut position = editor.scroll_position(cx);
3269 position.y = top_row as f32;
3270 editor.set_scroll_position(position, cx);
3271 } else {
3272 editor.scroll_manager.show_scrollbar(cx);
3273 }
3274
3275 cx.stop_propagation();
3276 });
3277 }
3278 });
3279 }
3280 }
3281
3282 fn collect_fast_scrollbar_markers(
3283 &self,
3284 layout: &EditorLayout,
3285 scrollbar_layout: &ScrollbarLayout,
3286 cx: &mut WindowContext,
3287 ) -> Vec<PaintQuad> {
3288 const LIMIT: usize = 100;
3289 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3290 return vec![];
3291 }
3292 let cursor_ranges = layout
3293 .cursors
3294 .iter()
3295 .map(|(point, color)| ColoredRange {
3296 start: point.row(),
3297 end: point.row(),
3298 color: *color,
3299 })
3300 .collect_vec();
3301 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3302 }
3303
3304 fn refresh_slow_scrollbar_markers(
3305 &self,
3306 layout: &EditorLayout,
3307 scrollbar_layout: &ScrollbarLayout,
3308 cx: &mut WindowContext,
3309 ) {
3310 self.editor.update(cx, |editor, cx| {
3311 if !editor.is_singleton(cx)
3312 || !editor
3313 .scrollbar_marker_state
3314 .should_refresh(scrollbar_layout.hitbox.size)
3315 {
3316 return;
3317 }
3318
3319 let scrollbar_layout = scrollbar_layout.clone();
3320 let background_highlights = editor.background_highlights.clone();
3321 let snapshot = layout.position_map.snapshot.clone();
3322 let theme = cx.theme().clone();
3323 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3324
3325 editor.scrollbar_marker_state.dirty = false;
3326 editor.scrollbar_marker_state.pending_refresh =
3327 Some(cx.spawn(|editor, mut cx| async move {
3328 let scrollbar_size = scrollbar_layout.hitbox.size;
3329 let scrollbar_markers = cx
3330 .background_executor()
3331 .spawn(async move {
3332 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3333 let mut marker_quads = Vec::new();
3334 if scrollbar_settings.git_diff {
3335 let marker_row_ranges = snapshot
3336 .buffer_snapshot
3337 .git_diff_hunks_in_range(
3338 MultiBufferRow::MIN..MultiBufferRow::MAX,
3339 )
3340 .map(|hunk| {
3341 let start_display_row =
3342 MultiBufferPoint::new(hunk.associated_range.start.0, 0)
3343 .to_display_point(&snapshot.display_snapshot)
3344 .row();
3345 let mut end_display_row =
3346 MultiBufferPoint::new(hunk.associated_range.end.0, 0)
3347 .to_display_point(&snapshot.display_snapshot)
3348 .row();
3349 if end_display_row != start_display_row {
3350 end_display_row.0 -= 1;
3351 }
3352 let color = match hunk_status(&hunk) {
3353 DiffHunkStatus::Added => theme.status().created,
3354 DiffHunkStatus::Modified => theme.status().modified,
3355 DiffHunkStatus::Removed => theme.status().deleted,
3356 };
3357 ColoredRange {
3358 start: start_display_row,
3359 end: end_display_row,
3360 color,
3361 }
3362 });
3363
3364 marker_quads.extend(
3365 scrollbar_layout
3366 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3367 );
3368 }
3369
3370 for (background_highlight_id, (_, background_ranges)) in
3371 background_highlights.iter()
3372 {
3373 let is_search_highlights = *background_highlight_id
3374 == TypeId::of::<BufferSearchHighlights>();
3375 let is_symbol_occurrences = *background_highlight_id
3376 == TypeId::of::<DocumentHighlightRead>()
3377 || *background_highlight_id
3378 == TypeId::of::<DocumentHighlightWrite>();
3379 if (is_search_highlights && scrollbar_settings.search_results)
3380 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3381 {
3382 let mut color = theme.status().info;
3383 if is_symbol_occurrences {
3384 color.fade_out(0.5);
3385 }
3386 let marker_row_ranges =
3387 background_ranges.into_iter().map(|range| {
3388 let display_start = range
3389 .start
3390 .to_display_point(&snapshot.display_snapshot);
3391 let display_end = range
3392 .end
3393 .to_display_point(&snapshot.display_snapshot);
3394 ColoredRange {
3395 start: display_start.row(),
3396 end: display_end.row(),
3397 color,
3398 }
3399 });
3400 marker_quads.extend(
3401 scrollbar_layout
3402 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3403 );
3404 }
3405 }
3406
3407 if scrollbar_settings.diagnostics {
3408 let diagnostics = snapshot
3409 .buffer_snapshot
3410 .diagnostics_in_range::<_, Point>(
3411 Point::zero()..max_point,
3412 false,
3413 )
3414 // We want to sort by severity, in order to paint the most severe diagnostics last.
3415 .sorted_by_key(|diagnostic| {
3416 std::cmp::Reverse(diagnostic.diagnostic.severity)
3417 });
3418
3419 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
3420 let start_display = diagnostic
3421 .range
3422 .start
3423 .to_display_point(&snapshot.display_snapshot);
3424 let end_display = diagnostic
3425 .range
3426 .end
3427 .to_display_point(&snapshot.display_snapshot);
3428 let color = match diagnostic.diagnostic.severity {
3429 DiagnosticSeverity::ERROR => theme.status().error,
3430 DiagnosticSeverity::WARNING => theme.status().warning,
3431 DiagnosticSeverity::INFORMATION => theme.status().info,
3432 _ => theme.status().hint,
3433 };
3434 ColoredRange {
3435 start: start_display.row(),
3436 end: end_display.row(),
3437 color,
3438 }
3439 });
3440 marker_quads.extend(
3441 scrollbar_layout
3442 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
3443 );
3444 }
3445
3446 Arc::from(marker_quads)
3447 })
3448 .await;
3449
3450 editor.update(&mut cx, |editor, cx| {
3451 editor.scrollbar_marker_state.markers = scrollbar_markers;
3452 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
3453 editor.scrollbar_marker_state.pending_refresh = None;
3454 cx.notify();
3455 })?;
3456
3457 Ok(())
3458 }));
3459 });
3460 }
3461
3462 #[allow(clippy::too_many_arguments)]
3463 fn paint_highlighted_range(
3464 &self,
3465 range: Range<DisplayPoint>,
3466 color: Hsla,
3467 corner_radius: Pixels,
3468 line_end_overshoot: Pixels,
3469 layout: &EditorLayout,
3470 cx: &mut WindowContext,
3471 ) {
3472 let start_row = layout.visible_display_row_range.start;
3473 let end_row = layout.visible_display_row_range.end;
3474 if range.start != range.end {
3475 let row_range = if range.end.column() == 0 {
3476 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3477 } else {
3478 cmp::max(range.start.row(), start_row)
3479 ..cmp::min(range.end.row().next_row(), end_row)
3480 };
3481
3482 let highlighted_range = HighlightedRange {
3483 color,
3484 line_height: layout.position_map.line_height,
3485 corner_radius,
3486 start_y: layout.content_origin.y
3487 + row_range.start.as_f32() * layout.position_map.line_height
3488 - layout.position_map.scroll_pixel_position.y,
3489 lines: row_range
3490 .iter_rows()
3491 .map(|row| {
3492 let line_layout =
3493 &layout.position_map.line_layouts[row.minus(start_row) as usize];
3494 HighlightedRangeLine {
3495 start_x: if row == range.start.row() {
3496 layout.content_origin.x
3497 + line_layout.x_for_index(range.start.column() as usize)
3498 - layout.position_map.scroll_pixel_position.x
3499 } else {
3500 layout.content_origin.x
3501 - layout.position_map.scroll_pixel_position.x
3502 },
3503 end_x: if row == range.end.row() {
3504 layout.content_origin.x
3505 + line_layout.x_for_index(range.end.column() as usize)
3506 - layout.position_map.scroll_pixel_position.x
3507 } else {
3508 layout.content_origin.x + line_layout.width + line_end_overshoot
3509 - layout.position_map.scroll_pixel_position.x
3510 },
3511 }
3512 })
3513 .collect(),
3514 };
3515
3516 highlighted_range.paint(layout.text_hitbox.bounds, cx);
3517 }
3518 }
3519
3520 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3521 if let Some(mut inline_blame) = layout.inline_blame.take() {
3522 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3523 inline_blame.paint(cx);
3524 })
3525 }
3526 }
3527
3528 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3529 for mut block in layout.blocks.drain(..) {
3530 block.element.paint(cx);
3531 }
3532 }
3533
3534 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3535 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3536 mouse_context_menu.paint(cx);
3537 }
3538 }
3539
3540 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3541 cx.on_mouse_event({
3542 let position_map = layout.position_map.clone();
3543 let editor = self.editor.clone();
3544 let hitbox = layout.hitbox.clone();
3545 let mut delta = ScrollDelta::default();
3546
3547 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3548 // accidentally turn off their scrolling.
3549 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3550
3551 move |event: &ScrollWheelEvent, phase, cx| {
3552 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3553 delta = delta.coalesce(event.delta);
3554 editor.update(cx, |editor, cx| {
3555 let position_map: &PositionMap = &position_map;
3556
3557 let line_height = position_map.line_height;
3558 let max_glyph_width = position_map.em_width;
3559 let (delta, axis) = match delta {
3560 gpui::ScrollDelta::Pixels(mut pixels) => {
3561 //Trackpad
3562 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3563 (pixels, axis)
3564 }
3565
3566 gpui::ScrollDelta::Lines(lines) => {
3567 //Not trackpad
3568 let pixels =
3569 point(lines.x * max_glyph_width, lines.y * line_height);
3570 (pixels, None)
3571 }
3572 };
3573
3574 let current_scroll_position = position_map.snapshot.scroll_position();
3575 let x = (current_scroll_position.x * max_glyph_width
3576 - (delta.x * scroll_sensitivity))
3577 / max_glyph_width;
3578 let y = (current_scroll_position.y * line_height
3579 - (delta.y * scroll_sensitivity))
3580 / line_height;
3581 let mut scroll_position =
3582 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3583 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3584 if forbid_vertical_scroll {
3585 scroll_position.y = current_scroll_position.y;
3586 if scroll_position == current_scroll_position {
3587 return;
3588 }
3589 }
3590 editor.scroll(scroll_position, axis, cx);
3591 cx.stop_propagation();
3592 });
3593 }
3594 }
3595 });
3596 }
3597
3598 fn paint_mouse_listeners(
3599 &mut self,
3600 layout: &EditorLayout,
3601 hovered_hunk: Option<HunkToExpand>,
3602 cx: &mut WindowContext,
3603 ) {
3604 self.paint_scroll_wheel_listener(layout, cx);
3605
3606 cx.on_mouse_event({
3607 let position_map = layout.position_map.clone();
3608 let editor = self.editor.clone();
3609 let text_hitbox = layout.text_hitbox.clone();
3610 let gutter_hitbox = layout.gutter_hitbox.clone();
3611
3612 move |event: &MouseDownEvent, phase, cx| {
3613 if phase == DispatchPhase::Bubble {
3614 match event.button {
3615 MouseButton::Left => editor.update(cx, |editor, cx| {
3616 Self::mouse_left_down(
3617 editor,
3618 event,
3619 hovered_hunk.as_ref(),
3620 &position_map,
3621 &text_hitbox,
3622 &gutter_hitbox,
3623 cx,
3624 );
3625 }),
3626 MouseButton::Right => editor.update(cx, |editor, cx| {
3627 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3628 }),
3629 MouseButton::Middle => editor.update(cx, |editor, cx| {
3630 Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3631 }),
3632 _ => {}
3633 };
3634 }
3635 }
3636 });
3637
3638 cx.on_mouse_event({
3639 let editor = self.editor.clone();
3640 let position_map = layout.position_map.clone();
3641 let text_hitbox = layout.text_hitbox.clone();
3642
3643 move |event: &MouseUpEvent, phase, cx| {
3644 if phase == DispatchPhase::Bubble {
3645 editor.update(cx, |editor, cx| {
3646 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3647 });
3648 }
3649 }
3650 });
3651 cx.on_mouse_event({
3652 let position_map = layout.position_map.clone();
3653 let editor = self.editor.clone();
3654 let text_hitbox = layout.text_hitbox.clone();
3655 let gutter_hitbox = layout.gutter_hitbox.clone();
3656
3657 move |event: &MouseMoveEvent, phase, cx| {
3658 if phase == DispatchPhase::Bubble {
3659 editor.update(cx, |editor, cx| {
3660 if event.pressed_button == Some(MouseButton::Left)
3661 || event.pressed_button == Some(MouseButton::Middle)
3662 {
3663 Self::mouse_dragged(
3664 editor,
3665 event,
3666 &position_map,
3667 text_hitbox.bounds,
3668 cx,
3669 )
3670 }
3671
3672 Self::mouse_moved(
3673 editor,
3674 event,
3675 &position_map,
3676 &text_hitbox,
3677 &gutter_hitbox,
3678 cx,
3679 )
3680 });
3681 }
3682 }
3683 });
3684 }
3685
3686 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3687 bounds.upper_right().x - self.style.scrollbar_width
3688 }
3689
3690 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3691 let style = &self.style;
3692 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3693 let layout = cx
3694 .text_system()
3695 .shape_line(
3696 SharedString::from(" ".repeat(column)),
3697 font_size,
3698 &[TextRun {
3699 len: column,
3700 font: style.text.font(),
3701 color: Hsla::default(),
3702 background_color: None,
3703 underline: None,
3704 strikethrough: None,
3705 }],
3706 )
3707 .unwrap();
3708
3709 layout.width
3710 }
3711
3712 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3713 let digit_count = snapshot
3714 .max_buffer_row()
3715 .next_row()
3716 .as_f32()
3717 .log10()
3718 .floor() as usize
3719 + 1;
3720 self.column_pixels(digit_count, cx)
3721 }
3722}
3723
3724fn prepaint_gutter_button(
3725 button: IconButton,
3726 row: DisplayRow,
3727 line_height: Pixels,
3728 gutter_dimensions: &GutterDimensions,
3729 scroll_pixel_position: gpui::Point<Pixels>,
3730 gutter_hitbox: &Hitbox,
3731 cx: &mut WindowContext<'_>,
3732) -> AnyElement {
3733 let mut button = button.into_any_element();
3734 let available_space = size(
3735 AvailableSpace::MinContent,
3736 AvailableSpace::Definite(line_height),
3737 );
3738 let indicator_size = button.layout_as_root(available_space, cx);
3739
3740 let blame_width = gutter_dimensions
3741 .git_blame_entries_width
3742 .unwrap_or(Pixels::ZERO);
3743
3744 let mut x = blame_width;
3745 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
3746 - indicator_size.width
3747 - blame_width;
3748 x += available_width / 2.;
3749
3750 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
3751 y += (line_height - indicator_size.height) / 2.;
3752
3753 button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
3754 button
3755}
3756
3757fn render_inline_blame_entry(
3758 blame: &gpui::Model<GitBlame>,
3759 blame_entry: BlameEntry,
3760 style: &EditorStyle,
3761 workspace: Option<WeakView<Workspace>>,
3762 cx: &mut WindowContext<'_>,
3763) -> AnyElement {
3764 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3765
3766 let author = blame_entry.author.as_deref().unwrap_or_default();
3767 let text = format!("{}, {}", author, relative_timestamp);
3768
3769 let details = blame.read(cx).details_for_entry(&blame_entry);
3770
3771 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3772
3773 h_flex()
3774 .id("inline-blame")
3775 .w_full()
3776 .font_family(style.text.font().family)
3777 .text_color(cx.theme().status().hint)
3778 .line_height(style.text.line_height)
3779 .child(Icon::new(IconName::FileGit).color(Color::Hint))
3780 .child(text)
3781 .gap_2()
3782 .hoverable_tooltip(move |_| tooltip.clone().into())
3783 .into_any()
3784}
3785
3786fn render_blame_entry(
3787 ix: usize,
3788 blame: &gpui::Model<GitBlame>,
3789 blame_entry: BlameEntry,
3790 style: &EditorStyle,
3791 last_used_color: &mut Option<(PlayerColor, Oid)>,
3792 editor: View<Editor>,
3793 cx: &mut WindowContext<'_>,
3794) -> AnyElement {
3795 let mut sha_color = cx
3796 .theme()
3797 .players()
3798 .color_for_participant(blame_entry.sha.into());
3799 // If the last color we used is the same as the one we get for this line, but
3800 // the commit SHAs are different, then we try again to get a different color.
3801 match *last_used_color {
3802 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3803 let index: u32 = blame_entry.sha.into();
3804 sha_color = cx.theme().players().color_for_participant(index + 1);
3805 }
3806 _ => {}
3807 };
3808 last_used_color.replace((sha_color, blame_entry.sha));
3809
3810 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3811
3812 let short_commit_id = blame_entry.sha.display_short();
3813
3814 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3815 let name = util::truncate_and_trailoff(author_name, 20);
3816
3817 let details = blame.read(cx).details_for_entry(&blame_entry);
3818
3819 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3820
3821 let tooltip = cx.new_view(|_| {
3822 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3823 });
3824
3825 h_flex()
3826 .w_full()
3827 .font_family(style.text.font().family)
3828 .line_height(style.text.line_height)
3829 .id(("blame", ix))
3830 .children([
3831 div()
3832 .text_color(sha_color.cursor)
3833 .child(short_commit_id)
3834 .mr_2(),
3835 div()
3836 .w_full()
3837 .h_flex()
3838 .justify_between()
3839 .text_color(cx.theme().status().hint)
3840 .child(name)
3841 .child(relative_timestamp),
3842 ])
3843 .on_mouse_down(MouseButton::Right, {
3844 let blame_entry = blame_entry.clone();
3845 let details = details.clone();
3846 move |event, cx| {
3847 deploy_blame_entry_context_menu(
3848 &blame_entry,
3849 details.as_ref(),
3850 editor.clone(),
3851 event.position,
3852 cx,
3853 );
3854 }
3855 })
3856 .hover(|style| style.bg(cx.theme().colors().element_hover))
3857 .when_some(
3858 details.and_then(|details| details.permalink),
3859 |this, url| {
3860 let url = url.clone();
3861 this.cursor_pointer().on_click(move |_, cx| {
3862 cx.stop_propagation();
3863 cx.open_url(url.as_str())
3864 })
3865 },
3866 )
3867 .hoverable_tooltip(move |_| tooltip.clone().into())
3868 .into_any()
3869}
3870
3871fn deploy_blame_entry_context_menu(
3872 blame_entry: &BlameEntry,
3873 details: Option<&CommitDetails>,
3874 editor: View<Editor>,
3875 position: gpui::Point<Pixels>,
3876 cx: &mut WindowContext<'_>,
3877) {
3878 let context_menu = ContextMenu::build(cx, move |this, _| {
3879 let sha = format!("{}", blame_entry.sha);
3880 this.entry("Copy commit SHA", None, move |cx| {
3881 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3882 })
3883 .when_some(
3884 details.and_then(|details| details.permalink.clone()),
3885 |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
3886 )
3887 });
3888
3889 editor.update(cx, move |editor, cx| {
3890 editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3891 cx.notify();
3892 });
3893}
3894
3895#[derive(Debug)]
3896pub(crate) struct LineWithInvisibles {
3897 fragments: SmallVec<[LineFragment; 1]>,
3898 invisibles: Vec<Invisible>,
3899 len: usize,
3900 width: Pixels,
3901 font_size: Pixels,
3902}
3903
3904#[allow(clippy::large_enum_variant)]
3905enum LineFragment {
3906 Text(ShapedLine),
3907 Element {
3908 element: Option<AnyElement>,
3909 size: Size<Pixels>,
3910 len: usize,
3911 },
3912}
3913
3914impl fmt::Debug for LineFragment {
3915 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3916 match self {
3917 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
3918 LineFragment::Element { size, len, .. } => f
3919 .debug_struct("Element")
3920 .field("size", size)
3921 .field("len", len)
3922 .finish(),
3923 }
3924 }
3925}
3926
3927impl LineWithInvisibles {
3928 fn from_chunks<'a>(
3929 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3930 text_style: &TextStyle,
3931 max_line_len: usize,
3932 max_line_count: usize,
3933 line_number_layouts: &[Option<ShapedLine>],
3934 editor_mode: EditorMode,
3935 cx: &mut WindowContext,
3936 ) -> Vec<Self> {
3937 let mut layouts = Vec::with_capacity(max_line_count);
3938 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
3939 let mut line = String::new();
3940 let mut invisibles = Vec::new();
3941 let mut width = Pixels::ZERO;
3942 let mut len = 0;
3943 let mut styles = Vec::new();
3944 let mut non_whitespace_added = false;
3945 let mut row = 0;
3946 let mut line_exceeded_max_len = false;
3947 let font_size = text_style.font_size.to_pixels(cx.rem_size());
3948
3949 let ellipsis = SharedString::from("⋯");
3950
3951 for highlighted_chunk in chunks.chain([HighlightedChunk {
3952 text: "\n",
3953 style: None,
3954 is_tab: false,
3955 renderer: None,
3956 }]) {
3957 if let Some(renderer) = highlighted_chunk.renderer {
3958 if !line.is_empty() {
3959 let shaped_line = cx
3960 .text_system()
3961 .shape_line(line.clone().into(), font_size, &styles)
3962 .unwrap();
3963 width += shaped_line.width;
3964 len += shaped_line.len;
3965 fragments.push(LineFragment::Text(shaped_line));
3966 line.clear();
3967 styles.clear();
3968 }
3969
3970 let available_width = if renderer.constrain_width {
3971 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
3972 ellipsis.clone()
3973 } else {
3974 SharedString::from(Arc::from(highlighted_chunk.text))
3975 };
3976 let shaped_line = cx
3977 .text_system()
3978 .shape_line(
3979 chunk,
3980 font_size,
3981 &[text_style.to_run(highlighted_chunk.text.len())],
3982 )
3983 .unwrap();
3984 AvailableSpace::Definite(shaped_line.width)
3985 } else {
3986 AvailableSpace::MinContent
3987 };
3988
3989 let mut element = (renderer.render)(cx);
3990 let line_height = text_style.line_height_in_pixels(cx.rem_size());
3991 let size = element.layout_as_root(
3992 size(available_width, AvailableSpace::Definite(line_height)),
3993 cx,
3994 );
3995
3996 width += size.width;
3997 len += highlighted_chunk.text.len();
3998 fragments.push(LineFragment::Element {
3999 element: Some(element),
4000 size,
4001 len: highlighted_chunk.text.len(),
4002 });
4003 } else {
4004 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4005 if ix > 0 {
4006 let shaped_line = cx
4007 .text_system()
4008 .shape_line(line.clone().into(), font_size, &styles)
4009 .unwrap();
4010 width += shaped_line.width;
4011 len += shaped_line.len;
4012 fragments.push(LineFragment::Text(shaped_line));
4013 layouts.push(Self {
4014 width: mem::take(&mut width),
4015 len: mem::take(&mut len),
4016 fragments: mem::take(&mut fragments),
4017 invisibles: std::mem::take(&mut invisibles),
4018 font_size,
4019 });
4020
4021 line.clear();
4022 styles.clear();
4023 row += 1;
4024 line_exceeded_max_len = false;
4025 non_whitespace_added = false;
4026 if row == max_line_count {
4027 return layouts;
4028 }
4029 }
4030
4031 if !line_chunk.is_empty() && !line_exceeded_max_len {
4032 let text_style = if let Some(style) = highlighted_chunk.style {
4033 Cow::Owned(text_style.clone().highlight(style))
4034 } else {
4035 Cow::Borrowed(text_style)
4036 };
4037
4038 if line.len() + line_chunk.len() > max_line_len {
4039 let mut chunk_len = max_line_len - line.len();
4040 while !line_chunk.is_char_boundary(chunk_len) {
4041 chunk_len -= 1;
4042 }
4043 line_chunk = &line_chunk[..chunk_len];
4044 line_exceeded_max_len = true;
4045 }
4046
4047 styles.push(TextRun {
4048 len: line_chunk.len(),
4049 font: text_style.font(),
4050 color: text_style.color,
4051 background_color: text_style.background_color,
4052 underline: text_style.underline,
4053 strikethrough: text_style.strikethrough,
4054 });
4055
4056 if editor_mode == EditorMode::Full {
4057 // Line wrap pads its contents with fake whitespaces,
4058 // avoid printing them
4059 let inside_wrapped_string = line_number_layouts
4060 .get(row)
4061 .and_then(|layout| layout.as_ref())
4062 .is_none();
4063 if highlighted_chunk.is_tab {
4064 if non_whitespace_added || !inside_wrapped_string {
4065 invisibles.push(Invisible::Tab {
4066 line_start_offset: line.len(),
4067 });
4068 }
4069 } else {
4070 invisibles.extend(
4071 line_chunk
4072 .bytes()
4073 .enumerate()
4074 .filter(|(_, line_byte)| {
4075 let is_whitespace =
4076 (*line_byte as char).is_whitespace();
4077 non_whitespace_added |= !is_whitespace;
4078 is_whitespace
4079 && (non_whitespace_added || !inside_wrapped_string)
4080 })
4081 .map(|(whitespace_index, _)| Invisible::Whitespace {
4082 line_offset: line.len() + whitespace_index,
4083 }),
4084 )
4085 }
4086 }
4087
4088 line.push_str(line_chunk);
4089 }
4090 }
4091 }
4092 }
4093
4094 layouts
4095 }
4096
4097 fn prepaint(
4098 &mut self,
4099 line_height: Pixels,
4100 scroll_pixel_position: gpui::Point<Pixels>,
4101 row: DisplayRow,
4102 content_origin: gpui::Point<Pixels>,
4103 line_elements: &mut SmallVec<[AnyElement; 1]>,
4104 cx: &mut WindowContext,
4105 ) {
4106 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4107 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4108 for fragment in &mut self.fragments {
4109 match fragment {
4110 LineFragment::Text(line) => {
4111 fragment_origin.x += line.width;
4112 }
4113 LineFragment::Element { element, size, .. } => {
4114 let mut element = element
4115 .take()
4116 .expect("you can't prepaint LineWithInvisibles twice");
4117
4118 // Center the element vertically within the line.
4119 let mut element_origin = fragment_origin;
4120 element_origin.y += (line_height - size.height) / 2.;
4121 element.prepaint_at(element_origin, cx);
4122 line_elements.push(element);
4123
4124 fragment_origin.x += size.width;
4125 }
4126 }
4127 }
4128 }
4129
4130 fn draw(
4131 &self,
4132 layout: &EditorLayout,
4133 row: DisplayRow,
4134 content_origin: gpui::Point<Pixels>,
4135 whitespace_setting: ShowWhitespaceSetting,
4136 selection_ranges: &[Range<DisplayPoint>],
4137 cx: &mut WindowContext,
4138 ) {
4139 let line_height = layout.position_map.line_height;
4140 let line_y = line_height
4141 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4142
4143 let mut fragment_origin =
4144 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4145
4146 for fragment in &self.fragments {
4147 match fragment {
4148 LineFragment::Text(line) => {
4149 line.paint(fragment_origin, line_height, cx).log_err();
4150 fragment_origin.x += line.width;
4151 }
4152 LineFragment::Element { size, .. } => {
4153 fragment_origin.x += size.width;
4154 }
4155 }
4156 }
4157
4158 self.draw_invisibles(
4159 &selection_ranges,
4160 layout,
4161 content_origin,
4162 line_y,
4163 row,
4164 line_height,
4165 whitespace_setting,
4166 cx,
4167 );
4168 }
4169
4170 #[allow(clippy::too_many_arguments)]
4171 fn draw_invisibles(
4172 &self,
4173 selection_ranges: &[Range<DisplayPoint>],
4174 layout: &EditorLayout,
4175 content_origin: gpui::Point<Pixels>,
4176 line_y: Pixels,
4177 row: DisplayRow,
4178 line_height: Pixels,
4179 whitespace_setting: ShowWhitespaceSetting,
4180 cx: &mut WindowContext,
4181 ) {
4182 let allowed_invisibles_regions = match whitespace_setting {
4183 ShowWhitespaceSetting::None => return,
4184 ShowWhitespaceSetting::Selection => Some(selection_ranges),
4185 ShowWhitespaceSetting::All => None,
4186 };
4187
4188 for invisible in &self.invisibles {
4189 let (&token_offset, invisible_symbol) = match invisible {
4190 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
4191 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
4192 };
4193
4194 let x_offset = self.x_for_index(token_offset);
4195 let invisible_offset =
4196 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
4197 let origin = content_origin
4198 + gpui::point(
4199 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
4200 line_y,
4201 );
4202
4203 if let Some(allowed_regions) = allowed_invisibles_regions {
4204 let invisible_point = DisplayPoint::new(row, token_offset as u32);
4205 if !allowed_regions
4206 .iter()
4207 .any(|region| region.start <= invisible_point && invisible_point < region.end)
4208 {
4209 continue;
4210 }
4211 }
4212 invisible_symbol.paint(origin, line_height, cx).log_err();
4213 }
4214 }
4215
4216 pub fn x_for_index(&self, index: usize) -> Pixels {
4217 let mut fragment_start_x = Pixels::ZERO;
4218 let mut fragment_start_index = 0;
4219
4220 for fragment in &self.fragments {
4221 match fragment {
4222 LineFragment::Text(shaped_line) => {
4223 let fragment_end_index = fragment_start_index + shaped_line.len;
4224 if index < fragment_end_index {
4225 return fragment_start_x
4226 + shaped_line.x_for_index(index - fragment_start_index);
4227 }
4228 fragment_start_x += shaped_line.width;
4229 fragment_start_index = fragment_end_index;
4230 }
4231 LineFragment::Element { len, size, .. } => {
4232 let fragment_end_index = fragment_start_index + len;
4233 if index < fragment_end_index {
4234 return fragment_start_x;
4235 }
4236 fragment_start_x += size.width;
4237 fragment_start_index = fragment_end_index;
4238 }
4239 }
4240 }
4241
4242 fragment_start_x
4243 }
4244
4245 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
4246 let mut fragment_start_x = Pixels::ZERO;
4247 let mut fragment_start_index = 0;
4248
4249 for fragment in &self.fragments {
4250 match fragment {
4251 LineFragment::Text(shaped_line) => {
4252 let fragment_end_x = fragment_start_x + shaped_line.width;
4253 if x < fragment_end_x {
4254 return Some(
4255 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
4256 );
4257 }
4258 fragment_start_x = fragment_end_x;
4259 fragment_start_index += shaped_line.len;
4260 }
4261 LineFragment::Element { len, size, .. } => {
4262 let fragment_end_x = fragment_start_x + size.width;
4263 if x < fragment_end_x {
4264 return Some(fragment_start_index);
4265 }
4266 fragment_start_index += len;
4267 fragment_start_x = fragment_end_x;
4268 }
4269 }
4270 }
4271
4272 None
4273 }
4274
4275 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
4276 let mut fragment_start_index = 0;
4277
4278 for fragment in &self.fragments {
4279 match fragment {
4280 LineFragment::Text(shaped_line) => {
4281 let fragment_end_index = fragment_start_index + shaped_line.len;
4282 if index < fragment_end_index {
4283 return shaped_line.font_id_for_index(index - fragment_start_index);
4284 }
4285 fragment_start_index = fragment_end_index;
4286 }
4287 LineFragment::Element { len, .. } => {
4288 let fragment_end_index = fragment_start_index + len;
4289 if index < fragment_end_index {
4290 return None;
4291 }
4292 fragment_start_index = fragment_end_index;
4293 }
4294 }
4295 }
4296
4297 None
4298 }
4299}
4300
4301#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4302enum Invisible {
4303 Tab { line_start_offset: usize },
4304 Whitespace { line_offset: usize },
4305}
4306
4307impl EditorElement {
4308 /// Returns the rem size to use when rendering the [`EditorElement`].
4309 ///
4310 /// This allows UI elements to scale based on the `buffer_font_size`.
4311 fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
4312 match self.editor.read(cx).mode {
4313 EditorMode::Full => {
4314 let buffer_font_size = self.style.text.font_size;
4315 match buffer_font_size {
4316 AbsoluteLength::Pixels(pixels) => {
4317 let rem_size_scale = {
4318 // Our default UI font size is 14px on a 16px base scale.
4319 // This means the default UI font size is 0.875rems.
4320 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
4321
4322 // We then determine the delta between a single rem and the default font
4323 // size scale.
4324 let default_font_size_delta = 1. - default_font_size_scale;
4325
4326 // Finally, we add this delta to 1rem to get the scale factor that
4327 // should be used to scale up the UI.
4328 1. + default_font_size_delta
4329 };
4330
4331 Some(pixels * rem_size_scale)
4332 }
4333 AbsoluteLength::Rems(rems) => {
4334 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
4335 }
4336 }
4337 }
4338 // We currently use single-line and auto-height editors in UI contexts,
4339 // so we don't want to scale everything with the buffer font size, as it
4340 // ends up looking off.
4341 EditorMode::SingleLine | EditorMode::AutoHeight { .. } => None,
4342 }
4343 }
4344}
4345
4346impl Element for EditorElement {
4347 type RequestLayoutState = ();
4348 type PrepaintState = EditorLayout;
4349
4350 fn id(&self) -> Option<ElementId> {
4351 None
4352 }
4353
4354 fn request_layout(
4355 &mut self,
4356 _: Option<&GlobalElementId>,
4357 cx: &mut WindowContext,
4358 ) -> (gpui::LayoutId, ()) {
4359 let rem_size = self.rem_size(cx);
4360 cx.with_rem_size(rem_size, |cx| {
4361 self.editor.update(cx, |editor, cx| {
4362 editor.set_style(self.style.clone(), cx);
4363
4364 let layout_id = match editor.mode {
4365 EditorMode::SingleLine => {
4366 let rem_size = cx.rem_size();
4367 let mut style = Style::default();
4368 style.size.width = relative(1.).into();
4369 style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
4370 cx.request_layout(style, None)
4371 }
4372 EditorMode::AutoHeight { max_lines } => {
4373 let editor_handle = cx.view().clone();
4374 let max_line_number_width =
4375 self.max_line_number_width(&editor.snapshot(cx), cx);
4376 cx.request_measured_layout(
4377 Style::default(),
4378 move |known_dimensions, available_space, cx| {
4379 editor_handle
4380 .update(cx, |editor, cx| {
4381 compute_auto_height_layout(
4382 editor,
4383 max_lines,
4384 max_line_number_width,
4385 known_dimensions,
4386 available_space.width,
4387 cx,
4388 )
4389 })
4390 .unwrap_or_default()
4391 },
4392 )
4393 }
4394 EditorMode::Full => {
4395 let mut style = Style::default();
4396 style.size.width = relative(1.).into();
4397 style.size.height = relative(1.).into();
4398 cx.request_layout(style, None)
4399 }
4400 };
4401
4402 (layout_id, ())
4403 })
4404 })
4405 }
4406
4407 fn prepaint(
4408 &mut self,
4409 _: Option<&GlobalElementId>,
4410 bounds: Bounds<Pixels>,
4411 _: &mut Self::RequestLayoutState,
4412 cx: &mut WindowContext,
4413 ) -> Self::PrepaintState {
4414 let text_style = TextStyleRefinement {
4415 font_size: Some(self.style.text.font_size),
4416 line_height: Some(self.style.text.line_height),
4417 ..Default::default()
4418 };
4419 cx.set_view_id(self.editor.entity_id());
4420
4421 let rem_size = self.rem_size(cx);
4422 cx.with_rem_size(rem_size, |cx| {
4423 cx.with_text_style(Some(text_style), |cx| {
4424 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4425 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
4426 let style = self.style.clone();
4427
4428 let font_id = cx.text_system().resolve_font(&style.text.font());
4429 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4430 let line_height = style.text.line_height_in_pixels(cx.rem_size());
4431 let em_width = cx
4432 .text_system()
4433 .typographic_bounds(font_id, font_size, 'm')
4434 .unwrap()
4435 .size
4436 .width;
4437 let em_advance = cx
4438 .text_system()
4439 .advance(font_id, font_size, 'm')
4440 .unwrap()
4441 .width;
4442
4443 let gutter_dimensions = snapshot.gutter_dimensions(
4444 font_id,
4445 font_size,
4446 em_width,
4447 self.max_line_number_width(&snapshot, cx),
4448 cx,
4449 );
4450 let text_width = bounds.size.width - gutter_dimensions.width;
4451
4452 let right_margin = if snapshot.mode == EditorMode::Full {
4453 EditorElement::SCROLLBAR_WIDTH
4454 } else {
4455 px(0.)
4456 };
4457 let overscroll = size(em_width + right_margin, px(0.));
4458
4459 snapshot = self.editor.update(cx, |editor, cx| {
4460 editor.last_bounds = Some(bounds);
4461 editor.gutter_dimensions = gutter_dimensions;
4462 editor.set_visible_line_count(bounds.size.height / line_height, cx);
4463
4464 let editor_width =
4465 text_width - gutter_dimensions.margin - overscroll.width - em_width;
4466 let wrap_width = match editor.soft_wrap_mode(cx) {
4467 SoftWrap::None => None,
4468 SoftWrap::PreferLine => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
4469 SoftWrap::EditorWidth => Some(editor_width),
4470 SoftWrap::Column(column) => {
4471 Some(editor_width.min(column as f32 * em_advance))
4472 }
4473 };
4474
4475 if editor.set_wrap_width(wrap_width, cx) {
4476 editor.snapshot(cx)
4477 } else {
4478 snapshot
4479 }
4480 });
4481
4482 let wrap_guides = self
4483 .editor
4484 .read(cx)
4485 .wrap_guides(cx)
4486 .iter()
4487 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
4488 .collect::<SmallVec<[_; 2]>>();
4489
4490 let hitbox = cx.insert_hitbox(bounds, false);
4491 let gutter_hitbox = cx.insert_hitbox(
4492 Bounds {
4493 origin: bounds.origin,
4494 size: size(gutter_dimensions.width, bounds.size.height),
4495 },
4496 false,
4497 );
4498 let text_hitbox = cx.insert_hitbox(
4499 Bounds {
4500 origin: gutter_hitbox.upper_right(),
4501 size: size(text_width, bounds.size.height),
4502 },
4503 false,
4504 );
4505 // Offset the content_bounds from the text_bounds by the gutter margin (which
4506 // is roughly half a character wide) to make hit testing work more like how we want.
4507 let content_origin =
4508 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
4509
4510 let mut autoscroll_containing_element = false;
4511 let mut autoscroll_horizontally = false;
4512 self.editor.update(cx, |editor, cx| {
4513 autoscroll_containing_element =
4514 editor.autoscroll_requested() || editor.has_pending_selection();
4515 autoscroll_horizontally =
4516 editor.autoscroll_vertically(bounds, line_height, cx);
4517 snapshot = editor.snapshot(cx);
4518 });
4519
4520 let mut scroll_position = snapshot.scroll_position();
4521 // The scroll position is a fractional point, the whole number of which represents
4522 // the top of the window in terms of display rows.
4523 let start_row = DisplayRow(scroll_position.y as u32);
4524 let height_in_lines = bounds.size.height / line_height;
4525 let max_row = snapshot.max_point().row();
4526 let end_row = cmp::min(
4527 (scroll_position.y + height_in_lines).ceil() as u32,
4528 max_row.next_row().0,
4529 );
4530 let end_row = DisplayRow(end_row);
4531
4532 let buffer_rows = snapshot
4533 .buffer_rows(start_row)
4534 .take((start_row..end_row).len())
4535 .collect::<Vec<_>>();
4536
4537 let start_anchor = if start_row == Default::default() {
4538 Anchor::min()
4539 } else {
4540 snapshot.buffer_snapshot.anchor_before(
4541 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
4542 )
4543 };
4544 let end_anchor = if end_row > max_row {
4545 Anchor::max()
4546 } else {
4547 snapshot.buffer_snapshot.anchor_before(
4548 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
4549 )
4550 };
4551
4552 let highlighted_rows = self
4553 .editor
4554 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
4555 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
4556 start_anchor..end_anchor,
4557 &snapshot.display_snapshot,
4558 cx.theme().colors(),
4559 );
4560
4561 let redacted_ranges = self.editor.read(cx).redacted_ranges(
4562 start_anchor..end_anchor,
4563 &snapshot.display_snapshot,
4564 cx,
4565 );
4566
4567 let (selections, active_rows, newest_selection_head) = self.layout_selections(
4568 start_anchor,
4569 end_anchor,
4570 &snapshot,
4571 start_row,
4572 end_row,
4573 cx,
4574 );
4575
4576 let line_numbers = self.layout_line_numbers(
4577 start_row..end_row,
4578 buffer_rows.iter().copied(),
4579 &active_rows,
4580 newest_selection_head,
4581 &snapshot,
4582 cx,
4583 );
4584
4585 let mut gutter_fold_toggles =
4586 cx.with_element_namespace("gutter_fold_toggles", |cx| {
4587 self.layout_gutter_fold_toggles(
4588 start_row..end_row,
4589 buffer_rows.iter().copied(),
4590 &active_rows,
4591 &snapshot,
4592 cx,
4593 )
4594 });
4595 let flap_trailers = cx.with_element_namespace("flap_trailers", |cx| {
4596 self.layout_flap_trailers(buffer_rows.iter().copied(), &snapshot, cx)
4597 });
4598
4599 let display_hunks = self.layout_git_gutters(
4600 line_height,
4601 &gutter_hitbox,
4602 start_row..end_row,
4603 &snapshot,
4604 cx,
4605 );
4606
4607 let mut max_visible_line_width = Pixels::ZERO;
4608 let mut line_layouts =
4609 self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
4610 for line_with_invisibles in &line_layouts {
4611 if line_with_invisibles.width > max_visible_line_width {
4612 max_visible_line_width = line_with_invisibles.width;
4613 }
4614 }
4615
4616 let longest_line_width =
4617 layout_line(snapshot.longest_row(), &snapshot, &style, cx).width;
4618 let mut scroll_width =
4619 longest_line_width.max(max_visible_line_width) + overscroll.width;
4620
4621 let mut blocks = cx.with_element_namespace("blocks", |cx| {
4622 self.build_blocks(
4623 start_row..end_row,
4624 &snapshot,
4625 &hitbox,
4626 &text_hitbox,
4627 &mut scroll_width,
4628 &gutter_dimensions,
4629 em_width,
4630 gutter_dimensions.full_width(),
4631 line_height,
4632 &line_layouts,
4633 cx,
4634 )
4635 });
4636
4637 let scroll_pixel_position = point(
4638 scroll_position.x * em_width,
4639 scroll_position.y * line_height,
4640 );
4641
4642 let start_buffer_row =
4643 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
4644 let end_buffer_row =
4645 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
4646
4647 let indent_guides = self.layout_indent_guides(
4648 content_origin,
4649 text_hitbox.origin,
4650 start_buffer_row..end_buffer_row,
4651 scroll_pixel_position,
4652 line_height,
4653 &snapshot,
4654 cx,
4655 );
4656
4657 let flap_trailers = cx.with_element_namespace("flap_trailers", |cx| {
4658 self.prepaint_flap_trailers(
4659 flap_trailers,
4660 &line_layouts,
4661 line_height,
4662 content_origin,
4663 scroll_pixel_position,
4664 em_width,
4665 cx,
4666 )
4667 });
4668
4669 let mut inline_blame = None;
4670 if let Some(newest_selection_head) = newest_selection_head {
4671 let display_row = newest_selection_head.row();
4672 if (start_row..end_row).contains(&display_row) {
4673 let line_ix = display_row.minus(start_row) as usize;
4674 let line_layout = &line_layouts[line_ix];
4675 let flap_trailer_layout = flap_trailers[line_ix].as_ref();
4676 inline_blame = self.layout_inline_blame(
4677 display_row,
4678 &snapshot.display_snapshot,
4679 line_layout,
4680 flap_trailer_layout,
4681 em_width,
4682 content_origin,
4683 scroll_pixel_position,
4684 line_height,
4685 cx,
4686 );
4687 }
4688 }
4689
4690 let blamed_display_rows = self.layout_blame_entries(
4691 buffer_rows.into_iter(),
4692 em_width,
4693 scroll_position,
4694 line_height,
4695 &gutter_hitbox,
4696 gutter_dimensions.git_blame_entries_width,
4697 cx,
4698 );
4699
4700 let scroll_max = point(
4701 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
4702 max_row.as_f32(),
4703 );
4704
4705 self.editor.update(cx, |editor, cx| {
4706 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
4707
4708 let autoscrolled = if autoscroll_horizontally {
4709 editor.autoscroll_horizontally(
4710 start_row,
4711 text_hitbox.size.width,
4712 scroll_width,
4713 em_width,
4714 &line_layouts,
4715 cx,
4716 )
4717 } else {
4718 false
4719 };
4720
4721 if clamped || autoscrolled {
4722 snapshot = editor.snapshot(cx);
4723 scroll_position = snapshot.scroll_position();
4724 }
4725 });
4726
4727 let line_elements = self.prepaint_lines(
4728 start_row,
4729 &mut line_layouts,
4730 line_height,
4731 scroll_pixel_position,
4732 content_origin,
4733 cx,
4734 );
4735
4736 cx.with_element_namespace("blocks", |cx| {
4737 self.layout_blocks(
4738 &mut blocks,
4739 &hitbox,
4740 line_height,
4741 scroll_pixel_position,
4742 cx,
4743 );
4744 });
4745
4746 let cursors = self.collect_cursors(&snapshot, cx);
4747 let visible_row_range = start_row..end_row;
4748 let non_visible_cursors = cursors
4749 .iter()
4750 .any(move |c| !visible_row_range.contains(&c.0.row()));
4751
4752 let visible_cursors = self.layout_visible_cursors(
4753 &snapshot,
4754 &selections,
4755 start_row..end_row,
4756 &line_layouts,
4757 &text_hitbox,
4758 content_origin,
4759 scroll_position,
4760 scroll_pixel_position,
4761 line_height,
4762 em_width,
4763 autoscroll_containing_element,
4764 cx,
4765 );
4766
4767 let scrollbar_layout = self.layout_scrollbar(
4768 &snapshot,
4769 bounds,
4770 scroll_position,
4771 height_in_lines,
4772 non_visible_cursors,
4773 cx,
4774 );
4775
4776 let gutter_settings = EditorSettings::get_global(cx).gutter;
4777
4778 let mut _context_menu_visible = false;
4779 let mut code_actions_indicator = None;
4780 if let Some(newest_selection_head) = newest_selection_head {
4781 if (start_row..end_row).contains(&newest_selection_head.row()) {
4782 _context_menu_visible = self.layout_context_menu(
4783 line_height,
4784 &hitbox,
4785 &text_hitbox,
4786 content_origin,
4787 start_row,
4788 scroll_pixel_position,
4789 &line_layouts,
4790 newest_selection_head,
4791 gutter_dimensions.width - gutter_dimensions.left_padding,
4792 cx,
4793 );
4794
4795 let show_code_actions = snapshot
4796 .show_code_actions
4797 .unwrap_or_else(|| gutter_settings.code_actions);
4798 if show_code_actions {
4799 let newest_selection_point =
4800 newest_selection_head.to_point(&snapshot.display_snapshot);
4801 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
4802 MultiBufferRow(newest_selection_point.row),
4803 );
4804 if let Some((buffer, range)) = buffer {
4805 let buffer_id = buffer.remote_id();
4806 let row = range.start.row;
4807 let has_test_indicator =
4808 self.editor.read(cx).tasks.contains_key(&(buffer_id, row));
4809
4810 if !has_test_indicator {
4811 code_actions_indicator = self
4812 .layout_code_actions_indicator(
4813 line_height,
4814 newest_selection_head,
4815 scroll_pixel_position,
4816 &gutter_dimensions,
4817 &gutter_hitbox,
4818 cx,
4819 );
4820 }
4821 }
4822 }
4823 }
4824 }
4825
4826 let test_indicators = self.layout_run_indicators(
4827 line_height,
4828 scroll_pixel_position,
4829 &gutter_dimensions,
4830 &gutter_hitbox,
4831 &snapshot,
4832 cx,
4833 );
4834
4835 if !cx.has_active_drag() {
4836 self.layout_hover_popovers(
4837 &snapshot,
4838 &hitbox,
4839 &text_hitbox,
4840 start_row..end_row,
4841 content_origin,
4842 scroll_pixel_position,
4843 &line_layouts,
4844 line_height,
4845 em_width,
4846 cx,
4847 );
4848 }
4849
4850 let mouse_context_menu = self.layout_mouse_context_menu(cx);
4851
4852 cx.with_element_namespace("gutter_fold_toggles", |cx| {
4853 self.prepaint_gutter_fold_toggles(
4854 &mut gutter_fold_toggles,
4855 line_height,
4856 &gutter_dimensions,
4857 gutter_settings,
4858 scroll_pixel_position,
4859 &gutter_hitbox,
4860 cx,
4861 )
4862 });
4863
4864 let invisible_symbol_font_size = font_size / 2.;
4865 let tab_invisible = cx
4866 .text_system()
4867 .shape_line(
4868 "→".into(),
4869 invisible_symbol_font_size,
4870 &[TextRun {
4871 len: "→".len(),
4872 font: self.style.text.font(),
4873 color: cx.theme().colors().editor_invisible,
4874 background_color: None,
4875 underline: None,
4876 strikethrough: None,
4877 }],
4878 )
4879 .unwrap();
4880 let space_invisible = cx
4881 .text_system()
4882 .shape_line(
4883 "•".into(),
4884 invisible_symbol_font_size,
4885 &[TextRun {
4886 len: "•".len(),
4887 font: self.style.text.font(),
4888 color: cx.theme().colors().editor_invisible,
4889 background_color: None,
4890 underline: None,
4891 strikethrough: None,
4892 }],
4893 )
4894 .unwrap();
4895
4896 EditorLayout {
4897 mode: snapshot.mode,
4898 position_map: Arc::new(PositionMap {
4899 size: bounds.size,
4900 scroll_pixel_position,
4901 scroll_max,
4902 line_layouts,
4903 line_height,
4904 em_width,
4905 em_advance,
4906 snapshot,
4907 }),
4908 visible_display_row_range: start_row..end_row,
4909 wrap_guides,
4910 indent_guides,
4911 hitbox,
4912 text_hitbox,
4913 gutter_hitbox,
4914 gutter_dimensions,
4915 content_origin,
4916 scrollbar_layout,
4917 active_rows,
4918 highlighted_rows,
4919 highlighted_ranges,
4920 redacted_ranges,
4921 line_elements,
4922 line_numbers,
4923 display_hunks,
4924 blamed_display_rows,
4925 inline_blame,
4926 blocks,
4927 cursors,
4928 visible_cursors,
4929 selections,
4930 mouse_context_menu,
4931 test_indicators,
4932 code_actions_indicator,
4933 gutter_fold_toggles,
4934 flap_trailers,
4935 tab_invisible,
4936 space_invisible,
4937 }
4938 })
4939 })
4940 })
4941 }
4942
4943 fn paint(
4944 &mut self,
4945 _: Option<&GlobalElementId>,
4946 bounds: Bounds<gpui::Pixels>,
4947 _: &mut Self::RequestLayoutState,
4948 layout: &mut Self::PrepaintState,
4949 cx: &mut WindowContext,
4950 ) {
4951 let focus_handle = self.editor.focus_handle(cx);
4952 let key_context = self.editor.read(cx).key_context(cx);
4953 cx.set_focus_handle(&focus_handle);
4954 cx.set_key_context(key_context);
4955 cx.handle_input(
4956 &focus_handle,
4957 ElementInputHandler::new(bounds, self.editor.clone()),
4958 );
4959 self.register_actions(cx);
4960 self.register_key_listeners(cx, layout);
4961
4962 let text_style = TextStyleRefinement {
4963 font_size: Some(self.style.text.font_size),
4964 line_height: Some(self.style.text.line_height),
4965 ..Default::default()
4966 };
4967 let mouse_position = cx.mouse_position();
4968 let hovered_hunk = layout
4969 .display_hunks
4970 .iter()
4971 .find_map(|(hunk, hunk_hitbox)| match hunk {
4972 DisplayDiffHunk::Folded { .. } => None,
4973 DisplayDiffHunk::Unfolded {
4974 diff_base_byte_range,
4975 multi_buffer_range,
4976 status,
4977 ..
4978 } => {
4979 if hunk_hitbox
4980 .as_ref()
4981 .map(|hitbox| hitbox.contains(&mouse_position))
4982 .unwrap_or(false)
4983 {
4984 Some(HunkToExpand {
4985 status: *status,
4986 multi_buffer_range: multi_buffer_range.clone(),
4987 diff_base_byte_range: diff_base_byte_range.clone(),
4988 })
4989 } else {
4990 None
4991 }
4992 }
4993 });
4994 let rem_size = self.rem_size(cx);
4995 cx.with_rem_size(rem_size, |cx| {
4996 cx.with_text_style(Some(text_style), |cx| {
4997 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4998 self.paint_mouse_listeners(layout, hovered_hunk, cx);
4999 self.paint_background(layout, cx);
5000 self.paint_indent_guides(layout, cx);
5001 if layout.gutter_hitbox.size.width > Pixels::ZERO {
5002 self.paint_gutter(layout, cx)
5003 }
5004
5005 self.paint_text(layout, cx);
5006
5007 if !layout.blocks.is_empty() {
5008 cx.with_element_namespace("blocks", |cx| {
5009 self.paint_blocks(layout, cx);
5010 });
5011 }
5012
5013 self.paint_scrollbar(layout, cx);
5014 self.paint_mouse_context_menu(layout, cx);
5015 });
5016 })
5017 })
5018 }
5019}
5020
5021impl IntoElement for EditorElement {
5022 type Element = Self;
5023
5024 fn into_element(self) -> Self::Element {
5025 self
5026 }
5027}
5028
5029pub struct EditorLayout {
5030 position_map: Arc<PositionMap>,
5031 hitbox: Hitbox,
5032 text_hitbox: Hitbox,
5033 gutter_hitbox: Hitbox,
5034 gutter_dimensions: GutterDimensions,
5035 content_origin: gpui::Point<Pixels>,
5036 scrollbar_layout: Option<ScrollbarLayout>,
5037 mode: EditorMode,
5038 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
5039 indent_guides: Option<Vec<IndentGuideLayout>>,
5040 visible_display_row_range: Range<DisplayRow>,
5041 active_rows: BTreeMap<DisplayRow, bool>,
5042 highlighted_rows: BTreeMap<DisplayRow, Hsla>,
5043 line_elements: SmallVec<[AnyElement; 1]>,
5044 line_numbers: Vec<Option<ShapedLine>>,
5045 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
5046 blamed_display_rows: Option<Vec<AnyElement>>,
5047 inline_blame: Option<AnyElement>,
5048 blocks: Vec<BlockLayout>,
5049 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5050 redacted_ranges: Vec<Range<DisplayPoint>>,
5051 cursors: Vec<(DisplayPoint, Hsla)>,
5052 visible_cursors: Vec<CursorLayout>,
5053 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
5054 code_actions_indicator: Option<AnyElement>,
5055 test_indicators: Vec<AnyElement>,
5056 gutter_fold_toggles: Vec<Option<AnyElement>>,
5057 flap_trailers: Vec<Option<FlapTrailerLayout>>,
5058 mouse_context_menu: Option<AnyElement>,
5059 tab_invisible: ShapedLine,
5060 space_invisible: ShapedLine,
5061}
5062
5063impl EditorLayout {
5064 fn line_end_overshoot(&self) -> Pixels {
5065 0.15 * self.position_map.line_height
5066 }
5067}
5068
5069struct ColoredRange<T> {
5070 start: T,
5071 end: T,
5072 color: Hsla,
5073}
5074
5075#[derive(Clone)]
5076struct ScrollbarLayout {
5077 hitbox: Hitbox,
5078 visible_row_range: Range<f32>,
5079 visible: bool,
5080 row_height: Pixels,
5081 thumb_height: Pixels,
5082}
5083
5084impl ScrollbarLayout {
5085 const BORDER_WIDTH: Pixels = px(1.0);
5086 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
5087 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
5088 const MIN_THUMB_HEIGHT: Pixels = px(20.0);
5089
5090 fn thumb_bounds(&self) -> Bounds<Pixels> {
5091 let thumb_top = self.y_for_row(self.visible_row_range.start);
5092 let thumb_bottom = thumb_top + self.thumb_height;
5093 Bounds::from_corners(
5094 point(self.hitbox.left(), thumb_top),
5095 point(self.hitbox.right(), thumb_bottom),
5096 )
5097 }
5098
5099 fn y_for_row(&self, row: f32) -> Pixels {
5100 self.hitbox.top() + row * self.row_height
5101 }
5102
5103 fn marker_quads_for_ranges(
5104 &self,
5105 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
5106 column: Option<usize>,
5107 ) -> Vec<PaintQuad> {
5108 struct MinMax {
5109 min: Pixels,
5110 max: Pixels,
5111 }
5112 let (x_range, height_limit) = if let Some(column) = column {
5113 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
5114 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
5115 let end = start + column_width;
5116 (
5117 Range { start, end },
5118 MinMax {
5119 min: Self::MIN_MARKER_HEIGHT,
5120 max: px(f32::MAX),
5121 },
5122 )
5123 } else {
5124 (
5125 Range {
5126 start: Self::BORDER_WIDTH,
5127 end: self.hitbox.size.width,
5128 },
5129 MinMax {
5130 min: Self::LINE_MARKER_HEIGHT,
5131 max: Self::LINE_MARKER_HEIGHT,
5132 },
5133 )
5134 };
5135
5136 let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
5137 let mut pixel_ranges = row_ranges
5138 .into_iter()
5139 .map(|range| {
5140 let start_y = row_to_y(range.start);
5141 let end_y = row_to_y(range.end)
5142 + self.row_height.max(height_limit.min).min(height_limit.max);
5143 ColoredRange {
5144 start: start_y,
5145 end: end_y,
5146 color: range.color,
5147 }
5148 })
5149 .peekable();
5150
5151 let mut quads = Vec::new();
5152 while let Some(mut pixel_range) = pixel_ranges.next() {
5153 while let Some(next_pixel_range) = pixel_ranges.peek() {
5154 if pixel_range.end >= next_pixel_range.start - px(1.0)
5155 && pixel_range.color == next_pixel_range.color
5156 {
5157 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
5158 pixel_ranges.next();
5159 } else {
5160 break;
5161 }
5162 }
5163
5164 let bounds = Bounds::from_corners(
5165 point(x_range.start, pixel_range.start),
5166 point(x_range.end, pixel_range.end),
5167 );
5168 quads.push(quad(
5169 bounds,
5170 Corners::default(),
5171 pixel_range.color,
5172 Edges::default(),
5173 Hsla::transparent_black(),
5174 ));
5175 }
5176
5177 quads
5178 }
5179}
5180
5181struct FlapTrailerLayout {
5182 element: AnyElement,
5183 bounds: Bounds<Pixels>,
5184}
5185
5186struct PositionMap {
5187 size: Size<Pixels>,
5188 line_height: Pixels,
5189 scroll_pixel_position: gpui::Point<Pixels>,
5190 scroll_max: gpui::Point<f32>,
5191 em_width: Pixels,
5192 em_advance: Pixels,
5193 line_layouts: Vec<LineWithInvisibles>,
5194 snapshot: EditorSnapshot,
5195}
5196
5197#[derive(Debug, Copy, Clone)]
5198pub struct PointForPosition {
5199 pub previous_valid: DisplayPoint,
5200 pub next_valid: DisplayPoint,
5201 pub exact_unclipped: DisplayPoint,
5202 pub column_overshoot_after_line_end: u32,
5203}
5204
5205impl PointForPosition {
5206 pub fn as_valid(&self) -> Option<DisplayPoint> {
5207 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
5208 Some(self.previous_valid)
5209 } else {
5210 None
5211 }
5212 }
5213}
5214
5215impl PositionMap {
5216 fn point_for_position(
5217 &self,
5218 text_bounds: Bounds<Pixels>,
5219 position: gpui::Point<Pixels>,
5220 ) -> PointForPosition {
5221 let scroll_position = self.snapshot.scroll_position();
5222 let position = position - text_bounds.origin;
5223 let y = position.y.max(px(0.)).min(self.size.height);
5224 let x = position.x + (scroll_position.x * self.em_width);
5225 let row = ((y / self.line_height) + scroll_position.y) as u32;
5226
5227 let (column, x_overshoot_after_line_end) = if let Some(line) = self
5228 .line_layouts
5229 .get(row as usize - scroll_position.y as usize)
5230 {
5231 if let Some(ix) = line.index_for_x(x) {
5232 (ix as u32, px(0.))
5233 } else {
5234 (line.len as u32, px(0.).max(x - line.width))
5235 }
5236 } else {
5237 (0, x)
5238 };
5239
5240 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
5241 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
5242 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
5243
5244 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
5245 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
5246 PointForPosition {
5247 previous_valid,
5248 next_valid,
5249 exact_unclipped,
5250 column_overshoot_after_line_end,
5251 }
5252 }
5253}
5254
5255struct BlockLayout {
5256 row: DisplayRow,
5257 element: AnyElement,
5258 available_space: Size<AvailableSpace>,
5259 style: BlockStyle,
5260}
5261
5262fn layout_line(
5263 row: DisplayRow,
5264 snapshot: &EditorSnapshot,
5265 style: &EditorStyle,
5266 cx: &mut WindowContext,
5267) -> LineWithInvisibles {
5268 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
5269 LineWithInvisibles::from_chunks(chunks, &style.text, MAX_LINE_LEN, 1, &[], snapshot.mode, cx)
5270 .pop()
5271 .unwrap()
5272}
5273
5274#[derive(Debug)]
5275pub struct IndentGuideLayout {
5276 origin: gpui::Point<Pixels>,
5277 length: Pixels,
5278 single_indent_width: Pixels,
5279 depth: u32,
5280 active: bool,
5281 settings: IndentGuideSettings,
5282}
5283
5284pub struct CursorLayout {
5285 origin: gpui::Point<Pixels>,
5286 block_width: Pixels,
5287 line_height: Pixels,
5288 color: Hsla,
5289 shape: CursorShape,
5290 block_text: Option<ShapedLine>,
5291 cursor_name: Option<AnyElement>,
5292}
5293
5294#[derive(Debug)]
5295pub struct CursorName {
5296 string: SharedString,
5297 color: Hsla,
5298 is_top_row: bool,
5299}
5300
5301impl CursorLayout {
5302 pub fn new(
5303 origin: gpui::Point<Pixels>,
5304 block_width: Pixels,
5305 line_height: Pixels,
5306 color: Hsla,
5307 shape: CursorShape,
5308 block_text: Option<ShapedLine>,
5309 ) -> CursorLayout {
5310 CursorLayout {
5311 origin,
5312 block_width,
5313 line_height,
5314 color,
5315 shape,
5316 block_text,
5317 cursor_name: None,
5318 }
5319 }
5320
5321 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5322 Bounds {
5323 origin: self.origin + origin,
5324 size: size(self.block_width, self.line_height),
5325 }
5326 }
5327
5328 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5329 match self.shape {
5330 CursorShape::Bar => Bounds {
5331 origin: self.origin + origin,
5332 size: size(px(2.0), self.line_height),
5333 },
5334 CursorShape::Block | CursorShape::Hollow => Bounds {
5335 origin: self.origin + origin,
5336 size: size(self.block_width, self.line_height),
5337 },
5338 CursorShape::Underscore => Bounds {
5339 origin: self.origin
5340 + origin
5341 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
5342 size: size(self.block_width, px(2.0)),
5343 },
5344 }
5345 }
5346
5347 pub fn layout(
5348 &mut self,
5349 origin: gpui::Point<Pixels>,
5350 cursor_name: Option<CursorName>,
5351 cx: &mut WindowContext,
5352 ) {
5353 if let Some(cursor_name) = cursor_name {
5354 let bounds = self.bounds(origin);
5355 let text_size = self.line_height / 1.5;
5356
5357 let name_origin = if cursor_name.is_top_row {
5358 point(bounds.right() - px(1.), bounds.top())
5359 } else {
5360 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
5361 };
5362 let mut name_element = div()
5363 .bg(self.color)
5364 .text_size(text_size)
5365 .px_0p5()
5366 .line_height(text_size + px(2.))
5367 .text_color(cursor_name.color)
5368 .child(cursor_name.string.clone())
5369 .into_any_element();
5370
5371 name_element.prepaint_as_root(
5372 name_origin,
5373 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
5374 cx,
5375 );
5376
5377 self.cursor_name = Some(name_element);
5378 }
5379 }
5380
5381 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
5382 let bounds = self.bounds(origin);
5383
5384 //Draw background or border quad
5385 let cursor = if matches!(self.shape, CursorShape::Hollow) {
5386 outline(bounds, self.color)
5387 } else {
5388 fill(bounds, self.color)
5389 };
5390
5391 if let Some(name) = &mut self.cursor_name {
5392 name.paint(cx);
5393 }
5394
5395 cx.paint_quad(cursor);
5396
5397 if let Some(block_text) = &self.block_text {
5398 block_text
5399 .paint(self.origin + origin, self.line_height, cx)
5400 .log_err();
5401 }
5402 }
5403
5404 pub fn shape(&self) -> CursorShape {
5405 self.shape
5406 }
5407}
5408
5409#[derive(Debug)]
5410pub struct HighlightedRange {
5411 pub start_y: Pixels,
5412 pub line_height: Pixels,
5413 pub lines: Vec<HighlightedRangeLine>,
5414 pub color: Hsla,
5415 pub corner_radius: Pixels,
5416}
5417
5418#[derive(Debug)]
5419pub struct HighlightedRangeLine {
5420 pub start_x: Pixels,
5421 pub end_x: Pixels,
5422}
5423
5424impl HighlightedRange {
5425 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
5426 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
5427 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
5428 self.paint_lines(
5429 self.start_y + self.line_height,
5430 &self.lines[1..],
5431 bounds,
5432 cx,
5433 );
5434 } else {
5435 self.paint_lines(self.start_y, &self.lines, bounds, cx);
5436 }
5437 }
5438
5439 fn paint_lines(
5440 &self,
5441 start_y: Pixels,
5442 lines: &[HighlightedRangeLine],
5443 _bounds: Bounds<Pixels>,
5444 cx: &mut WindowContext,
5445 ) {
5446 if lines.is_empty() {
5447 return;
5448 }
5449
5450 let first_line = lines.first().unwrap();
5451 let last_line = lines.last().unwrap();
5452
5453 let first_top_left = point(first_line.start_x, start_y);
5454 let first_top_right = point(first_line.end_x, start_y);
5455
5456 let curve_height = point(Pixels::ZERO, self.corner_radius);
5457 let curve_width = |start_x: Pixels, end_x: Pixels| {
5458 let max = (end_x - start_x) / 2.;
5459 let width = if max < self.corner_radius {
5460 max
5461 } else {
5462 self.corner_radius
5463 };
5464
5465 point(width, Pixels::ZERO)
5466 };
5467
5468 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
5469 let mut path = gpui::Path::new(first_top_right - top_curve_width);
5470 path.curve_to(first_top_right + curve_height, first_top_right);
5471
5472 let mut iter = lines.iter().enumerate().peekable();
5473 while let Some((ix, line)) = iter.next() {
5474 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
5475
5476 if let Some((_, next_line)) = iter.peek() {
5477 let next_top_right = point(next_line.end_x, bottom_right.y);
5478
5479 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
5480 Ordering::Equal => {
5481 path.line_to(bottom_right);
5482 }
5483 Ordering::Less => {
5484 let curve_width = curve_width(next_top_right.x, bottom_right.x);
5485 path.line_to(bottom_right - curve_height);
5486 if self.corner_radius > Pixels::ZERO {
5487 path.curve_to(bottom_right - curve_width, bottom_right);
5488 }
5489 path.line_to(next_top_right + curve_width);
5490 if self.corner_radius > Pixels::ZERO {
5491 path.curve_to(next_top_right + curve_height, next_top_right);
5492 }
5493 }
5494 Ordering::Greater => {
5495 let curve_width = curve_width(bottom_right.x, next_top_right.x);
5496 path.line_to(bottom_right - curve_height);
5497 if self.corner_radius > Pixels::ZERO {
5498 path.curve_to(bottom_right + curve_width, bottom_right);
5499 }
5500 path.line_to(next_top_right - curve_width);
5501 if self.corner_radius > Pixels::ZERO {
5502 path.curve_to(next_top_right + curve_height, next_top_right);
5503 }
5504 }
5505 }
5506 } else {
5507 let curve_width = curve_width(line.start_x, line.end_x);
5508 path.line_to(bottom_right - curve_height);
5509 if self.corner_radius > Pixels::ZERO {
5510 path.curve_to(bottom_right - curve_width, bottom_right);
5511 }
5512
5513 let bottom_left = point(line.start_x, bottom_right.y);
5514 path.line_to(bottom_left + curve_width);
5515 if self.corner_radius > Pixels::ZERO {
5516 path.curve_to(bottom_left - curve_height, bottom_left);
5517 }
5518 }
5519 }
5520
5521 if first_line.start_x > last_line.start_x {
5522 let curve_width = curve_width(last_line.start_x, first_line.start_x);
5523 let second_top_left = point(last_line.start_x, start_y + self.line_height);
5524 path.line_to(second_top_left + curve_height);
5525 if self.corner_radius > Pixels::ZERO {
5526 path.curve_to(second_top_left + curve_width, second_top_left);
5527 }
5528 let first_bottom_left = point(first_line.start_x, second_top_left.y);
5529 path.line_to(first_bottom_left - curve_width);
5530 if self.corner_radius > Pixels::ZERO {
5531 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
5532 }
5533 }
5534
5535 path.line_to(first_top_left + curve_height);
5536 if self.corner_radius > Pixels::ZERO {
5537 path.curve_to(first_top_left + top_curve_width, first_top_left);
5538 }
5539 path.line_to(first_top_right - top_curve_width);
5540
5541 cx.paint_path(path, self.color);
5542 }
5543}
5544
5545pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5546 (delta.pow(1.5) / 100.0).into()
5547}
5548
5549fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
5550 (delta.pow(1.2) / 300.0).into()
5551}
5552
5553#[cfg(test)]
5554mod tests {
5555 use super::*;
5556 use crate::{
5557 display_map::{BlockDisposition, BlockProperties},
5558 editor_tests::{init_test, update_test_language_settings},
5559 Editor, MultiBuffer,
5560 };
5561 use gpui::{TestAppContext, VisualTestContext};
5562 use language::language_settings;
5563 use log::info;
5564 use std::num::NonZeroU32;
5565 use ui::Context;
5566 use util::test::sample_text;
5567
5568 #[gpui::test]
5569 fn test_shape_line_numbers(cx: &mut TestAppContext) {
5570 init_test(cx, |_| {});
5571 let window = cx.add_window(|cx| {
5572 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
5573 Editor::new(EditorMode::Full, buffer, None, true, cx)
5574 });
5575
5576 let editor = window.root(cx).unwrap();
5577 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5578 let element = EditorElement::new(&editor, style);
5579 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
5580
5581 let layouts = cx
5582 .update_window(*window, |_, cx| {
5583 element.layout_line_numbers(
5584 DisplayRow(0)..DisplayRow(6),
5585 (0..6).map(MultiBufferRow).map(Some),
5586 &Default::default(),
5587 Some(DisplayPoint::new(DisplayRow(0), 0)),
5588 &snapshot,
5589 cx,
5590 )
5591 })
5592 .unwrap();
5593 assert_eq!(layouts.len(), 6);
5594
5595 let relative_rows = window
5596 .update(cx, |editor, cx| {
5597 let snapshot = editor.snapshot(cx);
5598 element.calculate_relative_line_numbers(
5599 &snapshot,
5600 &(DisplayRow(0)..DisplayRow(6)),
5601 Some(DisplayRow(3)),
5602 )
5603 })
5604 .unwrap();
5605 assert_eq!(relative_rows[&DisplayRow(0)], 3);
5606 assert_eq!(relative_rows[&DisplayRow(1)], 2);
5607 assert_eq!(relative_rows[&DisplayRow(2)], 1);
5608 // current line has no relative number
5609 assert_eq!(relative_rows[&DisplayRow(4)], 1);
5610 assert_eq!(relative_rows[&DisplayRow(5)], 2);
5611
5612 // works if cursor is before screen
5613 let relative_rows = window
5614 .update(cx, |editor, cx| {
5615 let snapshot = editor.snapshot(cx);
5616 element.calculate_relative_line_numbers(
5617 &snapshot,
5618 &(DisplayRow(3)..DisplayRow(6)),
5619 Some(DisplayRow(1)),
5620 )
5621 })
5622 .unwrap();
5623 assert_eq!(relative_rows.len(), 3);
5624 assert_eq!(relative_rows[&DisplayRow(3)], 2);
5625 assert_eq!(relative_rows[&DisplayRow(4)], 3);
5626 assert_eq!(relative_rows[&DisplayRow(5)], 4);
5627
5628 // works if cursor is after screen
5629 let relative_rows = window
5630 .update(cx, |editor, cx| {
5631 let snapshot = editor.snapshot(cx);
5632 element.calculate_relative_line_numbers(
5633 &snapshot,
5634 &(DisplayRow(0)..DisplayRow(3)),
5635 Some(DisplayRow(6)),
5636 )
5637 })
5638 .unwrap();
5639 assert_eq!(relative_rows.len(), 3);
5640 assert_eq!(relative_rows[&DisplayRow(0)], 5);
5641 assert_eq!(relative_rows[&DisplayRow(1)], 4);
5642 assert_eq!(relative_rows[&DisplayRow(2)], 3);
5643 }
5644
5645 #[gpui::test]
5646 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
5647 init_test(cx, |_| {});
5648
5649 let window = cx.add_window(|cx| {
5650 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
5651 Editor::new(EditorMode::Full, buffer, None, true, cx)
5652 });
5653 let cx = &mut VisualTestContext::from_window(*window, cx);
5654 let editor = window.root(cx).unwrap();
5655 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5656
5657 window
5658 .update(cx, |editor, cx| {
5659 editor.cursor_shape = CursorShape::Block;
5660 editor.change_selections(None, cx, |s| {
5661 s.select_ranges([
5662 Point::new(0, 0)..Point::new(1, 0),
5663 Point::new(3, 2)..Point::new(3, 3),
5664 Point::new(5, 6)..Point::new(6, 0),
5665 ]);
5666 });
5667 })
5668 .unwrap();
5669
5670 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5671 EditorElement::new(&editor, style)
5672 });
5673
5674 assert_eq!(state.selections.len(), 1);
5675 let local_selections = &state.selections[0].1;
5676 assert_eq!(local_selections.len(), 3);
5677 // moves cursor back one line
5678 assert_eq!(
5679 local_selections[0].head,
5680 DisplayPoint::new(DisplayRow(0), 6)
5681 );
5682 assert_eq!(
5683 local_selections[0].range,
5684 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
5685 );
5686
5687 // moves cursor back one column
5688 assert_eq!(
5689 local_selections[1].range,
5690 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
5691 );
5692 assert_eq!(
5693 local_selections[1].head,
5694 DisplayPoint::new(DisplayRow(3), 2)
5695 );
5696
5697 // leaves cursor on the max point
5698 assert_eq!(
5699 local_selections[2].range,
5700 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
5701 );
5702 assert_eq!(
5703 local_selections[2].head,
5704 DisplayPoint::new(DisplayRow(6), 0)
5705 );
5706
5707 // active lines does not include 1 (even though the range of the selection does)
5708 assert_eq!(
5709 state.active_rows.keys().cloned().collect::<Vec<_>>(),
5710 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
5711 );
5712
5713 // multi-buffer support
5714 // in DisplayPoint coordinates, this is what we're dealing with:
5715 // 0: [[file
5716 // 1: header
5717 // 2: section]]
5718 // 3: aaaaaa
5719 // 4: bbbbbb
5720 // 5: cccccc
5721 // 6:
5722 // 7: [[footer]]
5723 // 8: [[header]]
5724 // 9: ffffff
5725 // 10: gggggg
5726 // 11: hhhhhh
5727 // 12:
5728 // 13: [[footer]]
5729 // 14: [[file
5730 // 15: header
5731 // 16: section]]
5732 // 17: bbbbbb
5733 // 18: cccccc
5734 // 19: dddddd
5735 // 20: [[footer]]
5736 let window = cx.add_window(|cx| {
5737 let buffer = MultiBuffer::build_multi(
5738 [
5739 (
5740 &(sample_text(8, 6, 'a') + "\n"),
5741 vec![
5742 Point::new(0, 0)..Point::new(3, 0),
5743 Point::new(4, 0)..Point::new(7, 0),
5744 ],
5745 ),
5746 (
5747 &(sample_text(8, 6, 'a') + "\n"),
5748 vec![Point::new(1, 0)..Point::new(3, 0)],
5749 ),
5750 ],
5751 cx,
5752 );
5753 Editor::new(EditorMode::Full, buffer, None, true, cx)
5754 });
5755 let editor = window.root(cx).unwrap();
5756 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5757 let _state = window.update(cx, |editor, cx| {
5758 editor.cursor_shape = CursorShape::Block;
5759 editor.change_selections(None, cx, |s| {
5760 s.select_display_ranges([
5761 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
5762 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
5763 ]);
5764 });
5765 });
5766
5767 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5768 EditorElement::new(&editor, style)
5769 });
5770 assert_eq!(state.selections.len(), 1);
5771 let local_selections = &state.selections[0].1;
5772 assert_eq!(local_selections.len(), 2);
5773
5774 // moves cursor on excerpt boundary back a line
5775 // and doesn't allow selection to bleed through
5776 assert_eq!(
5777 local_selections[0].range,
5778 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
5779 );
5780 assert_eq!(
5781 local_selections[0].head,
5782 DisplayPoint::new(DisplayRow(6), 0)
5783 );
5784 // moves cursor on buffer boundary back two lines
5785 // and doesn't allow selection to bleed through
5786 assert_eq!(
5787 local_selections[1].range,
5788 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
5789 );
5790 assert_eq!(
5791 local_selections[1].head,
5792 DisplayPoint::new(DisplayRow(12), 0)
5793 );
5794 }
5795
5796 #[gpui::test]
5797 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
5798 init_test(cx, |_| {});
5799
5800 let window = cx.add_window(|cx| {
5801 let buffer = MultiBuffer::build_simple("", cx);
5802 Editor::new(EditorMode::Full, buffer, None, true, cx)
5803 });
5804 let cx = &mut VisualTestContext::from_window(*window, cx);
5805 let editor = window.root(cx).unwrap();
5806 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5807 window
5808 .update(cx, |editor, cx| {
5809 editor.set_placeholder_text("hello", cx);
5810 editor.insert_blocks(
5811 [BlockProperties {
5812 style: BlockStyle::Fixed,
5813 disposition: BlockDisposition::Above,
5814 height: 3,
5815 position: Anchor::min(),
5816 render: Box::new(|_| div().into_any()),
5817 }],
5818 None,
5819 cx,
5820 );
5821
5822 // Blur the editor so that it displays placeholder text.
5823 cx.blur();
5824 })
5825 .unwrap();
5826
5827 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5828 EditorElement::new(&editor, style)
5829 });
5830 assert_eq!(state.position_map.line_layouts.len(), 4);
5831 assert_eq!(
5832 state
5833 .line_numbers
5834 .iter()
5835 .map(Option::is_some)
5836 .collect::<Vec<_>>(),
5837 &[false, false, false, true]
5838 );
5839 }
5840
5841 #[gpui::test]
5842 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
5843 const TAB_SIZE: u32 = 4;
5844
5845 let input_text = "\t \t|\t| a b";
5846 let expected_invisibles = vec![
5847 Invisible::Tab {
5848 line_start_offset: 0,
5849 },
5850 Invisible::Whitespace {
5851 line_offset: TAB_SIZE as usize,
5852 },
5853 Invisible::Tab {
5854 line_start_offset: TAB_SIZE as usize + 1,
5855 },
5856 Invisible::Tab {
5857 line_start_offset: TAB_SIZE as usize * 2 + 1,
5858 },
5859 Invisible::Whitespace {
5860 line_offset: TAB_SIZE as usize * 3 + 1,
5861 },
5862 Invisible::Whitespace {
5863 line_offset: TAB_SIZE as usize * 3 + 3,
5864 },
5865 ];
5866 assert_eq!(
5867 expected_invisibles.len(),
5868 input_text
5869 .chars()
5870 .filter(|initial_char| initial_char.is_whitespace())
5871 .count(),
5872 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
5873 );
5874
5875 init_test(cx, |s| {
5876 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
5877 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
5878 });
5879
5880 let actual_invisibles =
5881 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
5882
5883 assert_eq!(expected_invisibles, actual_invisibles);
5884 }
5885
5886 #[gpui::test]
5887 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
5888 init_test(cx, |s| {
5889 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
5890 s.defaults.tab_size = NonZeroU32::new(4);
5891 });
5892
5893 for editor_mode_without_invisibles in [
5894 EditorMode::SingleLine,
5895 EditorMode::AutoHeight { max_lines: 100 },
5896 ] {
5897 let invisibles = collect_invisibles_from_new_editor(
5898 cx,
5899 editor_mode_without_invisibles,
5900 "\t\t\t| | a b",
5901 px(500.0),
5902 );
5903 assert!(invisibles.is_empty(),
5904 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
5905 }
5906 }
5907
5908 #[gpui::test]
5909 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
5910 let tab_size = 4;
5911 let input_text = "a\tbcd ".repeat(9);
5912 let repeated_invisibles = [
5913 Invisible::Tab {
5914 line_start_offset: 1,
5915 },
5916 Invisible::Whitespace {
5917 line_offset: tab_size as usize + 3,
5918 },
5919 Invisible::Whitespace {
5920 line_offset: tab_size as usize + 4,
5921 },
5922 Invisible::Whitespace {
5923 line_offset: tab_size as usize + 5,
5924 },
5925 ];
5926 let expected_invisibles = std::iter::once(repeated_invisibles)
5927 .cycle()
5928 .take(9)
5929 .flatten()
5930 .collect::<Vec<_>>();
5931 assert_eq!(
5932 expected_invisibles.len(),
5933 input_text
5934 .chars()
5935 .filter(|initial_char| initial_char.is_whitespace())
5936 .count(),
5937 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
5938 );
5939 info!("Expected invisibles: {expected_invisibles:?}");
5940
5941 init_test(cx, |_| {});
5942
5943 // Put the same string with repeating whitespace pattern into editors of various size,
5944 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
5945 let resize_step = 10.0;
5946 let mut editor_width = 200.0;
5947 while editor_width <= 1000.0 {
5948 update_test_language_settings(cx, |s| {
5949 s.defaults.tab_size = NonZeroU32::new(tab_size);
5950 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
5951 s.defaults.preferred_line_length = Some(editor_width as u32);
5952 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
5953 });
5954
5955 let actual_invisibles = collect_invisibles_from_new_editor(
5956 cx,
5957 EditorMode::Full,
5958 &input_text,
5959 px(editor_width),
5960 );
5961
5962 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
5963 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
5964 let mut i = 0;
5965 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
5966 i = actual_index;
5967 match expected_invisibles.get(i) {
5968 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
5969 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
5970 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
5971 _ => {
5972 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
5973 }
5974 },
5975 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
5976 }
5977 }
5978 let missing_expected_invisibles = &expected_invisibles[i + 1..];
5979 assert!(
5980 missing_expected_invisibles.is_empty(),
5981 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
5982 );
5983
5984 editor_width += resize_step;
5985 }
5986 }
5987
5988 fn collect_invisibles_from_new_editor(
5989 cx: &mut TestAppContext,
5990 editor_mode: EditorMode,
5991 input_text: &str,
5992 editor_width: Pixels,
5993 ) -> Vec<Invisible> {
5994 info!(
5995 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
5996 editor_width.0
5997 );
5998 let window = cx.add_window(|cx| {
5999 let buffer = MultiBuffer::build_simple(&input_text, cx);
6000 Editor::new(editor_mode, buffer, None, true, cx)
6001 });
6002 let cx = &mut VisualTestContext::from_window(*window, cx);
6003 let editor = window.root(cx).unwrap();
6004 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6005 window
6006 .update(cx, |editor, cx| {
6007 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
6008 editor.set_wrap_width(Some(editor_width), cx);
6009 })
6010 .unwrap();
6011 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6012 EditorElement::new(&editor, style)
6013 });
6014 state
6015 .position_map
6016 .line_layouts
6017 .iter()
6018 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
6019 .cloned()
6020 .collect()
6021 }
6022}
6023
6024pub fn register_action<T: Action>(
6025 view: &View<Editor>,
6026 cx: &mut WindowContext,
6027 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6028) {
6029 let view = view.clone();
6030 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6031 let action = action.downcast_ref().unwrap();
6032 if phase == DispatchPhase::Bubble {
6033 view.update(cx, |editor, cx| {
6034 listener(editor, action, cx);
6035 })
6036 }
6037 })
6038}
6039
6040fn compute_auto_height_layout(
6041 editor: &mut Editor,
6042 max_lines: usize,
6043 max_line_number_width: Pixels,
6044 known_dimensions: Size<Option<Pixels>>,
6045 available_width: AvailableSpace,
6046 cx: &mut ViewContext<Editor>,
6047) -> Option<Size<Pixels>> {
6048 let width = known_dimensions.width.or_else(|| {
6049 if let AvailableSpace::Definite(available_width) = available_width {
6050 Some(available_width)
6051 } else {
6052 None
6053 }
6054 })?;
6055 if let Some(height) = known_dimensions.height {
6056 return Some(size(width, height));
6057 }
6058
6059 let style = editor.style.as_ref().unwrap();
6060 let font_id = cx.text_system().resolve_font(&style.text.font());
6061 let font_size = style.text.font_size.to_pixels(cx.rem_size());
6062 let line_height = style.text.line_height_in_pixels(cx.rem_size());
6063 let em_width = cx
6064 .text_system()
6065 .typographic_bounds(font_id, font_size, 'm')
6066 .unwrap()
6067 .size
6068 .width;
6069
6070 let mut snapshot = editor.snapshot(cx);
6071 let gutter_dimensions =
6072 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
6073
6074 editor.gutter_dimensions = gutter_dimensions;
6075 let text_width = width - gutter_dimensions.width;
6076 let overscroll = size(em_width, px(0.));
6077
6078 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6079 if editor.set_wrap_width(Some(editor_width), cx) {
6080 snapshot = editor.snapshot(cx);
6081 }
6082
6083 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6084 let height = scroll_height
6085 .max(line_height)
6086 .min(line_height * max_lines as f32);
6087
6088 Some(size(width, height))
6089}