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