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