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