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