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