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