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