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 return None;
1650 }
1651 let button = editor.render_run_indicator(
1652 &self.style,
1653 Some(display_row) == active_task_indicator_row,
1654 display_row,
1655 cx,
1656 );
1657
1658 let button = prepaint_gutter_button(
1659 button,
1660 display_row,
1661 line_height,
1662 gutter_dimensions,
1663 scroll_pixel_position,
1664 gutter_hitbox,
1665 rows_with_hunk_bounds,
1666 cx,
1667 );
1668 Some(button)
1669 })
1670 .collect_vec()
1671 })
1672 }
1673
1674 #[allow(clippy::too_many_arguments)]
1675 fn layout_code_actions_indicator(
1676 &self,
1677 line_height: Pixels,
1678 newest_selection_head: DisplayPoint,
1679 scroll_pixel_position: gpui::Point<Pixels>,
1680 gutter_dimensions: &GutterDimensions,
1681 gutter_hitbox: &Hitbox,
1682 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
1683 cx: &mut WindowContext,
1684 ) -> Option<AnyElement> {
1685 let mut active = false;
1686 let mut button = None;
1687 let row = newest_selection_head.row();
1688 self.editor.update(cx, |editor, cx| {
1689 if let Some(crate::ContextMenu::CodeActions(CodeActionsMenu {
1690 deployed_from_indicator,
1691 ..
1692 })) = editor.context_menu.read().as_ref()
1693 {
1694 active = deployed_from_indicator.map_or(true, |indicator_row| indicator_row == row);
1695 };
1696 button = editor.render_code_actions_indicator(&self.style, row, active, cx);
1697 });
1698
1699 let button = prepaint_gutter_button(
1700 button?,
1701 row,
1702 line_height,
1703 gutter_dimensions,
1704 scroll_pixel_position,
1705 gutter_hitbox,
1706 rows_with_hunk_bounds,
1707 cx,
1708 );
1709
1710 Some(button)
1711 }
1712
1713 fn get_participant_color(
1714 participant_index: Option<ParticipantIndex>,
1715 cx: &WindowContext,
1716 ) -> PlayerColor {
1717 if let Some(index) = participant_index {
1718 cx.theme().players().color_for_participant(index.0)
1719 } else {
1720 cx.theme().players().absent()
1721 }
1722 }
1723
1724 fn calculate_relative_line_numbers(
1725 &self,
1726 snapshot: &EditorSnapshot,
1727 rows: &Range<DisplayRow>,
1728 relative_to: Option<DisplayRow>,
1729 ) -> HashMap<DisplayRow, DisplayRowDelta> {
1730 let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
1731 let Some(relative_to) = relative_to else {
1732 return relative_rows;
1733 };
1734
1735 let start = rows.start.min(relative_to);
1736 let end = rows.end.max(relative_to);
1737
1738 let buffer_rows = snapshot
1739 .buffer_rows(start)
1740 .take(1 + end.minus(start) as usize)
1741 .collect::<Vec<_>>();
1742
1743 let head_idx = relative_to.minus(start);
1744 let mut delta = 1;
1745 let mut i = head_idx + 1;
1746 while i < buffer_rows.len() as u32 {
1747 if buffer_rows[i as usize].is_some() {
1748 if rows.contains(&DisplayRow(i + start.0)) {
1749 relative_rows.insert(DisplayRow(i + start.0), delta);
1750 }
1751 delta += 1;
1752 }
1753 i += 1;
1754 }
1755 delta = 1;
1756 i = head_idx.min(buffer_rows.len() as u32 - 1);
1757 while i > 0 && buffer_rows[i as usize].is_none() {
1758 i -= 1;
1759 }
1760
1761 while i > 0 {
1762 i -= 1;
1763 if buffer_rows[i as usize].is_some() {
1764 if rows.contains(&DisplayRow(i + start.0)) {
1765 relative_rows.insert(DisplayRow(i + start.0), delta);
1766 }
1767 delta += 1;
1768 }
1769 }
1770
1771 relative_rows
1772 }
1773
1774 fn layout_line_numbers(
1775 &self,
1776 rows: Range<DisplayRow>,
1777 buffer_rows: impl Iterator<Item = Option<MultiBufferRow>>,
1778 active_rows: &BTreeMap<DisplayRow, bool>,
1779 newest_selection_head: Option<DisplayPoint>,
1780 snapshot: &EditorSnapshot,
1781 cx: &mut WindowContext,
1782 ) -> Vec<Option<ShapedLine>> {
1783 let include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
1784 EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full
1785 });
1786 if !include_line_numbers {
1787 return Vec::new();
1788 }
1789
1790 let editor = self.editor.read(cx);
1791 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1792 let newest = editor.selections.newest::<Point>(cx);
1793 SelectionLayout::new(
1794 newest,
1795 editor.selections.line_mode,
1796 editor.cursor_shape,
1797 &snapshot.display_snapshot,
1798 true,
1799 true,
1800 None,
1801 )
1802 .head
1803 });
1804 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1805
1806 let is_relative = editor.should_use_relative_line_numbers(cx);
1807 let relative_to = if is_relative {
1808 Some(newest_selection_head.row())
1809 } else {
1810 None
1811 };
1812 let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
1813 let mut line_number = String::new();
1814 buffer_rows
1815 .into_iter()
1816 .enumerate()
1817 .map(|(ix, multibuffer_row)| {
1818 let multibuffer_row = multibuffer_row?;
1819 let display_row = DisplayRow(rows.start.0 + ix as u32);
1820 let color = if active_rows.contains_key(&display_row) {
1821 cx.theme().colors().editor_active_line_number
1822 } else {
1823 cx.theme().colors().editor_line_number
1824 };
1825 line_number.clear();
1826 let default_number = multibuffer_row.0 + 1;
1827 let number = relative_rows
1828 .get(&DisplayRow(ix as u32 + rows.start.0))
1829 .unwrap_or(&default_number);
1830 write!(&mut line_number, "{number}").unwrap();
1831 let run = TextRun {
1832 len: line_number.len(),
1833 font: self.style.text.font(),
1834 color,
1835 background_color: None,
1836 underline: None,
1837 strikethrough: None,
1838 };
1839 let shaped_line = cx
1840 .text_system()
1841 .shape_line(line_number.clone().into(), font_size, &[run])
1842 .unwrap();
1843 Some(shaped_line)
1844 })
1845 .collect()
1846 }
1847
1848 fn layout_gutter_fold_toggles(
1849 &self,
1850 rows: Range<DisplayRow>,
1851 buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1852 active_rows: &BTreeMap<DisplayRow, bool>,
1853 snapshot: &EditorSnapshot,
1854 cx: &mut WindowContext,
1855 ) -> Vec<Option<AnyElement>> {
1856 let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
1857 && snapshot.mode == EditorMode::Full
1858 && self.editor.read(cx).is_singleton(cx);
1859 if include_fold_statuses {
1860 buffer_rows
1861 .into_iter()
1862 .enumerate()
1863 .map(|(ix, row)| {
1864 if let Some(multibuffer_row) = row {
1865 let display_row = DisplayRow(rows.start.0 + ix as u32);
1866 let active = active_rows.contains_key(&display_row);
1867 snapshot.render_fold_toggle(
1868 multibuffer_row,
1869 active,
1870 self.editor.clone(),
1871 cx,
1872 )
1873 } else {
1874 None
1875 }
1876 })
1877 .collect()
1878 } else {
1879 Vec::new()
1880 }
1881 }
1882
1883 fn layout_crease_trailers(
1884 &self,
1885 buffer_rows: impl IntoIterator<Item = Option<MultiBufferRow>>,
1886 snapshot: &EditorSnapshot,
1887 cx: &mut WindowContext,
1888 ) -> Vec<Option<AnyElement>> {
1889 buffer_rows
1890 .into_iter()
1891 .map(|row| {
1892 if let Some(multibuffer_row) = row {
1893 snapshot.render_crease_trailer(multibuffer_row, cx)
1894 } else {
1895 None
1896 }
1897 })
1898 .collect()
1899 }
1900
1901 fn layout_lines(
1902 rows: Range<DisplayRow>,
1903 line_number_layouts: &[Option<ShapedLine>],
1904 snapshot: &EditorSnapshot,
1905 style: &EditorStyle,
1906 editor_width: Pixels,
1907 cx: &mut WindowContext,
1908 ) -> Vec<LineWithInvisibles> {
1909 if rows.start >= rows.end {
1910 return Vec::new();
1911 }
1912
1913 // Show the placeholder when the editor is empty
1914 if snapshot.is_empty() {
1915 let font_size = style.text.font_size.to_pixels(cx.rem_size());
1916 let placeholder_color = cx.theme().colors().text_placeholder;
1917 let placeholder_text = snapshot.placeholder_text();
1918
1919 let placeholder_lines = placeholder_text
1920 .as_ref()
1921 .map_or("", AsRef::as_ref)
1922 .split('\n')
1923 .skip(rows.start.0 as usize)
1924 .chain(iter::repeat(""))
1925 .take(rows.len());
1926 placeholder_lines
1927 .filter_map(move |line| {
1928 let run = TextRun {
1929 len: line.len(),
1930 font: style.text.font(),
1931 color: placeholder_color,
1932 background_color: None,
1933 underline: Default::default(),
1934 strikethrough: None,
1935 };
1936 cx.text_system()
1937 .shape_line(line.to_string().into(), font_size, &[run])
1938 .log_err()
1939 })
1940 .map(|line| LineWithInvisibles {
1941 width: line.width,
1942 len: line.len,
1943 fragments: smallvec![LineFragment::Text(line)],
1944 invisibles: Vec::new(),
1945 font_size,
1946 })
1947 .collect()
1948 } else {
1949 let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
1950 LineWithInvisibles::from_chunks(
1951 chunks,
1952 &style.text,
1953 MAX_LINE_LEN,
1954 rows.len(),
1955 line_number_layouts,
1956 snapshot.mode,
1957 editor_width,
1958 cx,
1959 )
1960 }
1961 }
1962
1963 fn prepaint_lines(
1964 &self,
1965 start_row: DisplayRow,
1966 line_layouts: &mut [LineWithInvisibles],
1967 line_height: Pixels,
1968 scroll_pixel_position: gpui::Point<Pixels>,
1969 content_origin: gpui::Point<Pixels>,
1970 cx: &mut WindowContext,
1971 ) -> SmallVec<[AnyElement; 1]> {
1972 let mut line_elements = SmallVec::new();
1973 for (ix, line) in line_layouts.iter_mut().enumerate() {
1974 let row = start_row + DisplayRow(ix as u32);
1975 line.prepaint(
1976 line_height,
1977 scroll_pixel_position,
1978 row,
1979 content_origin,
1980 &mut line_elements,
1981 cx,
1982 );
1983 }
1984 line_elements
1985 }
1986
1987 #[allow(clippy::too_many_arguments)]
1988 fn render_block(
1989 &self,
1990 block: &Block,
1991 available_width: AvailableSpace,
1992 block_id: BlockId,
1993 block_row_start: DisplayRow,
1994 snapshot: &EditorSnapshot,
1995 text_x: Pixels,
1996 rows: &Range<DisplayRow>,
1997 line_layouts: &[LineWithInvisibles],
1998 gutter_dimensions: &GutterDimensions,
1999 line_height: Pixels,
2000 em_width: Pixels,
2001 text_hitbox: &Hitbox,
2002 editor_width: Pixels,
2003 scroll_width: &mut Pixels,
2004 resized_blocks: &mut HashMap<CustomBlockId, u32>,
2005 cx: &mut WindowContext,
2006 ) -> (AnyElement, Size<Pixels>) {
2007 let mut element = match block {
2008 Block::Custom(block) => {
2009 let align_to = block
2010 .position()
2011 .to_point(&snapshot.buffer_snapshot)
2012 .to_display_point(snapshot);
2013 let anchor_x = text_x
2014 + if rows.contains(&align_to.row()) {
2015 line_layouts[align_to.row().minus(rows.start) as usize]
2016 .x_for_index(align_to.column() as usize)
2017 } else {
2018 layout_line(align_to.row(), snapshot, &self.style, editor_width, cx)
2019 .x_for_index(align_to.column() as usize)
2020 };
2021
2022 div()
2023 .size_full()
2024 .child(block.render(&mut BlockContext {
2025 context: cx,
2026 anchor_x,
2027 gutter_dimensions,
2028 line_height,
2029 em_width,
2030 block_id,
2031 max_width: text_hitbox.size.width.max(*scroll_width),
2032 editor_style: &self.style,
2033 }))
2034 .cursor(CursorStyle::Arrow)
2035 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
2036 .into_any_element()
2037 }
2038
2039 Block::ExcerptHeader {
2040 buffer,
2041 range,
2042 starts_new_buffer,
2043 height,
2044 id,
2045 show_excerpt_controls,
2046 ..
2047 } => {
2048 let include_root = self
2049 .editor
2050 .read(cx)
2051 .project
2052 .as_ref()
2053 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2054 .unwrap_or_default();
2055
2056 #[derive(Clone)]
2057 struct JumpData {
2058 position: Point,
2059 anchor: text::Anchor,
2060 path: ProjectPath,
2061 line_offset_from_top: u32,
2062 }
2063
2064 let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
2065 let jump_path = ProjectPath {
2066 worktree_id: file.worktree_id(cx),
2067 path: file.path.clone(),
2068 };
2069 let jump_anchor = range
2070 .primary
2071 .as_ref()
2072 .map_or(range.context.start, |primary| primary.start);
2073
2074 let excerpt_start = range.context.start;
2075 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2076 let offset_from_excerpt_start = if jump_anchor == excerpt_start {
2077 0
2078 } else {
2079 let excerpt_start_row =
2080 language::ToPoint::to_point(&jump_anchor, buffer).row;
2081 jump_position.row - excerpt_start_row
2082 };
2083
2084 let line_offset_from_top =
2085 block_row_start.0 + *height + offset_from_excerpt_start
2086 - snapshot
2087 .scroll_anchor
2088 .scroll_position(&snapshot.display_snapshot)
2089 .y as u32;
2090
2091 JumpData {
2092 position: jump_position,
2093 anchor: jump_anchor,
2094 path: jump_path,
2095 line_offset_from_top,
2096 }
2097 });
2098
2099 let icon_offset = gutter_dimensions.width
2100 - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2101
2102 let element = if *starts_new_buffer {
2103 let path = buffer.resolve_file_path(cx, include_root);
2104 let mut filename = None;
2105 let mut parent_path = None;
2106 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2107 if let Some(path) = path {
2108 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
2109 parent_path = path
2110 .parent()
2111 .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
2112 }
2113
2114 let header_padding = px(6.0);
2115
2116 v_flex()
2117 .id(("path excerpt header", EntityId::from(block_id)))
2118 .w_full()
2119 .px(header_padding)
2120 .pt(header_padding)
2121 .child(
2122 h_flex()
2123 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
2124 .id("path header block")
2125 .h(2. * cx.line_height())
2126 .px(gpui::px(12.))
2127 .rounded_md()
2128 .shadow_md()
2129 .border_1()
2130 .border_color(cx.theme().colors().border)
2131 .bg(cx.theme().colors().editor_subheader_background)
2132 .justify_between()
2133 .hover(|style| style.bg(cx.theme().colors().element_hover))
2134 .child(
2135 h_flex().gap_3().child(
2136 h_flex()
2137 .gap_2()
2138 .child(
2139 filename
2140 .map(SharedString::from)
2141 .unwrap_or_else(|| "untitled".into()),
2142 )
2143 .when_some(parent_path, |then, path| {
2144 then.child(
2145 div()
2146 .child(path)
2147 .text_color(cx.theme().colors().text_muted),
2148 )
2149 }),
2150 ),
2151 )
2152 .when_some(jump_data.clone(), |el, jump_data| {
2153 el.child(Icon::new(IconName::ArrowUpRight))
2154 .cursor_pointer()
2155 .tooltip(|cx| {
2156 Tooltip::for_action("Jump to File", &OpenExcerpts, cx)
2157 })
2158 .on_mouse_down(MouseButton::Left, |_, cx| {
2159 cx.stop_propagation()
2160 })
2161 .on_click(cx.listener_for(&self.editor, {
2162 move |editor, _, cx| {
2163 editor.jump(
2164 jump_data.path.clone(),
2165 jump_data.position,
2166 jump_data.anchor,
2167 jump_data.line_offset_from_top,
2168 cx,
2169 );
2170 }
2171 }))
2172 }),
2173 )
2174 .children(show_excerpt_controls.then(|| {
2175 h_flex()
2176 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.333)))
2177 .h(1. * cx.line_height())
2178 .pt_1()
2179 .justify_end()
2180 .flex_none()
2181 .w(icon_offset - header_padding)
2182 .child(
2183 ButtonLike::new("expand-icon")
2184 .style(ButtonStyle::Transparent)
2185 .child(
2186 svg()
2187 .path(IconName::ArrowUpFromLine.path())
2188 .size(IconSize::XSmall.rems())
2189 .text_color(cx.theme().colors().editor_line_number)
2190 .group("")
2191 .hover(|style| {
2192 style.text_color(
2193 cx.theme()
2194 .colors()
2195 .editor_active_line_number,
2196 )
2197 }),
2198 )
2199 .on_click(cx.listener_for(&self.editor, {
2200 let id = *id;
2201 move |editor, _, cx| {
2202 editor.expand_excerpt(
2203 id,
2204 multi_buffer::ExpandExcerptDirection::Up,
2205 cx,
2206 );
2207 }
2208 }))
2209 .tooltip({
2210 move |cx| {
2211 Tooltip::for_action(
2212 "Expand Excerpt",
2213 &ExpandExcerpts { lines: 0 },
2214 cx,
2215 )
2216 }
2217 }),
2218 )
2219 }))
2220 } else {
2221 v_flex()
2222 .id(("excerpt header", EntityId::from(block_id)))
2223 .w_full()
2224 .h(snapshot.excerpt_header_height() as f32 * cx.line_height())
2225 .child(
2226 div()
2227 .flex()
2228 .v_flex()
2229 .justify_start()
2230 .id("jump to collapsed context")
2231 .w(relative(1.0))
2232 .h_full()
2233 .child(
2234 div()
2235 .h_px()
2236 .w_full()
2237 .bg(cx.theme().colors().border_variant)
2238 .group_hover("excerpt-jump-action", |style| {
2239 style.bg(cx.theme().colors().border)
2240 }),
2241 ),
2242 )
2243 .child(
2244 h_flex()
2245 .justify_end()
2246 .flex_none()
2247 .w(icon_offset)
2248 .h_full()
2249 .child(
2250 show_excerpt_controls
2251 .then(|| {
2252 ButtonLike::new("expand-icon")
2253 .style(ButtonStyle::Transparent)
2254 .child(
2255 svg()
2256 .path(IconName::ArrowUpFromLine.path())
2257 .size(IconSize::XSmall.rems())
2258 .text_color(
2259 cx.theme().colors().editor_line_number,
2260 )
2261 .group("")
2262 .hover(|style| {
2263 style.text_color(
2264 cx.theme()
2265 .colors()
2266 .editor_active_line_number,
2267 )
2268 }),
2269 )
2270 .on_click(cx.listener_for(&self.editor, {
2271 let id = *id;
2272 move |editor, _, cx| {
2273 editor.expand_excerpt(
2274 id,
2275 multi_buffer::ExpandExcerptDirection::Up,
2276 cx,
2277 );
2278 }
2279 }))
2280 .tooltip({
2281 move |cx| {
2282 Tooltip::for_action(
2283 "Expand Excerpt",
2284 &ExpandExcerpts { lines: 0 },
2285 cx,
2286 )
2287 }
2288 })
2289 })
2290 .unwrap_or_else(|| {
2291 ButtonLike::new("jump-icon")
2292 .style(ButtonStyle::Transparent)
2293 .child(
2294 svg()
2295 .path(IconName::ArrowUpRight.path())
2296 .size(IconSize::XSmall.rems())
2297 .text_color(
2298 cx.theme().colors().border_variant,
2299 )
2300 .group("excerpt-jump-action")
2301 .group_hover(
2302 "excerpt-jump-action",
2303 |style| {
2304 style.text_color(
2305 cx.theme().colors().border,
2306 )
2307 },
2308 ),
2309 )
2310 .when_some(jump_data.clone(), |this, jump_data| {
2311 this.on_click(cx.listener_for(&self.editor, {
2312 let path = jump_data.path.clone();
2313 move |editor, _, cx| {
2314 cx.stop_propagation();
2315
2316 editor.jump(
2317 path.clone(),
2318 jump_data.position,
2319 jump_data.anchor,
2320 jump_data.line_offset_from_top,
2321 cx,
2322 );
2323 }
2324 }))
2325 .tooltip(move |cx| {
2326 Tooltip::for_action(
2327 format!(
2328 "Jump to {}:L{}",
2329 jump_data.path.path.display(),
2330 jump_data.position.row + 1
2331 ),
2332 &OpenExcerpts,
2333 cx,
2334 )
2335 })
2336 })
2337 }),
2338 ),
2339 )
2340 .group("excerpt-jump-action")
2341 .cursor_pointer()
2342 .when_some(jump_data.clone(), |this, jump_data| {
2343 this.on_click(cx.listener_for(&self.editor, {
2344 let path = jump_data.path.clone();
2345 move |editor, _, cx| {
2346 cx.stop_propagation();
2347
2348 editor.jump(
2349 path.clone(),
2350 jump_data.position,
2351 jump_data.anchor,
2352 jump_data.line_offset_from_top,
2353 cx,
2354 );
2355 }
2356 }))
2357 .tooltip(move |cx| {
2358 Tooltip::for_action(
2359 format!(
2360 "Jump to {}:L{}",
2361 jump_data.path.path.display(),
2362 jump_data.position.row + 1
2363 ),
2364 &OpenExcerpts,
2365 cx,
2366 )
2367 })
2368 })
2369 };
2370 element.into_any()
2371 }
2372
2373 Block::ExcerptFooter { id, .. } => {
2374 let element = v_flex()
2375 .id(("excerpt footer", EntityId::from(block_id)))
2376 .w_full()
2377 .h(snapshot.excerpt_footer_height() as f32 * cx.line_height())
2378 .child(
2379 h_flex()
2380 .justify_end()
2381 .flex_none()
2382 .w(gutter_dimensions.width
2383 - (gutter_dimensions.left_padding + gutter_dimensions.margin))
2384 .h_full()
2385 .child(
2386 ButtonLike::new("expand-icon")
2387 .style(ButtonStyle::Transparent)
2388 .child(
2389 svg()
2390 .path(IconName::ArrowDownFromLine.path())
2391 .size(IconSize::XSmall.rems())
2392 .text_color(cx.theme().colors().editor_line_number)
2393 .group("")
2394 .hover(|style| {
2395 style.text_color(
2396 cx.theme().colors().editor_active_line_number,
2397 )
2398 }),
2399 )
2400 .on_click(cx.listener_for(&self.editor, {
2401 let id = *id;
2402 move |editor, _, cx| {
2403 editor.expand_excerpt(
2404 id,
2405 multi_buffer::ExpandExcerptDirection::Down,
2406 cx,
2407 );
2408 }
2409 }))
2410 .tooltip({
2411 move |cx| {
2412 Tooltip::for_action(
2413 "Expand Excerpt",
2414 &ExpandExcerpts { lines: 0 },
2415 cx,
2416 )
2417 }
2418 }),
2419 ),
2420 );
2421 element.into_any()
2422 }
2423 };
2424
2425 // Discover the element's content height, then round up to the nearest multiple of line height.
2426 let preliminary_size =
2427 element.layout_as_root(size(available_width, AvailableSpace::MinContent), cx);
2428 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
2429 let final_size = if preliminary_size.height == quantized_height {
2430 preliminary_size
2431 } else {
2432 element.layout_as_root(size(available_width, quantized_height.into()), cx)
2433 };
2434
2435 if let BlockId::Custom(custom_block_id) = block_id {
2436 if block.height() > 0 {
2437 let element_height_in_lines =
2438 ((final_size.height / line_height).ceil() as u32).max(1);
2439 if element_height_in_lines != block.height() {
2440 resized_blocks.insert(custom_block_id, element_height_in_lines);
2441 }
2442 }
2443 }
2444
2445 (element, final_size)
2446 }
2447
2448 #[allow(clippy::too_many_arguments)]
2449 fn render_blocks(
2450 &self,
2451 rows: Range<DisplayRow>,
2452 snapshot: &EditorSnapshot,
2453 hitbox: &Hitbox,
2454 text_hitbox: &Hitbox,
2455 editor_width: Pixels,
2456 scroll_width: &mut Pixels,
2457 gutter_dimensions: &GutterDimensions,
2458 em_width: Pixels,
2459 text_x: Pixels,
2460 line_height: Pixels,
2461 line_layouts: &[LineWithInvisibles],
2462 cx: &mut WindowContext,
2463 ) -> Result<Vec<BlockLayout>, HashMap<CustomBlockId, u32>> {
2464 let (fixed_blocks, non_fixed_blocks) = snapshot
2465 .blocks_in_range(rows.clone())
2466 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
2467
2468 let mut focused_block = self
2469 .editor
2470 .update(cx, |editor, _| editor.take_focused_block());
2471 let mut fixed_block_max_width = Pixels::ZERO;
2472 let mut blocks = Vec::new();
2473 let mut resized_blocks = HashMap::default();
2474
2475 for (row, block) in fixed_blocks {
2476 let block_id = block.id();
2477
2478 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2479 focused_block = None;
2480 }
2481
2482 let (element, element_size) = self.render_block(
2483 block,
2484 AvailableSpace::MinContent,
2485 block_id,
2486 row,
2487 snapshot,
2488 text_x,
2489 &rows,
2490 line_layouts,
2491 gutter_dimensions,
2492 line_height,
2493 em_width,
2494 text_hitbox,
2495 editor_width,
2496 scroll_width,
2497 &mut resized_blocks,
2498 cx,
2499 );
2500 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2501 blocks.push(BlockLayout {
2502 id: block_id,
2503 row: Some(row),
2504 element,
2505 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
2506 style: BlockStyle::Fixed,
2507 });
2508 }
2509 for (row, block) in non_fixed_blocks {
2510 let style = block.style();
2511 let width = match style {
2512 BlockStyle::Sticky => hitbox.size.width,
2513 BlockStyle::Flex => hitbox
2514 .size
2515 .width
2516 .max(fixed_block_max_width)
2517 .max(gutter_dimensions.width + *scroll_width),
2518 BlockStyle::Fixed => unreachable!(),
2519 };
2520 let block_id = block.id();
2521
2522 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2523 focused_block = None;
2524 }
2525
2526 let (element, element_size) = self.render_block(
2527 block,
2528 width.into(),
2529 block_id,
2530 row,
2531 snapshot,
2532 text_x,
2533 &rows,
2534 line_layouts,
2535 gutter_dimensions,
2536 line_height,
2537 em_width,
2538 text_hitbox,
2539 editor_width,
2540 scroll_width,
2541 &mut resized_blocks,
2542 cx,
2543 );
2544
2545 blocks.push(BlockLayout {
2546 id: block_id,
2547 row: Some(row),
2548 element,
2549 available_space: size(width.into(), element_size.height.into()),
2550 style,
2551 });
2552 }
2553
2554 if let Some(focused_block) = focused_block {
2555 if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
2556 if focus_handle.is_focused(cx) {
2557 if let Some(block) = snapshot.block_for_id(focused_block.id) {
2558 let style = block.style();
2559 let width = match style {
2560 BlockStyle::Fixed => AvailableSpace::MinContent,
2561 BlockStyle::Flex => AvailableSpace::Definite(
2562 hitbox
2563 .size
2564 .width
2565 .max(fixed_block_max_width)
2566 .max(gutter_dimensions.width + *scroll_width),
2567 ),
2568 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
2569 };
2570
2571 let (element, element_size) = self.render_block(
2572 &block,
2573 width,
2574 focused_block.id,
2575 rows.end,
2576 snapshot,
2577 text_x,
2578 &rows,
2579 line_layouts,
2580 gutter_dimensions,
2581 line_height,
2582 em_width,
2583 text_hitbox,
2584 editor_width,
2585 scroll_width,
2586 &mut resized_blocks,
2587 cx,
2588 );
2589
2590 blocks.push(BlockLayout {
2591 id: block.id(),
2592 row: None,
2593 element,
2594 available_space: size(width, element_size.height.into()),
2595 style,
2596 });
2597 }
2598 }
2599 }
2600 }
2601
2602 if resized_blocks.is_empty() {
2603 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2604 Ok(blocks)
2605 } else {
2606 Err(resized_blocks)
2607 }
2608 }
2609
2610 /// Returns true if any of the blocks changed size since the previous frame. This will trigger
2611 /// a restart of rendering for the editor based on the new sizes.
2612 fn layout_blocks(
2613 &self,
2614 blocks: &mut Vec<BlockLayout>,
2615 hitbox: &Hitbox,
2616 line_height: Pixels,
2617 scroll_pixel_position: gpui::Point<Pixels>,
2618 cx: &mut WindowContext,
2619 ) {
2620 for block in blocks {
2621 let mut origin = if let Some(row) = block.row {
2622 hitbox.origin
2623 + point(
2624 Pixels::ZERO,
2625 row.as_f32() * line_height - scroll_pixel_position.y,
2626 )
2627 } else {
2628 // Position the block outside the visible area
2629 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
2630 };
2631
2632 if !matches!(block.style, BlockStyle::Sticky) {
2633 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2634 }
2635
2636 let focus_handle = block
2637 .element
2638 .prepaint_as_root(origin, block.available_space, cx);
2639
2640 if let Some(focus_handle) = focus_handle {
2641 self.editor.update(cx, |editor, _cx| {
2642 editor.set_focused_block(FocusedBlock {
2643 id: block.id,
2644 focus_handle: focus_handle.downgrade(),
2645 });
2646 });
2647 }
2648 }
2649 }
2650
2651 #[allow(clippy::too_many_arguments)]
2652 fn layout_context_menu(
2653 &self,
2654 line_height: Pixels,
2655 hitbox: &Hitbox,
2656 text_hitbox: &Hitbox,
2657 content_origin: gpui::Point<Pixels>,
2658 start_row: DisplayRow,
2659 scroll_pixel_position: gpui::Point<Pixels>,
2660 line_layouts: &[LineWithInvisibles],
2661 newest_selection_head: DisplayPoint,
2662 gutter_overshoot: Pixels,
2663 cx: &mut WindowContext,
2664 ) -> bool {
2665 let max_height = cmp::min(
2666 12. * line_height,
2667 cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
2668 );
2669 let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
2670 if editor.context_menu_visible() {
2671 editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
2672 } else {
2673 None
2674 }
2675 }) else {
2676 return false;
2677 };
2678
2679 let context_menu_size = context_menu.layout_as_root(AvailableSpace::min_size(), cx);
2680
2681 let (x, y) = match position {
2682 crate::ContextMenuOrigin::EditorPoint(point) => {
2683 let cursor_row_layout = &line_layouts[point.row().minus(start_row) as usize];
2684 let x = cursor_row_layout.x_for_index(point.column() as usize)
2685 - scroll_pixel_position.x;
2686 let y = point.row().next_row().as_f32() * line_height - scroll_pixel_position.y;
2687 (x, y)
2688 }
2689 crate::ContextMenuOrigin::GutterIndicator(row) => {
2690 // 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
2691 // text field.
2692 let x = -gutter_overshoot;
2693 let y = row.next_row().as_f32() * line_height - scroll_pixel_position.y;
2694 (x, y)
2695 }
2696 };
2697
2698 let mut list_origin = content_origin + point(x, y);
2699 let list_width = context_menu_size.width;
2700 let list_height = context_menu_size.height;
2701
2702 // Snap the right edge of the list to the right edge of the window if
2703 // its horizontal bounds overflow.
2704 if list_origin.x + list_width > cx.viewport_size().width {
2705 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
2706 }
2707
2708 if list_origin.y + list_height > text_hitbox.lower_right().y {
2709 list_origin.y -= line_height + list_height;
2710 }
2711
2712 cx.defer_draw(context_menu, list_origin, 1);
2713 true
2714 }
2715
2716 fn layout_mouse_context_menu(
2717 &self,
2718 editor_snapshot: &EditorSnapshot,
2719 visible_range: Range<DisplayRow>,
2720 cx: &mut WindowContext,
2721 ) -> Option<AnyElement> {
2722 let position = self.editor.update(cx, |editor, cx| {
2723 let visible_start_point = editor.display_to_pixel_point(
2724 DisplayPoint::new(visible_range.start, 0),
2725 editor_snapshot,
2726 cx,
2727 )?;
2728 let visible_end_point = editor.display_to_pixel_point(
2729 DisplayPoint::new(visible_range.end, 0),
2730 editor_snapshot,
2731 cx,
2732 )?;
2733
2734 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
2735 let (source_display_point, position) = match mouse_context_menu.position {
2736 MenuPosition::PinnedToScreen(point) => (None, point),
2737 MenuPosition::PinnedToEditor {
2738 source,
2739 offset_x,
2740 offset_y,
2741 } => {
2742 let source_display_point = source.to_display_point(editor_snapshot);
2743 let mut source_point = editor.to_pixel_point(source, editor_snapshot, cx)?;
2744 source_point.x += offset_x;
2745 source_point.y += offset_y;
2746 (Some(source_display_point), source_point)
2747 }
2748 };
2749
2750 let source_included = source_display_point.map_or(true, |source_display_point| {
2751 visible_range
2752 .to_inclusive()
2753 .contains(&source_display_point.row())
2754 });
2755 let position_included =
2756 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
2757 if !source_included && !position_included {
2758 None
2759 } else {
2760 Some(position)
2761 }
2762 })?;
2763
2764 let mut element = self.editor.update(cx, |editor, _| {
2765 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
2766 let context_menu = mouse_context_menu.context_menu.clone();
2767
2768 Some(
2769 deferred(
2770 anchored()
2771 .position(position)
2772 .child(context_menu)
2773 .anchor(AnchorCorner::TopLeft)
2774 .snap_to_window_with_margin(px(8.)),
2775 )
2776 .with_priority(1)
2777 .into_any(),
2778 )
2779 })?;
2780
2781 element.prepaint_as_root(position, AvailableSpace::min_size(), cx);
2782 Some(element)
2783 }
2784
2785 #[allow(clippy::too_many_arguments)]
2786 fn layout_hover_popovers(
2787 &self,
2788 snapshot: &EditorSnapshot,
2789 hitbox: &Hitbox,
2790 text_hitbox: &Hitbox,
2791 visible_display_row_range: Range<DisplayRow>,
2792 content_origin: gpui::Point<Pixels>,
2793 scroll_pixel_position: gpui::Point<Pixels>,
2794 line_layouts: &[LineWithInvisibles],
2795 line_height: Pixels,
2796 em_width: Pixels,
2797 cx: &mut WindowContext,
2798 ) {
2799 struct MeasuredHoverPopover {
2800 element: AnyElement,
2801 size: Size<Pixels>,
2802 horizontal_offset: Pixels,
2803 }
2804
2805 let max_size = size(
2806 (120. * em_width) // Default size
2807 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2808 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2809 (16. * line_height) // Default size
2810 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2811 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2812 );
2813
2814 let hover_popovers = self.editor.update(cx, |editor, cx| {
2815 editor
2816 .hover_state
2817 .render(snapshot, visible_display_row_range.clone(), max_size, cx)
2818 });
2819 let Some((position, hover_popovers)) = hover_popovers else {
2820 return;
2821 };
2822
2823 // This is safe because we check on layout whether the required row is available
2824 let hovered_row_layout =
2825 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
2826
2827 // Compute Hovered Point
2828 let x =
2829 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
2830 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
2831 let hovered_point = content_origin + point(x, y);
2832
2833 let mut overall_height = Pixels::ZERO;
2834 let mut measured_hover_popovers = Vec::new();
2835 for mut hover_popover in hover_popovers {
2836 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), cx);
2837 let horizontal_offset =
2838 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
2839
2840 overall_height += HOVER_POPOVER_GAP + size.height;
2841
2842 measured_hover_popovers.push(MeasuredHoverPopover {
2843 element: hover_popover,
2844 size,
2845 horizontal_offset,
2846 });
2847 }
2848 overall_height += HOVER_POPOVER_GAP;
2849
2850 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
2851 let mut occlusion = div()
2852 .size_full()
2853 .occlude()
2854 .on_mouse_move(|_, cx| cx.stop_propagation())
2855 .into_any_element();
2856 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
2857 cx.defer_draw(occlusion, origin, 2);
2858 }
2859
2860 if hovered_point.y > overall_height {
2861 // There is enough space above. Render popovers above the hovered point
2862 let mut current_y = hovered_point.y;
2863 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2864 let size = popover.size;
2865 let popover_origin = point(
2866 hovered_point.x + popover.horizontal_offset,
2867 current_y - size.height,
2868 );
2869
2870 cx.defer_draw(popover.element, popover_origin, 2);
2871 if position != itertools::Position::Last {
2872 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
2873 draw_occluder(size.width, origin, cx);
2874 }
2875
2876 current_y = popover_origin.y - HOVER_POPOVER_GAP;
2877 }
2878 } else {
2879 // There is not enough space above. Render popovers below the hovered point
2880 let mut current_y = hovered_point.y + line_height;
2881 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2882 let size = popover.size;
2883 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2884
2885 cx.defer_draw(popover.element, popover_origin, 2);
2886 if position != itertools::Position::Last {
2887 let origin = point(popover_origin.x, popover_origin.y + size.height);
2888 draw_occluder(size.width, origin, cx);
2889 }
2890
2891 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2892 }
2893 }
2894 }
2895
2896 #[allow(clippy::too_many_arguments)]
2897 fn layout_signature_help(
2898 &self,
2899 hitbox: &Hitbox,
2900 content_origin: gpui::Point<Pixels>,
2901 scroll_pixel_position: gpui::Point<Pixels>,
2902 newest_selection_head: Option<DisplayPoint>,
2903 start_row: DisplayRow,
2904 line_layouts: &[LineWithInvisibles],
2905 line_height: Pixels,
2906 em_width: Pixels,
2907 cx: &mut WindowContext,
2908 ) {
2909 if !self.editor.focus_handle(cx).is_focused(cx) {
2910 return;
2911 }
2912 let Some(newest_selection_head) = newest_selection_head else {
2913 return;
2914 };
2915 let selection_row = newest_selection_head.row();
2916 if selection_row < start_row {
2917 return;
2918 }
2919 let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
2920 else {
2921 return;
2922 };
2923
2924 let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
2925 - scroll_pixel_position.x
2926 + content_origin.x;
2927 let start_y =
2928 selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
2929
2930 let max_size = size(
2931 (120. * em_width) // Default size
2932 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2933 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2934 (16. * line_height) // Default size
2935 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2936 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2937 );
2938
2939 let maybe_element = self.editor.update(cx, |editor, cx| {
2940 if let Some(popover) = editor.signature_help_state.popover_mut() {
2941 let element = popover.render(
2942 &self.style,
2943 max_size,
2944 editor.workspace.as_ref().map(|(w, _)| w.clone()),
2945 cx,
2946 );
2947 Some(element)
2948 } else {
2949 None
2950 }
2951 });
2952 if let Some(mut element) = maybe_element {
2953 let window_size = cx.viewport_size();
2954 let size = element.layout_as_root(Size::<AvailableSpace>::default(), cx);
2955 let mut point = point(start_x, start_y - size.height);
2956
2957 // Adjusting to ensure the popover does not overflow in the X-axis direction.
2958 if point.x + size.width >= window_size.width {
2959 point.x = window_size.width - size.width;
2960 }
2961
2962 cx.defer_draw(element, point, 1)
2963 }
2964 }
2965
2966 fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2967 cx.paint_layer(layout.hitbox.bounds, |cx| {
2968 let scroll_top = layout.position_map.snapshot.scroll_position().y;
2969 let gutter_bg = cx.theme().colors().editor_gutter_background;
2970 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2971 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2972
2973 if let EditorMode::Full = layout.mode {
2974 let mut active_rows = layout.active_rows.iter().peekable();
2975 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2976 let mut end_row = start_row.0;
2977 while active_rows
2978 .peek()
2979 .map_or(false, |(active_row, has_selection)| {
2980 active_row.0 == end_row + 1
2981 && *has_selection == contains_non_empty_selection
2982 })
2983 {
2984 active_rows.next().unwrap();
2985 end_row += 1;
2986 }
2987
2988 if !contains_non_empty_selection {
2989 let highlight_h_range =
2990 match layout.position_map.snapshot.current_line_highlight {
2991 CurrentLineHighlight::Gutter => Some(Range {
2992 start: layout.hitbox.left(),
2993 end: layout.gutter_hitbox.right(),
2994 }),
2995 CurrentLineHighlight::Line => Some(Range {
2996 start: layout.text_hitbox.bounds.left(),
2997 end: layout.text_hitbox.bounds.right(),
2998 }),
2999 CurrentLineHighlight::All => Some(Range {
3000 start: layout.hitbox.left(),
3001 end: layout.hitbox.right(),
3002 }),
3003 CurrentLineHighlight::None => None,
3004 };
3005 if let Some(range) = highlight_h_range {
3006 let active_line_bg = cx.theme().colors().editor_active_line_background;
3007 let bounds = Bounds {
3008 origin: point(
3009 range.start,
3010 layout.hitbox.origin.y
3011 + (start_row.as_f32() - scroll_top)
3012 * layout.position_map.line_height,
3013 ),
3014 size: size(
3015 range.end - range.start,
3016 layout.position_map.line_height
3017 * (end_row - start_row.0 + 1) as f32,
3018 ),
3019 };
3020 cx.paint_quad(fill(bounds, active_line_bg));
3021 }
3022 }
3023 }
3024
3025 let mut paint_highlight =
3026 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
3027 let origin = point(
3028 layout.hitbox.origin.x,
3029 layout.hitbox.origin.y
3030 + (highlight_row_start.as_f32() - scroll_top)
3031 * layout.position_map.line_height,
3032 );
3033 let size = size(
3034 layout.hitbox.size.width,
3035 layout.position_map.line_height
3036 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
3037 );
3038 cx.paint_quad(fill(Bounds { origin, size }, color));
3039 };
3040
3041 let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
3042 for (&new_row, &new_color) in &layout.highlighted_rows {
3043 match &mut current_paint {
3044 Some((current_color, current_range)) => {
3045 let current_color = *current_color;
3046 let new_range_started = current_color != new_color
3047 || current_range.end.next_row() != new_row;
3048 if new_range_started {
3049 paint_highlight(
3050 current_range.start,
3051 current_range.end,
3052 current_color,
3053 );
3054 current_paint = Some((new_color, new_row..new_row));
3055 continue;
3056 } else {
3057 current_range.end = current_range.end.next_row();
3058 }
3059 }
3060 None => current_paint = Some((new_color, new_row..new_row)),
3061 };
3062 }
3063 if let Some((color, range)) = current_paint {
3064 paint_highlight(range.start, range.end, color);
3065 }
3066
3067 let scroll_left =
3068 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
3069
3070 for (wrap_position, active) in layout.wrap_guides.iter() {
3071 let x = (layout.text_hitbox.origin.x
3072 + *wrap_position
3073 + layout.position_map.em_width / 2.)
3074 - scroll_left;
3075
3076 let show_scrollbars = layout
3077 .scrollbar_layout
3078 .as_ref()
3079 .map_or(false, |scrollbar| scrollbar.visible);
3080 if x < layout.text_hitbox.origin.x
3081 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
3082 {
3083 continue;
3084 }
3085
3086 let color = if *active {
3087 cx.theme().colors().editor_active_wrap_guide
3088 } else {
3089 cx.theme().colors().editor_wrap_guide
3090 };
3091 cx.paint_quad(fill(
3092 Bounds {
3093 origin: point(x, layout.text_hitbox.origin.y),
3094 size: size(px(1.), layout.text_hitbox.size.height),
3095 },
3096 color,
3097 ));
3098 }
3099 }
3100 })
3101 }
3102
3103 fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3104 let Some(indent_guides) = &layout.indent_guides else {
3105 return;
3106 };
3107
3108 let faded_color = |color: Hsla, alpha: f32| {
3109 let mut faded = color;
3110 faded.a = alpha;
3111 faded
3112 };
3113
3114 for indent_guide in indent_guides {
3115 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
3116 let settings = indent_guide.settings;
3117
3118 // TODO fixed for now, expose them through themes later
3119 const INDENT_AWARE_ALPHA: f32 = 0.2;
3120 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
3121 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
3122 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
3123
3124 let line_color = match (settings.coloring, indent_guide.active) {
3125 (IndentGuideColoring::Disabled, _) => None,
3126 (IndentGuideColoring::Fixed, false) => {
3127 Some(cx.theme().colors().editor_indent_guide)
3128 }
3129 (IndentGuideColoring::Fixed, true) => {
3130 Some(cx.theme().colors().editor_indent_guide_active)
3131 }
3132 (IndentGuideColoring::IndentAware, false) => {
3133 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
3134 }
3135 (IndentGuideColoring::IndentAware, true) => {
3136 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
3137 }
3138 };
3139
3140 let background_color = match (settings.background_coloring, indent_guide.active) {
3141 (IndentGuideBackgroundColoring::Disabled, _) => None,
3142 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
3143 indent_accent_colors,
3144 INDENT_AWARE_BACKGROUND_ALPHA,
3145 )),
3146 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
3147 indent_accent_colors,
3148 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
3149 )),
3150 };
3151
3152 let requested_line_width = if indent_guide.active {
3153 settings.active_line_width
3154 } else {
3155 settings.line_width
3156 }
3157 .clamp(1, 10);
3158 let mut line_indicator_width = 0.;
3159 if let Some(color) = line_color {
3160 cx.paint_quad(fill(
3161 Bounds {
3162 origin: indent_guide.origin,
3163 size: size(px(requested_line_width as f32), indent_guide.length),
3164 },
3165 color,
3166 ));
3167 line_indicator_width = requested_line_width as f32;
3168 }
3169
3170 if let Some(color) = background_color {
3171 let width = indent_guide.single_indent_width - px(line_indicator_width);
3172 cx.paint_quad(fill(
3173 Bounds {
3174 origin: point(
3175 indent_guide.origin.x + px(line_indicator_width),
3176 indent_guide.origin.y,
3177 ),
3178 size: size(width, indent_guide.length),
3179 },
3180 color,
3181 ));
3182 }
3183 }
3184 }
3185
3186 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3187 let line_height = layout.position_map.line_height;
3188 let scroll_position = layout.position_map.snapshot.scroll_position();
3189 let scroll_top = scroll_position.y * line_height;
3190
3191 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
3192
3193 for (ix, line) in layout.line_numbers.iter().enumerate() {
3194 if let Some(line) = line {
3195 let line_origin = layout.gutter_hitbox.origin
3196 + point(
3197 layout.gutter_hitbox.size.width
3198 - line.width
3199 - layout.gutter_dimensions.right_padding,
3200 ix as f32 * line_height - (scroll_top % line_height),
3201 );
3202
3203 line.paint(line_origin, line_height, cx).log_err();
3204 }
3205 }
3206 }
3207
3208 fn paint_diff_hunks(layout: &mut EditorLayout, cx: &mut WindowContext) {
3209 if layout.display_hunks.is_empty() {
3210 return;
3211 }
3212
3213 let line_height = layout.position_map.line_height;
3214 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3215 for (hunk, hitbox) in &layout.display_hunks {
3216 let hunk_to_paint = match hunk {
3217 DisplayDiffHunk::Folded { .. } => {
3218 let hunk_bounds = Self::diff_hunk_bounds(
3219 &layout.position_map.snapshot,
3220 line_height,
3221 layout.gutter_hitbox.bounds,
3222 hunk,
3223 );
3224 Some((
3225 hunk_bounds,
3226 cx.theme().status().modified,
3227 Corners::all(px(0.)),
3228 ))
3229 }
3230 DisplayDiffHunk::Unfolded { status, .. } => {
3231 hitbox.as_ref().map(|hunk_hitbox| match status {
3232 DiffHunkStatus::Added => (
3233 hunk_hitbox.bounds,
3234 cx.theme().status().created,
3235 Corners::all(px(0.)),
3236 ),
3237 DiffHunkStatus::Modified => (
3238 hunk_hitbox.bounds,
3239 cx.theme().status().modified,
3240 Corners::all(px(0.)),
3241 ),
3242 DiffHunkStatus::Removed => (
3243 Bounds::new(
3244 point(
3245 hunk_hitbox.origin.x - hunk_hitbox.size.width,
3246 hunk_hitbox.origin.y,
3247 ),
3248 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
3249 ),
3250 cx.theme().status().deleted,
3251 Corners::all(1. * line_height),
3252 ),
3253 })
3254 }
3255 };
3256
3257 if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
3258 cx.paint_quad(quad(
3259 hunk_bounds,
3260 corner_radii,
3261 background_color,
3262 Edges::default(),
3263 transparent_black(),
3264 ));
3265 }
3266 }
3267 });
3268 }
3269
3270 pub(super) fn diff_hunk_bounds(
3271 snapshot: &EditorSnapshot,
3272 line_height: Pixels,
3273 gutter_bounds: Bounds<Pixels>,
3274 hunk: &DisplayDiffHunk,
3275 ) -> Bounds<Pixels> {
3276 let scroll_position = snapshot.scroll_position();
3277 let scroll_top = scroll_position.y * line_height;
3278
3279 match hunk {
3280 DisplayDiffHunk::Folded { display_row, .. } => {
3281 let start_y = display_row.as_f32() * line_height - scroll_top;
3282 let end_y = start_y + line_height;
3283
3284 let width = Self::diff_hunk_strip_width(line_height);
3285 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3286 let highlight_size = size(width, end_y - start_y);
3287 Bounds::new(highlight_origin, highlight_size)
3288 }
3289 DisplayDiffHunk::Unfolded {
3290 display_row_range,
3291 status,
3292 ..
3293 } => match status {
3294 DiffHunkStatus::Added | DiffHunkStatus::Modified => {
3295 let start_row = display_row_range.start;
3296 let end_row = display_row_range.end;
3297 // If we're in a multibuffer, row range span might include an
3298 // excerpt header, so if we were to draw the marker straight away,
3299 // the hunk might include the rows of that header.
3300 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
3301 // Instead, we simply check whether the range we're dealing with includes
3302 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
3303 let end_row_in_current_excerpt = snapshot
3304 .blocks_in_range(start_row..end_row)
3305 .find_map(|(start_row, block)| {
3306 if matches!(block, Block::ExcerptHeader { .. }) {
3307 Some(start_row)
3308 } else {
3309 None
3310 }
3311 })
3312 .unwrap_or(end_row);
3313
3314 let start_y = start_row.as_f32() * line_height - scroll_top;
3315 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
3316
3317 let width = Self::diff_hunk_strip_width(line_height);
3318 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3319 let highlight_size = size(width, end_y - start_y);
3320 Bounds::new(highlight_origin, highlight_size)
3321 }
3322 DiffHunkStatus::Removed => {
3323 let row = display_row_range.start;
3324
3325 let offset = line_height / 2.;
3326 let start_y = row.as_f32() * line_height - offset - scroll_top;
3327 let end_y = start_y + line_height;
3328
3329 let width = (0.35 * line_height).floor();
3330 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3331 let highlight_size = size(width, end_y - start_y);
3332 Bounds::new(highlight_origin, highlight_size)
3333 }
3334 },
3335 }
3336 }
3337
3338 /// Returns the width of the diff strip that will be displayed in the gutter.
3339 pub(super) fn diff_hunk_strip_width(line_height: Pixels) -> Pixels {
3340 // We floor the value to prevent pixel rounding.
3341 (0.275 * line_height).floor()
3342 }
3343
3344 fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3345 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3346 cx.with_element_namespace("gutter_fold_toggles", |cx| {
3347 for fold_indicator in layout.gutter_fold_toggles.iter_mut().flatten() {
3348 fold_indicator.paint(cx);
3349 }
3350 });
3351
3352 for test_indicator in layout.test_indicators.iter_mut() {
3353 test_indicator.paint(cx);
3354 }
3355
3356 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
3357 indicator.paint(cx);
3358 }
3359 });
3360 }
3361
3362 fn paint_gutter_highlights(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3363 for (_, hunk_hitbox) in &layout.display_hunks {
3364 if let Some(hunk_hitbox) = hunk_hitbox {
3365 cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
3366 }
3367 }
3368
3369 let show_git_gutter = layout
3370 .position_map
3371 .snapshot
3372 .show_git_diff_gutter
3373 .unwrap_or_else(|| {
3374 matches!(
3375 ProjectSettings::get_global(cx).git.git_gutter,
3376 Some(GitGutterSetting::TrackedFiles)
3377 )
3378 });
3379 if show_git_gutter {
3380 Self::paint_diff_hunks(layout, cx)
3381 }
3382
3383 let highlight_width = 0.275 * layout.position_map.line_height;
3384 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3385 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3386 for (range, color) in &layout.highlighted_gutter_ranges {
3387 let start_row = if range.start.row() < layout.visible_display_row_range.start {
3388 layout.visible_display_row_range.start - DisplayRow(1)
3389 } else {
3390 range.start.row()
3391 };
3392 let end_row = if range.end.row() > layout.visible_display_row_range.end {
3393 layout.visible_display_row_range.end + DisplayRow(1)
3394 } else {
3395 range.end.row()
3396 };
3397
3398 let start_y = layout.gutter_hitbox.top()
3399 + start_row.0 as f32 * layout.position_map.line_height
3400 - layout.position_map.scroll_pixel_position.y;
3401 let end_y = layout.gutter_hitbox.top()
3402 + (end_row.0 + 1) as f32 * layout.position_map.line_height
3403 - layout.position_map.scroll_pixel_position.y;
3404 let bounds = Bounds::from_corners(
3405 point(layout.gutter_hitbox.left(), start_y),
3406 point(layout.gutter_hitbox.left() + highlight_width, end_y),
3407 );
3408 cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3409 }
3410 });
3411 }
3412
3413 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3414 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3415 return;
3416 };
3417
3418 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3419 for mut blame_element in blamed_display_rows.into_iter() {
3420 blame_element.paint(cx);
3421 }
3422 })
3423 }
3424
3425 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3426 cx.with_content_mask(
3427 Some(ContentMask {
3428 bounds: layout.text_hitbox.bounds,
3429 }),
3430 |cx| {
3431 let cursor_style = if self
3432 .editor
3433 .read(cx)
3434 .hovered_link_state
3435 .as_ref()
3436 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3437 {
3438 CursorStyle::PointingHand
3439 } else {
3440 CursorStyle::IBeam
3441 };
3442 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3443
3444 let invisible_display_ranges = self.paint_highlights(layout, cx);
3445 self.paint_lines(&invisible_display_ranges, layout, cx);
3446 self.paint_redactions(layout, cx);
3447 self.paint_cursors(layout, cx);
3448 self.paint_inline_blame(layout, cx);
3449 cx.with_element_namespace("crease_trailers", |cx| {
3450 for trailer in layout.crease_trailers.iter_mut().flatten() {
3451 trailer.element.paint(cx);
3452 }
3453 });
3454 },
3455 )
3456 }
3457
3458 fn paint_highlights(
3459 &mut self,
3460 layout: &mut EditorLayout,
3461 cx: &mut WindowContext,
3462 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3463 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3464 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3465 let line_end_overshoot = 0.15 * layout.position_map.line_height;
3466 for (range, color) in &layout.highlighted_ranges {
3467 self.paint_highlighted_range(
3468 range.clone(),
3469 *color,
3470 Pixels::ZERO,
3471 line_end_overshoot,
3472 layout,
3473 cx,
3474 );
3475 }
3476
3477 let corner_radius = 0.15 * layout.position_map.line_height;
3478
3479 for (player_color, selections) in &layout.selections {
3480 for selection in selections.iter() {
3481 self.paint_highlighted_range(
3482 selection.range.clone(),
3483 player_color.selection,
3484 corner_radius,
3485 corner_radius * 2.,
3486 layout,
3487 cx,
3488 );
3489
3490 if selection.is_local && !selection.range.is_empty() {
3491 invisible_display_ranges.push(selection.range.clone());
3492 }
3493 }
3494 }
3495 invisible_display_ranges
3496 })
3497 }
3498
3499 fn paint_lines(
3500 &mut self,
3501 invisible_display_ranges: &[Range<DisplayPoint>],
3502 layout: &mut EditorLayout,
3503 cx: &mut WindowContext,
3504 ) {
3505 let whitespace_setting = self
3506 .editor
3507 .read(cx)
3508 .buffer
3509 .read(cx)
3510 .settings_at(0, cx)
3511 .show_whitespaces;
3512
3513 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3514 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3515 line_with_invisibles.draw(
3516 layout,
3517 row,
3518 layout.content_origin,
3519 whitespace_setting,
3520 invisible_display_ranges,
3521 cx,
3522 )
3523 }
3524
3525 for line_element in &mut layout.line_elements {
3526 line_element.paint(cx);
3527 }
3528 }
3529
3530 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3531 if layout.redacted_ranges.is_empty() {
3532 return;
3533 }
3534
3535 let line_end_overshoot = layout.line_end_overshoot();
3536
3537 // A softer than perfect black
3538 let redaction_color = gpui::rgb(0x0e1111);
3539
3540 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3541 for range in layout.redacted_ranges.iter() {
3542 self.paint_highlighted_range(
3543 range.clone(),
3544 redaction_color.into(),
3545 Pixels::ZERO,
3546 line_end_overshoot,
3547 layout,
3548 cx,
3549 );
3550 }
3551 });
3552 }
3553
3554 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3555 for cursor in &mut layout.visible_cursors {
3556 cursor.paint(layout.content_origin, cx);
3557 }
3558 }
3559
3560 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3561 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3562 return;
3563 };
3564
3565 let thumb_bounds = scrollbar_layout.thumb_bounds();
3566 if scrollbar_layout.visible {
3567 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3568 cx.paint_quad(quad(
3569 scrollbar_layout.hitbox.bounds,
3570 Corners::default(),
3571 cx.theme().colors().scrollbar_track_background,
3572 Edges {
3573 top: Pixels::ZERO,
3574 right: Pixels::ZERO,
3575 bottom: Pixels::ZERO,
3576 left: ScrollbarLayout::BORDER_WIDTH,
3577 },
3578 cx.theme().colors().scrollbar_track_border,
3579 ));
3580
3581 let fast_markers =
3582 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3583 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3584 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3585
3586 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3587 for marker in markers.iter().chain(&fast_markers) {
3588 let mut marker = marker.clone();
3589 marker.bounds.origin += scrollbar_layout.hitbox.origin;
3590 cx.paint_quad(marker);
3591 }
3592
3593 cx.paint_quad(quad(
3594 thumb_bounds,
3595 Corners::default(),
3596 cx.theme().colors().scrollbar_thumb_background,
3597 Edges {
3598 top: Pixels::ZERO,
3599 right: Pixels::ZERO,
3600 bottom: Pixels::ZERO,
3601 left: ScrollbarLayout::BORDER_WIDTH,
3602 },
3603 cx.theme().colors().scrollbar_thumb_border,
3604 ));
3605 });
3606 }
3607
3608 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3609
3610 let row_height = scrollbar_layout.row_height;
3611 let row_range = scrollbar_layout.visible_row_range.clone();
3612
3613 cx.on_mouse_event({
3614 let editor = self.editor.clone();
3615 let hitbox = scrollbar_layout.hitbox.clone();
3616 let mut mouse_position = cx.mouse_position();
3617 move |event: &MouseMoveEvent, phase, cx| {
3618 if phase == DispatchPhase::Capture {
3619 return;
3620 }
3621
3622 editor.update(cx, |editor, cx| {
3623 if event.pressed_button == Some(MouseButton::Left)
3624 && editor.scroll_manager.is_dragging_scrollbar()
3625 {
3626 let y = mouse_position.y;
3627 let new_y = event.position.y;
3628 if (hitbox.top()..hitbox.bottom()).contains(&y) {
3629 let mut position = editor.scroll_position(cx);
3630 position.y += (new_y - y) / row_height;
3631 if position.y < 0.0 {
3632 position.y = 0.0;
3633 }
3634 editor.set_scroll_position(position, cx);
3635 }
3636
3637 cx.stop_propagation();
3638 } else {
3639 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3640 if hitbox.is_hovered(cx) {
3641 editor.scroll_manager.show_scrollbar(cx);
3642 }
3643 }
3644 mouse_position = event.position;
3645 })
3646 }
3647 });
3648
3649 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3650 cx.on_mouse_event({
3651 let editor = self.editor.clone();
3652 move |_: &MouseUpEvent, phase, cx| {
3653 if phase == DispatchPhase::Capture {
3654 return;
3655 }
3656
3657 editor.update(cx, |editor, cx| {
3658 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3659 cx.stop_propagation();
3660 });
3661 }
3662 });
3663 } else {
3664 cx.on_mouse_event({
3665 let editor = self.editor.clone();
3666 let hitbox = scrollbar_layout.hitbox.clone();
3667 move |event: &MouseDownEvent, phase, cx| {
3668 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3669 return;
3670 }
3671
3672 editor.update(cx, |editor, cx| {
3673 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3674
3675 let y = event.position.y;
3676 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3677 let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3678 let top_row = center_row
3679 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3680 let mut position = editor.scroll_position(cx);
3681 position.y = top_row as f32;
3682 editor.set_scroll_position(position, cx);
3683 } else {
3684 editor.scroll_manager.show_scrollbar(cx);
3685 }
3686
3687 cx.stop_propagation();
3688 });
3689 }
3690 });
3691 }
3692 }
3693
3694 fn collect_fast_scrollbar_markers(
3695 &self,
3696 layout: &EditorLayout,
3697 scrollbar_layout: &ScrollbarLayout,
3698 cx: &mut WindowContext,
3699 ) -> Vec<PaintQuad> {
3700 const LIMIT: usize = 100;
3701 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3702 return vec![];
3703 }
3704 let cursor_ranges = layout
3705 .cursors
3706 .iter()
3707 .map(|(point, color)| ColoredRange {
3708 start: point.row(),
3709 end: point.row(),
3710 color: *color,
3711 })
3712 .collect_vec();
3713 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3714 }
3715
3716 fn refresh_slow_scrollbar_markers(
3717 &self,
3718 layout: &EditorLayout,
3719 scrollbar_layout: &ScrollbarLayout,
3720 cx: &mut WindowContext,
3721 ) {
3722 self.editor.update(cx, |editor, cx| {
3723 if !editor.is_singleton(cx)
3724 || !editor
3725 .scrollbar_marker_state
3726 .should_refresh(scrollbar_layout.hitbox.size)
3727 {
3728 return;
3729 }
3730
3731 let scrollbar_layout = scrollbar_layout.clone();
3732 let background_highlights = editor.background_highlights.clone();
3733 let snapshot = layout.position_map.snapshot.clone();
3734 let theme = cx.theme().clone();
3735 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3736
3737 editor.scrollbar_marker_state.dirty = false;
3738 editor.scrollbar_marker_state.pending_refresh =
3739 Some(cx.spawn(|editor, mut cx| async move {
3740 let scrollbar_size = scrollbar_layout.hitbox.size;
3741 let scrollbar_markers = cx
3742 .background_executor()
3743 .spawn(async move {
3744 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3745 let mut marker_quads = Vec::new();
3746 if scrollbar_settings.git_diff {
3747 let marker_row_ranges = snapshot
3748 .buffer_snapshot
3749 .git_diff_hunks_in_range(
3750 MultiBufferRow::MIN..MultiBufferRow::MAX,
3751 )
3752 .map(|hunk| {
3753 let start_display_row =
3754 MultiBufferPoint::new(hunk.row_range.start.0, 0)
3755 .to_display_point(&snapshot.display_snapshot)
3756 .row();
3757 let mut end_display_row =
3758 MultiBufferPoint::new(hunk.row_range.end.0, 0)
3759 .to_display_point(&snapshot.display_snapshot)
3760 .row();
3761 if end_display_row != start_display_row {
3762 end_display_row.0 -= 1;
3763 }
3764 let color = match hunk_status(&hunk) {
3765 DiffHunkStatus::Added => theme.status().created,
3766 DiffHunkStatus::Modified => theme.status().modified,
3767 DiffHunkStatus::Removed => theme.status().deleted,
3768 };
3769 ColoredRange {
3770 start: start_display_row,
3771 end: end_display_row,
3772 color,
3773 }
3774 });
3775
3776 marker_quads.extend(
3777 scrollbar_layout
3778 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3779 );
3780 }
3781
3782 for (background_highlight_id, (_, background_ranges)) in
3783 background_highlights.iter()
3784 {
3785 let is_search_highlights = *background_highlight_id
3786 == TypeId::of::<BufferSearchHighlights>();
3787 let is_symbol_occurrences = *background_highlight_id
3788 == TypeId::of::<DocumentHighlightRead>()
3789 || *background_highlight_id
3790 == TypeId::of::<DocumentHighlightWrite>();
3791 if (is_search_highlights && scrollbar_settings.search_results)
3792 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3793 {
3794 let mut color = theme.status().info;
3795 if is_symbol_occurrences {
3796 color.fade_out(0.5);
3797 }
3798 let marker_row_ranges = background_ranges.iter().map(|range| {
3799 let display_start = range
3800 .start
3801 .to_display_point(&snapshot.display_snapshot);
3802 let display_end =
3803 range.end.to_display_point(&snapshot.display_snapshot);
3804 ColoredRange {
3805 start: display_start.row(),
3806 end: display_end.row(),
3807 color,
3808 }
3809 });
3810 marker_quads.extend(
3811 scrollbar_layout
3812 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3813 );
3814 }
3815 }
3816
3817 if scrollbar_settings.diagnostics {
3818 let diagnostics = snapshot
3819 .buffer_snapshot
3820 .diagnostics_in_range::<_, Point>(
3821 Point::zero()..max_point,
3822 false,
3823 )
3824 // We want to sort by severity, in order to paint the most severe diagnostics last.
3825 .sorted_by_key(|diagnostic| {
3826 std::cmp::Reverse(diagnostic.diagnostic.severity)
3827 });
3828
3829 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
3830 let start_display = diagnostic
3831 .range
3832 .start
3833 .to_display_point(&snapshot.display_snapshot);
3834 let end_display = diagnostic
3835 .range
3836 .end
3837 .to_display_point(&snapshot.display_snapshot);
3838 let color = match diagnostic.diagnostic.severity {
3839 DiagnosticSeverity::ERROR => theme.status().error,
3840 DiagnosticSeverity::WARNING => theme.status().warning,
3841 DiagnosticSeverity::INFORMATION => theme.status().info,
3842 _ => theme.status().hint,
3843 };
3844 ColoredRange {
3845 start: start_display.row(),
3846 end: end_display.row(),
3847 color,
3848 }
3849 });
3850 marker_quads.extend(
3851 scrollbar_layout
3852 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
3853 );
3854 }
3855
3856 Arc::from(marker_quads)
3857 })
3858 .await;
3859
3860 editor.update(&mut cx, |editor, cx| {
3861 editor.scrollbar_marker_state.markers = scrollbar_markers;
3862 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
3863 editor.scrollbar_marker_state.pending_refresh = None;
3864 cx.notify();
3865 })?;
3866
3867 Ok(())
3868 }));
3869 });
3870 }
3871
3872 #[allow(clippy::too_many_arguments)]
3873 fn paint_highlighted_range(
3874 &self,
3875 range: Range<DisplayPoint>,
3876 color: Hsla,
3877 corner_radius: Pixels,
3878 line_end_overshoot: Pixels,
3879 layout: &EditorLayout,
3880 cx: &mut WindowContext,
3881 ) {
3882 let start_row = layout.visible_display_row_range.start;
3883 let end_row = layout.visible_display_row_range.end;
3884 if range.start != range.end {
3885 let row_range = if range.end.column() == 0 {
3886 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3887 } else {
3888 cmp::max(range.start.row(), start_row)
3889 ..cmp::min(range.end.row().next_row(), end_row)
3890 };
3891
3892 let highlighted_range = HighlightedRange {
3893 color,
3894 line_height: layout.position_map.line_height,
3895 corner_radius,
3896 start_y: layout.content_origin.y
3897 + row_range.start.as_f32() * layout.position_map.line_height
3898 - layout.position_map.scroll_pixel_position.y,
3899 lines: row_range
3900 .iter_rows()
3901 .map(|row| {
3902 let line_layout =
3903 &layout.position_map.line_layouts[row.minus(start_row) as usize];
3904 HighlightedRangeLine {
3905 start_x: if row == range.start.row() {
3906 layout.content_origin.x
3907 + line_layout.x_for_index(range.start.column() as usize)
3908 - layout.position_map.scroll_pixel_position.x
3909 } else {
3910 layout.content_origin.x
3911 - layout.position_map.scroll_pixel_position.x
3912 },
3913 end_x: if row == range.end.row() {
3914 layout.content_origin.x
3915 + line_layout.x_for_index(range.end.column() as usize)
3916 - layout.position_map.scroll_pixel_position.x
3917 } else {
3918 layout.content_origin.x + line_layout.width + line_end_overshoot
3919 - layout.position_map.scroll_pixel_position.x
3920 },
3921 }
3922 })
3923 .collect(),
3924 };
3925
3926 highlighted_range.paint(layout.text_hitbox.bounds, cx);
3927 }
3928 }
3929
3930 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3931 if let Some(mut inline_blame) = layout.inline_blame.take() {
3932 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3933 inline_blame.paint(cx);
3934 })
3935 }
3936 }
3937
3938 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3939 for mut block in layout.blocks.drain(..) {
3940 block.element.paint(cx);
3941 }
3942 }
3943
3944 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3945 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3946 mouse_context_menu.paint(cx);
3947 }
3948 }
3949
3950 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3951 cx.on_mouse_event({
3952 let position_map = layout.position_map.clone();
3953 let editor = self.editor.clone();
3954 let hitbox = layout.hitbox.clone();
3955 let mut delta = ScrollDelta::default();
3956
3957 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3958 // accidentally turn off their scrolling.
3959 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3960
3961 move |event: &ScrollWheelEvent, phase, cx| {
3962 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3963 delta = delta.coalesce(event.delta);
3964 editor.update(cx, |editor, cx| {
3965 let position_map: &PositionMap = &position_map;
3966
3967 let line_height = position_map.line_height;
3968 let max_glyph_width = position_map.em_width;
3969 let (delta, axis) = match delta {
3970 gpui::ScrollDelta::Pixels(mut pixels) => {
3971 //Trackpad
3972 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3973 (pixels, axis)
3974 }
3975
3976 gpui::ScrollDelta::Lines(lines) => {
3977 //Not trackpad
3978 let pixels =
3979 point(lines.x * max_glyph_width, lines.y * line_height);
3980 (pixels, None)
3981 }
3982 };
3983
3984 let current_scroll_position = position_map.snapshot.scroll_position();
3985 let x = (current_scroll_position.x * max_glyph_width
3986 - (delta.x * scroll_sensitivity))
3987 / max_glyph_width;
3988 let y = (current_scroll_position.y * line_height
3989 - (delta.y * scroll_sensitivity))
3990 / line_height;
3991 let mut scroll_position =
3992 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3993 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3994 if forbid_vertical_scroll {
3995 scroll_position.y = current_scroll_position.y;
3996 }
3997
3998 if scroll_position != current_scroll_position {
3999 editor.scroll(scroll_position, axis, cx);
4000 cx.stop_propagation();
4001 } else if y < 0. {
4002 // Due to clamping, we may fail to detect cases of overscroll to the top;
4003 // We want the scroll manager to get an update in such cases and detect the change of direction
4004 // on the next frame.
4005 cx.notify();
4006 }
4007 });
4008 }
4009 }
4010 });
4011 }
4012
4013 fn paint_mouse_listeners(
4014 &mut self,
4015 layout: &EditorLayout,
4016 hovered_hunk: Option<HoveredHunk>,
4017 cx: &mut WindowContext,
4018 ) {
4019 self.paint_scroll_wheel_listener(layout, cx);
4020
4021 cx.on_mouse_event({
4022 let position_map = layout.position_map.clone();
4023 let editor = self.editor.clone();
4024 let text_hitbox = layout.text_hitbox.clone();
4025 let gutter_hitbox = layout.gutter_hitbox.clone();
4026
4027 move |event: &MouseDownEvent, phase, cx| {
4028 if phase == DispatchPhase::Bubble {
4029 match event.button {
4030 MouseButton::Left => editor.update(cx, |editor, cx| {
4031 Self::mouse_left_down(
4032 editor,
4033 event,
4034 hovered_hunk.clone(),
4035 &position_map,
4036 &text_hitbox,
4037 &gutter_hitbox,
4038 cx,
4039 );
4040 }),
4041 MouseButton::Right => editor.update(cx, |editor, cx| {
4042 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
4043 }),
4044 MouseButton::Middle => editor.update(cx, |editor, cx| {
4045 Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
4046 }),
4047 _ => {}
4048 };
4049 }
4050 }
4051 });
4052
4053 cx.on_mouse_event({
4054 let editor = self.editor.clone();
4055 let position_map = layout.position_map.clone();
4056 let text_hitbox = layout.text_hitbox.clone();
4057
4058 move |event: &MouseUpEvent, phase, cx| {
4059 if phase == DispatchPhase::Bubble {
4060 editor.update(cx, |editor, cx| {
4061 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
4062 });
4063 }
4064 }
4065 });
4066 cx.on_mouse_event({
4067 let position_map = layout.position_map.clone();
4068 let editor = self.editor.clone();
4069 let text_hitbox = layout.text_hitbox.clone();
4070 let gutter_hitbox = layout.gutter_hitbox.clone();
4071
4072 move |event: &MouseMoveEvent, phase, cx| {
4073 if phase == DispatchPhase::Bubble {
4074 editor.update(cx, |editor, cx| {
4075 if editor.hover_state.focused(cx) {
4076 return;
4077 }
4078 if event.pressed_button == Some(MouseButton::Left)
4079 || event.pressed_button == Some(MouseButton::Middle)
4080 {
4081 Self::mouse_dragged(
4082 editor,
4083 event,
4084 &position_map,
4085 text_hitbox.bounds,
4086 cx,
4087 )
4088 }
4089
4090 Self::mouse_moved(
4091 editor,
4092 event,
4093 &position_map,
4094 &text_hitbox,
4095 &gutter_hitbox,
4096 cx,
4097 )
4098 });
4099 }
4100 }
4101 });
4102 }
4103
4104 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
4105 bounds.upper_right().x - self.style.scrollbar_width
4106 }
4107
4108 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
4109 let style = &self.style;
4110 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4111 let layout = cx
4112 .text_system()
4113 .shape_line(
4114 SharedString::from(" ".repeat(column)),
4115 font_size,
4116 &[TextRun {
4117 len: column,
4118 font: style.text.font(),
4119 color: Hsla::default(),
4120 background_color: None,
4121 underline: None,
4122 strikethrough: None,
4123 }],
4124 )
4125 .unwrap();
4126
4127 layout.width
4128 }
4129
4130 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
4131 let digit_count = snapshot
4132 .max_buffer_row()
4133 .next_row()
4134 .as_f32()
4135 .log10()
4136 .floor() as usize
4137 + 1;
4138 self.column_pixels(digit_count, cx)
4139 }
4140}
4141
4142#[allow(clippy::too_many_arguments)]
4143fn prepaint_gutter_button(
4144 button: IconButton,
4145 row: DisplayRow,
4146 line_height: Pixels,
4147 gutter_dimensions: &GutterDimensions,
4148 scroll_pixel_position: gpui::Point<Pixels>,
4149 gutter_hitbox: &Hitbox,
4150 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
4151 cx: &mut WindowContext<'_>,
4152) -> AnyElement {
4153 let mut button = button.into_any_element();
4154 let available_space = size(
4155 AvailableSpace::MinContent,
4156 AvailableSpace::Definite(line_height),
4157 );
4158 let indicator_size = button.layout_as_root(available_space, cx);
4159
4160 let blame_width = gutter_dimensions.git_blame_entries_width;
4161 let gutter_width = rows_with_hunk_bounds
4162 .get(&row)
4163 .map(|bounds| bounds.size.width);
4164 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
4165
4166 let mut x = left_offset;
4167 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
4168 - indicator_size.width
4169 - left_offset;
4170 x += available_width / 2.;
4171
4172 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
4173 y += (line_height - indicator_size.height) / 2.;
4174
4175 button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
4176 button
4177}
4178
4179fn render_inline_blame_entry(
4180 blame: &gpui::Model<GitBlame>,
4181 blame_entry: BlameEntry,
4182 style: &EditorStyle,
4183 workspace: Option<WeakView<Workspace>>,
4184 cx: &mut WindowContext<'_>,
4185) -> AnyElement {
4186 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4187
4188 let author = blame_entry.author.as_deref().unwrap_or_default();
4189 let text = format!("{}, {}", author, relative_timestamp);
4190
4191 let details = blame.read(cx).details_for_entry(&blame_entry);
4192
4193 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
4194
4195 h_flex()
4196 .id("inline-blame")
4197 .w_full()
4198 .font_family(style.text.font().family)
4199 .text_color(cx.theme().status().hint)
4200 .line_height(style.text.line_height)
4201 .child(Icon::new(IconName::FileGit).color(Color::Hint))
4202 .child(text)
4203 .gap_2()
4204 .hoverable_tooltip(move |_| tooltip.clone().into())
4205 .into_any()
4206}
4207
4208fn render_blame_entry(
4209 ix: usize,
4210 blame: &gpui::Model<GitBlame>,
4211 blame_entry: BlameEntry,
4212 style: &EditorStyle,
4213 last_used_color: &mut Option<(PlayerColor, Oid)>,
4214 editor: View<Editor>,
4215 cx: &mut WindowContext<'_>,
4216) -> AnyElement {
4217 let mut sha_color = cx
4218 .theme()
4219 .players()
4220 .color_for_participant(blame_entry.sha.into());
4221 // If the last color we used is the same as the one we get for this line, but
4222 // the commit SHAs are different, then we try again to get a different color.
4223 match *last_used_color {
4224 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
4225 let index: u32 = blame_entry.sha.into();
4226 sha_color = cx.theme().players().color_for_participant(index + 1);
4227 }
4228 _ => {}
4229 };
4230 last_used_color.replace((sha_color, blame_entry.sha));
4231
4232 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4233
4234 let short_commit_id = blame_entry.sha.display_short();
4235
4236 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
4237 let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
4238
4239 let details = blame.read(cx).details_for_entry(&blame_entry);
4240
4241 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
4242
4243 let tooltip = cx.new_view(|_| {
4244 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
4245 });
4246
4247 h_flex()
4248 .w_full()
4249 .justify_between()
4250 .font_family(style.text.font().family)
4251 .line_height(style.text.line_height)
4252 .id(("blame", ix))
4253 .text_color(cx.theme().status().hint)
4254 .pr_2()
4255 .gap_2()
4256 .child(
4257 h_flex()
4258 .items_center()
4259 .gap_2()
4260 .child(div().text_color(sha_color.cursor).child(short_commit_id))
4261 .child(name),
4262 )
4263 .child(relative_timestamp)
4264 .on_mouse_down(MouseButton::Right, {
4265 let blame_entry = blame_entry.clone();
4266 let details = details.clone();
4267 move |event, cx| {
4268 deploy_blame_entry_context_menu(
4269 &blame_entry,
4270 details.as_ref(),
4271 editor.clone(),
4272 event.position,
4273 cx,
4274 );
4275 }
4276 })
4277 .hover(|style| style.bg(cx.theme().colors().element_hover))
4278 .when_some(
4279 details.and_then(|details| details.permalink),
4280 |this, url| {
4281 let url = url.clone();
4282 this.cursor_pointer().on_click(move |_, cx| {
4283 cx.stop_propagation();
4284 cx.open_url(url.as_str())
4285 })
4286 },
4287 )
4288 .hoverable_tooltip(move |_| tooltip.clone().into())
4289 .into_any()
4290}
4291
4292fn deploy_blame_entry_context_menu(
4293 blame_entry: &BlameEntry,
4294 details: Option<&CommitDetails>,
4295 editor: View<Editor>,
4296 position: gpui::Point<Pixels>,
4297 cx: &mut WindowContext<'_>,
4298) {
4299 let context_menu = ContextMenu::build(cx, move |menu, _| {
4300 let sha = format!("{}", blame_entry.sha);
4301 menu.on_blur_subscription(Subscription::new(|| {}))
4302 .entry("Copy commit SHA", None, move |cx| {
4303 cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
4304 })
4305 .when_some(
4306 details.and_then(|details| details.permalink.clone()),
4307 |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
4308 )
4309 });
4310
4311 editor.update(cx, move |editor, cx| {
4312 editor.mouse_context_menu = Some(MouseContextMenu::pinned_to_screen(
4313 position,
4314 context_menu,
4315 cx,
4316 ));
4317 cx.notify();
4318 });
4319}
4320
4321#[derive(Debug)]
4322pub(crate) struct LineWithInvisibles {
4323 fragments: SmallVec<[LineFragment; 1]>,
4324 invisibles: Vec<Invisible>,
4325 len: usize,
4326 width: Pixels,
4327 font_size: Pixels,
4328}
4329
4330#[allow(clippy::large_enum_variant)]
4331enum LineFragment {
4332 Text(ShapedLine),
4333 Element {
4334 element: Option<AnyElement>,
4335 size: Size<Pixels>,
4336 len: usize,
4337 },
4338}
4339
4340impl fmt::Debug for LineFragment {
4341 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4342 match self {
4343 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
4344 LineFragment::Element { size, len, .. } => f
4345 .debug_struct("Element")
4346 .field("size", size)
4347 .field("len", len)
4348 .finish(),
4349 }
4350 }
4351}
4352
4353impl LineWithInvisibles {
4354 #[allow(clippy::too_many_arguments)]
4355 fn from_chunks<'a>(
4356 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
4357 text_style: &TextStyle,
4358 max_line_len: usize,
4359 max_line_count: usize,
4360 line_number_layouts: &[Option<ShapedLine>],
4361 editor_mode: EditorMode,
4362 text_width: Pixels,
4363 cx: &mut WindowContext,
4364 ) -> Vec<Self> {
4365 let mut layouts = Vec::with_capacity(max_line_count);
4366 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
4367 let mut line = String::new();
4368 let mut invisibles = Vec::new();
4369 let mut width = Pixels::ZERO;
4370 let mut len = 0;
4371 let mut styles = Vec::new();
4372 let mut non_whitespace_added = false;
4373 let mut row = 0;
4374 let mut line_exceeded_max_len = false;
4375 let font_size = text_style.font_size.to_pixels(cx.rem_size());
4376
4377 let ellipsis = SharedString::from("⋯");
4378
4379 for highlighted_chunk in chunks.chain([HighlightedChunk {
4380 text: "\n",
4381 style: None,
4382 is_tab: false,
4383 renderer: None,
4384 }]) {
4385 if let Some(renderer) = highlighted_chunk.renderer {
4386 if !line.is_empty() {
4387 let shaped_line = cx
4388 .text_system()
4389 .shape_line(line.clone().into(), font_size, &styles)
4390 .unwrap();
4391 width += shaped_line.width;
4392 len += shaped_line.len;
4393 fragments.push(LineFragment::Text(shaped_line));
4394 line.clear();
4395 styles.clear();
4396 }
4397
4398 let available_width = if renderer.constrain_width {
4399 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4400 ellipsis.clone()
4401 } else {
4402 SharedString::from(Arc::from(highlighted_chunk.text))
4403 };
4404 let shaped_line = cx
4405 .text_system()
4406 .shape_line(
4407 chunk,
4408 font_size,
4409 &[text_style.to_run(highlighted_chunk.text.len())],
4410 )
4411 .unwrap();
4412 AvailableSpace::Definite(shaped_line.width)
4413 } else {
4414 AvailableSpace::MinContent
4415 };
4416
4417 let mut element = (renderer.render)(&mut ChunkRendererContext {
4418 context: cx,
4419 max_width: text_width,
4420 });
4421 let line_height = text_style.line_height_in_pixels(cx.rem_size());
4422 let size = element.layout_as_root(
4423 size(available_width, AvailableSpace::Definite(line_height)),
4424 cx,
4425 );
4426
4427 width += size.width;
4428 len += highlighted_chunk.text.len();
4429 fragments.push(LineFragment::Element {
4430 element: Some(element),
4431 size,
4432 len: highlighted_chunk.text.len(),
4433 });
4434 } else {
4435 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4436 if ix > 0 {
4437 let shaped_line = cx
4438 .text_system()
4439 .shape_line(line.clone().into(), font_size, &styles)
4440 .unwrap();
4441 width += shaped_line.width;
4442 len += shaped_line.len;
4443 fragments.push(LineFragment::Text(shaped_line));
4444 layouts.push(Self {
4445 width: mem::take(&mut width),
4446 len: mem::take(&mut len),
4447 fragments: mem::take(&mut fragments),
4448 invisibles: std::mem::take(&mut invisibles),
4449 font_size,
4450 });
4451
4452 line.clear();
4453 styles.clear();
4454 row += 1;
4455 line_exceeded_max_len = false;
4456 non_whitespace_added = false;
4457 if row == max_line_count {
4458 return layouts;
4459 }
4460 }
4461
4462 if !line_chunk.is_empty() && !line_exceeded_max_len {
4463 let text_style = if let Some(style) = highlighted_chunk.style {
4464 Cow::Owned(text_style.clone().highlight(style))
4465 } else {
4466 Cow::Borrowed(text_style)
4467 };
4468
4469 if line.len() + line_chunk.len() > max_line_len {
4470 let mut chunk_len = max_line_len - line.len();
4471 while !line_chunk.is_char_boundary(chunk_len) {
4472 chunk_len -= 1;
4473 }
4474 line_chunk = &line_chunk[..chunk_len];
4475 line_exceeded_max_len = true;
4476 }
4477
4478 styles.push(TextRun {
4479 len: line_chunk.len(),
4480 font: text_style.font(),
4481 color: text_style.color,
4482 background_color: text_style.background_color,
4483 underline: text_style.underline,
4484 strikethrough: text_style.strikethrough,
4485 });
4486
4487 if editor_mode == EditorMode::Full {
4488 // Line wrap pads its contents with fake whitespaces,
4489 // avoid printing them
4490 let inside_wrapped_string = line_number_layouts
4491 .get(row)
4492 .and_then(|layout| layout.as_ref())
4493 .is_none();
4494 if highlighted_chunk.is_tab {
4495 if non_whitespace_added || !inside_wrapped_string {
4496 invisibles.push(Invisible::Tab {
4497 line_start_offset: line.len(),
4498 line_end_offset: line.len() + line_chunk.len(),
4499 });
4500 }
4501 } else {
4502 invisibles.extend(
4503 line_chunk
4504 .bytes()
4505 .enumerate()
4506 .filter(|(_, line_byte)| {
4507 let is_whitespace =
4508 (*line_byte as char).is_whitespace();
4509 non_whitespace_added |= !is_whitespace;
4510 is_whitespace
4511 && (non_whitespace_added || !inside_wrapped_string)
4512 })
4513 .map(|(whitespace_index, _)| Invisible::Whitespace {
4514 line_offset: line.len() + whitespace_index,
4515 }),
4516 )
4517 }
4518 }
4519
4520 line.push_str(line_chunk);
4521 }
4522 }
4523 }
4524 }
4525
4526 layouts
4527 }
4528
4529 fn prepaint(
4530 &mut self,
4531 line_height: Pixels,
4532 scroll_pixel_position: gpui::Point<Pixels>,
4533 row: DisplayRow,
4534 content_origin: gpui::Point<Pixels>,
4535 line_elements: &mut SmallVec<[AnyElement; 1]>,
4536 cx: &mut WindowContext,
4537 ) {
4538 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4539 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4540 for fragment in &mut self.fragments {
4541 match fragment {
4542 LineFragment::Text(line) => {
4543 fragment_origin.x += line.width;
4544 }
4545 LineFragment::Element { element, size, .. } => {
4546 let mut element = element
4547 .take()
4548 .expect("you can't prepaint LineWithInvisibles twice");
4549
4550 // Center the element vertically within the line.
4551 let mut element_origin = fragment_origin;
4552 element_origin.y += (line_height - size.height) / 2.;
4553 element.prepaint_at(element_origin, cx);
4554 line_elements.push(element);
4555
4556 fragment_origin.x += size.width;
4557 }
4558 }
4559 }
4560 }
4561
4562 fn draw(
4563 &self,
4564 layout: &EditorLayout,
4565 row: DisplayRow,
4566 content_origin: gpui::Point<Pixels>,
4567 whitespace_setting: ShowWhitespaceSetting,
4568 selection_ranges: &[Range<DisplayPoint>],
4569 cx: &mut WindowContext,
4570 ) {
4571 let line_height = layout.position_map.line_height;
4572 let line_y = line_height
4573 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4574
4575 let mut fragment_origin =
4576 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4577
4578 for fragment in &self.fragments {
4579 match fragment {
4580 LineFragment::Text(line) => {
4581 line.paint(fragment_origin, line_height, cx).log_err();
4582 fragment_origin.x += line.width;
4583 }
4584 LineFragment::Element { size, .. } => {
4585 fragment_origin.x += size.width;
4586 }
4587 }
4588 }
4589
4590 self.draw_invisibles(
4591 selection_ranges,
4592 layout,
4593 content_origin,
4594 line_y,
4595 row,
4596 line_height,
4597 whitespace_setting,
4598 cx,
4599 );
4600 }
4601
4602 #[allow(clippy::too_many_arguments)]
4603 fn draw_invisibles(
4604 &self,
4605 selection_ranges: &[Range<DisplayPoint>],
4606 layout: &EditorLayout,
4607 content_origin: gpui::Point<Pixels>,
4608 line_y: Pixels,
4609 row: DisplayRow,
4610 line_height: Pixels,
4611 whitespace_setting: ShowWhitespaceSetting,
4612 cx: &mut WindowContext,
4613 ) {
4614 let extract_whitespace_info = |invisible: &Invisible| {
4615 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
4616 Invisible::Tab {
4617 line_start_offset,
4618 line_end_offset,
4619 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
4620 Invisible::Whitespace { line_offset } => {
4621 (*line_offset, line_offset + 1, &layout.space_invisible)
4622 }
4623 };
4624
4625 let x_offset = self.x_for_index(token_offset);
4626 let invisible_offset =
4627 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
4628 let origin = content_origin
4629 + gpui::point(
4630 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
4631 line_y,
4632 );
4633
4634 (
4635 [token_offset, token_end_offset],
4636 Box::new(move |cx: &mut WindowContext| {
4637 invisible_symbol.paint(origin, line_height, cx).log_err();
4638 }),
4639 )
4640 };
4641
4642 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
4643 match whitespace_setting {
4644 ShowWhitespaceSetting::None => (),
4645 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
4646 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
4647 let invisible_point = DisplayPoint::new(row, start as u32);
4648 if !selection_ranges
4649 .iter()
4650 .any(|region| region.start <= invisible_point && invisible_point < region.end)
4651 {
4652 return;
4653 }
4654
4655 paint(cx);
4656 }),
4657
4658 // For a whitespace to be on a boundary, any of the following conditions need to be met:
4659 // - It is a tab
4660 // - It is adjacent to an edge (start or end)
4661 // - It is adjacent to a whitespace (left or right)
4662 ShowWhitespaceSetting::Boundary => {
4663 // 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
4664 // the above cases.
4665 // Note: We zip in the original `invisibles` to check for tab equality
4666 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
4667 for (([start, end], paint), invisible) in
4668 invisible_iter.zip_eq(self.invisibles.iter())
4669 {
4670 let should_render = match (&last_seen, invisible) {
4671 (_, Invisible::Tab { .. }) => true,
4672 (Some((_, last_end, _)), _) => *last_end == start,
4673 _ => false,
4674 };
4675
4676 if should_render || start == 0 || end == self.len {
4677 paint(cx);
4678
4679 // Since we are scanning from the left, we will skip over the first available whitespace that is part
4680 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
4681 if let Some((should_render_last, last_end, paint_last)) = last_seen {
4682 // Note that we need to make sure that the last one is actually adjacent
4683 if !should_render_last && last_end == start {
4684 paint_last(cx);
4685 }
4686 }
4687 }
4688
4689 // Manually render anything within a selection
4690 let invisible_point = DisplayPoint::new(row, start as u32);
4691 if selection_ranges.iter().any(|region| {
4692 region.start <= invisible_point && invisible_point < region.end
4693 }) {
4694 paint(cx);
4695 }
4696
4697 last_seen = Some((should_render, end, paint));
4698 }
4699 }
4700 }
4701 }
4702
4703 pub fn x_for_index(&self, index: usize) -> Pixels {
4704 let mut fragment_start_x = Pixels::ZERO;
4705 let mut fragment_start_index = 0;
4706
4707 for fragment in &self.fragments {
4708 match fragment {
4709 LineFragment::Text(shaped_line) => {
4710 let fragment_end_index = fragment_start_index + shaped_line.len;
4711 if index < fragment_end_index {
4712 return fragment_start_x
4713 + shaped_line.x_for_index(index - fragment_start_index);
4714 }
4715 fragment_start_x += shaped_line.width;
4716 fragment_start_index = fragment_end_index;
4717 }
4718 LineFragment::Element { len, size, .. } => {
4719 let fragment_end_index = fragment_start_index + len;
4720 if index < fragment_end_index {
4721 return fragment_start_x;
4722 }
4723 fragment_start_x += size.width;
4724 fragment_start_index = fragment_end_index;
4725 }
4726 }
4727 }
4728
4729 fragment_start_x
4730 }
4731
4732 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
4733 let mut fragment_start_x = Pixels::ZERO;
4734 let mut fragment_start_index = 0;
4735
4736 for fragment in &self.fragments {
4737 match fragment {
4738 LineFragment::Text(shaped_line) => {
4739 let fragment_end_x = fragment_start_x + shaped_line.width;
4740 if x < fragment_end_x {
4741 return Some(
4742 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
4743 );
4744 }
4745 fragment_start_x = fragment_end_x;
4746 fragment_start_index += shaped_line.len;
4747 }
4748 LineFragment::Element { len, size, .. } => {
4749 let fragment_end_x = fragment_start_x + size.width;
4750 if x < fragment_end_x {
4751 return Some(fragment_start_index);
4752 }
4753 fragment_start_index += len;
4754 fragment_start_x = fragment_end_x;
4755 }
4756 }
4757 }
4758
4759 None
4760 }
4761
4762 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
4763 let mut fragment_start_index = 0;
4764
4765 for fragment in &self.fragments {
4766 match fragment {
4767 LineFragment::Text(shaped_line) => {
4768 let fragment_end_index = fragment_start_index + shaped_line.len;
4769 if index < fragment_end_index {
4770 return shaped_line.font_id_for_index(index - fragment_start_index);
4771 }
4772 fragment_start_index = fragment_end_index;
4773 }
4774 LineFragment::Element { len, .. } => {
4775 let fragment_end_index = fragment_start_index + len;
4776 if index < fragment_end_index {
4777 return None;
4778 }
4779 fragment_start_index = fragment_end_index;
4780 }
4781 }
4782 }
4783
4784 None
4785 }
4786}
4787
4788#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4789enum Invisible {
4790 /// A tab character
4791 ///
4792 /// A tab character is internally represented by spaces (configured by the user's tab width)
4793 /// aligned to the nearest column, so it's necessary to store the start and end offset for
4794 /// adjacency checks.
4795 Tab {
4796 line_start_offset: usize,
4797 line_end_offset: usize,
4798 },
4799 Whitespace {
4800 line_offset: usize,
4801 },
4802}
4803
4804impl EditorElement {
4805 /// Returns the rem size to use when rendering the [`EditorElement`].
4806 ///
4807 /// This allows UI elements to scale based on the `buffer_font_size`.
4808 fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
4809 match self.editor.read(cx).mode {
4810 EditorMode::Full => {
4811 let buffer_font_size = self.style.text.font_size;
4812 match buffer_font_size {
4813 AbsoluteLength::Pixels(pixels) => {
4814 let rem_size_scale = {
4815 // Our default UI font size is 14px on a 16px base scale.
4816 // This means the default UI font size is 0.875rems.
4817 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
4818
4819 // We then determine the delta between a single rem and the default font
4820 // size scale.
4821 let default_font_size_delta = 1. - default_font_size_scale;
4822
4823 // Finally, we add this delta to 1rem to get the scale factor that
4824 // should be used to scale up the UI.
4825 1. + default_font_size_delta
4826 };
4827
4828 Some(pixels * rem_size_scale)
4829 }
4830 AbsoluteLength::Rems(rems) => {
4831 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
4832 }
4833 }
4834 }
4835 // We currently use single-line and auto-height editors in UI contexts,
4836 // so we don't want to scale everything with the buffer font size, as it
4837 // ends up looking off.
4838 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
4839 }
4840 }
4841}
4842
4843impl Element for EditorElement {
4844 type RequestLayoutState = ();
4845 type PrepaintState = EditorLayout;
4846
4847 fn id(&self) -> Option<ElementId> {
4848 None
4849 }
4850
4851 fn request_layout(
4852 &mut self,
4853 _: Option<&GlobalElementId>,
4854 cx: &mut WindowContext,
4855 ) -> (gpui::LayoutId, ()) {
4856 let rem_size = self.rem_size(cx);
4857 cx.with_rem_size(rem_size, |cx| {
4858 self.editor.update(cx, |editor, cx| {
4859 editor.set_style(self.style.clone(), cx);
4860
4861 let layout_id = match editor.mode {
4862 EditorMode::SingleLine { auto_width } => {
4863 let rem_size = cx.rem_size();
4864
4865 let height = self.style.text.line_height_in_pixels(rem_size);
4866 if auto_width {
4867 let editor_handle = cx.view().clone();
4868 let style = self.style.clone();
4869 cx.request_measured_layout(Style::default(), move |_, _, cx| {
4870 let editor_snapshot =
4871 editor_handle.update(cx, |editor, cx| editor.snapshot(cx));
4872 let line = Self::layout_lines(
4873 DisplayRow(0)..DisplayRow(1),
4874 &[],
4875 &editor_snapshot,
4876 &style,
4877 px(f32::MAX),
4878 cx,
4879 )
4880 .pop()
4881 .unwrap();
4882
4883 let font_id = cx.text_system().resolve_font(&style.text.font());
4884 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4885 let em_width = cx
4886 .text_system()
4887 .typographic_bounds(font_id, font_size, 'm')
4888 .unwrap()
4889 .size
4890 .width;
4891
4892 size(line.width + em_width, height)
4893 })
4894 } else {
4895 let mut style = Style::default();
4896 style.size.height = height.into();
4897 style.size.width = relative(1.).into();
4898 cx.request_layout(style, None)
4899 }
4900 }
4901 EditorMode::AutoHeight { max_lines } => {
4902 let editor_handle = cx.view().clone();
4903 let max_line_number_width =
4904 self.max_line_number_width(&editor.snapshot(cx), cx);
4905 cx.request_measured_layout(
4906 Style::default(),
4907 move |known_dimensions, available_space, cx| {
4908 editor_handle
4909 .update(cx, |editor, cx| {
4910 compute_auto_height_layout(
4911 editor,
4912 max_lines,
4913 max_line_number_width,
4914 known_dimensions,
4915 available_space.width,
4916 cx,
4917 )
4918 })
4919 .unwrap_or_default()
4920 },
4921 )
4922 }
4923 EditorMode::Full => {
4924 let mut style = Style::default();
4925 style.size.width = relative(1.).into();
4926 style.size.height = relative(1.).into();
4927 cx.request_layout(style, None)
4928 }
4929 };
4930
4931 (layout_id, ())
4932 })
4933 })
4934 }
4935
4936 fn prepaint(
4937 &mut self,
4938 _: Option<&GlobalElementId>,
4939 bounds: Bounds<Pixels>,
4940 _: &mut Self::RequestLayoutState,
4941 cx: &mut WindowContext,
4942 ) -> Self::PrepaintState {
4943 let text_style = TextStyleRefinement {
4944 font_size: Some(self.style.text.font_size),
4945 line_height: Some(self.style.text.line_height),
4946 ..Default::default()
4947 };
4948 let focus_handle = self.editor.focus_handle(cx);
4949 cx.set_view_id(self.editor.entity_id());
4950 cx.set_focus_handle(&focus_handle);
4951
4952 let rem_size = self.rem_size(cx);
4953 cx.with_rem_size(rem_size, |cx| {
4954 cx.with_text_style(Some(text_style), |cx| {
4955 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4956 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
4957 let style = self.style.clone();
4958
4959 let font_id = cx.text_system().resolve_font(&style.text.font());
4960 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4961 let line_height = style.text.line_height_in_pixels(cx.rem_size());
4962 let em_width = cx
4963 .text_system()
4964 .typographic_bounds(font_id, font_size, 'm')
4965 .unwrap()
4966 .size
4967 .width;
4968 let em_advance = cx
4969 .text_system()
4970 .advance(font_id, font_size, 'm')
4971 .unwrap()
4972 .width;
4973
4974 let gutter_dimensions = snapshot.gutter_dimensions(
4975 font_id,
4976 font_size,
4977 em_width,
4978 em_advance,
4979 self.max_line_number_width(&snapshot, cx),
4980 cx,
4981 );
4982 let text_width = bounds.size.width - gutter_dimensions.width;
4983
4984 let right_margin = if snapshot.mode == EditorMode::Full {
4985 EditorElement::SCROLLBAR_WIDTH
4986 } else {
4987 px(0.)
4988 };
4989 let overscroll = size(em_width + right_margin, px(0.));
4990
4991 let editor_width =
4992 text_width - gutter_dimensions.margin - overscroll.width - em_width;
4993
4994 snapshot = self.editor.update(cx, |editor, cx| {
4995 editor.last_bounds = Some(bounds);
4996 editor.gutter_dimensions = gutter_dimensions;
4997 editor.set_visible_line_count(bounds.size.height / line_height, cx);
4998
4999 if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
5000 snapshot
5001 } else {
5002 let wrap_width = match editor.soft_wrap_mode(cx) {
5003 SoftWrap::GitDiff => None,
5004 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
5005 SoftWrap::EditorWidth => Some(editor_width),
5006 SoftWrap::Column(column) => Some(column as f32 * em_advance),
5007 SoftWrap::Bounded(column) => {
5008 Some(editor_width.min(column as f32 * em_advance))
5009 }
5010 };
5011
5012 if editor.set_wrap_width(wrap_width, cx) {
5013 editor.snapshot(cx)
5014 } else {
5015 snapshot
5016 }
5017 }
5018 });
5019
5020 let wrap_guides = self
5021 .editor
5022 .read(cx)
5023 .wrap_guides(cx)
5024 .iter()
5025 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
5026 .collect::<SmallVec<[_; 2]>>();
5027
5028 let hitbox = cx.insert_hitbox(bounds, false);
5029 let gutter_hitbox =
5030 cx.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
5031 let text_hitbox = cx.insert_hitbox(
5032 Bounds {
5033 origin: gutter_hitbox.upper_right(),
5034 size: size(text_width, bounds.size.height),
5035 },
5036 false,
5037 );
5038 // Offset the content_bounds from the text_bounds by the gutter margin (which
5039 // is roughly half a character wide) to make hit testing work more like how we want.
5040 let content_origin =
5041 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
5042
5043 let height_in_lines = bounds.size.height / line_height;
5044 let max_row = snapshot.max_point().row().as_f32();
5045 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
5046 (max_row - height_in_lines + 1.).max(0.)
5047 } else {
5048 let settings = EditorSettings::get_global(cx);
5049 match settings.scroll_beyond_last_line {
5050 ScrollBeyondLastLine::OnePage => max_row,
5051 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
5052 ScrollBeyondLastLine::VerticalScrollMargin => {
5053 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
5054 .max(0.)
5055 }
5056 }
5057 };
5058
5059 let mut autoscroll_request = None;
5060 let mut autoscroll_containing_element = false;
5061 let mut autoscroll_horizontally = false;
5062 self.editor.update(cx, |editor, cx| {
5063 autoscroll_request = editor.autoscroll_request();
5064 autoscroll_containing_element =
5065 autoscroll_request.is_some() || editor.has_pending_selection();
5066 autoscroll_horizontally =
5067 editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
5068 snapshot = editor.snapshot(cx);
5069 });
5070
5071 let mut scroll_position = snapshot.scroll_position();
5072 // The scroll position is a fractional point, the whole number of which represents
5073 // the top of the window in terms of display rows.
5074 let start_row = DisplayRow(scroll_position.y as u32);
5075 let max_row = snapshot.max_point().row();
5076 let end_row = cmp::min(
5077 (scroll_position.y + height_in_lines).ceil() as u32,
5078 max_row.next_row().0,
5079 );
5080 let end_row = DisplayRow(end_row);
5081
5082 let buffer_rows = snapshot
5083 .buffer_rows(start_row)
5084 .take((start_row..end_row).len())
5085 .collect::<Vec<_>>();
5086
5087 let start_anchor = if start_row == Default::default() {
5088 Anchor::min()
5089 } else {
5090 snapshot.buffer_snapshot.anchor_before(
5091 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
5092 )
5093 };
5094 let end_anchor = if end_row > max_row {
5095 Anchor::max()
5096 } else {
5097 snapshot.buffer_snapshot.anchor_before(
5098 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
5099 )
5100 };
5101
5102 let highlighted_rows = self
5103 .editor
5104 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
5105 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
5106 start_anchor..end_anchor,
5107 &snapshot.display_snapshot,
5108 cx.theme().colors(),
5109 );
5110 let highlighted_gutter_ranges =
5111 self.editor.read(cx).gutter_highlights_in_range(
5112 start_anchor..end_anchor,
5113 &snapshot.display_snapshot,
5114 cx,
5115 );
5116
5117 let redacted_ranges = self.editor.read(cx).redacted_ranges(
5118 start_anchor..end_anchor,
5119 &snapshot.display_snapshot,
5120 cx,
5121 );
5122
5123 let (selections, active_rows, newest_selection_head) = self.layout_selections(
5124 start_anchor,
5125 end_anchor,
5126 &snapshot,
5127 start_row,
5128 end_row,
5129 cx,
5130 );
5131
5132 let line_numbers = self.layout_line_numbers(
5133 start_row..end_row,
5134 buffer_rows.iter().copied(),
5135 &active_rows,
5136 newest_selection_head,
5137 &snapshot,
5138 cx,
5139 );
5140
5141 let mut gutter_fold_toggles =
5142 cx.with_element_namespace("gutter_fold_toggles", |cx| {
5143 self.layout_gutter_fold_toggles(
5144 start_row..end_row,
5145 buffer_rows.iter().copied(),
5146 &active_rows,
5147 &snapshot,
5148 cx,
5149 )
5150 });
5151 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5152 self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
5153 });
5154
5155 let display_hunks = self.layout_gutter_git_hunks(
5156 line_height,
5157 &gutter_hitbox,
5158 start_row..end_row,
5159 start_anchor..end_anchor,
5160 &snapshot,
5161 cx,
5162 );
5163
5164 let mut max_visible_line_width = Pixels::ZERO;
5165 let mut line_layouts = Self::layout_lines(
5166 start_row..end_row,
5167 &line_numbers,
5168 &snapshot,
5169 &self.style,
5170 editor_width,
5171 cx,
5172 );
5173 for line_with_invisibles in &line_layouts {
5174 if line_with_invisibles.width > max_visible_line_width {
5175 max_visible_line_width = line_with_invisibles.width;
5176 }
5177 }
5178
5179 let longest_line_width =
5180 layout_line(snapshot.longest_row(), &snapshot, &style, editor_width, cx)
5181 .width;
5182 let mut scroll_width =
5183 longest_line_width.max(max_visible_line_width) + overscroll.width;
5184
5185 let blocks = cx.with_element_namespace("blocks", |cx| {
5186 self.render_blocks(
5187 start_row..end_row,
5188 &snapshot,
5189 &hitbox,
5190 &text_hitbox,
5191 editor_width,
5192 &mut scroll_width,
5193 &gutter_dimensions,
5194 em_width,
5195 gutter_dimensions.full_width(),
5196 line_height,
5197 &line_layouts,
5198 cx,
5199 )
5200 });
5201 let mut blocks = match blocks {
5202 Ok(blocks) => blocks,
5203 Err(resized_blocks) => {
5204 self.editor.update(cx, |editor, cx| {
5205 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
5206 });
5207 return self.prepaint(None, bounds, &mut (), cx);
5208 }
5209 };
5210
5211 let start_buffer_row =
5212 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
5213 let end_buffer_row =
5214 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
5215
5216 let scroll_max = point(
5217 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5218 max_row.as_f32(),
5219 );
5220
5221 self.editor.update(cx, |editor, cx| {
5222 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5223
5224 let autoscrolled = if autoscroll_horizontally {
5225 editor.autoscroll_horizontally(
5226 start_row,
5227 text_hitbox.size.width,
5228 scroll_width,
5229 em_width,
5230 &line_layouts,
5231 cx,
5232 )
5233 } else {
5234 false
5235 };
5236
5237 if clamped || autoscrolled {
5238 snapshot = editor.snapshot(cx);
5239 scroll_position = snapshot.scroll_position();
5240 }
5241 });
5242
5243 let scroll_pixel_position = point(
5244 scroll_position.x * em_width,
5245 scroll_position.y * line_height,
5246 );
5247
5248 let indent_guides = self.layout_indent_guides(
5249 content_origin,
5250 text_hitbox.origin,
5251 start_buffer_row..end_buffer_row,
5252 scroll_pixel_position,
5253 line_height,
5254 &snapshot,
5255 cx,
5256 );
5257
5258 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5259 self.prepaint_crease_trailers(
5260 crease_trailers,
5261 &line_layouts,
5262 line_height,
5263 content_origin,
5264 scroll_pixel_position,
5265 em_width,
5266 cx,
5267 )
5268 });
5269
5270 let mut inline_blame = None;
5271 if let Some(newest_selection_head) = newest_selection_head {
5272 let display_row = newest_selection_head.row();
5273 if (start_row..end_row).contains(&display_row) {
5274 let line_ix = display_row.minus(start_row) as usize;
5275 let line_layout = &line_layouts[line_ix];
5276 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
5277 inline_blame = self.layout_inline_blame(
5278 display_row,
5279 &snapshot.display_snapshot,
5280 line_layout,
5281 crease_trailer_layout,
5282 em_width,
5283 content_origin,
5284 scroll_pixel_position,
5285 line_height,
5286 cx,
5287 );
5288 }
5289 }
5290
5291 let blamed_display_rows = self.layout_blame_entries(
5292 buffer_rows.into_iter(),
5293 em_width,
5294 scroll_position,
5295 line_height,
5296 &gutter_hitbox,
5297 gutter_dimensions.git_blame_entries_width,
5298 cx,
5299 );
5300
5301 let scroll_max = point(
5302 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5303 max_scroll_top,
5304 );
5305
5306 self.editor.update(cx, |editor, cx| {
5307 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5308
5309 let autoscrolled = if autoscroll_horizontally {
5310 editor.autoscroll_horizontally(
5311 start_row,
5312 text_hitbox.size.width,
5313 scroll_width,
5314 em_width,
5315 &line_layouts,
5316 cx,
5317 )
5318 } else {
5319 false
5320 };
5321
5322 if clamped || autoscrolled {
5323 snapshot = editor.snapshot(cx);
5324 scroll_position = snapshot.scroll_position();
5325 }
5326 });
5327
5328 let line_elements = self.prepaint_lines(
5329 start_row,
5330 &mut line_layouts,
5331 line_height,
5332 scroll_pixel_position,
5333 content_origin,
5334 cx,
5335 );
5336
5337 cx.with_element_namespace("blocks", |cx| {
5338 self.layout_blocks(
5339 &mut blocks,
5340 &hitbox,
5341 line_height,
5342 scroll_pixel_position,
5343 cx,
5344 );
5345 });
5346
5347 let cursors = self.collect_cursors(&snapshot, cx);
5348 let visible_row_range = start_row..end_row;
5349 let non_visible_cursors = cursors
5350 .iter()
5351 .any(move |c| !visible_row_range.contains(&c.0.row()));
5352
5353 let visible_cursors = self.layout_visible_cursors(
5354 &snapshot,
5355 &selections,
5356 start_row..end_row,
5357 &line_layouts,
5358 &text_hitbox,
5359 content_origin,
5360 scroll_position,
5361 scroll_pixel_position,
5362 line_height,
5363 em_width,
5364 autoscroll_containing_element,
5365 cx,
5366 );
5367
5368 let scrollbar_layout = self.layout_scrollbar(
5369 &snapshot,
5370 bounds,
5371 scroll_position,
5372 height_in_lines,
5373 non_visible_cursors,
5374 cx,
5375 );
5376
5377 let gutter_settings = EditorSettings::get_global(cx).gutter;
5378
5379 let expanded_add_hunks_by_rows = self.editor.update(cx, |editor, _| {
5380 editor
5381 .expanded_hunks
5382 .hunks(false)
5383 .filter(|hunk| hunk.status == DiffHunkStatus::Added)
5384 .map(|expanded_hunk| {
5385 let start_row = expanded_hunk
5386 .hunk_range
5387 .start
5388 .to_display_point(&snapshot)
5389 .row();
5390 (start_row, expanded_hunk.clone())
5391 })
5392 .collect::<HashMap<_, _>>()
5393 });
5394
5395 let rows_with_hunk_bounds = display_hunks
5396 .iter()
5397 .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
5398 .fold(
5399 HashMap::default(),
5400 |mut rows_with_hunk_bounds, (hunk, bounds)| {
5401 match hunk {
5402 DisplayDiffHunk::Folded { display_row } => {
5403 rows_with_hunk_bounds.insert(*display_row, bounds);
5404 }
5405 DisplayDiffHunk::Unfolded {
5406 display_row_range, ..
5407 } => {
5408 for display_row in display_row_range.iter_rows() {
5409 rows_with_hunk_bounds.insert(display_row, bounds);
5410 }
5411 }
5412 }
5413 rows_with_hunk_bounds
5414 },
5415 );
5416 let mut _context_menu_visible = false;
5417 let mut code_actions_indicator = None;
5418 if let Some(newest_selection_head) = newest_selection_head {
5419 if (start_row..end_row).contains(&newest_selection_head.row()) {
5420 _context_menu_visible = self.layout_context_menu(
5421 line_height,
5422 &hitbox,
5423 &text_hitbox,
5424 content_origin,
5425 start_row,
5426 scroll_pixel_position,
5427 &line_layouts,
5428 newest_selection_head,
5429 gutter_dimensions.width - gutter_dimensions.left_padding,
5430 cx,
5431 );
5432
5433 let show_code_actions = snapshot
5434 .show_code_actions
5435 .unwrap_or(gutter_settings.code_actions);
5436 if show_code_actions {
5437 let newest_selection_point =
5438 newest_selection_head.to_point(&snapshot.display_snapshot);
5439 let newest_selection_display_row =
5440 newest_selection_point.to_display_point(&snapshot).row();
5441 if !expanded_add_hunks_by_rows
5442 .contains_key(&newest_selection_display_row)
5443 {
5444 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
5445 MultiBufferRow(newest_selection_point.row),
5446 );
5447 if let Some((buffer, range)) = buffer {
5448 let buffer_id = buffer.remote_id();
5449 let row = range.start.row;
5450 let has_test_indicator = self
5451 .editor
5452 .read(cx)
5453 .tasks
5454 .contains_key(&(buffer_id, row));
5455
5456 if !has_test_indicator {
5457 code_actions_indicator = self
5458 .layout_code_actions_indicator(
5459 line_height,
5460 newest_selection_head,
5461 scroll_pixel_position,
5462 &gutter_dimensions,
5463 &gutter_hitbox,
5464 &rows_with_hunk_bounds,
5465 cx,
5466 );
5467 }
5468 }
5469 }
5470 }
5471 }
5472 }
5473
5474 let test_indicators = if gutter_settings.runnables {
5475 self.layout_run_indicators(
5476 line_height,
5477 start_row..end_row,
5478 scroll_pixel_position,
5479 &gutter_dimensions,
5480 &gutter_hitbox,
5481 &rows_with_hunk_bounds,
5482 &snapshot,
5483 cx,
5484 )
5485 } else {
5486 Vec::new()
5487 };
5488
5489 self.layout_signature_help(
5490 &hitbox,
5491 content_origin,
5492 scroll_pixel_position,
5493 newest_selection_head,
5494 start_row,
5495 &line_layouts,
5496 line_height,
5497 em_width,
5498 cx,
5499 );
5500
5501 if !cx.has_active_drag() {
5502 self.layout_hover_popovers(
5503 &snapshot,
5504 &hitbox,
5505 &text_hitbox,
5506 start_row..end_row,
5507 content_origin,
5508 scroll_pixel_position,
5509 &line_layouts,
5510 line_height,
5511 em_width,
5512 cx,
5513 );
5514 }
5515
5516 let mouse_context_menu =
5517 self.layout_mouse_context_menu(&snapshot, start_row..end_row, cx);
5518
5519 cx.with_element_namespace("gutter_fold_toggles", |cx| {
5520 self.prepaint_gutter_fold_toggles(
5521 &mut gutter_fold_toggles,
5522 line_height,
5523 &gutter_dimensions,
5524 gutter_settings,
5525 scroll_pixel_position,
5526 &gutter_hitbox,
5527 cx,
5528 )
5529 });
5530
5531 let invisible_symbol_font_size = font_size / 2.;
5532 let tab_invisible = cx
5533 .text_system()
5534 .shape_line(
5535 "→".into(),
5536 invisible_symbol_font_size,
5537 &[TextRun {
5538 len: "→".len(),
5539 font: self.style.text.font(),
5540 color: cx.theme().colors().editor_invisible,
5541 background_color: None,
5542 underline: None,
5543 strikethrough: None,
5544 }],
5545 )
5546 .unwrap();
5547 let space_invisible = cx
5548 .text_system()
5549 .shape_line(
5550 "•".into(),
5551 invisible_symbol_font_size,
5552 &[TextRun {
5553 len: "•".len(),
5554 font: self.style.text.font(),
5555 color: cx.theme().colors().editor_invisible,
5556 background_color: None,
5557 underline: None,
5558 strikethrough: None,
5559 }],
5560 )
5561 .unwrap();
5562
5563 EditorLayout {
5564 mode: snapshot.mode,
5565 position_map: Rc::new(PositionMap {
5566 size: bounds.size,
5567 scroll_pixel_position,
5568 scroll_max,
5569 line_layouts,
5570 line_height,
5571 em_width,
5572 em_advance,
5573 snapshot,
5574 }),
5575 visible_display_row_range: start_row..end_row,
5576 wrap_guides,
5577 indent_guides,
5578 hitbox,
5579 text_hitbox,
5580 gutter_hitbox,
5581 gutter_dimensions,
5582 display_hunks,
5583 content_origin,
5584 scrollbar_layout,
5585 active_rows,
5586 highlighted_rows,
5587 highlighted_ranges,
5588 highlighted_gutter_ranges,
5589 redacted_ranges,
5590 line_elements,
5591 line_numbers,
5592 blamed_display_rows,
5593 inline_blame,
5594 blocks,
5595 cursors,
5596 visible_cursors,
5597 selections,
5598 mouse_context_menu,
5599 test_indicators,
5600 code_actions_indicator,
5601 gutter_fold_toggles,
5602 crease_trailers,
5603 tab_invisible,
5604 space_invisible,
5605 }
5606 })
5607 })
5608 })
5609 }
5610
5611 fn paint(
5612 &mut self,
5613 _: Option<&GlobalElementId>,
5614 bounds: Bounds<gpui::Pixels>,
5615 _: &mut Self::RequestLayoutState,
5616 layout: &mut Self::PrepaintState,
5617 cx: &mut WindowContext,
5618 ) {
5619 let focus_handle = self.editor.focus_handle(cx);
5620 let key_context = self.editor.update(cx, |editor, cx| editor.key_context(cx));
5621 cx.set_key_context(key_context);
5622 cx.handle_input(
5623 &focus_handle,
5624 ElementInputHandler::new(bounds, self.editor.clone()),
5625 );
5626 self.register_actions(cx);
5627 self.register_key_listeners(cx, layout);
5628
5629 let text_style = TextStyleRefinement {
5630 font_size: Some(self.style.text.font_size),
5631 line_height: Some(self.style.text.line_height),
5632 ..Default::default()
5633 };
5634 let mouse_position = cx.mouse_position();
5635 let hovered_hunk = layout
5636 .display_hunks
5637 .iter()
5638 .find_map(|(hunk, hunk_hitbox)| match hunk {
5639 DisplayDiffHunk::Folded { .. } => None,
5640 DisplayDiffHunk::Unfolded {
5641 diff_base_byte_range,
5642 multi_buffer_range,
5643 status,
5644 ..
5645 } => {
5646 if hunk_hitbox
5647 .as_ref()
5648 .map(|hitbox| hitbox.contains(&mouse_position))
5649 .unwrap_or(false)
5650 {
5651 Some(HoveredHunk {
5652 status: *status,
5653 multi_buffer_range: multi_buffer_range.clone(),
5654 diff_base_byte_range: diff_base_byte_range.clone(),
5655 })
5656 } else {
5657 None
5658 }
5659 }
5660 });
5661 let rem_size = self.rem_size(cx);
5662 cx.with_rem_size(rem_size, |cx| {
5663 cx.with_text_style(Some(text_style), |cx| {
5664 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5665 self.paint_mouse_listeners(layout, hovered_hunk, cx);
5666 self.paint_background(layout, cx);
5667 self.paint_indent_guides(layout, cx);
5668
5669 if layout.gutter_hitbox.size.width > Pixels::ZERO {
5670 self.paint_blamed_display_rows(layout, cx);
5671 self.paint_line_numbers(layout, cx);
5672 }
5673
5674 self.paint_text(layout, cx);
5675
5676 if layout.gutter_hitbox.size.width > Pixels::ZERO {
5677 self.paint_gutter_highlights(layout, cx);
5678 self.paint_gutter_indicators(layout, cx);
5679 }
5680
5681 if !layout.blocks.is_empty() {
5682 cx.with_element_namespace("blocks", |cx| {
5683 self.paint_blocks(layout, cx);
5684 });
5685 }
5686
5687 self.paint_scrollbar(layout, cx);
5688 self.paint_mouse_context_menu(layout, cx);
5689 });
5690 })
5691 })
5692 }
5693}
5694
5695pub(super) fn gutter_bounds(
5696 editor_bounds: Bounds<Pixels>,
5697 gutter_dimensions: GutterDimensions,
5698) -> Bounds<Pixels> {
5699 Bounds {
5700 origin: editor_bounds.origin,
5701 size: size(gutter_dimensions.width, editor_bounds.size.height),
5702 }
5703}
5704
5705impl IntoElement for EditorElement {
5706 type Element = Self;
5707
5708 fn into_element(self) -> Self::Element {
5709 self
5710 }
5711}
5712
5713pub struct EditorLayout {
5714 position_map: Rc<PositionMap>,
5715 hitbox: Hitbox,
5716 text_hitbox: Hitbox,
5717 gutter_hitbox: Hitbox,
5718 gutter_dimensions: GutterDimensions,
5719 content_origin: gpui::Point<Pixels>,
5720 scrollbar_layout: Option<ScrollbarLayout>,
5721 mode: EditorMode,
5722 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
5723 indent_guides: Option<Vec<IndentGuideLayout>>,
5724 visible_display_row_range: Range<DisplayRow>,
5725 active_rows: BTreeMap<DisplayRow, bool>,
5726 highlighted_rows: BTreeMap<DisplayRow, Hsla>,
5727 line_elements: SmallVec<[AnyElement; 1]>,
5728 line_numbers: Vec<Option<ShapedLine>>,
5729 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
5730 blamed_display_rows: Option<Vec<AnyElement>>,
5731 inline_blame: Option<AnyElement>,
5732 blocks: Vec<BlockLayout>,
5733 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5734 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5735 redacted_ranges: Vec<Range<DisplayPoint>>,
5736 cursors: Vec<(DisplayPoint, Hsla)>,
5737 visible_cursors: Vec<CursorLayout>,
5738 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
5739 code_actions_indicator: Option<AnyElement>,
5740 test_indicators: Vec<AnyElement>,
5741 gutter_fold_toggles: Vec<Option<AnyElement>>,
5742 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
5743 mouse_context_menu: Option<AnyElement>,
5744 tab_invisible: ShapedLine,
5745 space_invisible: ShapedLine,
5746}
5747
5748impl EditorLayout {
5749 fn line_end_overshoot(&self) -> Pixels {
5750 0.15 * self.position_map.line_height
5751 }
5752}
5753
5754struct ColoredRange<T> {
5755 start: T,
5756 end: T,
5757 color: Hsla,
5758}
5759
5760#[derive(Clone)]
5761struct ScrollbarLayout {
5762 hitbox: Hitbox,
5763 visible_row_range: Range<f32>,
5764 visible: bool,
5765 row_height: Pixels,
5766 thumb_height: Pixels,
5767}
5768
5769impl ScrollbarLayout {
5770 const BORDER_WIDTH: Pixels = px(1.0);
5771 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
5772 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
5773 const MIN_THUMB_HEIGHT: Pixels = px(20.0);
5774
5775 fn thumb_bounds(&self) -> Bounds<Pixels> {
5776 let thumb_top = self.y_for_row(self.visible_row_range.start);
5777 let thumb_bottom = thumb_top + self.thumb_height;
5778 Bounds::from_corners(
5779 point(self.hitbox.left(), thumb_top),
5780 point(self.hitbox.right(), thumb_bottom),
5781 )
5782 }
5783
5784 fn y_for_row(&self, row: f32) -> Pixels {
5785 self.hitbox.top() + row * self.row_height
5786 }
5787
5788 fn marker_quads_for_ranges(
5789 &self,
5790 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
5791 column: Option<usize>,
5792 ) -> Vec<PaintQuad> {
5793 struct MinMax {
5794 min: Pixels,
5795 max: Pixels,
5796 }
5797 let (x_range, height_limit) = if let Some(column) = column {
5798 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
5799 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
5800 let end = start + column_width;
5801 (
5802 Range { start, end },
5803 MinMax {
5804 min: Self::MIN_MARKER_HEIGHT,
5805 max: px(f32::MAX),
5806 },
5807 )
5808 } else {
5809 (
5810 Range {
5811 start: Self::BORDER_WIDTH,
5812 end: self.hitbox.size.width,
5813 },
5814 MinMax {
5815 min: Self::LINE_MARKER_HEIGHT,
5816 max: Self::LINE_MARKER_HEIGHT,
5817 },
5818 )
5819 };
5820
5821 let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
5822 let mut pixel_ranges = row_ranges
5823 .into_iter()
5824 .map(|range| {
5825 let start_y = row_to_y(range.start);
5826 let end_y = row_to_y(range.end)
5827 + self.row_height.max(height_limit.min).min(height_limit.max);
5828 ColoredRange {
5829 start: start_y,
5830 end: end_y,
5831 color: range.color,
5832 }
5833 })
5834 .peekable();
5835
5836 let mut quads = Vec::new();
5837 while let Some(mut pixel_range) = pixel_ranges.next() {
5838 while let Some(next_pixel_range) = pixel_ranges.peek() {
5839 if pixel_range.end >= next_pixel_range.start - px(1.0)
5840 && pixel_range.color == next_pixel_range.color
5841 {
5842 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
5843 pixel_ranges.next();
5844 } else {
5845 break;
5846 }
5847 }
5848
5849 let bounds = Bounds::from_corners(
5850 point(x_range.start, pixel_range.start),
5851 point(x_range.end, pixel_range.end),
5852 );
5853 quads.push(quad(
5854 bounds,
5855 Corners::default(),
5856 pixel_range.color,
5857 Edges::default(),
5858 Hsla::transparent_black(),
5859 ));
5860 }
5861
5862 quads
5863 }
5864}
5865
5866struct CreaseTrailerLayout {
5867 element: AnyElement,
5868 bounds: Bounds<Pixels>,
5869}
5870
5871struct PositionMap {
5872 size: Size<Pixels>,
5873 line_height: Pixels,
5874 scroll_pixel_position: gpui::Point<Pixels>,
5875 scroll_max: gpui::Point<f32>,
5876 em_width: Pixels,
5877 em_advance: Pixels,
5878 line_layouts: Vec<LineWithInvisibles>,
5879 snapshot: EditorSnapshot,
5880}
5881
5882#[derive(Debug, Copy, Clone)]
5883pub struct PointForPosition {
5884 pub previous_valid: DisplayPoint,
5885 pub next_valid: DisplayPoint,
5886 pub exact_unclipped: DisplayPoint,
5887 pub column_overshoot_after_line_end: u32,
5888}
5889
5890impl PointForPosition {
5891 pub fn as_valid(&self) -> Option<DisplayPoint> {
5892 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
5893 Some(self.previous_valid)
5894 } else {
5895 None
5896 }
5897 }
5898}
5899
5900impl PositionMap {
5901 fn point_for_position(
5902 &self,
5903 text_bounds: Bounds<Pixels>,
5904 position: gpui::Point<Pixels>,
5905 ) -> PointForPosition {
5906 let scroll_position = self.snapshot.scroll_position();
5907 let position = position - text_bounds.origin;
5908 let y = position.y.max(px(0.)).min(self.size.height);
5909 let x = position.x + (scroll_position.x * self.em_width);
5910 let row = ((y / self.line_height) + scroll_position.y) as u32;
5911
5912 let (column, x_overshoot_after_line_end) = if let Some(line) = self
5913 .line_layouts
5914 .get(row as usize - scroll_position.y as usize)
5915 {
5916 if let Some(ix) = line.index_for_x(x) {
5917 (ix as u32, px(0.))
5918 } else {
5919 (line.len as u32, px(0.).max(x - line.width))
5920 }
5921 } else {
5922 (0, x)
5923 };
5924
5925 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
5926 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
5927 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
5928
5929 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
5930 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
5931 PointForPosition {
5932 previous_valid,
5933 next_valid,
5934 exact_unclipped,
5935 column_overshoot_after_line_end,
5936 }
5937 }
5938}
5939
5940struct BlockLayout {
5941 id: BlockId,
5942 row: Option<DisplayRow>,
5943 element: AnyElement,
5944 available_space: Size<AvailableSpace>,
5945 style: BlockStyle,
5946}
5947
5948fn layout_line(
5949 row: DisplayRow,
5950 snapshot: &EditorSnapshot,
5951 style: &EditorStyle,
5952 text_width: Pixels,
5953 cx: &mut WindowContext,
5954) -> LineWithInvisibles {
5955 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
5956 LineWithInvisibles::from_chunks(
5957 chunks,
5958 &style.text,
5959 MAX_LINE_LEN,
5960 1,
5961 &[],
5962 snapshot.mode,
5963 text_width,
5964 cx,
5965 )
5966 .pop()
5967 .unwrap()
5968}
5969
5970#[derive(Debug)]
5971pub struct IndentGuideLayout {
5972 origin: gpui::Point<Pixels>,
5973 length: Pixels,
5974 single_indent_width: Pixels,
5975 depth: u32,
5976 active: bool,
5977 settings: IndentGuideSettings,
5978}
5979
5980pub struct CursorLayout {
5981 origin: gpui::Point<Pixels>,
5982 block_width: Pixels,
5983 line_height: Pixels,
5984 color: Hsla,
5985 shape: CursorShape,
5986 block_text: Option<ShapedLine>,
5987 cursor_name: Option<AnyElement>,
5988}
5989
5990#[derive(Debug)]
5991pub struct CursorName {
5992 string: SharedString,
5993 color: Hsla,
5994 is_top_row: bool,
5995}
5996
5997impl CursorLayout {
5998 pub fn new(
5999 origin: gpui::Point<Pixels>,
6000 block_width: Pixels,
6001 line_height: Pixels,
6002 color: Hsla,
6003 shape: CursorShape,
6004 block_text: Option<ShapedLine>,
6005 ) -> CursorLayout {
6006 CursorLayout {
6007 origin,
6008 block_width,
6009 line_height,
6010 color,
6011 shape,
6012 block_text,
6013 cursor_name: None,
6014 }
6015 }
6016
6017 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6018 Bounds {
6019 origin: self.origin + origin,
6020 size: size(self.block_width, self.line_height),
6021 }
6022 }
6023
6024 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
6025 match self.shape {
6026 CursorShape::Bar => Bounds {
6027 origin: self.origin + origin,
6028 size: size(px(2.0), self.line_height),
6029 },
6030 CursorShape::Block | CursorShape::Hollow => Bounds {
6031 origin: self.origin + origin,
6032 size: size(self.block_width, self.line_height),
6033 },
6034 CursorShape::Underscore => Bounds {
6035 origin: self.origin
6036 + origin
6037 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
6038 size: size(self.block_width, px(2.0)),
6039 },
6040 }
6041 }
6042
6043 pub fn layout(
6044 &mut self,
6045 origin: gpui::Point<Pixels>,
6046 cursor_name: Option<CursorName>,
6047 cx: &mut WindowContext,
6048 ) {
6049 if let Some(cursor_name) = cursor_name {
6050 let bounds = self.bounds(origin);
6051 let text_size = self.line_height / 1.5;
6052
6053 let name_origin = if cursor_name.is_top_row {
6054 point(bounds.right() - px(1.), bounds.top())
6055 } else {
6056 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
6057 };
6058 let mut name_element = div()
6059 .bg(self.color)
6060 .text_size(text_size)
6061 .px_0p5()
6062 .line_height(text_size + px(2.))
6063 .text_color(cursor_name.color)
6064 .child(cursor_name.string.clone())
6065 .into_any_element();
6066
6067 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), cx);
6068
6069 self.cursor_name = Some(name_element);
6070 }
6071 }
6072
6073 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
6074 let bounds = self.bounds(origin);
6075
6076 //Draw background or border quad
6077 let cursor = if matches!(self.shape, CursorShape::Hollow) {
6078 outline(bounds, self.color)
6079 } else {
6080 fill(bounds, self.color)
6081 };
6082
6083 if let Some(name) = &mut self.cursor_name {
6084 name.paint(cx);
6085 }
6086
6087 cx.paint_quad(cursor);
6088
6089 if let Some(block_text) = &self.block_text {
6090 block_text
6091 .paint(self.origin + origin, self.line_height, cx)
6092 .log_err();
6093 }
6094 }
6095
6096 pub fn shape(&self) -> CursorShape {
6097 self.shape
6098 }
6099}
6100
6101#[derive(Debug)]
6102pub struct HighlightedRange {
6103 pub start_y: Pixels,
6104 pub line_height: Pixels,
6105 pub lines: Vec<HighlightedRangeLine>,
6106 pub color: Hsla,
6107 pub corner_radius: Pixels,
6108}
6109
6110#[derive(Debug)]
6111pub struct HighlightedRangeLine {
6112 pub start_x: Pixels,
6113 pub end_x: Pixels,
6114}
6115
6116impl HighlightedRange {
6117 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
6118 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
6119 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
6120 self.paint_lines(
6121 self.start_y + self.line_height,
6122 &self.lines[1..],
6123 bounds,
6124 cx,
6125 );
6126 } else {
6127 self.paint_lines(self.start_y, &self.lines, bounds, cx);
6128 }
6129 }
6130
6131 fn paint_lines(
6132 &self,
6133 start_y: Pixels,
6134 lines: &[HighlightedRangeLine],
6135 _bounds: Bounds<Pixels>,
6136 cx: &mut WindowContext,
6137 ) {
6138 if lines.is_empty() {
6139 return;
6140 }
6141
6142 let first_line = lines.first().unwrap();
6143 let last_line = lines.last().unwrap();
6144
6145 let first_top_left = point(first_line.start_x, start_y);
6146 let first_top_right = point(first_line.end_x, start_y);
6147
6148 let curve_height = point(Pixels::ZERO, self.corner_radius);
6149 let curve_width = |start_x: Pixels, end_x: Pixels| {
6150 let max = (end_x - start_x) / 2.;
6151 let width = if max < self.corner_radius {
6152 max
6153 } else {
6154 self.corner_radius
6155 };
6156
6157 point(width, Pixels::ZERO)
6158 };
6159
6160 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
6161 let mut path = gpui::Path::new(first_top_right - top_curve_width);
6162 path.curve_to(first_top_right + curve_height, first_top_right);
6163
6164 let mut iter = lines.iter().enumerate().peekable();
6165 while let Some((ix, line)) = iter.next() {
6166 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
6167
6168 if let Some((_, next_line)) = iter.peek() {
6169 let next_top_right = point(next_line.end_x, bottom_right.y);
6170
6171 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
6172 Ordering::Equal => {
6173 path.line_to(bottom_right);
6174 }
6175 Ordering::Less => {
6176 let curve_width = curve_width(next_top_right.x, bottom_right.x);
6177 path.line_to(bottom_right - curve_height);
6178 if self.corner_radius > Pixels::ZERO {
6179 path.curve_to(bottom_right - curve_width, bottom_right);
6180 }
6181 path.line_to(next_top_right + curve_width);
6182 if self.corner_radius > Pixels::ZERO {
6183 path.curve_to(next_top_right + curve_height, next_top_right);
6184 }
6185 }
6186 Ordering::Greater => {
6187 let curve_width = curve_width(bottom_right.x, next_top_right.x);
6188 path.line_to(bottom_right - curve_height);
6189 if self.corner_radius > Pixels::ZERO {
6190 path.curve_to(bottom_right + curve_width, bottom_right);
6191 }
6192 path.line_to(next_top_right - curve_width);
6193 if self.corner_radius > Pixels::ZERO {
6194 path.curve_to(next_top_right + curve_height, next_top_right);
6195 }
6196 }
6197 }
6198 } else {
6199 let curve_width = curve_width(line.start_x, line.end_x);
6200 path.line_to(bottom_right - curve_height);
6201 if self.corner_radius > Pixels::ZERO {
6202 path.curve_to(bottom_right - curve_width, bottom_right);
6203 }
6204
6205 let bottom_left = point(line.start_x, bottom_right.y);
6206 path.line_to(bottom_left + curve_width);
6207 if self.corner_radius > Pixels::ZERO {
6208 path.curve_to(bottom_left - curve_height, bottom_left);
6209 }
6210 }
6211 }
6212
6213 if first_line.start_x > last_line.start_x {
6214 let curve_width = curve_width(last_line.start_x, first_line.start_x);
6215 let second_top_left = point(last_line.start_x, start_y + self.line_height);
6216 path.line_to(second_top_left + curve_height);
6217 if self.corner_radius > Pixels::ZERO {
6218 path.curve_to(second_top_left + curve_width, second_top_left);
6219 }
6220 let first_bottom_left = point(first_line.start_x, second_top_left.y);
6221 path.line_to(first_bottom_left - curve_width);
6222 if self.corner_radius > Pixels::ZERO {
6223 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
6224 }
6225 }
6226
6227 path.line_to(first_top_left + curve_height);
6228 if self.corner_radius > Pixels::ZERO {
6229 path.curve_to(first_top_left + top_curve_width, first_top_left);
6230 }
6231 path.line_to(first_top_right - top_curve_width);
6232
6233 cx.paint_path(path, self.color);
6234 }
6235}
6236
6237pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6238 (delta.pow(1.5) / 100.0).into()
6239}
6240
6241fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6242 (delta.pow(1.2) / 300.0).into()
6243}
6244
6245pub fn register_action<T: Action>(
6246 view: &View<Editor>,
6247 cx: &mut WindowContext,
6248 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6249) {
6250 let view = view.clone();
6251 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6252 let action = action.downcast_ref().unwrap();
6253 if phase == DispatchPhase::Bubble {
6254 view.update(cx, |editor, cx| {
6255 listener(editor, action, cx);
6256 })
6257 }
6258 })
6259}
6260
6261fn compute_auto_height_layout(
6262 editor: &mut Editor,
6263 max_lines: usize,
6264 max_line_number_width: Pixels,
6265 known_dimensions: Size<Option<Pixels>>,
6266 available_width: AvailableSpace,
6267 cx: &mut ViewContext<Editor>,
6268) -> Option<Size<Pixels>> {
6269 let width = known_dimensions.width.or({
6270 if let AvailableSpace::Definite(available_width) = available_width {
6271 Some(available_width)
6272 } else {
6273 None
6274 }
6275 })?;
6276 if let Some(height) = known_dimensions.height {
6277 return Some(size(width, height));
6278 }
6279
6280 let style = editor.style.as_ref().unwrap();
6281 let font_id = cx.text_system().resolve_font(&style.text.font());
6282 let font_size = style.text.font_size.to_pixels(cx.rem_size());
6283 let line_height = style.text.line_height_in_pixels(cx.rem_size());
6284 let em_width = cx
6285 .text_system()
6286 .typographic_bounds(font_id, font_size, 'm')
6287 .unwrap()
6288 .size
6289 .width;
6290 let em_advance = cx
6291 .text_system()
6292 .advance(font_id, font_size, 'm')
6293 .unwrap()
6294 .width;
6295
6296 let mut snapshot = editor.snapshot(cx);
6297 let gutter_dimensions = snapshot.gutter_dimensions(
6298 font_id,
6299 font_size,
6300 em_width,
6301 em_advance,
6302 max_line_number_width,
6303 cx,
6304 );
6305
6306 editor.gutter_dimensions = gutter_dimensions;
6307 let text_width = width - gutter_dimensions.width;
6308 let overscroll = size(em_width, px(0.));
6309
6310 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6311 if editor.set_wrap_width(Some(editor_width), cx) {
6312 snapshot = editor.snapshot(cx);
6313 }
6314
6315 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6316 let height = scroll_height
6317 .max(line_height)
6318 .min(line_height * max_lines as f32);
6319
6320 Some(size(width, height))
6321}
6322
6323#[cfg(test)]
6324mod tests {
6325 use super::*;
6326 use crate::{
6327 display_map::{BlockDisposition, BlockProperties},
6328 editor_tests::{init_test, update_test_language_settings},
6329 Editor, MultiBuffer,
6330 };
6331 use gpui::{TestAppContext, VisualTestContext};
6332 use language::language_settings;
6333 use log::info;
6334 use std::num::NonZeroU32;
6335 use ui::Context;
6336 use util::test::sample_text;
6337
6338 #[gpui::test]
6339 fn test_shape_line_numbers(cx: &mut TestAppContext) {
6340 init_test(cx, |_| {});
6341 let window = cx.add_window(|cx| {
6342 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6343 Editor::new(EditorMode::Full, buffer, None, true, cx)
6344 });
6345
6346 let editor = window.root(cx).unwrap();
6347 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6348 let element = EditorElement::new(&editor, style);
6349 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
6350
6351 let layouts = cx
6352 .update_window(*window, |_, cx| {
6353 element.layout_line_numbers(
6354 DisplayRow(0)..DisplayRow(6),
6355 (0..6).map(MultiBufferRow).map(Some),
6356 &Default::default(),
6357 Some(DisplayPoint::new(DisplayRow(0), 0)),
6358 &snapshot,
6359 cx,
6360 )
6361 })
6362 .unwrap();
6363 assert_eq!(layouts.len(), 6);
6364
6365 let relative_rows = window
6366 .update(cx, |editor, cx| {
6367 let snapshot = editor.snapshot(cx);
6368 element.calculate_relative_line_numbers(
6369 &snapshot,
6370 &(DisplayRow(0)..DisplayRow(6)),
6371 Some(DisplayRow(3)),
6372 )
6373 })
6374 .unwrap();
6375 assert_eq!(relative_rows[&DisplayRow(0)], 3);
6376 assert_eq!(relative_rows[&DisplayRow(1)], 2);
6377 assert_eq!(relative_rows[&DisplayRow(2)], 1);
6378 // current line has no relative number
6379 assert_eq!(relative_rows[&DisplayRow(4)], 1);
6380 assert_eq!(relative_rows[&DisplayRow(5)], 2);
6381
6382 // works if cursor is before screen
6383 let relative_rows = window
6384 .update(cx, |editor, cx| {
6385 let snapshot = editor.snapshot(cx);
6386 element.calculate_relative_line_numbers(
6387 &snapshot,
6388 &(DisplayRow(3)..DisplayRow(6)),
6389 Some(DisplayRow(1)),
6390 )
6391 })
6392 .unwrap();
6393 assert_eq!(relative_rows.len(), 3);
6394 assert_eq!(relative_rows[&DisplayRow(3)], 2);
6395 assert_eq!(relative_rows[&DisplayRow(4)], 3);
6396 assert_eq!(relative_rows[&DisplayRow(5)], 4);
6397
6398 // works if cursor is after screen
6399 let relative_rows = window
6400 .update(cx, |editor, cx| {
6401 let snapshot = editor.snapshot(cx);
6402 element.calculate_relative_line_numbers(
6403 &snapshot,
6404 &(DisplayRow(0)..DisplayRow(3)),
6405 Some(DisplayRow(6)),
6406 )
6407 })
6408 .unwrap();
6409 assert_eq!(relative_rows.len(), 3);
6410 assert_eq!(relative_rows[&DisplayRow(0)], 5);
6411 assert_eq!(relative_rows[&DisplayRow(1)], 4);
6412 assert_eq!(relative_rows[&DisplayRow(2)], 3);
6413 }
6414
6415 #[gpui::test]
6416 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
6417 init_test(cx, |_| {});
6418
6419 let window = cx.add_window(|cx| {
6420 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
6421 Editor::new(EditorMode::Full, buffer, None, true, cx)
6422 });
6423 let cx = &mut VisualTestContext::from_window(*window, cx);
6424 let editor = window.root(cx).unwrap();
6425 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6426
6427 window
6428 .update(cx, |editor, cx| {
6429 editor.cursor_shape = CursorShape::Block;
6430 editor.change_selections(None, cx, |s| {
6431 s.select_ranges([
6432 Point::new(0, 0)..Point::new(1, 0),
6433 Point::new(3, 2)..Point::new(3, 3),
6434 Point::new(5, 6)..Point::new(6, 0),
6435 ]);
6436 });
6437 })
6438 .unwrap();
6439
6440 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6441 EditorElement::new(&editor, style)
6442 });
6443
6444 assert_eq!(state.selections.len(), 1);
6445 let local_selections = &state.selections[0].1;
6446 assert_eq!(local_selections.len(), 3);
6447 // moves cursor back one line
6448 assert_eq!(
6449 local_selections[0].head,
6450 DisplayPoint::new(DisplayRow(0), 6)
6451 );
6452 assert_eq!(
6453 local_selections[0].range,
6454 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
6455 );
6456
6457 // moves cursor back one column
6458 assert_eq!(
6459 local_selections[1].range,
6460 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
6461 );
6462 assert_eq!(
6463 local_selections[1].head,
6464 DisplayPoint::new(DisplayRow(3), 2)
6465 );
6466
6467 // leaves cursor on the max point
6468 assert_eq!(
6469 local_selections[2].range,
6470 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
6471 );
6472 assert_eq!(
6473 local_selections[2].head,
6474 DisplayPoint::new(DisplayRow(6), 0)
6475 );
6476
6477 // active lines does not include 1 (even though the range of the selection does)
6478 assert_eq!(
6479 state.active_rows.keys().cloned().collect::<Vec<_>>(),
6480 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
6481 );
6482
6483 // multi-buffer support
6484 // in DisplayPoint coordinates, this is what we're dealing with:
6485 // 0: [[file
6486 // 1: header
6487 // 2: section]]
6488 // 3: aaaaaa
6489 // 4: bbbbbb
6490 // 5: cccccc
6491 // 6:
6492 // 7: [[footer]]
6493 // 8: [[header]]
6494 // 9: ffffff
6495 // 10: gggggg
6496 // 11: hhhhhh
6497 // 12:
6498 // 13: [[footer]]
6499 // 14: [[file
6500 // 15: header
6501 // 16: section]]
6502 // 17: bbbbbb
6503 // 18: cccccc
6504 // 19: dddddd
6505 // 20: [[footer]]
6506 let window = cx.add_window(|cx| {
6507 let buffer = MultiBuffer::build_multi(
6508 [
6509 (
6510 &(sample_text(8, 6, 'a') + "\n"),
6511 vec![
6512 Point::new(0, 0)..Point::new(3, 0),
6513 Point::new(4, 0)..Point::new(7, 0),
6514 ],
6515 ),
6516 (
6517 &(sample_text(8, 6, 'a') + "\n"),
6518 vec![Point::new(1, 0)..Point::new(3, 0)],
6519 ),
6520 ],
6521 cx,
6522 );
6523 Editor::new(EditorMode::Full, buffer, None, true, cx)
6524 });
6525 let editor = window.root(cx).unwrap();
6526 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6527 let _state = window.update(cx, |editor, cx| {
6528 editor.cursor_shape = CursorShape::Block;
6529 editor.change_selections(None, cx, |s| {
6530 s.select_display_ranges([
6531 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
6532 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
6533 ]);
6534 });
6535 });
6536
6537 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6538 EditorElement::new(&editor, style)
6539 });
6540 assert_eq!(state.selections.len(), 1);
6541 let local_selections = &state.selections[0].1;
6542 assert_eq!(local_selections.len(), 2);
6543
6544 // moves cursor on excerpt boundary back a line
6545 // and doesn't allow selection to bleed through
6546 assert_eq!(
6547 local_selections[0].range,
6548 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
6549 );
6550 assert_eq!(
6551 local_selections[0].head,
6552 DisplayPoint::new(DisplayRow(6), 0)
6553 );
6554 // moves cursor on buffer boundary back two lines
6555 // and doesn't allow selection to bleed through
6556 assert_eq!(
6557 local_selections[1].range,
6558 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
6559 );
6560 assert_eq!(
6561 local_selections[1].head,
6562 DisplayPoint::new(DisplayRow(12), 0)
6563 );
6564 }
6565
6566 #[gpui::test]
6567 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
6568 init_test(cx, |_| {});
6569
6570 let window = cx.add_window(|cx| {
6571 let buffer = MultiBuffer::build_simple("", cx);
6572 Editor::new(EditorMode::Full, buffer, None, true, cx)
6573 });
6574 let cx = &mut VisualTestContext::from_window(*window, cx);
6575 let editor = window.root(cx).unwrap();
6576 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6577 window
6578 .update(cx, |editor, cx| {
6579 editor.set_placeholder_text("hello", cx);
6580 editor.insert_blocks(
6581 [BlockProperties {
6582 style: BlockStyle::Fixed,
6583 disposition: BlockDisposition::Above,
6584 height: 3,
6585 position: Anchor::min(),
6586 render: Box::new(|cx| div().h(3. * cx.line_height()).into_any()),
6587 priority: 0,
6588 }],
6589 None,
6590 cx,
6591 );
6592
6593 // Blur the editor so that it displays placeholder text.
6594 cx.blur();
6595 })
6596 .unwrap();
6597
6598 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6599 EditorElement::new(&editor, style)
6600 });
6601 assert_eq!(state.position_map.line_layouts.len(), 4);
6602 assert_eq!(
6603 state
6604 .line_numbers
6605 .iter()
6606 .map(Option::is_some)
6607 .collect::<Vec<_>>(),
6608 &[false, false, false, true]
6609 );
6610 }
6611
6612 #[gpui::test]
6613 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
6614 const TAB_SIZE: u32 = 4;
6615
6616 let input_text = "\t \t|\t| a b";
6617 let expected_invisibles = vec![
6618 Invisible::Tab {
6619 line_start_offset: 0,
6620 line_end_offset: TAB_SIZE as usize,
6621 },
6622 Invisible::Whitespace {
6623 line_offset: TAB_SIZE as usize,
6624 },
6625 Invisible::Tab {
6626 line_start_offset: TAB_SIZE as usize + 1,
6627 line_end_offset: TAB_SIZE as usize * 2,
6628 },
6629 Invisible::Tab {
6630 line_start_offset: TAB_SIZE as usize * 2 + 1,
6631 line_end_offset: TAB_SIZE as usize * 3,
6632 },
6633 Invisible::Whitespace {
6634 line_offset: TAB_SIZE as usize * 3 + 1,
6635 },
6636 Invisible::Whitespace {
6637 line_offset: TAB_SIZE as usize * 3 + 3,
6638 },
6639 ];
6640 assert_eq!(
6641 expected_invisibles.len(),
6642 input_text
6643 .chars()
6644 .filter(|initial_char| initial_char.is_whitespace())
6645 .count(),
6646 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6647 );
6648
6649 init_test(cx, |s| {
6650 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6651 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
6652 });
6653
6654 let actual_invisibles =
6655 collect_invisibles_from_new_editor(cx, EditorMode::Full, input_text, px(500.0));
6656
6657 assert_eq!(expected_invisibles, actual_invisibles);
6658 }
6659
6660 #[gpui::test]
6661 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
6662 init_test(cx, |s| {
6663 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6664 s.defaults.tab_size = NonZeroU32::new(4);
6665 });
6666
6667 for editor_mode_without_invisibles in [
6668 EditorMode::SingleLine { auto_width: false },
6669 EditorMode::AutoHeight { max_lines: 100 },
6670 ] {
6671 let invisibles = collect_invisibles_from_new_editor(
6672 cx,
6673 editor_mode_without_invisibles,
6674 "\t\t\t| | a b",
6675 px(500.0),
6676 );
6677 assert!(invisibles.is_empty(),
6678 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
6679 }
6680 }
6681
6682 #[gpui::test]
6683 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
6684 let tab_size = 4;
6685 let input_text = "a\tbcd ".repeat(9);
6686 let repeated_invisibles = [
6687 Invisible::Tab {
6688 line_start_offset: 1,
6689 line_end_offset: tab_size as usize,
6690 },
6691 Invisible::Whitespace {
6692 line_offset: tab_size as usize + 3,
6693 },
6694 Invisible::Whitespace {
6695 line_offset: tab_size as usize + 4,
6696 },
6697 Invisible::Whitespace {
6698 line_offset: tab_size as usize + 5,
6699 },
6700 Invisible::Whitespace {
6701 line_offset: tab_size as usize + 6,
6702 },
6703 Invisible::Whitespace {
6704 line_offset: tab_size as usize + 7,
6705 },
6706 ];
6707 let expected_invisibles = std::iter::once(repeated_invisibles)
6708 .cycle()
6709 .take(9)
6710 .flatten()
6711 .collect::<Vec<_>>();
6712 assert_eq!(
6713 expected_invisibles.len(),
6714 input_text
6715 .chars()
6716 .filter(|initial_char| initial_char.is_whitespace())
6717 .count(),
6718 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6719 );
6720 info!("Expected invisibles: {expected_invisibles:?}");
6721
6722 init_test(cx, |_| {});
6723
6724 // Put the same string with repeating whitespace pattern into editors of various size,
6725 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
6726 let resize_step = 10.0;
6727 let mut editor_width = 200.0;
6728 while editor_width <= 1000.0 {
6729 update_test_language_settings(cx, |s| {
6730 s.defaults.tab_size = NonZeroU32::new(tab_size);
6731 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6732 s.defaults.preferred_line_length = Some(editor_width as u32);
6733 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
6734 });
6735
6736 let actual_invisibles = collect_invisibles_from_new_editor(
6737 cx,
6738 EditorMode::Full,
6739 &input_text,
6740 px(editor_width),
6741 );
6742
6743 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
6744 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
6745 let mut i = 0;
6746 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
6747 i = actual_index;
6748 match expected_invisibles.get(i) {
6749 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
6750 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
6751 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
6752 _ => {
6753 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
6754 }
6755 },
6756 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
6757 }
6758 }
6759 let missing_expected_invisibles = &expected_invisibles[i + 1..];
6760 assert!(
6761 missing_expected_invisibles.is_empty(),
6762 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
6763 );
6764
6765 editor_width += resize_step;
6766 }
6767 }
6768
6769 fn collect_invisibles_from_new_editor(
6770 cx: &mut TestAppContext,
6771 editor_mode: EditorMode,
6772 input_text: &str,
6773 editor_width: Pixels,
6774 ) -> Vec<Invisible> {
6775 info!(
6776 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
6777 editor_width.0
6778 );
6779 let window = cx.add_window(|cx| {
6780 let buffer = MultiBuffer::build_simple(input_text, cx);
6781 Editor::new(editor_mode, buffer, None, true, cx)
6782 });
6783 let cx = &mut VisualTestContext::from_window(*window, cx);
6784 let editor = window.root(cx).unwrap();
6785 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6786 window
6787 .update(cx, |editor, cx| {
6788 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
6789 editor.set_wrap_width(Some(editor_width), cx);
6790 })
6791 .unwrap();
6792 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6793 EditorElement::new(&editor, style)
6794 });
6795 state
6796 .position_map
6797 .line_layouts
6798 .iter()
6799 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
6800 .cloned()
6801 .collect()
6802 }
6803}