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