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 snapshot = self.editor.update(cx, |this, cx| this.snapshot(cx));
2086 let row = Point::new(row, 0)
2087 .to_display_point(&snapshot.display_snapshot)
2088 .row();
2089 let x = -gutter_overshoot;
2090 let y = (row + 1) as f32 * line_height - scroll_pixel_position.y;
2091 (x, y)
2092 }
2093 };
2094
2095 let mut list_origin = content_origin + point(x, y);
2096 let list_width = context_menu_size.width;
2097 let list_height = context_menu_size.height;
2098
2099 // Snap the right edge of the list to the right edge of the window if
2100 // its horizontal bounds overflow.
2101 if list_origin.x + list_width > cx.viewport_size().width {
2102 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
2103 }
2104
2105 if list_origin.y + list_height > text_hitbox.lower_right().y {
2106 list_origin.y -= line_height + list_height;
2107 }
2108
2109 cx.defer_draw(context_menu, list_origin, 1);
2110 true
2111 }
2112
2113 fn layout_mouse_context_menu(&self, cx: &mut WindowContext) -> Option<AnyElement> {
2114 let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
2115 let mut element = deferred(
2116 anchored()
2117 .position(mouse_context_menu.position)
2118 .child(mouse_context_menu.context_menu.clone())
2119 .anchor(AnchorCorner::TopLeft)
2120 .snap_to_window(),
2121 )
2122 .with_priority(1)
2123 .into_any();
2124
2125 element.prepaint_as_root(gpui::Point::default(), AvailableSpace::min_size(), cx);
2126 Some(element)
2127 }
2128
2129 #[allow(clippy::too_many_arguments)]
2130 fn layout_hover_popovers(
2131 &self,
2132 snapshot: &EditorSnapshot,
2133 hitbox: &Hitbox,
2134 text_hitbox: &Hitbox,
2135 visible_display_row_range: Range<u32>,
2136 content_origin: gpui::Point<Pixels>,
2137 scroll_pixel_position: gpui::Point<Pixels>,
2138 line_layouts: &[LineWithInvisibles],
2139 line_height: Pixels,
2140 em_width: Pixels,
2141 cx: &mut WindowContext,
2142 ) {
2143 struct MeasuredHoverPopover {
2144 element: AnyElement,
2145 size: Size<Pixels>,
2146 horizontal_offset: Pixels,
2147 }
2148
2149 let max_size = size(
2150 (120. * em_width) // Default size
2151 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2152 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2153 (16. * line_height) // Default size
2154 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2155 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2156 );
2157
2158 let hover_popovers = self.editor.update(cx, |editor, cx| {
2159 editor.hover_state.render(
2160 &snapshot,
2161 &self.style,
2162 visible_display_row_range.clone(),
2163 max_size,
2164 editor.workspace.as_ref().map(|(w, _)| w.clone()),
2165 cx,
2166 )
2167 });
2168 let Some((position, hover_popovers)) = hover_popovers else {
2169 return;
2170 };
2171
2172 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2173
2174 // This is safe because we check on layout whether the required row is available
2175 let hovered_row_layout =
2176 &line_layouts[(position.row() - visible_display_row_range.start) as usize].line;
2177
2178 // Compute Hovered Point
2179 let x =
2180 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
2181 let y = position.row() as f32 * line_height - scroll_pixel_position.y;
2182 let hovered_point = content_origin + point(x, y);
2183
2184 let mut overall_height = Pixels::ZERO;
2185 let mut measured_hover_popovers = Vec::new();
2186 for mut hover_popover in hover_popovers {
2187 let size = hover_popover.layout_as_root(available_space, cx);
2188 let horizontal_offset =
2189 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
2190
2191 overall_height += HOVER_POPOVER_GAP + size.height;
2192
2193 measured_hover_popovers.push(MeasuredHoverPopover {
2194 element: hover_popover,
2195 size,
2196 horizontal_offset,
2197 });
2198 }
2199 overall_height += HOVER_POPOVER_GAP;
2200
2201 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
2202 let mut occlusion = div()
2203 .size_full()
2204 .occlude()
2205 .on_mouse_move(|_, cx| cx.stop_propagation())
2206 .into_any_element();
2207 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
2208 cx.defer_draw(occlusion, origin, 2);
2209 }
2210
2211 if hovered_point.y > overall_height {
2212 // There is enough space above. Render popovers above the hovered point
2213 let mut current_y = hovered_point.y;
2214 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2215 let size = popover.size;
2216 let popover_origin = point(
2217 hovered_point.x + popover.horizontal_offset,
2218 current_y - size.height,
2219 );
2220
2221 cx.defer_draw(popover.element, popover_origin, 2);
2222 if position != itertools::Position::Last {
2223 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
2224 draw_occluder(size.width, origin, cx);
2225 }
2226
2227 current_y = popover_origin.y - HOVER_POPOVER_GAP;
2228 }
2229 } else {
2230 // There is not enough space above. Render popovers below the hovered point
2231 let mut current_y = hovered_point.y + line_height;
2232 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2233 let size = popover.size;
2234 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2235
2236 cx.defer_draw(popover.element, popover_origin, 2);
2237 if position != itertools::Position::Last {
2238 let origin = point(popover_origin.x, popover_origin.y + size.height);
2239 draw_occluder(size.width, origin, cx);
2240 }
2241
2242 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2243 }
2244 }
2245 }
2246
2247 fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2248 cx.paint_layer(layout.hitbox.bounds, |cx| {
2249 let scroll_top = layout.position_map.snapshot.scroll_position().y;
2250 let gutter_bg = cx.theme().colors().editor_gutter_background;
2251 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2252 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2253
2254 if let EditorMode::Full = layout.mode {
2255 let mut active_rows = layout.active_rows.iter().peekable();
2256 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2257 let mut end_row = *start_row;
2258 while active_rows.peek().map_or(false, |r| {
2259 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
2260 }) {
2261 active_rows.next().unwrap();
2262 end_row += 1;
2263 }
2264
2265 if !contains_non_empty_selection {
2266 let origin = point(
2267 layout.hitbox.origin.x,
2268 layout.hitbox.origin.y
2269 + (*start_row as f32 - scroll_top)
2270 * layout.position_map.line_height,
2271 );
2272 let size = size(
2273 layout.hitbox.size.width,
2274 layout.position_map.line_height * (end_row - start_row + 1) as f32,
2275 );
2276 let active_line_bg = cx.theme().colors().editor_active_line_background;
2277 cx.paint_quad(fill(Bounds { origin, size }, active_line_bg));
2278 }
2279 }
2280
2281 let mut paint_highlight =
2282 |highlight_row_start: u32, highlight_row_end: u32, color| {
2283 let origin = point(
2284 layout.hitbox.origin.x,
2285 layout.hitbox.origin.y
2286 + (highlight_row_start as f32 - scroll_top)
2287 * layout.position_map.line_height,
2288 );
2289 let size = size(
2290 layout.hitbox.size.width,
2291 layout.position_map.line_height
2292 * (highlight_row_end + 1 - highlight_row_start) as f32,
2293 );
2294 cx.paint_quad(fill(Bounds { origin, size }, color));
2295 };
2296
2297 let mut current_paint: Option<(Hsla, Range<u32>)> = None;
2298 for (&new_row, &new_color) in &layout.highlighted_rows {
2299 match &mut current_paint {
2300 Some((current_color, current_range)) => {
2301 let current_color = *current_color;
2302 let new_range_started =
2303 current_color != new_color || current_range.end + 1 != new_row;
2304 if new_range_started {
2305 paint_highlight(
2306 current_range.start,
2307 current_range.end,
2308 current_color,
2309 );
2310 current_paint = Some((new_color, new_row..new_row));
2311 continue;
2312 } else {
2313 current_range.end += 1;
2314 }
2315 }
2316 None => current_paint = Some((new_color, new_row..new_row)),
2317 };
2318 }
2319 if let Some((color, range)) = current_paint {
2320 paint_highlight(range.start, range.end, color);
2321 }
2322
2323 let scroll_left =
2324 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2325
2326 for (wrap_position, active) in layout.wrap_guides.iter() {
2327 let x = (layout.text_hitbox.origin.x
2328 + *wrap_position
2329 + layout.position_map.em_width / 2.)
2330 - scroll_left;
2331
2332 let show_scrollbars = layout
2333 .scrollbar_layout
2334 .as_ref()
2335 .map_or(false, |scrollbar| scrollbar.visible);
2336 if x < layout.text_hitbox.origin.x
2337 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2338 {
2339 continue;
2340 }
2341
2342 let color = if *active {
2343 cx.theme().colors().editor_active_wrap_guide
2344 } else {
2345 cx.theme().colors().editor_wrap_guide
2346 };
2347 cx.paint_quad(fill(
2348 Bounds {
2349 origin: point(x, layout.text_hitbox.origin.y),
2350 size: size(px(1.), layout.text_hitbox.size.height),
2351 },
2352 color,
2353 ));
2354 }
2355 }
2356 })
2357 }
2358
2359 fn paint_gutter(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2360 let line_height = layout.position_map.line_height;
2361
2362 let scroll_position = layout.position_map.snapshot.scroll_position();
2363 let scroll_top = scroll_position.y * line_height;
2364
2365 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2366 for (_, hunk_hitbox) in &layout.display_hunks {
2367 if let Some(hunk_hitbox) = hunk_hitbox {
2368 cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
2369 }
2370 }
2371
2372 let show_git_gutter = matches!(
2373 ProjectSettings::get_global(cx).git.git_gutter,
2374 Some(GitGutterSetting::TrackedFiles)
2375 );
2376 if show_git_gutter {
2377 Self::paint_diff_hunks(layout.gutter_hitbox.bounds, layout, cx)
2378 }
2379
2380 if layout.blamed_display_rows.is_some() {
2381 self.paint_blamed_display_rows(layout, cx);
2382 }
2383
2384 for (ix, line) in layout.line_numbers.iter().enumerate() {
2385 if let Some(line) = line {
2386 let line_origin = layout.gutter_hitbox.origin
2387 + point(
2388 layout.gutter_hitbox.size.width
2389 - line.width
2390 - layout.gutter_dimensions.right_padding,
2391 ix as f32 * line_height - (scroll_top % line_height),
2392 );
2393
2394 line.paint(line_origin, line_height, cx).log_err();
2395 }
2396 }
2397
2398 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2399 cx.with_element_namespace("gutter_fold_indicators", |cx| {
2400 for fold_indicator in layout.fold_indicators.iter_mut().flatten() {
2401 fold_indicator.paint(cx);
2402 }
2403 });
2404
2405 for test_indicators in layout.test_indicators.iter_mut() {
2406 test_indicators.paint(cx);
2407 }
2408
2409 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2410 indicator.paint(cx);
2411 }
2412 });
2413 }
2414
2415 fn paint_diff_hunks(
2416 gutter_bounds: Bounds<Pixels>,
2417 layout: &EditorLayout,
2418 cx: &mut WindowContext,
2419 ) {
2420 if layout.display_hunks.is_empty() {
2421 return;
2422 }
2423
2424 let line_height = layout.position_map.line_height;
2425 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2426 for (hunk, hitbox) in &layout.display_hunks {
2427 let hunk_to_paint = match hunk {
2428 DisplayDiffHunk::Folded { .. } => {
2429 let hunk_bounds = Self::diff_hunk_bounds(
2430 &layout.position_map.snapshot,
2431 line_height,
2432 gutter_bounds,
2433 &hunk,
2434 );
2435 Some((
2436 hunk_bounds,
2437 cx.theme().status().modified,
2438 Corners::all(1. * line_height),
2439 ))
2440 }
2441 DisplayDiffHunk::Unfolded { status, .. } => {
2442 hitbox.as_ref().map(|hunk_hitbox| match status {
2443 DiffHunkStatus::Added => (
2444 hunk_hitbox.bounds,
2445 cx.theme().status().created,
2446 Corners::all(0.05 * line_height),
2447 ),
2448 DiffHunkStatus::Modified => (
2449 hunk_hitbox.bounds,
2450 cx.theme().status().modified,
2451 Corners::all(0.05 * line_height),
2452 ),
2453 DiffHunkStatus::Removed => (
2454 hunk_hitbox.bounds,
2455 cx.theme().status().deleted,
2456 Corners::all(1. * line_height),
2457 ),
2458 })
2459 }
2460 };
2461
2462 if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
2463 cx.paint_quad(quad(
2464 hunk_bounds,
2465 corner_radii,
2466 background_color,
2467 Edges::default(),
2468 transparent_black(),
2469 ));
2470 }
2471 }
2472 });
2473 }
2474
2475 fn diff_hunk_bounds(
2476 snapshot: &EditorSnapshot,
2477 line_height: Pixels,
2478 bounds: Bounds<Pixels>,
2479 hunk: &DisplayDiffHunk,
2480 ) -> Bounds<Pixels> {
2481 let scroll_position = snapshot.scroll_position();
2482 let scroll_top = scroll_position.y * line_height;
2483
2484 match hunk {
2485 DisplayDiffHunk::Folded { display_row, .. } => {
2486 let start_y = *display_row as f32 * line_height - scroll_top;
2487 let end_y = start_y + line_height;
2488
2489 let width = 0.275 * line_height;
2490 let highlight_origin = bounds.origin + point(-width, start_y);
2491 let highlight_size = size(width * 2., end_y - start_y);
2492 Bounds::new(highlight_origin, highlight_size)
2493 }
2494 DisplayDiffHunk::Unfolded {
2495 display_row_range,
2496 status,
2497 ..
2498 } => match status {
2499 DiffHunkStatus::Added | DiffHunkStatus::Modified => {
2500 let start_row = display_row_range.start;
2501 let end_row = display_row_range.end;
2502 // If we're in a multibuffer, row range span might include an
2503 // excerpt header, so if we were to draw the marker straight away,
2504 // the hunk might include the rows of that header.
2505 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2506 // Instead, we simply check whether the range we're dealing with includes
2507 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2508 let end_row_in_current_excerpt = snapshot
2509 .blocks_in_range(start_row..end_row)
2510 .find_map(|(start_row, block)| {
2511 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2512 Some(start_row)
2513 } else {
2514 None
2515 }
2516 })
2517 .unwrap_or(end_row);
2518
2519 let start_y = start_row as f32 * line_height - scroll_top;
2520 let end_y = end_row_in_current_excerpt as f32 * line_height - scroll_top;
2521
2522 let width = 0.275 * line_height;
2523 let highlight_origin = bounds.origin + point(-width, start_y);
2524 let highlight_size = size(width * 2., end_y - start_y);
2525 Bounds::new(highlight_origin, highlight_size)
2526 }
2527 DiffHunkStatus::Removed => {
2528 let row = display_row_range.start;
2529
2530 let offset = line_height / 2.;
2531 let start_y = row as f32 * line_height - offset - scroll_top;
2532 let end_y = start_y + line_height;
2533
2534 let width = 0.35 * line_height;
2535 let highlight_origin = bounds.origin + point(-width, start_y);
2536 let highlight_size = size(width * 2., end_y - start_y);
2537 Bounds::new(highlight_origin, highlight_size)
2538 }
2539 },
2540 }
2541 }
2542
2543 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2544 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
2545 return;
2546 };
2547
2548 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2549 for mut blame_element in blamed_display_rows.into_iter() {
2550 blame_element.paint(cx);
2551 }
2552 })
2553 }
2554
2555 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2556 cx.with_content_mask(
2557 Some(ContentMask {
2558 bounds: layout.text_hitbox.bounds,
2559 }),
2560 |cx| {
2561 let cursor_style = if self
2562 .editor
2563 .read(cx)
2564 .hovered_link_state
2565 .as_ref()
2566 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
2567 {
2568 CursorStyle::PointingHand
2569 } else {
2570 CursorStyle::IBeam
2571 };
2572 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
2573
2574 cx.with_element_namespace("folds", |cx| self.paint_folds(layout, cx));
2575 let invisible_display_ranges = self.paint_highlights(layout, cx);
2576 self.paint_lines(&invisible_display_ranges, layout, cx);
2577 self.paint_redactions(layout, cx);
2578 self.paint_cursors(layout, cx);
2579 self.paint_inline_blame(layout, cx);
2580 },
2581 )
2582 }
2583
2584 fn paint_highlights(
2585 &mut self,
2586 layout: &mut EditorLayout,
2587 cx: &mut WindowContext,
2588 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
2589 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2590 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
2591 let line_end_overshoot = 0.15 * layout.position_map.line_height;
2592 for (range, color) in &layout.highlighted_ranges {
2593 self.paint_highlighted_range(
2594 range.clone(),
2595 *color,
2596 Pixels::ZERO,
2597 line_end_overshoot,
2598 layout,
2599 cx,
2600 );
2601 }
2602
2603 let corner_radius = 0.15 * layout.position_map.line_height;
2604
2605 for (player_color, selections) in &layout.selections {
2606 for selection in selections.into_iter() {
2607 self.paint_highlighted_range(
2608 selection.range.clone(),
2609 player_color.selection,
2610 corner_radius,
2611 corner_radius * 2.,
2612 layout,
2613 cx,
2614 );
2615
2616 if selection.is_local && !selection.range.is_empty() {
2617 invisible_display_ranges.push(selection.range.clone());
2618 }
2619 }
2620 }
2621 invisible_display_ranges
2622 })
2623 }
2624
2625 fn paint_lines(
2626 &mut self,
2627 invisible_display_ranges: &[Range<DisplayPoint>],
2628 layout: &EditorLayout,
2629 cx: &mut WindowContext,
2630 ) {
2631 let whitespace_setting = self
2632 .editor
2633 .read(cx)
2634 .buffer
2635 .read(cx)
2636 .settings_at(0, cx)
2637 .show_whitespaces;
2638
2639 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
2640 let row = layout.visible_display_row_range.start + ix as u32;
2641 line_with_invisibles.draw(
2642 layout,
2643 row,
2644 layout.content_origin,
2645 whitespace_setting,
2646 invisible_display_ranges,
2647 cx,
2648 )
2649 }
2650 }
2651
2652 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
2653 if layout.redacted_ranges.is_empty() {
2654 return;
2655 }
2656
2657 let line_end_overshoot = layout.line_end_overshoot();
2658
2659 // A softer than perfect black
2660 let redaction_color = gpui::rgb(0x0e1111);
2661
2662 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2663 for range in layout.redacted_ranges.iter() {
2664 self.paint_highlighted_range(
2665 range.clone(),
2666 redaction_color.into(),
2667 Pixels::ZERO,
2668 line_end_overshoot,
2669 layout,
2670 cx,
2671 );
2672 }
2673 });
2674 }
2675
2676 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2677 for cursor in &mut layout.visible_cursors {
2678 cursor.paint(layout.content_origin, cx);
2679 }
2680 }
2681
2682 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2683 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
2684 return;
2685 };
2686
2687 let thumb_bounds = scrollbar_layout.thumb_bounds();
2688 if scrollbar_layout.visible {
2689 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
2690 cx.paint_quad(quad(
2691 scrollbar_layout.hitbox.bounds,
2692 Corners::default(),
2693 cx.theme().colors().scrollbar_track_background,
2694 Edges {
2695 top: Pixels::ZERO,
2696 right: Pixels::ZERO,
2697 bottom: Pixels::ZERO,
2698 left: ScrollbarLayout::BORDER_WIDTH,
2699 },
2700 cx.theme().colors().scrollbar_track_border,
2701 ));
2702
2703 let fast_markers =
2704 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
2705 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
2706 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
2707
2708 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
2709 for marker in markers.iter().chain(&fast_markers) {
2710 let mut marker = marker.clone();
2711 marker.bounds.origin += scrollbar_layout.hitbox.origin;
2712 cx.paint_quad(marker);
2713 }
2714
2715 cx.paint_quad(quad(
2716 thumb_bounds,
2717 Corners::default(),
2718 cx.theme().colors().scrollbar_thumb_background,
2719 Edges {
2720 top: Pixels::ZERO,
2721 right: Pixels::ZERO,
2722 bottom: Pixels::ZERO,
2723 left: ScrollbarLayout::BORDER_WIDTH,
2724 },
2725 cx.theme().colors().scrollbar_thumb_border,
2726 ));
2727 });
2728 }
2729
2730 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2731
2732 let row_height = scrollbar_layout.row_height;
2733 let row_range = scrollbar_layout.visible_row_range.clone();
2734
2735 cx.on_mouse_event({
2736 let editor = self.editor.clone();
2737 let hitbox = scrollbar_layout.hitbox.clone();
2738 let mut mouse_position = cx.mouse_position();
2739 move |event: &MouseMoveEvent, phase, cx| {
2740 if phase == DispatchPhase::Capture {
2741 return;
2742 }
2743
2744 editor.update(cx, |editor, cx| {
2745 if event.pressed_button == Some(MouseButton::Left)
2746 && editor.scroll_manager.is_dragging_scrollbar()
2747 {
2748 let y = mouse_position.y;
2749 let new_y = event.position.y;
2750 if (hitbox.top()..hitbox.bottom()).contains(&y) {
2751 let mut position = editor.scroll_position(cx);
2752 position.y += (new_y - y) / row_height;
2753 if position.y < 0.0 {
2754 position.y = 0.0;
2755 }
2756 editor.set_scroll_position(position, cx);
2757 }
2758
2759 cx.stop_propagation();
2760 } else {
2761 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2762 if hitbox.is_hovered(cx) {
2763 editor.scroll_manager.show_scrollbar(cx);
2764 }
2765 }
2766 mouse_position = event.position;
2767 })
2768 }
2769 });
2770
2771 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2772 cx.on_mouse_event({
2773 let editor = self.editor.clone();
2774 move |_: &MouseUpEvent, phase, cx| {
2775 if phase == DispatchPhase::Capture {
2776 return;
2777 }
2778
2779 editor.update(cx, |editor, cx| {
2780 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2781 cx.stop_propagation();
2782 });
2783 }
2784 });
2785 } else {
2786 cx.on_mouse_event({
2787 let editor = self.editor.clone();
2788 let hitbox = scrollbar_layout.hitbox.clone();
2789 move |event: &MouseDownEvent, phase, cx| {
2790 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2791 return;
2792 }
2793
2794 editor.update(cx, |editor, cx| {
2795 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2796
2797 let y = event.position.y;
2798 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2799 let center_row = ((y - hitbox.top()) / row_height).round() as u32;
2800 let top_row = center_row
2801 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2802 let mut position = editor.scroll_position(cx);
2803 position.y = top_row as f32;
2804 editor.set_scroll_position(position, cx);
2805 } else {
2806 editor.scroll_manager.show_scrollbar(cx);
2807 }
2808
2809 cx.stop_propagation();
2810 });
2811 }
2812 });
2813 }
2814 }
2815
2816 fn collect_fast_scrollbar_markers(
2817 &self,
2818 layout: &EditorLayout,
2819 scrollbar_layout: &ScrollbarLayout,
2820 cx: &mut WindowContext,
2821 ) -> Vec<PaintQuad> {
2822 const LIMIT: usize = 100;
2823 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
2824 return vec![];
2825 }
2826 let cursor_ranges = layout
2827 .cursors
2828 .iter()
2829 .map(|(point, color)| ColoredRange {
2830 start: point.row(),
2831 end: point.row(),
2832 color: *color,
2833 })
2834 .collect_vec();
2835 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
2836 }
2837
2838 fn refresh_slow_scrollbar_markers(
2839 &self,
2840 layout: &EditorLayout,
2841 scrollbar_layout: &ScrollbarLayout,
2842 cx: &mut WindowContext,
2843 ) {
2844 self.editor.update(cx, |editor, cx| {
2845 if !editor.is_singleton(cx)
2846 || !editor
2847 .scrollbar_marker_state
2848 .should_refresh(scrollbar_layout.hitbox.size)
2849 {
2850 return;
2851 }
2852
2853 let scrollbar_layout = scrollbar_layout.clone();
2854 let background_highlights = editor.background_highlights.clone();
2855 let snapshot = layout.position_map.snapshot.clone();
2856 let theme = cx.theme().clone();
2857 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
2858 let max_row = layout.max_row;
2859
2860 editor.scrollbar_marker_state.dirty = false;
2861 editor.scrollbar_marker_state.pending_refresh =
2862 Some(cx.spawn(|editor, mut cx| async move {
2863 let scrollbar_size = scrollbar_layout.hitbox.size;
2864 let scrollbar_markers = cx
2865 .background_executor()
2866 .spawn(async move {
2867 let mut marker_quads = Vec::new();
2868
2869 if scrollbar_settings.git_diff {
2870 let marker_row_ranges = snapshot
2871 .buffer_snapshot
2872 .git_diff_hunks_in_range(0..max_row)
2873 .map(|hunk| {
2874 let start_display_row =
2875 Point::new(hunk.associated_range.start, 0)
2876 .to_display_point(&snapshot.display_snapshot)
2877 .row();
2878 let mut end_display_row =
2879 Point::new(hunk.associated_range.end, 0)
2880 .to_display_point(&snapshot.display_snapshot)
2881 .row();
2882 if end_display_row != start_display_row {
2883 end_display_row -= 1;
2884 }
2885 let color = match hunk.status() {
2886 DiffHunkStatus::Added => theme.status().created,
2887 DiffHunkStatus::Modified => theme.status().modified,
2888 DiffHunkStatus::Removed => theme.status().deleted,
2889 };
2890 ColoredRange {
2891 start: start_display_row,
2892 end: end_display_row,
2893 color,
2894 }
2895 });
2896
2897 marker_quads.extend(
2898 scrollbar_layout
2899 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
2900 );
2901 }
2902
2903 for (background_highlight_id, (_, background_ranges)) in
2904 background_highlights.iter()
2905 {
2906 let is_search_highlights = *background_highlight_id
2907 == TypeId::of::<BufferSearchHighlights>();
2908 let is_symbol_occurrences = *background_highlight_id
2909 == TypeId::of::<DocumentHighlightRead>()
2910 || *background_highlight_id
2911 == TypeId::of::<DocumentHighlightWrite>();
2912 if (is_search_highlights && scrollbar_settings.search_results)
2913 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
2914 {
2915 let mut color = theme.status().info;
2916 if is_symbol_occurrences {
2917 color.fade_out(0.5);
2918 }
2919 let marker_row_ranges =
2920 background_ranges.into_iter().map(|range| {
2921 let display_start = range
2922 .start
2923 .to_display_point(&snapshot.display_snapshot);
2924 let display_end = range
2925 .end
2926 .to_display_point(&snapshot.display_snapshot);
2927 ColoredRange {
2928 start: display_start.row(),
2929 end: display_end.row(),
2930 color,
2931 }
2932 });
2933 marker_quads.extend(
2934 scrollbar_layout
2935 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
2936 );
2937 }
2938 }
2939
2940 if scrollbar_settings.diagnostics {
2941 let max_point =
2942 snapshot.display_snapshot.buffer_snapshot.max_point();
2943
2944 let diagnostics = snapshot
2945 .buffer_snapshot
2946 .diagnostics_in_range::<_, Point>(
2947 Point::zero()..max_point,
2948 false,
2949 )
2950 // We want to sort by severity, in order to paint the most severe diagnostics last.
2951 .sorted_by_key(|diagnostic| {
2952 std::cmp::Reverse(diagnostic.diagnostic.severity)
2953 });
2954
2955 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
2956 let start_display = diagnostic
2957 .range
2958 .start
2959 .to_display_point(&snapshot.display_snapshot);
2960 let end_display = diagnostic
2961 .range
2962 .end
2963 .to_display_point(&snapshot.display_snapshot);
2964 let color = match diagnostic.diagnostic.severity {
2965 DiagnosticSeverity::ERROR => theme.status().error,
2966 DiagnosticSeverity::WARNING => theme.status().warning,
2967 DiagnosticSeverity::INFORMATION => theme.status().info,
2968 _ => theme.status().hint,
2969 };
2970 ColoredRange {
2971 start: start_display.row(),
2972 end: end_display.row(),
2973 color,
2974 }
2975 });
2976 marker_quads.extend(
2977 scrollbar_layout
2978 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
2979 );
2980 }
2981
2982 Arc::from(marker_quads)
2983 })
2984 .await;
2985
2986 editor.update(&mut cx, |editor, cx| {
2987 editor.scrollbar_marker_state.markers = scrollbar_markers;
2988 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
2989 editor.scrollbar_marker_state.pending_refresh = None;
2990 cx.notify();
2991 })?;
2992
2993 Ok(())
2994 }));
2995 });
2996 }
2997
2998 #[allow(clippy::too_many_arguments)]
2999 fn paint_highlighted_range(
3000 &self,
3001 range: Range<DisplayPoint>,
3002 color: Hsla,
3003 corner_radius: Pixels,
3004 line_end_overshoot: Pixels,
3005 layout: &EditorLayout,
3006 cx: &mut WindowContext,
3007 ) {
3008 let start_row = layout.visible_display_row_range.start;
3009 let end_row = layout.visible_display_row_range.end;
3010 if range.start != range.end {
3011 let row_range = if range.end.column() == 0 {
3012 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3013 } else {
3014 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
3015 };
3016
3017 let highlighted_range = HighlightedRange {
3018 color,
3019 line_height: layout.position_map.line_height,
3020 corner_radius,
3021 start_y: layout.content_origin.y
3022 + row_range.start as f32 * layout.position_map.line_height
3023 - layout.position_map.scroll_pixel_position.y,
3024 lines: row_range
3025 .into_iter()
3026 .map(|row| {
3027 let line_layout =
3028 &layout.position_map.line_layouts[(row - start_row) as usize].line;
3029 HighlightedRangeLine {
3030 start_x: if row == range.start.row() {
3031 layout.content_origin.x
3032 + line_layout.x_for_index(range.start.column() as usize)
3033 - layout.position_map.scroll_pixel_position.x
3034 } else {
3035 layout.content_origin.x
3036 - layout.position_map.scroll_pixel_position.x
3037 },
3038 end_x: if row == range.end.row() {
3039 layout.content_origin.x
3040 + line_layout.x_for_index(range.end.column() as usize)
3041 - layout.position_map.scroll_pixel_position.x
3042 } else {
3043 layout.content_origin.x + line_layout.width + line_end_overshoot
3044 - layout.position_map.scroll_pixel_position.x
3045 },
3046 }
3047 })
3048 .collect(),
3049 };
3050
3051 highlighted_range.paint(layout.text_hitbox.bounds, cx);
3052 }
3053 }
3054
3055 fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3056 if layout.folds.is_empty() {
3057 return;
3058 }
3059
3060 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3061 let fold_corner_radius = 0.15 * layout.position_map.line_height;
3062 for mut fold in mem::take(&mut layout.folds) {
3063 fold.hover_element.paint(cx);
3064
3065 let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
3066 let fold_background = if hover_element.interactivity().active.unwrap() {
3067 cx.theme().colors().ghost_element_active
3068 } else if hover_element.interactivity().hovered.unwrap() {
3069 cx.theme().colors().ghost_element_hover
3070 } else {
3071 cx.theme().colors().ghost_element_background
3072 };
3073
3074 self.paint_highlighted_range(
3075 fold.display_range.clone(),
3076 fold_background,
3077 fold_corner_radius,
3078 fold_corner_radius * 2.,
3079 layout,
3080 cx,
3081 );
3082 }
3083 })
3084 }
3085
3086 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3087 if let Some(mut inline_blame) = layout.inline_blame.take() {
3088 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3089 inline_blame.paint(cx);
3090 })
3091 }
3092 }
3093
3094 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3095 for mut block in layout.blocks.drain(..) {
3096 block.element.paint(cx);
3097 }
3098 }
3099
3100 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3101 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3102 mouse_context_menu.paint(cx);
3103 }
3104 }
3105
3106 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3107 cx.on_mouse_event({
3108 let position_map = layout.position_map.clone();
3109 let editor = self.editor.clone();
3110 let hitbox = layout.hitbox.clone();
3111 let mut delta = ScrollDelta::default();
3112
3113 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3114 // accidentally turn off their scrolling.
3115 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3116
3117 move |event: &ScrollWheelEvent, phase, cx| {
3118 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3119 delta = delta.coalesce(event.delta);
3120 editor.update(cx, |editor, cx| {
3121 let position_map: &PositionMap = &position_map;
3122
3123 let line_height = position_map.line_height;
3124 let max_glyph_width = position_map.em_width;
3125 let (delta, axis) = match delta {
3126 gpui::ScrollDelta::Pixels(mut pixels) => {
3127 //Trackpad
3128 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3129 (pixels, axis)
3130 }
3131
3132 gpui::ScrollDelta::Lines(lines) => {
3133 //Not trackpad
3134 let pixels =
3135 point(lines.x * max_glyph_width, lines.y * line_height);
3136 (pixels, None)
3137 }
3138 };
3139
3140 let current_scroll_position = position_map.snapshot.scroll_position();
3141 let x = (current_scroll_position.x * max_glyph_width
3142 - (delta.x * scroll_sensitivity))
3143 / max_glyph_width;
3144 let y = (current_scroll_position.y * line_height
3145 - (delta.y * scroll_sensitivity))
3146 / line_height;
3147 let mut scroll_position =
3148 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3149 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3150 if forbid_vertical_scroll {
3151 scroll_position.y = current_scroll_position.y;
3152 if scroll_position == current_scroll_position {
3153 return;
3154 }
3155 }
3156 editor.scroll(scroll_position, axis, cx);
3157 cx.stop_propagation();
3158 });
3159 }
3160 }
3161 });
3162 }
3163
3164 fn paint_mouse_listeners(
3165 &mut self,
3166 layout: &EditorLayout,
3167 hovered_hunk: Option<HunkToExpand>,
3168 cx: &mut WindowContext,
3169 ) {
3170 self.paint_scroll_wheel_listener(layout, cx);
3171
3172 cx.on_mouse_event({
3173 let position_map = layout.position_map.clone();
3174 let editor = self.editor.clone();
3175 let text_hitbox = layout.text_hitbox.clone();
3176 let gutter_hitbox = layout.gutter_hitbox.clone();
3177
3178 move |event: &MouseDownEvent, phase, cx| {
3179 if phase == DispatchPhase::Bubble {
3180 match event.button {
3181 MouseButton::Left => editor.update(cx, |editor, cx| {
3182 Self::mouse_left_down(
3183 editor,
3184 event,
3185 hovered_hunk.as_ref(),
3186 &position_map,
3187 &text_hitbox,
3188 &gutter_hitbox,
3189 cx,
3190 );
3191 }),
3192 MouseButton::Right => editor.update(cx, |editor, cx| {
3193 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3194 }),
3195 MouseButton::Middle => editor.update(cx, |editor, cx| {
3196 Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3197 }),
3198 _ => {}
3199 };
3200 }
3201 }
3202 });
3203
3204 cx.on_mouse_event({
3205 let editor = self.editor.clone();
3206 let position_map = layout.position_map.clone();
3207 let text_hitbox = layout.text_hitbox.clone();
3208
3209 move |event: &MouseUpEvent, phase, cx| {
3210 if phase == DispatchPhase::Bubble {
3211 editor.update(cx, |editor, cx| {
3212 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3213 });
3214 }
3215 }
3216 });
3217 cx.on_mouse_event({
3218 let position_map = layout.position_map.clone();
3219 let editor = self.editor.clone();
3220 let text_hitbox = layout.text_hitbox.clone();
3221 let gutter_hitbox = layout.gutter_hitbox.clone();
3222
3223 move |event: &MouseMoveEvent, phase, cx| {
3224 if phase == DispatchPhase::Bubble {
3225 editor.update(cx, |editor, cx| {
3226 if event.pressed_button == Some(MouseButton::Left) {
3227 Self::mouse_dragged(
3228 editor,
3229 event,
3230 &position_map,
3231 text_hitbox.bounds,
3232 cx,
3233 )
3234 }
3235
3236 Self::mouse_moved(
3237 editor,
3238 event,
3239 &position_map,
3240 &text_hitbox,
3241 &gutter_hitbox,
3242 cx,
3243 )
3244 });
3245 }
3246 }
3247 });
3248 }
3249
3250 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3251 bounds.upper_right().x - self.style.scrollbar_width
3252 }
3253
3254 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3255 let style = &self.style;
3256 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3257 let layout = cx
3258 .text_system()
3259 .shape_line(
3260 SharedString::from(" ".repeat(column)),
3261 font_size,
3262 &[TextRun {
3263 len: column,
3264 font: style.text.font(),
3265 color: Hsla::default(),
3266 background_color: None,
3267 underline: None,
3268 strikethrough: None,
3269 }],
3270 )
3271 .unwrap();
3272
3273 layout.width
3274 }
3275
3276 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3277 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
3278 self.column_pixels(digit_count, cx)
3279 }
3280}
3281
3282fn prepaint_gutter_button(
3283 button: IconButton,
3284 row: u32,
3285 line_height: Pixels,
3286 gutter_dimensions: &GutterDimensions,
3287 scroll_pixel_position: gpui::Point<Pixels>,
3288 gutter_hitbox: &Hitbox,
3289 cx: &mut WindowContext<'_>,
3290) -> AnyElement {
3291 let mut button = button.into_any_element();
3292 let available_space = size(
3293 AvailableSpace::MinContent,
3294 AvailableSpace::Definite(line_height),
3295 );
3296 let indicator_size = button.layout_as_root(available_space, cx);
3297
3298 let blame_width = gutter_dimensions
3299 .git_blame_entries_width
3300 .unwrap_or(Pixels::ZERO);
3301
3302 let mut x = blame_width;
3303 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
3304 - indicator_size.width
3305 - blame_width;
3306 x += available_width / 2.;
3307
3308 let mut y = row as f32 * line_height - scroll_pixel_position.y;
3309 y += (line_height - indicator_size.height) / 2.;
3310
3311 button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
3312 button
3313}
3314
3315fn render_inline_blame_entry(
3316 blame: &gpui::Model<GitBlame>,
3317 blame_entry: BlameEntry,
3318 style: &EditorStyle,
3319 workspace: Option<WeakView<Workspace>>,
3320 cx: &mut WindowContext<'_>,
3321) -> AnyElement {
3322 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3323
3324 let author = blame_entry.author.as_deref().unwrap_or_default();
3325 let text = format!("{}, {}", author, relative_timestamp);
3326
3327 let details = blame.read(cx).details_for_entry(&blame_entry);
3328
3329 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3330
3331 h_flex()
3332 .id("inline-blame")
3333 .w_full()
3334 .font_family(style.text.font().family)
3335 .text_color(cx.theme().status().hint)
3336 .line_height(style.text.line_height)
3337 .child(Icon::new(IconName::FileGit).color(Color::Hint))
3338 .child(text)
3339 .gap_2()
3340 .hoverable_tooltip(move |_| tooltip.clone().into())
3341 .into_any()
3342}
3343
3344fn render_blame_entry(
3345 ix: usize,
3346 blame: &gpui::Model<GitBlame>,
3347 blame_entry: BlameEntry,
3348 style: &EditorStyle,
3349 last_used_color: &mut Option<(PlayerColor, Oid)>,
3350 editor: View<Editor>,
3351 cx: &mut WindowContext<'_>,
3352) -> AnyElement {
3353 let mut sha_color = cx
3354 .theme()
3355 .players()
3356 .color_for_participant(blame_entry.sha.into());
3357 // If the last color we used is the same as the one we get for this line, but
3358 // the commit SHAs are different, then we try again to get a different color.
3359 match *last_used_color {
3360 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3361 let index: u32 = blame_entry.sha.into();
3362 sha_color = cx.theme().players().color_for_participant(index + 1);
3363 }
3364 _ => {}
3365 };
3366 last_used_color.replace((sha_color, blame_entry.sha));
3367
3368 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3369
3370 let short_commit_id = blame_entry.sha.display_short();
3371
3372 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3373 let name = util::truncate_and_trailoff(author_name, 20);
3374
3375 let details = blame.read(cx).details_for_entry(&blame_entry);
3376
3377 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3378
3379 let tooltip = cx.new_view(|_| {
3380 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3381 });
3382
3383 h_flex()
3384 .w_full()
3385 .font_family(style.text.font().family)
3386 .line_height(style.text.line_height)
3387 .id(("blame", ix))
3388 .children([
3389 div()
3390 .text_color(sha_color.cursor)
3391 .child(short_commit_id)
3392 .mr_2(),
3393 div()
3394 .w_full()
3395 .h_flex()
3396 .justify_between()
3397 .text_color(cx.theme().status().hint)
3398 .child(name)
3399 .child(relative_timestamp),
3400 ])
3401 .on_mouse_down(MouseButton::Right, {
3402 let blame_entry = blame_entry.clone();
3403 move |event, cx| {
3404 deploy_blame_entry_context_menu(&blame_entry, editor.clone(), event.position, cx);
3405 }
3406 })
3407 .hover(|style| style.bg(cx.theme().colors().element_hover))
3408 .when_some(
3409 details.and_then(|details| details.permalink),
3410 |this, url| {
3411 let url = url.clone();
3412 this.cursor_pointer().on_click(move |_, cx| {
3413 cx.stop_propagation();
3414 cx.open_url(url.as_str())
3415 })
3416 },
3417 )
3418 .hoverable_tooltip(move |_| tooltip.clone().into())
3419 .into_any()
3420}
3421
3422fn deploy_blame_entry_context_menu(
3423 blame_entry: &BlameEntry,
3424 editor: View<Editor>,
3425 position: gpui::Point<Pixels>,
3426 cx: &mut WindowContext<'_>,
3427) {
3428 let context_menu = ContextMenu::build(cx, move |this, _| {
3429 let sha = format!("{}", blame_entry.sha);
3430 this.entry("Copy commit SHA", None, move |cx| {
3431 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3432 })
3433 });
3434
3435 editor.update(cx, move |editor, cx| {
3436 editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3437 cx.notify();
3438 });
3439}
3440
3441#[derive(Debug)]
3442pub(crate) struct LineWithInvisibles {
3443 pub line: ShapedLine,
3444 invisibles: Vec<Invisible>,
3445}
3446
3447impl LineWithInvisibles {
3448 fn from_chunks<'a>(
3449 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3450 text_style: &TextStyle,
3451 max_line_len: usize,
3452 max_line_count: usize,
3453 line_number_layouts: &[Option<ShapedLine>],
3454 editor_mode: EditorMode,
3455 cx: &WindowContext,
3456 ) -> Vec<Self> {
3457 let mut layouts = Vec::with_capacity(max_line_count);
3458 let mut line = String::new();
3459 let mut invisibles = Vec::new();
3460 let mut styles = Vec::new();
3461 let mut non_whitespace_added = false;
3462 let mut row = 0;
3463 let mut line_exceeded_max_len = false;
3464 let font_size = text_style.font_size.to_pixels(cx.rem_size());
3465
3466 for highlighted_chunk in chunks.chain([HighlightedChunk {
3467 chunk: "\n",
3468 style: None,
3469 is_tab: false,
3470 }]) {
3471 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
3472 if ix > 0 {
3473 let shaped_line = cx
3474 .text_system()
3475 .shape_line(line.clone().into(), font_size, &styles)
3476 .unwrap();
3477 layouts.push(Self {
3478 line: shaped_line,
3479 invisibles: std::mem::take(&mut invisibles),
3480 });
3481
3482 line.clear();
3483 styles.clear();
3484 row += 1;
3485 line_exceeded_max_len = false;
3486 non_whitespace_added = false;
3487 if row == max_line_count {
3488 return layouts;
3489 }
3490 }
3491
3492 if !line_chunk.is_empty() && !line_exceeded_max_len {
3493 let text_style = if let Some(style) = highlighted_chunk.style {
3494 Cow::Owned(text_style.clone().highlight(style))
3495 } else {
3496 Cow::Borrowed(text_style)
3497 };
3498
3499 if line.len() + line_chunk.len() > max_line_len {
3500 let mut chunk_len = max_line_len - line.len();
3501 while !line_chunk.is_char_boundary(chunk_len) {
3502 chunk_len -= 1;
3503 }
3504 line_chunk = &line_chunk[..chunk_len];
3505 line_exceeded_max_len = true;
3506 }
3507
3508 styles.push(TextRun {
3509 len: line_chunk.len(),
3510 font: text_style.font(),
3511 color: text_style.color,
3512 background_color: text_style.background_color,
3513 underline: text_style.underline,
3514 strikethrough: text_style.strikethrough,
3515 });
3516
3517 if editor_mode == EditorMode::Full {
3518 // Line wrap pads its contents with fake whitespaces,
3519 // avoid printing them
3520 let inside_wrapped_string = line_number_layouts
3521 .get(row)
3522 .and_then(|layout| layout.as_ref())
3523 .is_none();
3524 if highlighted_chunk.is_tab {
3525 if non_whitespace_added || !inside_wrapped_string {
3526 invisibles.push(Invisible::Tab {
3527 line_start_offset: line.len(),
3528 });
3529 }
3530 } else {
3531 invisibles.extend(
3532 line_chunk
3533 .chars()
3534 .enumerate()
3535 .filter(|(_, line_char)| {
3536 let is_whitespace = line_char.is_whitespace();
3537 non_whitespace_added |= !is_whitespace;
3538 is_whitespace
3539 && (non_whitespace_added || !inside_wrapped_string)
3540 })
3541 .map(|(whitespace_index, _)| Invisible::Whitespace {
3542 line_offset: line.len() + whitespace_index,
3543 }),
3544 )
3545 }
3546 }
3547
3548 line.push_str(line_chunk);
3549 }
3550 }
3551 }
3552
3553 layouts
3554 }
3555
3556 fn draw(
3557 &self,
3558 layout: &EditorLayout,
3559 row: u32,
3560 content_origin: gpui::Point<Pixels>,
3561 whitespace_setting: ShowWhitespaceSetting,
3562 selection_ranges: &[Range<DisplayPoint>],
3563 cx: &mut WindowContext,
3564 ) {
3565 let line_height = layout.position_map.line_height;
3566 let line_y =
3567 line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
3568
3569 let line_origin =
3570 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
3571 self.line.paint(line_origin, line_height, cx).log_err();
3572
3573 self.draw_invisibles(
3574 &selection_ranges,
3575 layout,
3576 content_origin,
3577 line_y,
3578 row,
3579 line_height,
3580 whitespace_setting,
3581 cx,
3582 );
3583 }
3584
3585 #[allow(clippy::too_many_arguments)]
3586 fn draw_invisibles(
3587 &self,
3588 selection_ranges: &[Range<DisplayPoint>],
3589 layout: &EditorLayout,
3590 content_origin: gpui::Point<Pixels>,
3591 line_y: Pixels,
3592 row: u32,
3593 line_height: Pixels,
3594 whitespace_setting: ShowWhitespaceSetting,
3595 cx: &mut WindowContext,
3596 ) {
3597 let allowed_invisibles_regions = match whitespace_setting {
3598 ShowWhitespaceSetting::None => return,
3599 ShowWhitespaceSetting::Selection => Some(selection_ranges),
3600 ShowWhitespaceSetting::All => None,
3601 };
3602
3603 for invisible in &self.invisibles {
3604 let (&token_offset, invisible_symbol) = match invisible {
3605 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
3606 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
3607 };
3608
3609 let x_offset = self.line.x_for_index(token_offset);
3610 let invisible_offset =
3611 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
3612 let origin = content_origin
3613 + gpui::point(
3614 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
3615 line_y,
3616 );
3617
3618 if let Some(allowed_regions) = allowed_invisibles_regions {
3619 let invisible_point = DisplayPoint::new(row, token_offset as u32);
3620 if !allowed_regions
3621 .iter()
3622 .any(|region| region.start <= invisible_point && invisible_point < region.end)
3623 {
3624 continue;
3625 }
3626 }
3627 invisible_symbol.paint(origin, line_height, cx).log_err();
3628 }
3629 }
3630}
3631
3632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3633enum Invisible {
3634 Tab { line_start_offset: usize },
3635 Whitespace { line_offset: usize },
3636}
3637
3638impl Element for EditorElement {
3639 type RequestLayoutState = ();
3640 type PrepaintState = EditorLayout;
3641
3642 fn id(&self) -> Option<ElementId> {
3643 None
3644 }
3645
3646 fn request_layout(
3647 &mut self,
3648 _: Option<&GlobalElementId>,
3649 cx: &mut WindowContext,
3650 ) -> (gpui::LayoutId, ()) {
3651 self.editor.update(cx, |editor, cx| {
3652 editor.set_style(self.style.clone(), cx);
3653
3654 let layout_id = match editor.mode {
3655 EditorMode::SingleLine => {
3656 let rem_size = cx.rem_size();
3657 let mut style = Style::default();
3658 style.size.width = relative(1.).into();
3659 style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
3660 cx.request_layout(&style, None)
3661 }
3662 EditorMode::AutoHeight { max_lines } => {
3663 let editor_handle = cx.view().clone();
3664 let max_line_number_width =
3665 self.max_line_number_width(&editor.snapshot(cx), cx);
3666 cx.request_measured_layout(Style::default(), move |known_dimensions, _, cx| {
3667 editor_handle
3668 .update(cx, |editor, cx| {
3669 compute_auto_height_layout(
3670 editor,
3671 max_lines,
3672 max_line_number_width,
3673 known_dimensions,
3674 cx,
3675 )
3676 })
3677 .unwrap_or_default()
3678 })
3679 }
3680 EditorMode::Full => {
3681 let mut style = Style::default();
3682 style.size.width = relative(1.).into();
3683 style.size.height = relative(1.).into();
3684 cx.request_layout(&style, None)
3685 }
3686 };
3687
3688 (layout_id, ())
3689 })
3690 }
3691
3692 fn prepaint(
3693 &mut self,
3694 _: Option<&GlobalElementId>,
3695 bounds: Bounds<Pixels>,
3696 _: &mut Self::RequestLayoutState,
3697 cx: &mut WindowContext,
3698 ) -> Self::PrepaintState {
3699 let text_style = TextStyleRefinement {
3700 font_size: Some(self.style.text.font_size),
3701 line_height: Some(self.style.text.line_height),
3702 ..Default::default()
3703 };
3704 cx.set_view_id(self.editor.entity_id());
3705 cx.with_text_style(Some(text_style), |cx| {
3706 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3707 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3708 let style = self.style.clone();
3709
3710 let font_id = cx.text_system().resolve_font(&style.text.font());
3711 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3712 let line_height = style.text.line_height_in_pixels(cx.rem_size());
3713 let em_width = cx
3714 .text_system()
3715 .typographic_bounds(font_id, font_size, 'm')
3716 .unwrap()
3717 .size
3718 .width;
3719 let em_advance = cx
3720 .text_system()
3721 .advance(font_id, font_size, 'm')
3722 .unwrap()
3723 .width;
3724
3725 let gutter_dimensions = snapshot.gutter_dimensions(
3726 font_id,
3727 font_size,
3728 em_width,
3729 self.max_line_number_width(&snapshot, cx),
3730 cx,
3731 );
3732 let text_width = bounds.size.width - gutter_dimensions.width;
3733 let overscroll = size(em_width, px(0.));
3734
3735 snapshot = self.editor.update(cx, |editor, cx| {
3736 editor.last_bounds = Some(bounds);
3737 editor.gutter_dimensions = gutter_dimensions;
3738 editor.set_visible_line_count(bounds.size.height / line_height, cx);
3739
3740 let editor_width =
3741 text_width - gutter_dimensions.margin - overscroll.width - em_width;
3742 let wrap_width = match editor.soft_wrap_mode(cx) {
3743 SoftWrap::None => None,
3744 SoftWrap::PreferLine => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
3745 SoftWrap::EditorWidth => Some(editor_width),
3746 SoftWrap::Column(column) => {
3747 Some(editor_width.min(column as f32 * em_advance))
3748 }
3749 };
3750
3751 if editor.set_wrap_width(wrap_width, cx) {
3752 editor.snapshot(cx)
3753 } else {
3754 snapshot
3755 }
3756 });
3757
3758 let wrap_guides = self
3759 .editor
3760 .read(cx)
3761 .wrap_guides(cx)
3762 .iter()
3763 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
3764 .collect::<SmallVec<[_; 2]>>();
3765
3766 let hitbox = cx.insert_hitbox(bounds, false);
3767 let gutter_hitbox = cx.insert_hitbox(
3768 Bounds {
3769 origin: bounds.origin,
3770 size: size(gutter_dimensions.width, bounds.size.height),
3771 },
3772 false,
3773 );
3774 let text_hitbox = cx.insert_hitbox(
3775 Bounds {
3776 origin: gutter_hitbox.upper_right(),
3777 size: size(text_width, bounds.size.height),
3778 },
3779 false,
3780 );
3781 // Offset the content_bounds from the text_bounds by the gutter margin (which
3782 // is roughly half a character wide) to make hit testing work more like how we want.
3783 let content_origin =
3784 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
3785
3786 let mut autoscroll_containing_element = false;
3787 let mut autoscroll_horizontally = false;
3788 self.editor.update(cx, |editor, cx| {
3789 autoscroll_containing_element =
3790 editor.autoscroll_requested() || editor.has_pending_selection();
3791 autoscroll_horizontally = editor.autoscroll_vertically(bounds, line_height, cx);
3792 snapshot = editor.snapshot(cx);
3793 });
3794
3795 let mut scroll_position = snapshot.scroll_position();
3796 // The scroll position is a fractional point, the whole number of which represents
3797 // the top of the window in terms of display rows.
3798 let start_row = scroll_position.y as u32;
3799 let height_in_lines = bounds.size.height / line_height;
3800 let max_row = snapshot.max_point().row();
3801 let end_row = cmp::min(
3802 (scroll_position.y + height_in_lines).ceil() as u32,
3803 max_row + 1,
3804 );
3805
3806 let buffer_rows = snapshot
3807 .buffer_rows(start_row)
3808 .take((start_row..end_row).len());
3809
3810 let start_anchor = if start_row == 0 {
3811 Anchor::min()
3812 } else {
3813 snapshot.buffer_snapshot.anchor_before(
3814 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3815 )
3816 };
3817 let end_anchor = if end_row > max_row {
3818 Anchor::max()
3819 } else {
3820 snapshot.buffer_snapshot.anchor_before(
3821 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3822 )
3823 };
3824
3825 let highlighted_rows = self.editor.update(cx, |editor, cx| {
3826 editor.highlighted_display_rows(HashSet::default(), cx)
3827 });
3828 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3829 start_anchor..end_anchor,
3830 &snapshot.display_snapshot,
3831 cx.theme().colors(),
3832 );
3833
3834 let redacted_ranges = self.editor.read(cx).redacted_ranges(
3835 start_anchor..end_anchor,
3836 &snapshot.display_snapshot,
3837 cx,
3838 );
3839
3840 let (selections, active_rows, newest_selection_head) = self.layout_selections(
3841 start_anchor,
3842 end_anchor,
3843 &snapshot,
3844 start_row,
3845 end_row,
3846 cx,
3847 );
3848
3849 let (line_numbers, fold_statuses) = self.layout_line_numbers(
3850 start_row..end_row,
3851 buffer_rows.clone(),
3852 &active_rows,
3853 newest_selection_head,
3854 &snapshot,
3855 cx,
3856 );
3857
3858 let display_hunks = self.layout_git_gutters(
3859 line_height,
3860 &gutter_hitbox,
3861 start_row..end_row,
3862 &snapshot,
3863 cx,
3864 );
3865
3866 let mut max_visible_line_width = Pixels::ZERO;
3867 let line_layouts =
3868 self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3869 for line_with_invisibles in &line_layouts {
3870 if line_with_invisibles.line.width > max_visible_line_width {
3871 max_visible_line_width = line_with_invisibles.line.width;
3872 }
3873 }
3874
3875 let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3876 .unwrap()
3877 .width;
3878 let mut scroll_width =
3879 longest_line_width.max(max_visible_line_width) + overscroll.width;
3880
3881 let mut blocks = cx.with_element_namespace("blocks", |cx| {
3882 self.build_blocks(
3883 start_row..end_row,
3884 &snapshot,
3885 &hitbox,
3886 &text_hitbox,
3887 &mut scroll_width,
3888 &gutter_dimensions,
3889 em_width,
3890 gutter_dimensions.width + gutter_dimensions.margin,
3891 line_height,
3892 &line_layouts,
3893 cx,
3894 )
3895 });
3896
3897 let scroll_pixel_position = point(
3898 scroll_position.x * em_width,
3899 scroll_position.y * line_height,
3900 );
3901
3902 let mut inline_blame = None;
3903 if let Some(newest_selection_head) = newest_selection_head {
3904 let display_row = newest_selection_head.row();
3905 if (start_row..end_row).contains(&display_row) {
3906 let line_layout = &line_layouts[(display_row - start_row) as usize];
3907 inline_blame = self.layout_inline_blame(
3908 display_row,
3909 &snapshot.display_snapshot,
3910 line_layout,
3911 em_width,
3912 content_origin,
3913 scroll_pixel_position,
3914 line_height,
3915 cx,
3916 );
3917 }
3918 }
3919
3920 let blamed_display_rows = self.layout_blame_entries(
3921 buffer_rows,
3922 em_width,
3923 scroll_position,
3924 line_height,
3925 &gutter_hitbox,
3926 gutter_dimensions.git_blame_entries_width,
3927 cx,
3928 );
3929
3930 let scroll_max = point(
3931 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3932 max_row as f32,
3933 );
3934
3935 self.editor.update(cx, |editor, cx| {
3936 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3937
3938 let autoscrolled = if autoscroll_horizontally {
3939 editor.autoscroll_horizontally(
3940 start_row,
3941 text_hitbox.size.width,
3942 scroll_width,
3943 em_width,
3944 &line_layouts,
3945 cx,
3946 )
3947 } else {
3948 false
3949 };
3950
3951 if clamped || autoscrolled {
3952 snapshot = editor.snapshot(cx);
3953 scroll_position = snapshot.scroll_position();
3954 }
3955 });
3956
3957 cx.with_element_namespace("blocks", |cx| {
3958 self.layout_blocks(
3959 &mut blocks,
3960 &hitbox,
3961 line_height,
3962 scroll_pixel_position,
3963 cx,
3964 );
3965 });
3966
3967 let cursors = self.collect_cursors(&snapshot, cx);
3968 let visible_row_range = start_row..end_row;
3969 let non_visible_cursors = cursors
3970 .iter()
3971 .any(move |c| !visible_row_range.contains(&c.0.row()));
3972
3973 let visible_cursors = self.layout_visible_cursors(
3974 &snapshot,
3975 &selections,
3976 start_row..end_row,
3977 &line_layouts,
3978 &text_hitbox,
3979 content_origin,
3980 scroll_position,
3981 scroll_pixel_position,
3982 line_height,
3983 em_width,
3984 autoscroll_containing_element,
3985 cx,
3986 );
3987
3988 let scrollbar_layout = self.layout_scrollbar(
3989 &snapshot,
3990 bounds,
3991 scroll_position,
3992 height_in_lines,
3993 non_visible_cursors,
3994 cx,
3995 );
3996
3997 let folds = cx.with_element_namespace("folds", |cx| {
3998 self.layout_folds(
3999 &snapshot,
4000 content_origin,
4001 start_anchor..end_anchor,
4002 start_row..end_row,
4003 scroll_pixel_position,
4004 line_height,
4005 &line_layouts,
4006 cx,
4007 )
4008 });
4009
4010 let gutter_settings = EditorSettings::get_global(cx).gutter;
4011
4012 let mut context_menu_visible = false;
4013 let mut code_actions_indicator = None;
4014 if let Some(newest_selection_head) = newest_selection_head {
4015 if (start_row..end_row).contains(&newest_selection_head.row()) {
4016 context_menu_visible = self.layout_context_menu(
4017 line_height,
4018 &hitbox,
4019 &text_hitbox,
4020 content_origin,
4021 start_row,
4022 scroll_pixel_position,
4023 &line_layouts,
4024 newest_selection_head,
4025 gutter_dimensions.width - gutter_dimensions.left_padding,
4026 cx,
4027 );
4028 if gutter_settings.code_actions {
4029 let newest_selection_point =
4030 newest_selection_head.to_point(&snapshot.display_snapshot);
4031 let has_test_indicator = self
4032 .editor
4033 .read(cx)
4034 .tasks
4035 .contains_key(&newest_selection_point.row);
4036 if !has_test_indicator {
4037 code_actions_indicator = self.layout_code_actions_indicator(
4038 line_height,
4039 newest_selection_head,
4040 scroll_pixel_position,
4041 &gutter_dimensions,
4042 &gutter_hitbox,
4043 cx,
4044 );
4045 }
4046 }
4047 }
4048 }
4049
4050 let test_indicators = self.layout_run_indicators(
4051 line_height,
4052 scroll_pixel_position,
4053 &gutter_dimensions,
4054 &gutter_hitbox,
4055 &snapshot,
4056 cx,
4057 );
4058
4059 if !context_menu_visible && !cx.has_active_drag() {
4060 self.layout_hover_popovers(
4061 &snapshot,
4062 &hitbox,
4063 &text_hitbox,
4064 start_row..end_row,
4065 content_origin,
4066 scroll_pixel_position,
4067 &line_layouts,
4068 line_height,
4069 em_width,
4070 cx,
4071 );
4072 }
4073
4074 let mouse_context_menu = self.layout_mouse_context_menu(cx);
4075
4076 let fold_indicators = if gutter_settings.folds {
4077 cx.with_element_namespace("gutter_fold_indicators", |cx| {
4078 self.layout_gutter_fold_indicators(
4079 fold_statuses,
4080 line_height,
4081 &gutter_dimensions,
4082 gutter_settings,
4083 scroll_pixel_position,
4084 &gutter_hitbox,
4085 cx,
4086 )
4087 })
4088 } else {
4089 Vec::new()
4090 };
4091
4092 let invisible_symbol_font_size = font_size / 2.;
4093 let tab_invisible = cx
4094 .text_system()
4095 .shape_line(
4096 "→".into(),
4097 invisible_symbol_font_size,
4098 &[TextRun {
4099 len: "→".len(),
4100 font: self.style.text.font(),
4101 color: cx.theme().colors().editor_invisible,
4102 background_color: None,
4103 underline: None,
4104 strikethrough: None,
4105 }],
4106 )
4107 .unwrap();
4108 let space_invisible = cx
4109 .text_system()
4110 .shape_line(
4111 "•".into(),
4112 invisible_symbol_font_size,
4113 &[TextRun {
4114 len: "•".len(),
4115 font: self.style.text.font(),
4116 color: cx.theme().colors().editor_invisible,
4117 background_color: None,
4118 underline: None,
4119 strikethrough: None,
4120 }],
4121 )
4122 .unwrap();
4123
4124 EditorLayout {
4125 mode: snapshot.mode,
4126 position_map: Arc::new(PositionMap {
4127 size: bounds.size,
4128 scroll_pixel_position,
4129 scroll_max,
4130 line_layouts,
4131 line_height,
4132 em_width,
4133 em_advance,
4134 snapshot,
4135 }),
4136 visible_display_row_range: start_row..end_row,
4137 wrap_guides,
4138 hitbox,
4139 text_hitbox,
4140 gutter_hitbox,
4141 gutter_dimensions,
4142 content_origin,
4143 scrollbar_layout,
4144 max_row,
4145 active_rows,
4146 highlighted_rows,
4147 highlighted_ranges,
4148 redacted_ranges,
4149 line_numbers,
4150 display_hunks,
4151 blamed_display_rows,
4152 inline_blame,
4153 folds,
4154 blocks,
4155 cursors,
4156 visible_cursors,
4157 selections,
4158 mouse_context_menu,
4159 test_indicators,
4160 code_actions_indicator,
4161 fold_indicators,
4162 tab_invisible,
4163 space_invisible,
4164 }
4165 })
4166 })
4167 }
4168
4169 fn paint(
4170 &mut self,
4171 _: Option<&GlobalElementId>,
4172 bounds: Bounds<gpui::Pixels>,
4173 _: &mut Self::RequestLayoutState,
4174 layout: &mut Self::PrepaintState,
4175 cx: &mut WindowContext,
4176 ) {
4177 let focus_handle = self.editor.focus_handle(cx);
4178 let key_context = self.editor.read(cx).key_context(cx);
4179 cx.set_focus_handle(&focus_handle);
4180 cx.set_key_context(key_context);
4181 cx.handle_input(
4182 &focus_handle,
4183 ElementInputHandler::new(bounds, self.editor.clone()),
4184 );
4185 self.register_actions(cx);
4186 self.register_key_listeners(cx, layout);
4187
4188 let text_style = TextStyleRefinement {
4189 font_size: Some(self.style.text.font_size),
4190 line_height: Some(self.style.text.line_height),
4191 ..Default::default()
4192 };
4193 let mouse_position = cx.mouse_position();
4194 let hovered_hunk = layout
4195 .display_hunks
4196 .iter()
4197 .find_map(|(hunk, hunk_hitbox)| match hunk {
4198 DisplayDiffHunk::Folded { .. } => None,
4199 DisplayDiffHunk::Unfolded {
4200 diff_base_byte_range,
4201 multi_buffer_range,
4202 status,
4203 ..
4204 } => {
4205 if hunk_hitbox
4206 .as_ref()
4207 .map(|hitbox| hitbox.contains(&mouse_position))
4208 .unwrap_or(false)
4209 {
4210 Some(HunkToExpand {
4211 status: *status,
4212 multi_buffer_range: multi_buffer_range.clone(),
4213 diff_base_byte_range: diff_base_byte_range.clone(),
4214 })
4215 } else {
4216 None
4217 }
4218 }
4219 });
4220 cx.with_text_style(Some(text_style), |cx| {
4221 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4222 self.paint_mouse_listeners(layout, hovered_hunk, cx);
4223 self.paint_background(layout, cx);
4224 if layout.gutter_hitbox.size.width > Pixels::ZERO {
4225 self.paint_gutter(layout, cx)
4226 }
4227
4228 self.paint_text(layout, cx);
4229
4230 if !layout.blocks.is_empty() {
4231 cx.with_element_namespace("blocks", |cx| {
4232 self.paint_blocks(layout, cx);
4233 });
4234 }
4235
4236 self.paint_scrollbar(layout, cx);
4237 self.paint_mouse_context_menu(layout, cx);
4238 });
4239 })
4240 }
4241}
4242
4243impl IntoElement for EditorElement {
4244 type Element = Self;
4245
4246 fn into_element(self) -> Self::Element {
4247 self
4248 }
4249}
4250
4251type BufferRow = u32;
4252
4253pub struct EditorLayout {
4254 position_map: Arc<PositionMap>,
4255 hitbox: Hitbox,
4256 text_hitbox: Hitbox,
4257 gutter_hitbox: Hitbox,
4258 gutter_dimensions: GutterDimensions,
4259 content_origin: gpui::Point<Pixels>,
4260 scrollbar_layout: Option<ScrollbarLayout>,
4261 mode: EditorMode,
4262 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
4263 visible_display_row_range: Range<u32>,
4264 active_rows: BTreeMap<u32, bool>,
4265 highlighted_rows: BTreeMap<u32, Hsla>,
4266 line_numbers: Vec<Option<ShapedLine>>,
4267 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
4268 blamed_display_rows: Option<Vec<AnyElement>>,
4269 inline_blame: Option<AnyElement>,
4270 folds: Vec<FoldLayout>,
4271 blocks: Vec<BlockLayout>,
4272 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
4273 redacted_ranges: Vec<Range<DisplayPoint>>,
4274 cursors: Vec<(DisplayPoint, Hsla)>,
4275 visible_cursors: Vec<CursorLayout>,
4276 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
4277 max_row: u32,
4278 code_actions_indicator: Option<AnyElement>,
4279 test_indicators: Vec<AnyElement>,
4280 fold_indicators: Vec<Option<AnyElement>>,
4281 mouse_context_menu: Option<AnyElement>,
4282 tab_invisible: ShapedLine,
4283 space_invisible: ShapedLine,
4284}
4285
4286impl EditorLayout {
4287 fn line_end_overshoot(&self) -> Pixels {
4288 0.15 * self.position_map.line_height
4289 }
4290}
4291
4292struct ColoredRange<T> {
4293 start: T,
4294 end: T,
4295 color: Hsla,
4296}
4297
4298#[derive(Clone)]
4299struct ScrollbarLayout {
4300 hitbox: Hitbox,
4301 visible_row_range: Range<f32>,
4302 visible: bool,
4303 row_height: Pixels,
4304 thumb_height: Pixels,
4305}
4306
4307impl ScrollbarLayout {
4308 const BORDER_WIDTH: Pixels = px(1.0);
4309 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
4310 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
4311 const MIN_THUMB_HEIGHT: Pixels = px(20.0);
4312
4313 fn thumb_bounds(&self) -> Bounds<Pixels> {
4314 let thumb_top = self.y_for_row(self.visible_row_range.start);
4315 let thumb_bottom = thumb_top + self.thumb_height;
4316 Bounds::from_corners(
4317 point(self.hitbox.left(), thumb_top),
4318 point(self.hitbox.right(), thumb_bottom),
4319 )
4320 }
4321
4322 fn y_for_row(&self, row: f32) -> Pixels {
4323 self.hitbox.top() + row * self.row_height
4324 }
4325
4326 fn marker_quads_for_ranges(
4327 &self,
4328 row_ranges: impl IntoIterator<Item = ColoredRange<u32>>,
4329 column: Option<usize>,
4330 ) -> Vec<PaintQuad> {
4331 struct MinMax {
4332 min: Pixels,
4333 max: Pixels,
4334 }
4335 let (x_range, height_limit) = if let Some(column) = column {
4336 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
4337 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
4338 let end = start + column_width;
4339 (
4340 Range { start, end },
4341 MinMax {
4342 min: Self::MIN_MARKER_HEIGHT,
4343 max: px(f32::MAX),
4344 },
4345 )
4346 } else {
4347 (
4348 Range {
4349 start: Self::BORDER_WIDTH,
4350 end: self.hitbox.size.width,
4351 },
4352 MinMax {
4353 min: Self::LINE_MARKER_HEIGHT,
4354 max: Self::LINE_MARKER_HEIGHT,
4355 },
4356 )
4357 };
4358
4359 let row_to_y = |row: u32| row as f32 * self.row_height;
4360 let mut pixel_ranges = row_ranges
4361 .into_iter()
4362 .map(|range| {
4363 let start_y = row_to_y(range.start);
4364 let end_y = row_to_y(range.end)
4365 + self.row_height.max(height_limit.min).min(height_limit.max);
4366 ColoredRange {
4367 start: start_y,
4368 end: end_y,
4369 color: range.color,
4370 }
4371 })
4372 .peekable();
4373
4374 let mut quads = Vec::new();
4375 while let Some(mut pixel_range) = pixel_ranges.next() {
4376 while let Some(next_pixel_range) = pixel_ranges.peek() {
4377 if pixel_range.end >= next_pixel_range.start - px(1.0)
4378 && pixel_range.color == next_pixel_range.color
4379 {
4380 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
4381 pixel_ranges.next();
4382 } else {
4383 break;
4384 }
4385 }
4386
4387 let bounds = Bounds::from_corners(
4388 point(x_range.start, pixel_range.start),
4389 point(x_range.end, pixel_range.end),
4390 );
4391 quads.push(quad(
4392 bounds,
4393 Corners::default(),
4394 pixel_range.color,
4395 Edges::default(),
4396 Hsla::transparent_black(),
4397 ));
4398 }
4399
4400 quads
4401 }
4402}
4403
4404struct FoldLayout {
4405 display_range: Range<DisplayPoint>,
4406 hover_element: AnyElement,
4407}
4408
4409struct PositionMap {
4410 size: Size<Pixels>,
4411 line_height: Pixels,
4412 scroll_pixel_position: gpui::Point<Pixels>,
4413 scroll_max: gpui::Point<f32>,
4414 em_width: Pixels,
4415 em_advance: Pixels,
4416 line_layouts: Vec<LineWithInvisibles>,
4417 snapshot: EditorSnapshot,
4418}
4419
4420#[derive(Debug, Copy, Clone)]
4421pub struct PointForPosition {
4422 pub previous_valid: DisplayPoint,
4423 pub next_valid: DisplayPoint,
4424 pub exact_unclipped: DisplayPoint,
4425 pub column_overshoot_after_line_end: u32,
4426}
4427
4428impl PointForPosition {
4429 pub fn as_valid(&self) -> Option<DisplayPoint> {
4430 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
4431 Some(self.previous_valid)
4432 } else {
4433 None
4434 }
4435 }
4436}
4437
4438impl PositionMap {
4439 fn point_for_position(
4440 &self,
4441 text_bounds: Bounds<Pixels>,
4442 position: gpui::Point<Pixels>,
4443 ) -> PointForPosition {
4444 let scroll_position = self.snapshot.scroll_position();
4445 let position = position - text_bounds.origin;
4446 let y = position.y.max(px(0.)).min(self.size.height);
4447 let x = position.x + (scroll_position.x * self.em_width);
4448 let row = ((y / self.line_height) + scroll_position.y) as u32;
4449
4450 let (column, x_overshoot_after_line_end) = if let Some(line) = self
4451 .line_layouts
4452 .get(row as usize - scroll_position.y as usize)
4453 .map(|LineWithInvisibles { line, .. }| line)
4454 {
4455 if let Some(ix) = line.index_for_x(x) {
4456 (ix as u32, px(0.))
4457 } else {
4458 (line.len as u32, px(0.).max(x - line.width))
4459 }
4460 } else {
4461 (0, x)
4462 };
4463
4464 let mut exact_unclipped = DisplayPoint::new(row, column);
4465 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
4466 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
4467
4468 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
4469 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
4470 PointForPosition {
4471 previous_valid,
4472 next_valid,
4473 exact_unclipped,
4474 column_overshoot_after_line_end,
4475 }
4476 }
4477}
4478
4479struct BlockLayout {
4480 row: u32,
4481 element: AnyElement,
4482 available_space: Size<AvailableSpace>,
4483 style: BlockStyle,
4484}
4485
4486fn layout_line(
4487 row: u32,
4488 snapshot: &EditorSnapshot,
4489 style: &EditorStyle,
4490 cx: &WindowContext,
4491) -> Result<ShapedLine> {
4492 let mut line = snapshot.line(row);
4493
4494 if line.len() > MAX_LINE_LEN {
4495 let mut len = MAX_LINE_LEN;
4496 while !line.is_char_boundary(len) {
4497 len -= 1;
4498 }
4499
4500 line.truncate(len);
4501 }
4502
4503 cx.text_system().shape_line(
4504 line.into(),
4505 style.text.font_size.to_pixels(cx.rem_size()),
4506 &[TextRun {
4507 len: snapshot.line_len(row) as usize,
4508 font: style.text.font(),
4509 color: Hsla::default(),
4510 background_color: None,
4511 underline: None,
4512 strikethrough: None,
4513 }],
4514 )
4515}
4516
4517pub struct CursorLayout {
4518 origin: gpui::Point<Pixels>,
4519 block_width: Pixels,
4520 line_height: Pixels,
4521 color: Hsla,
4522 shape: CursorShape,
4523 block_text: Option<ShapedLine>,
4524 cursor_name: Option<AnyElement>,
4525}
4526
4527#[derive(Debug)]
4528pub struct CursorName {
4529 string: SharedString,
4530 color: Hsla,
4531 is_top_row: bool,
4532}
4533
4534impl CursorLayout {
4535 pub fn new(
4536 origin: gpui::Point<Pixels>,
4537 block_width: Pixels,
4538 line_height: Pixels,
4539 color: Hsla,
4540 shape: CursorShape,
4541 block_text: Option<ShapedLine>,
4542 ) -> CursorLayout {
4543 CursorLayout {
4544 origin,
4545 block_width,
4546 line_height,
4547 color,
4548 shape,
4549 block_text,
4550 cursor_name: None,
4551 }
4552 }
4553
4554 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4555 Bounds {
4556 origin: self.origin + origin,
4557 size: size(self.block_width, self.line_height),
4558 }
4559 }
4560
4561 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4562 match self.shape {
4563 CursorShape::Bar => Bounds {
4564 origin: self.origin + origin,
4565 size: size(px(2.0), self.line_height),
4566 },
4567 CursorShape::Block | CursorShape::Hollow => Bounds {
4568 origin: self.origin + origin,
4569 size: size(self.block_width, self.line_height),
4570 },
4571 CursorShape::Underscore => Bounds {
4572 origin: self.origin
4573 + origin
4574 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
4575 size: size(self.block_width, px(2.0)),
4576 },
4577 }
4578 }
4579
4580 pub fn layout(
4581 &mut self,
4582 origin: gpui::Point<Pixels>,
4583 cursor_name: Option<CursorName>,
4584 cx: &mut WindowContext,
4585 ) {
4586 if let Some(cursor_name) = cursor_name {
4587 let bounds = self.bounds(origin);
4588 let text_size = self.line_height / 1.5;
4589
4590 let name_origin = if cursor_name.is_top_row {
4591 point(bounds.right() - px(1.), bounds.top())
4592 } else {
4593 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
4594 };
4595 let mut name_element = div()
4596 .bg(self.color)
4597 .text_size(text_size)
4598 .px_0p5()
4599 .line_height(text_size + px(2.))
4600 .text_color(cursor_name.color)
4601 .child(cursor_name.string.clone())
4602 .into_any_element();
4603
4604 name_element.prepaint_as_root(
4605 name_origin,
4606 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
4607 cx,
4608 );
4609
4610 self.cursor_name = Some(name_element);
4611 }
4612 }
4613
4614 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
4615 let bounds = self.bounds(origin);
4616
4617 //Draw background or border quad
4618 let cursor = if matches!(self.shape, CursorShape::Hollow) {
4619 outline(bounds, self.color)
4620 } else {
4621 fill(bounds, self.color)
4622 };
4623
4624 if let Some(name) = &mut self.cursor_name {
4625 name.paint(cx);
4626 }
4627
4628 cx.paint_quad(cursor);
4629
4630 if let Some(block_text) = &self.block_text {
4631 block_text
4632 .paint(self.origin + origin, self.line_height, cx)
4633 .log_err();
4634 }
4635 }
4636
4637 pub fn shape(&self) -> CursorShape {
4638 self.shape
4639 }
4640}
4641
4642#[derive(Debug)]
4643pub struct HighlightedRange {
4644 pub start_y: Pixels,
4645 pub line_height: Pixels,
4646 pub lines: Vec<HighlightedRangeLine>,
4647 pub color: Hsla,
4648 pub corner_radius: Pixels,
4649}
4650
4651#[derive(Debug)]
4652pub struct HighlightedRangeLine {
4653 pub start_x: Pixels,
4654 pub end_x: Pixels,
4655}
4656
4657impl HighlightedRange {
4658 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
4659 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
4660 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
4661 self.paint_lines(
4662 self.start_y + self.line_height,
4663 &self.lines[1..],
4664 bounds,
4665 cx,
4666 );
4667 } else {
4668 self.paint_lines(self.start_y, &self.lines, bounds, cx);
4669 }
4670 }
4671
4672 fn paint_lines(
4673 &self,
4674 start_y: Pixels,
4675 lines: &[HighlightedRangeLine],
4676 _bounds: Bounds<Pixels>,
4677 cx: &mut WindowContext,
4678 ) {
4679 if lines.is_empty() {
4680 return;
4681 }
4682
4683 let first_line = lines.first().unwrap();
4684 let last_line = lines.last().unwrap();
4685
4686 let first_top_left = point(first_line.start_x, start_y);
4687 let first_top_right = point(first_line.end_x, start_y);
4688
4689 let curve_height = point(Pixels::ZERO, self.corner_radius);
4690 let curve_width = |start_x: Pixels, end_x: Pixels| {
4691 let max = (end_x - start_x) / 2.;
4692 let width = if max < self.corner_radius {
4693 max
4694 } else {
4695 self.corner_radius
4696 };
4697
4698 point(width, Pixels::ZERO)
4699 };
4700
4701 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
4702 let mut path = gpui::Path::new(first_top_right - top_curve_width);
4703 path.curve_to(first_top_right + curve_height, first_top_right);
4704
4705 let mut iter = lines.iter().enumerate().peekable();
4706 while let Some((ix, line)) = iter.next() {
4707 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
4708
4709 if let Some((_, next_line)) = iter.peek() {
4710 let next_top_right = point(next_line.end_x, bottom_right.y);
4711
4712 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
4713 Ordering::Equal => {
4714 path.line_to(bottom_right);
4715 }
4716 Ordering::Less => {
4717 let curve_width = curve_width(next_top_right.x, bottom_right.x);
4718 path.line_to(bottom_right - curve_height);
4719 if self.corner_radius > Pixels::ZERO {
4720 path.curve_to(bottom_right - curve_width, bottom_right);
4721 }
4722 path.line_to(next_top_right + curve_width);
4723 if self.corner_radius > Pixels::ZERO {
4724 path.curve_to(next_top_right + curve_height, next_top_right);
4725 }
4726 }
4727 Ordering::Greater => {
4728 let curve_width = curve_width(bottom_right.x, next_top_right.x);
4729 path.line_to(bottom_right - curve_height);
4730 if self.corner_radius > Pixels::ZERO {
4731 path.curve_to(bottom_right + curve_width, bottom_right);
4732 }
4733 path.line_to(next_top_right - curve_width);
4734 if self.corner_radius > Pixels::ZERO {
4735 path.curve_to(next_top_right + curve_height, next_top_right);
4736 }
4737 }
4738 }
4739 } else {
4740 let curve_width = curve_width(line.start_x, line.end_x);
4741 path.line_to(bottom_right - curve_height);
4742 if self.corner_radius > Pixels::ZERO {
4743 path.curve_to(bottom_right - curve_width, bottom_right);
4744 }
4745
4746 let bottom_left = point(line.start_x, bottom_right.y);
4747 path.line_to(bottom_left + curve_width);
4748 if self.corner_radius > Pixels::ZERO {
4749 path.curve_to(bottom_left - curve_height, bottom_left);
4750 }
4751 }
4752 }
4753
4754 if first_line.start_x > last_line.start_x {
4755 let curve_width = curve_width(last_line.start_x, first_line.start_x);
4756 let second_top_left = point(last_line.start_x, start_y + self.line_height);
4757 path.line_to(second_top_left + curve_height);
4758 if self.corner_radius > Pixels::ZERO {
4759 path.curve_to(second_top_left + curve_width, second_top_left);
4760 }
4761 let first_bottom_left = point(first_line.start_x, second_top_left.y);
4762 path.line_to(first_bottom_left - curve_width);
4763 if self.corner_radius > Pixels::ZERO {
4764 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
4765 }
4766 }
4767
4768 path.line_to(first_top_left + curve_height);
4769 if self.corner_radius > Pixels::ZERO {
4770 path.curve_to(first_top_left + top_curve_width, first_top_left);
4771 }
4772 path.line_to(first_top_right - top_curve_width);
4773
4774 cx.paint_path(path, self.color);
4775 }
4776}
4777
4778pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4779 (delta.pow(1.5) / 100.0).into()
4780}
4781
4782fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4783 (delta.pow(1.2) / 300.0).into()
4784}
4785
4786#[cfg(test)]
4787mod tests {
4788 use super::*;
4789 use crate::{
4790 display_map::{BlockDisposition, BlockProperties},
4791 editor_tests::{init_test, update_test_language_settings},
4792 Editor, MultiBuffer,
4793 };
4794 use gpui::{TestAppContext, VisualTestContext};
4795 use language::language_settings;
4796 use log::info;
4797 use std::num::NonZeroU32;
4798 use ui::Context;
4799 use util::test::sample_text;
4800
4801 #[gpui::test]
4802 fn test_shape_line_numbers(cx: &mut TestAppContext) {
4803 init_test(cx, |_| {});
4804 let window = cx.add_window(|cx| {
4805 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4806 Editor::new(EditorMode::Full, buffer, None, cx)
4807 });
4808
4809 let editor = window.root(cx).unwrap();
4810 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4811 let element = EditorElement::new(&editor, style);
4812 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
4813
4814 let layouts = cx
4815 .update_window(*window, |_, cx| {
4816 element
4817 .layout_line_numbers(
4818 0..6,
4819 (0..6).map(Some),
4820 &Default::default(),
4821 Some(DisplayPoint::new(0, 0)),
4822 &snapshot,
4823 cx,
4824 )
4825 .0
4826 })
4827 .unwrap();
4828 assert_eq!(layouts.len(), 6);
4829
4830 let relative_rows = window
4831 .update(cx, |editor, cx| {
4832 let snapshot = editor.snapshot(cx);
4833 element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
4834 })
4835 .unwrap();
4836 assert_eq!(relative_rows[&0], 3);
4837 assert_eq!(relative_rows[&1], 2);
4838 assert_eq!(relative_rows[&2], 1);
4839 // current line has no relative number
4840 assert_eq!(relative_rows[&4], 1);
4841 assert_eq!(relative_rows[&5], 2);
4842
4843 // works if cursor is before screen
4844 let relative_rows = window
4845 .update(cx, |editor, cx| {
4846 let snapshot = editor.snapshot(cx);
4847 element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
4848 })
4849 .unwrap();
4850 assert_eq!(relative_rows.len(), 3);
4851 assert_eq!(relative_rows[&3], 2);
4852 assert_eq!(relative_rows[&4], 3);
4853 assert_eq!(relative_rows[&5], 4);
4854
4855 // works if cursor is after screen
4856 let relative_rows = window
4857 .update(cx, |editor, cx| {
4858 let snapshot = editor.snapshot(cx);
4859 element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
4860 })
4861 .unwrap();
4862 assert_eq!(relative_rows.len(), 3);
4863 assert_eq!(relative_rows[&0], 5);
4864 assert_eq!(relative_rows[&1], 4);
4865 assert_eq!(relative_rows[&2], 3);
4866 }
4867
4868 #[gpui::test]
4869 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
4870 init_test(cx, |_| {});
4871
4872 let window = cx.add_window(|cx| {
4873 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
4874 Editor::new(EditorMode::Full, buffer, None, cx)
4875 });
4876 let cx = &mut VisualTestContext::from_window(*window, cx);
4877 let editor = window.root(cx).unwrap();
4878 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4879
4880 window
4881 .update(cx, |editor, cx| {
4882 editor.cursor_shape = CursorShape::Block;
4883 editor.change_selections(None, cx, |s| {
4884 s.select_ranges([
4885 Point::new(0, 0)..Point::new(1, 0),
4886 Point::new(3, 2)..Point::new(3, 3),
4887 Point::new(5, 6)..Point::new(6, 0),
4888 ]);
4889 });
4890 })
4891 .unwrap();
4892
4893 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
4894 EditorElement::new(&editor, style)
4895 });
4896
4897 assert_eq!(state.selections.len(), 1);
4898 let local_selections = &state.selections[0].1;
4899 assert_eq!(local_selections.len(), 3);
4900 // moves cursor back one line
4901 assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
4902 assert_eq!(
4903 local_selections[0].range,
4904 DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
4905 );
4906
4907 // moves cursor back one column
4908 assert_eq!(
4909 local_selections[1].range,
4910 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
4911 );
4912 assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
4913
4914 // leaves cursor on the max point
4915 assert_eq!(
4916 local_selections[2].range,
4917 DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
4918 );
4919 assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
4920
4921 // active lines does not include 1 (even though the range of the selection does)
4922 assert_eq!(
4923 state.active_rows.keys().cloned().collect::<Vec<u32>>(),
4924 vec![0, 3, 5, 6]
4925 );
4926
4927 // multi-buffer support
4928 // in DisplayPoint coordinates, this is what we're dealing with:
4929 // 0: [[file
4930 // 1: header]]
4931 // 2: aaaaaa
4932 // 3: bbbbbb
4933 // 4: cccccc
4934 // 5:
4935 // 6: ...
4936 // 7: ffffff
4937 // 8: gggggg
4938 // 9: hhhhhh
4939 // 10:
4940 // 11: [[file
4941 // 12: header]]
4942 // 13: bbbbbb
4943 // 14: cccccc
4944 // 15: dddddd
4945 let window = cx.add_window(|cx| {
4946 let buffer = MultiBuffer::build_multi(
4947 [
4948 (
4949 &(sample_text(8, 6, 'a') + "\n"),
4950 vec![
4951 Point::new(0, 0)..Point::new(3, 0),
4952 Point::new(4, 0)..Point::new(7, 0),
4953 ],
4954 ),
4955 (
4956 &(sample_text(8, 6, 'a') + "\n"),
4957 vec![Point::new(1, 0)..Point::new(3, 0)],
4958 ),
4959 ],
4960 cx,
4961 );
4962 Editor::new(EditorMode::Full, buffer, None, cx)
4963 });
4964 let editor = window.root(cx).unwrap();
4965 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4966 let _state = window.update(cx, |editor, cx| {
4967 editor.cursor_shape = CursorShape::Block;
4968 editor.change_selections(None, cx, |s| {
4969 s.select_display_ranges([
4970 DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4971 DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4972 ]);
4973 });
4974 });
4975
4976 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
4977 EditorElement::new(&editor, style)
4978 });
4979 assert_eq!(state.selections.len(), 1);
4980 let local_selections = &state.selections[0].1;
4981 assert_eq!(local_selections.len(), 2);
4982
4983 // moves cursor on excerpt boundary back a line
4984 // and doesn't allow selection to bleed through
4985 assert_eq!(
4986 local_selections[0].range,
4987 DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
4988 );
4989 assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
4990 // moves cursor on buffer boundary back two lines
4991 // and doesn't allow selection to bleed through
4992 assert_eq!(
4993 local_selections[1].range,
4994 DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
4995 );
4996 assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
4997 }
4998
4999 #[gpui::test]
5000 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
5001 init_test(cx, |_| {});
5002
5003 let window = cx.add_window(|cx| {
5004 let buffer = MultiBuffer::build_simple("", cx);
5005 Editor::new(EditorMode::Full, buffer, None, cx)
5006 });
5007 let cx = &mut VisualTestContext::from_window(*window, cx);
5008 let editor = window.root(cx).unwrap();
5009 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5010 window
5011 .update(cx, |editor, cx| {
5012 editor.set_placeholder_text("hello", cx);
5013 editor.insert_blocks(
5014 [BlockProperties {
5015 style: BlockStyle::Fixed,
5016 disposition: BlockDisposition::Above,
5017 height: 3,
5018 position: Anchor::min(),
5019 render: Box::new(|_| div().into_any()),
5020 }],
5021 None,
5022 cx,
5023 );
5024
5025 // Blur the editor so that it displays placeholder text.
5026 cx.blur();
5027 })
5028 .unwrap();
5029
5030 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5031 EditorElement::new(&editor, style)
5032 });
5033 assert_eq!(state.position_map.line_layouts.len(), 4);
5034 assert_eq!(
5035 state
5036 .line_numbers
5037 .iter()
5038 .map(Option::is_some)
5039 .collect::<Vec<_>>(),
5040 &[false, false, false, true]
5041 );
5042 }
5043
5044 #[gpui::test]
5045 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
5046 const TAB_SIZE: u32 = 4;
5047
5048 let input_text = "\t \t|\t| a b";
5049 let expected_invisibles = vec![
5050 Invisible::Tab {
5051 line_start_offset: 0,
5052 },
5053 Invisible::Whitespace {
5054 line_offset: TAB_SIZE as usize,
5055 },
5056 Invisible::Tab {
5057 line_start_offset: TAB_SIZE as usize + 1,
5058 },
5059 Invisible::Tab {
5060 line_start_offset: TAB_SIZE as usize * 2 + 1,
5061 },
5062 Invisible::Whitespace {
5063 line_offset: TAB_SIZE as usize * 3 + 1,
5064 },
5065 Invisible::Whitespace {
5066 line_offset: TAB_SIZE as usize * 3 + 3,
5067 },
5068 ];
5069 assert_eq!(
5070 expected_invisibles.len(),
5071 input_text
5072 .chars()
5073 .filter(|initial_char| initial_char.is_whitespace())
5074 .count(),
5075 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
5076 );
5077
5078 init_test(cx, |s| {
5079 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
5080 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
5081 });
5082
5083 let actual_invisibles =
5084 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
5085
5086 assert_eq!(expected_invisibles, actual_invisibles);
5087 }
5088
5089 #[gpui::test]
5090 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
5091 init_test(cx, |s| {
5092 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
5093 s.defaults.tab_size = NonZeroU32::new(4);
5094 });
5095
5096 for editor_mode_without_invisibles in [
5097 EditorMode::SingleLine,
5098 EditorMode::AutoHeight { max_lines: 100 },
5099 ] {
5100 let invisibles = collect_invisibles_from_new_editor(
5101 cx,
5102 editor_mode_without_invisibles,
5103 "\t\t\t| | a b",
5104 px(500.0),
5105 );
5106 assert!(invisibles.is_empty(),
5107 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
5108 }
5109 }
5110
5111 #[gpui::test]
5112 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
5113 let tab_size = 4;
5114 let input_text = "a\tbcd ".repeat(9);
5115 let repeated_invisibles = [
5116 Invisible::Tab {
5117 line_start_offset: 1,
5118 },
5119 Invisible::Whitespace {
5120 line_offset: tab_size as usize + 3,
5121 },
5122 Invisible::Whitespace {
5123 line_offset: tab_size as usize + 4,
5124 },
5125 Invisible::Whitespace {
5126 line_offset: tab_size as usize + 5,
5127 },
5128 ];
5129 let expected_invisibles = std::iter::once(repeated_invisibles)
5130 .cycle()
5131 .take(9)
5132 .flatten()
5133 .collect::<Vec<_>>();
5134 assert_eq!(
5135 expected_invisibles.len(),
5136 input_text
5137 .chars()
5138 .filter(|initial_char| initial_char.is_whitespace())
5139 .count(),
5140 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
5141 );
5142 info!("Expected invisibles: {expected_invisibles:?}");
5143
5144 init_test(cx, |_| {});
5145
5146 // Put the same string with repeating whitespace pattern into editors of various size,
5147 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
5148 let resize_step = 10.0;
5149 let mut editor_width = 200.0;
5150 while editor_width <= 1000.0 {
5151 update_test_language_settings(cx, |s| {
5152 s.defaults.tab_size = NonZeroU32::new(tab_size);
5153 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
5154 s.defaults.preferred_line_length = Some(editor_width as u32);
5155 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
5156 });
5157
5158 let actual_invisibles = collect_invisibles_from_new_editor(
5159 cx,
5160 EditorMode::Full,
5161 &input_text,
5162 px(editor_width),
5163 );
5164
5165 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
5166 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
5167 let mut i = 0;
5168 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
5169 i = actual_index;
5170 match expected_invisibles.get(i) {
5171 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
5172 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
5173 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
5174 _ => {
5175 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
5176 }
5177 },
5178 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
5179 }
5180 }
5181 let missing_expected_invisibles = &expected_invisibles[i + 1..];
5182 assert!(
5183 missing_expected_invisibles.is_empty(),
5184 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
5185 );
5186
5187 editor_width += resize_step;
5188 }
5189 }
5190
5191 fn collect_invisibles_from_new_editor(
5192 cx: &mut TestAppContext,
5193 editor_mode: EditorMode,
5194 input_text: &str,
5195 editor_width: Pixels,
5196 ) -> Vec<Invisible> {
5197 info!(
5198 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
5199 editor_width.0
5200 );
5201 let window = cx.add_window(|cx| {
5202 let buffer = MultiBuffer::build_simple(&input_text, cx);
5203 Editor::new(editor_mode, buffer, None, cx)
5204 });
5205 let cx = &mut VisualTestContext::from_window(*window, cx);
5206 let editor = window.root(cx).unwrap();
5207 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5208 window
5209 .update(cx, |editor, cx| {
5210 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
5211 editor.set_wrap_width(Some(editor_width), cx);
5212 })
5213 .unwrap();
5214 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5215 EditorElement::new(&editor, style)
5216 });
5217 state
5218 .position_map
5219 .line_layouts
5220 .iter()
5221 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
5222 .cloned()
5223 .collect()
5224 }
5225}
5226
5227pub fn register_action<T: Action>(
5228 view: &View<Editor>,
5229 cx: &mut WindowContext,
5230 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
5231) {
5232 let view = view.clone();
5233 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
5234 let action = action.downcast_ref().unwrap();
5235 if phase == DispatchPhase::Bubble {
5236 view.update(cx, |editor, cx| {
5237 listener(editor, action, cx);
5238 })
5239 }
5240 })
5241}
5242
5243fn compute_auto_height_layout(
5244 editor: &mut Editor,
5245 max_lines: usize,
5246 max_line_number_width: Pixels,
5247 known_dimensions: Size<Option<Pixels>>,
5248 cx: &mut ViewContext<Editor>,
5249) -> Option<Size<Pixels>> {
5250 let width = known_dimensions.width?;
5251 if let Some(height) = known_dimensions.height {
5252 return Some(size(width, height));
5253 }
5254
5255 let style = editor.style.as_ref().unwrap();
5256 let font_id = cx.text_system().resolve_font(&style.text.font());
5257 let font_size = style.text.font_size.to_pixels(cx.rem_size());
5258 let line_height = style.text.line_height_in_pixels(cx.rem_size());
5259 let em_width = cx
5260 .text_system()
5261 .typographic_bounds(font_id, font_size, 'm')
5262 .unwrap()
5263 .size
5264 .width;
5265
5266 let mut snapshot = editor.snapshot(cx);
5267 let gutter_dimensions =
5268 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
5269
5270 editor.gutter_dimensions = gutter_dimensions;
5271 let text_width = width - gutter_dimensions.width;
5272 let overscroll = size(em_width, px(0.));
5273
5274 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
5275 if editor.set_wrap_width(Some(editor_width), cx) {
5276 snapshot = editor.snapshot(cx);
5277 }
5278
5279 let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
5280 let height = scroll_height
5281 .max(line_height)
5282 .min(line_height * max_lines as f32);
5283
5284 Some(size(width, height))
5285}