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