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