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, RunnableTasks, SelectPhase, Selection, SoftWrap,
19 ToPoint, 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), 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 task_lines: Vec<(u32, RunnableTasks)>,
1381 line_height: Pixels,
1382 scroll_pixel_position: gpui::Point<Pixels>,
1383 gutter_dimensions: &GutterDimensions,
1384 gutter_hitbox: &Hitbox,
1385 cx: &mut WindowContext,
1386 ) -> Vec<AnyElement> {
1387 self.editor.update(cx, |editor, cx| {
1388 editor.clear_tasks();
1389
1390 let active_task_indicator_row =
1391 if let Some(crate::ContextMenu::CodeActions(CodeActionsMenu {
1392 deployed_from_indicator,
1393 actions,
1394 ..
1395 })) = editor.context_menu.read().as_ref()
1396 {
1397 actions
1398 .tasks
1399 .as_ref()
1400 .map(|tasks| tasks.position.row)
1401 .or_else(|| *deployed_from_indicator)
1402 } else {
1403 None
1404 };
1405 task_lines
1406 .into_iter()
1407 .map(|(row, tasks)| {
1408 editor.insert_tasks(row, tasks);
1409
1410 let button = editor.render_run_indicator(
1411 &self.style,
1412 Some(row) == active_task_indicator_row,
1413 row,
1414 cx,
1415 );
1416
1417 let button = prepaint_gutter_button(
1418 button,
1419 row,
1420 line_height,
1421 gutter_dimensions,
1422 scroll_pixel_position,
1423 gutter_hitbox,
1424 cx,
1425 );
1426 button
1427 })
1428 .collect_vec()
1429 })
1430 }
1431
1432 fn layout_code_actions_indicator(
1433 &self,
1434 line_height: Pixels,
1435 newest_selection_head: DisplayPoint,
1436 scroll_pixel_position: gpui::Point<Pixels>,
1437 gutter_dimensions: &GutterDimensions,
1438 gutter_hitbox: &Hitbox,
1439 cx: &mut WindowContext,
1440 ) -> Option<AnyElement> {
1441 let mut active = false;
1442 let mut button = None;
1443 let row = newest_selection_head.row();
1444 self.editor.update(cx, |editor, cx| {
1445 if let Some(crate::ContextMenu::CodeActions(CodeActionsMenu {
1446 deployed_from_indicator,
1447 ..
1448 })) = editor.context_menu.read().as_ref()
1449 {
1450 active = deployed_from_indicator.map_or(true, |indicator_row| indicator_row == row);
1451 };
1452 button = editor.render_code_actions_indicator(&self.style, row, active, cx);
1453 });
1454
1455 let button = prepaint_gutter_button(
1456 button?,
1457 row,
1458 line_height,
1459 gutter_dimensions,
1460 scroll_pixel_position,
1461 gutter_hitbox,
1462 cx,
1463 );
1464
1465 Some(button)
1466 }
1467
1468 fn get_participant_color(
1469 participant_index: Option<ParticipantIndex>,
1470 cx: &WindowContext,
1471 ) -> PlayerColor {
1472 if let Some(index) = participant_index {
1473 cx.theme().players().color_for_participant(index.0)
1474 } else {
1475 cx.theme().players().absent()
1476 }
1477 }
1478
1479 fn calculate_relative_line_numbers(
1480 &self,
1481 snapshot: &EditorSnapshot,
1482 rows: &Range<u32>,
1483 relative_to: Option<u32>,
1484 ) -> HashMap<u32, u32> {
1485 let mut relative_rows: HashMap<u32, u32> = Default::default();
1486 let Some(relative_to) = relative_to else {
1487 return relative_rows;
1488 };
1489
1490 let start = rows.start.min(relative_to);
1491 let end = rows.end.max(relative_to);
1492
1493 let buffer_rows = snapshot
1494 .buffer_rows(start)
1495 .take(1 + (end - start) as usize)
1496 .collect::<Vec<_>>();
1497
1498 let head_idx = relative_to - start;
1499 let mut delta = 1;
1500 let mut i = head_idx + 1;
1501 while i < buffer_rows.len() as u32 {
1502 if buffer_rows[i as usize].is_some() {
1503 if rows.contains(&(i + start)) {
1504 relative_rows.insert(i + start, delta);
1505 }
1506 delta += 1;
1507 }
1508 i += 1;
1509 }
1510 delta = 1;
1511 i = head_idx.min(buffer_rows.len() as u32 - 1);
1512 while i > 0 && buffer_rows[i as usize].is_none() {
1513 i -= 1;
1514 }
1515
1516 while i > 0 {
1517 i -= 1;
1518 if buffer_rows[i as usize].is_some() {
1519 if rows.contains(&(i + start)) {
1520 relative_rows.insert(i + start, delta);
1521 }
1522 delta += 1;
1523 }
1524 }
1525
1526 relative_rows
1527 }
1528
1529 fn layout_line_numbers(
1530 &self,
1531 rows: Range<u32>,
1532 buffer_rows: impl Iterator<Item = Option<u32>>,
1533 active_rows: &BTreeMap<u32, bool>,
1534 newest_selection_head: Option<DisplayPoint>,
1535 snapshot: &EditorSnapshot,
1536 cx: &WindowContext,
1537 ) -> (
1538 Vec<Option<ShapedLine>>,
1539 Vec<Option<(FoldStatus, BufferRow, bool)>>,
1540 ) {
1541 let editor = self.editor.read(cx);
1542 let is_singleton = editor.is_singleton(cx);
1543 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1544 let newest = editor.selections.newest::<Point>(cx);
1545 SelectionLayout::new(
1546 newest,
1547 editor.selections.line_mode,
1548 editor.cursor_shape,
1549 &snapshot.display_snapshot,
1550 true,
1551 true,
1552 None,
1553 )
1554 .head
1555 });
1556 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1557 let include_line_numbers =
1558 EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full;
1559 let include_fold_statuses =
1560 EditorSettings::get_global(cx).gutter.folds && snapshot.mode == EditorMode::Full;
1561 let mut shaped_line_numbers = Vec::with_capacity(rows.len());
1562 let mut fold_statuses = Vec::with_capacity(rows.len());
1563 let mut line_number = String::new();
1564 let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1565 let relative_to = if is_relative {
1566 Some(newest_selection_head.row())
1567 } else {
1568 None
1569 };
1570
1571 let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
1572
1573 for (ix, row) in buffer_rows.into_iter().enumerate() {
1574 let display_row = rows.start + ix as u32;
1575 let (active, color) = if active_rows.contains_key(&display_row) {
1576 (true, cx.theme().colors().editor_active_line_number)
1577 } else {
1578 (false, cx.theme().colors().editor_line_number)
1579 };
1580 if let Some(buffer_row) = row {
1581 if include_line_numbers {
1582 line_number.clear();
1583 let default_number = buffer_row + 1;
1584 let number = relative_rows
1585 .get(&(ix as u32 + rows.start))
1586 .unwrap_or(&default_number);
1587 write!(&mut line_number, "{}", number).unwrap();
1588 let run = TextRun {
1589 len: line_number.len(),
1590 font: self.style.text.font(),
1591 color,
1592 background_color: None,
1593 underline: None,
1594 strikethrough: None,
1595 };
1596 let shaped_line = cx
1597 .text_system()
1598 .shape_line(line_number.clone().into(), font_size, &[run])
1599 .unwrap();
1600 shaped_line_numbers.push(Some(shaped_line));
1601 }
1602 if include_fold_statuses {
1603 fold_statuses.push(
1604 is_singleton
1605 .then(|| {
1606 snapshot
1607 .fold_for_line(buffer_row)
1608 .map(|fold_status| (fold_status, buffer_row, active))
1609 })
1610 .flatten(),
1611 )
1612 }
1613 } else {
1614 fold_statuses.push(None);
1615 shaped_line_numbers.push(None);
1616 }
1617 }
1618
1619 (shaped_line_numbers, fold_statuses)
1620 }
1621
1622 fn layout_lines(
1623 &self,
1624 rows: Range<u32>,
1625 line_number_layouts: &[Option<ShapedLine>],
1626 snapshot: &EditorSnapshot,
1627 cx: &WindowContext,
1628 ) -> Vec<LineWithInvisibles> {
1629 if rows.start >= rows.end {
1630 return Vec::new();
1631 }
1632
1633 // Show the placeholder when the editor is empty
1634 if snapshot.is_empty() {
1635 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1636 let placeholder_color = cx.theme().colors().text_placeholder;
1637 let placeholder_text = snapshot.placeholder_text();
1638
1639 let placeholder_lines = placeholder_text
1640 .as_ref()
1641 .map_or("", AsRef::as_ref)
1642 .split('\n')
1643 .skip(rows.start as usize)
1644 .chain(iter::repeat(""))
1645 .take(rows.len());
1646 placeholder_lines
1647 .filter_map(move |line| {
1648 let run = TextRun {
1649 len: line.len(),
1650 font: self.style.text.font(),
1651 color: placeholder_color,
1652 background_color: None,
1653 underline: Default::default(),
1654 strikethrough: None,
1655 };
1656 cx.text_system()
1657 .shape_line(line.to_string().into(), font_size, &[run])
1658 .log_err()
1659 })
1660 .map(|line| LineWithInvisibles {
1661 line,
1662 invisibles: Vec::new(),
1663 })
1664 .collect()
1665 } else {
1666 let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1667 LineWithInvisibles::from_chunks(
1668 chunks,
1669 &self.style.text,
1670 MAX_LINE_LEN,
1671 rows.len(),
1672 line_number_layouts,
1673 snapshot.mode,
1674 cx,
1675 )
1676 }
1677 }
1678
1679 #[allow(clippy::too_many_arguments)]
1680 fn build_blocks(
1681 &self,
1682 rows: Range<u32>,
1683 snapshot: &EditorSnapshot,
1684 hitbox: &Hitbox,
1685 text_hitbox: &Hitbox,
1686 scroll_width: &mut Pixels,
1687 gutter_dimensions: &GutterDimensions,
1688 em_width: Pixels,
1689 text_x: Pixels,
1690 line_height: Pixels,
1691 line_layouts: &[LineWithInvisibles],
1692 cx: &mut WindowContext,
1693 ) -> Vec<BlockLayout> {
1694 let mut block_id = 0;
1695 let (fixed_blocks, non_fixed_blocks) = snapshot
1696 .blocks_in_range(rows.clone())
1697 .partition::<Vec<_>, _>(|(_, block)| match block {
1698 TransformBlock::ExcerptHeader { .. } => false,
1699 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1700 });
1701
1702 let render_block = |block: &TransformBlock,
1703 available_space: Size<AvailableSpace>,
1704 block_id: usize,
1705 block_row_start: u32,
1706 cx: &mut WindowContext| {
1707 let mut element = match block {
1708 TransformBlock::Custom(block) => {
1709 let align_to = block
1710 .position()
1711 .to_point(&snapshot.buffer_snapshot)
1712 .to_display_point(snapshot);
1713 let anchor_x = text_x
1714 + if rows.contains(&align_to.row()) {
1715 line_layouts[(align_to.row() - rows.start) as usize]
1716 .line
1717 .x_for_index(align_to.column() as usize)
1718 } else {
1719 layout_line(align_to.row(), snapshot, &self.style, cx)
1720 .unwrap()
1721 .x_for_index(align_to.column() as usize)
1722 };
1723
1724 block.render(&mut BlockContext {
1725 context: cx,
1726 anchor_x,
1727 gutter_dimensions,
1728 line_height,
1729 em_width,
1730 block_id,
1731 max_width: text_hitbox.size.width.max(*scroll_width),
1732 editor_style: &self.style,
1733 })
1734 }
1735
1736 TransformBlock::ExcerptHeader {
1737 buffer,
1738 range,
1739 starts_new_buffer,
1740 height,
1741 id,
1742 ..
1743 } => {
1744 let include_root = self
1745 .editor
1746 .read(cx)
1747 .project
1748 .as_ref()
1749 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1750 .unwrap_or_default();
1751
1752 #[derive(Clone)]
1753 struct JumpData {
1754 position: Point,
1755 anchor: text::Anchor,
1756 path: ProjectPath,
1757 line_offset_from_top: u32,
1758 }
1759
1760 let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
1761 let jump_path = ProjectPath {
1762 worktree_id: file.worktree_id(cx),
1763 path: file.path.clone(),
1764 };
1765 let jump_anchor = range
1766 .primary
1767 .as_ref()
1768 .map_or(range.context.start, |primary| primary.start);
1769
1770 let excerpt_start = range.context.start;
1771 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1772 let offset_from_excerpt_start = if jump_anchor == excerpt_start {
1773 0
1774 } else {
1775 let excerpt_start_row =
1776 language::ToPoint::to_point(&jump_anchor, buffer).row;
1777 jump_position.row - excerpt_start_row
1778 };
1779
1780 let line_offset_from_top =
1781 block_row_start + *height as u32 + offset_from_excerpt_start
1782 - snapshot
1783 .scroll_anchor
1784 .scroll_position(&snapshot.display_snapshot)
1785 .y as u32;
1786
1787 JumpData {
1788 position: jump_position,
1789 anchor: jump_anchor,
1790 path: jump_path,
1791 line_offset_from_top,
1792 }
1793 });
1794
1795 let element = if *starts_new_buffer {
1796 let path = buffer.resolve_file_path(cx, include_root);
1797 let mut filename = None;
1798 let mut parent_path = None;
1799 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1800 if let Some(path) = path {
1801 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1802 parent_path = path
1803 .parent()
1804 .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
1805 }
1806
1807 v_flex()
1808 .id(("path header container", block_id))
1809 .size_full()
1810 .justify_center()
1811 .p(gpui::px(6.))
1812 .child(
1813 h_flex()
1814 .id("path header block")
1815 .size_full()
1816 .pl(gpui::px(12.))
1817 .pr(gpui::px(8.))
1818 .rounded_md()
1819 .shadow_md()
1820 .border()
1821 .border_color(cx.theme().colors().border)
1822 .bg(cx.theme().colors().editor_subheader_background)
1823 .justify_between()
1824 .hover(|style| style.bg(cx.theme().colors().element_hover))
1825 .child(
1826 h_flex().gap_3().child(
1827 h_flex()
1828 .gap_2()
1829 .child(
1830 filename
1831 .map(SharedString::from)
1832 .unwrap_or_else(|| "untitled".into()),
1833 )
1834 .when_some(parent_path, |then, path| {
1835 then.child(
1836 div().child(path).text_color(
1837 cx.theme().colors().text_muted,
1838 ),
1839 )
1840 }),
1841 ),
1842 )
1843 .when_some(jump_data.clone(), |this, jump_data| {
1844 this.cursor_pointer()
1845 .tooltip(|cx| {
1846 Tooltip::for_action(
1847 "Jump to File",
1848 &OpenExcerpts,
1849 cx,
1850 )
1851 })
1852 .on_mouse_down(MouseButton::Left, |_, cx| {
1853 cx.stop_propagation()
1854 })
1855 .on_click(cx.listener_for(&self.editor, {
1856 move |editor, _, cx| {
1857 editor.jump(
1858 jump_data.path.clone(),
1859 jump_data.position,
1860 jump_data.anchor,
1861 jump_data.line_offset_from_top,
1862 cx,
1863 );
1864 }
1865 }))
1866 }),
1867 )
1868 } else {
1869 v_flex()
1870 .id(("collapsed context", block_id))
1871 .size_full()
1872 .child(
1873 div()
1874 .flex()
1875 .v_flex()
1876 .justify_start()
1877 .id("jump to collapsed context")
1878 .w(relative(1.0))
1879 .h_full()
1880 .child(
1881 div()
1882 .h_px()
1883 .w_full()
1884 .bg(cx.theme().colors().border_variant)
1885 .group_hover("excerpt-jump-action", |style| {
1886 style.bg(cx.theme().colors().border)
1887 }),
1888 ),
1889 )
1890 .child(
1891 h_flex()
1892 .justify_end()
1893 .flex_none()
1894 .w(
1895 gutter_dimensions.width - (gutter_dimensions.left_padding), // + gutter_dimensions.right_padding)
1896 )
1897 .h_full()
1898 .child(
1899 ButtonLike::new("expand-icon")
1900 .style(ButtonStyle::Transparent)
1901 .child(
1902 svg()
1903 .path(IconName::ExpandVertical.path())
1904 .size(IconSize::XSmall.rems())
1905 .text_color(
1906 cx.theme().colors().editor_line_number,
1907 )
1908 .group("")
1909 .hover(|style| {
1910 style.text_color(
1911 cx.theme()
1912 .colors()
1913 .editor_active_line_number,
1914 )
1915 }),
1916 )
1917 .on_click(cx.listener_for(&self.editor, {
1918 let id = *id;
1919 move |editor, _, cx| {
1920 editor.expand_excerpt(id, cx);
1921 }
1922 }))
1923 .tooltip({
1924 move |cx| {
1925 Tooltip::for_action(
1926 "Expand Excerpt",
1927 &ExpandExcerpts { lines: 0 },
1928 cx,
1929 )
1930 }
1931 }),
1932 ),
1933 )
1934 .group("excerpt-jump-action")
1935 .cursor_pointer()
1936 .when_some(jump_data.clone(), |this, jump_data| {
1937 this.on_click(cx.listener_for(&self.editor, {
1938 let path = jump_data.path.clone();
1939 move |editor, _, cx| {
1940 cx.stop_propagation();
1941
1942 editor.jump(
1943 path.clone(),
1944 jump_data.position,
1945 jump_data.anchor,
1946 jump_data.line_offset_from_top,
1947 cx,
1948 );
1949 }
1950 }))
1951 .tooltip(move |cx| {
1952 Tooltip::for_action(
1953 format!(
1954 "Jump to {}:L{}",
1955 jump_data.path.path.display(),
1956 jump_data.position.row + 1
1957 ),
1958 &OpenExcerpts,
1959 cx,
1960 )
1961 })
1962 })
1963 };
1964 element.into_any()
1965 }
1966 };
1967
1968 let size = element.layout_as_root(available_space, cx);
1969 (element, size)
1970 };
1971
1972 let mut fixed_block_max_width = Pixels::ZERO;
1973 let mut blocks = Vec::new();
1974 for (row, block) in fixed_blocks {
1975 let available_space = size(
1976 AvailableSpace::MinContent,
1977 AvailableSpace::Definite(block.height() as f32 * line_height),
1978 );
1979 let (element, element_size) = render_block(block, available_space, block_id, row, cx);
1980 block_id += 1;
1981 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
1982 blocks.push(BlockLayout {
1983 row,
1984 element,
1985 available_space,
1986 style: BlockStyle::Fixed,
1987 });
1988 }
1989 for (row, block) in non_fixed_blocks {
1990 let style = match block {
1991 TransformBlock::Custom(block) => block.style(),
1992 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1993 };
1994 let width = match style {
1995 BlockStyle::Sticky => hitbox.size.width,
1996 BlockStyle::Flex => hitbox
1997 .size
1998 .width
1999 .max(fixed_block_max_width)
2000 .max(gutter_dimensions.width + *scroll_width),
2001 BlockStyle::Fixed => unreachable!(),
2002 };
2003 let available_space = size(
2004 AvailableSpace::Definite(width),
2005 AvailableSpace::Definite(block.height() as f32 * line_height),
2006 );
2007 let (element, _) = render_block(block, available_space, block_id, row, cx);
2008 block_id += 1;
2009 blocks.push(BlockLayout {
2010 row,
2011 element,
2012 available_space,
2013 style,
2014 });
2015 }
2016
2017 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2018 blocks
2019 }
2020
2021 fn layout_blocks(
2022 &self,
2023 blocks: &mut Vec<BlockLayout>,
2024 hitbox: &Hitbox,
2025 line_height: Pixels,
2026 scroll_pixel_position: gpui::Point<Pixels>,
2027 cx: &mut WindowContext,
2028 ) {
2029 for block in blocks {
2030 let mut origin = hitbox.origin
2031 + point(
2032 Pixels::ZERO,
2033 block.row as f32 * line_height - scroll_pixel_position.y,
2034 );
2035 if !matches!(block.style, BlockStyle::Sticky) {
2036 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2037 }
2038 block
2039 .element
2040 .prepaint_as_root(origin, block.available_space, cx);
2041 }
2042 }
2043
2044 #[allow(clippy::too_many_arguments)]
2045 fn layout_context_menu(
2046 &self,
2047 line_height: Pixels,
2048 hitbox: &Hitbox,
2049 text_hitbox: &Hitbox,
2050 content_origin: gpui::Point<Pixels>,
2051 start_row: u32,
2052 scroll_pixel_position: gpui::Point<Pixels>,
2053 line_layouts: &[LineWithInvisibles],
2054 newest_selection_head: DisplayPoint,
2055 gutter_overshoot: Pixels,
2056 cx: &mut WindowContext,
2057 ) -> bool {
2058 let max_height = cmp::min(
2059 12. * line_height,
2060 cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
2061 );
2062 let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
2063 if editor.context_menu_visible() {
2064 editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
2065 } else {
2066 None
2067 }
2068 }) else {
2069 return false;
2070 };
2071
2072 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2073 let context_menu_size = context_menu.layout_as_root(available_space, cx);
2074
2075 let (x, y) = match position {
2076 crate::ContextMenuOrigin::EditorPoint(point) => {
2077 let cursor_row_layout = &line_layouts[(point.row() - start_row) as usize].line;
2078 let x = cursor_row_layout.x_for_index(point.column() as usize)
2079 - scroll_pixel_position.x;
2080 let y = (point.row() + 1) as f32 * line_height - scroll_pixel_position.y;
2081 (x, y)
2082 }
2083 crate::ContextMenuOrigin::GutterIndicator(row) => {
2084 // 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
2085 // text field.
2086 let x = -gutter_overshoot;
2087 let y = (row + 1) as f32 * line_height - scroll_pixel_position.y;
2088 (x, y)
2089 }
2090 };
2091
2092 let mut list_origin = content_origin + point(x, y);
2093 let list_width = context_menu_size.width;
2094 let list_height = context_menu_size.height;
2095
2096 // Snap the right edge of the list to the right edge of the window if
2097 // its horizontal bounds overflow.
2098 if list_origin.x + list_width > cx.viewport_size().width {
2099 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
2100 }
2101
2102 if list_origin.y + list_height > text_hitbox.lower_right().y {
2103 list_origin.y -= line_height + list_height;
2104 }
2105
2106 cx.defer_draw(context_menu, list_origin, 1);
2107 true
2108 }
2109
2110 fn layout_mouse_context_menu(&self, cx: &mut WindowContext) -> Option<AnyElement> {
2111 let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
2112 let mut element = deferred(
2113 anchored()
2114 .position(mouse_context_menu.position)
2115 .child(mouse_context_menu.context_menu.clone())
2116 .anchor(AnchorCorner::TopLeft)
2117 .snap_to_window(),
2118 )
2119 .with_priority(1)
2120 .into_any();
2121
2122 element.prepaint_as_root(gpui::Point::default(), AvailableSpace::min_size(), cx);
2123 Some(element)
2124 }
2125
2126 #[allow(clippy::too_many_arguments)]
2127 fn layout_hover_popovers(
2128 &self,
2129 snapshot: &EditorSnapshot,
2130 hitbox: &Hitbox,
2131 text_hitbox: &Hitbox,
2132 visible_display_row_range: Range<u32>,
2133 content_origin: gpui::Point<Pixels>,
2134 scroll_pixel_position: gpui::Point<Pixels>,
2135 line_layouts: &[LineWithInvisibles],
2136 line_height: Pixels,
2137 em_width: Pixels,
2138 cx: &mut WindowContext,
2139 ) {
2140 struct MeasuredHoverPopover {
2141 element: AnyElement,
2142 size: Size<Pixels>,
2143 horizontal_offset: Pixels,
2144 }
2145
2146 let max_size = size(
2147 (120. * em_width) // Default size
2148 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2149 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2150 (16. * line_height) // Default size
2151 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2152 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2153 );
2154
2155 let hover_popovers = self.editor.update(cx, |editor, cx| {
2156 editor.hover_state.render(
2157 &snapshot,
2158 &self.style,
2159 visible_display_row_range.clone(),
2160 max_size,
2161 editor.workspace.as_ref().map(|(w, _)| w.clone()),
2162 cx,
2163 )
2164 });
2165 let Some((position, hover_popovers)) = hover_popovers else {
2166 return;
2167 };
2168
2169 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2170
2171 // This is safe because we check on layout whether the required row is available
2172 let hovered_row_layout =
2173 &line_layouts[(position.row() - visible_display_row_range.start) as usize].line;
2174
2175 // Compute Hovered Point
2176 let x =
2177 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
2178 let y = position.row() as f32 * line_height - scroll_pixel_position.y;
2179 let hovered_point = content_origin + point(x, y);
2180
2181 let mut overall_height = Pixels::ZERO;
2182 let mut measured_hover_popovers = Vec::new();
2183 for mut hover_popover in hover_popovers {
2184 let size = hover_popover.layout_as_root(available_space, cx);
2185 let horizontal_offset =
2186 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
2187
2188 overall_height += HOVER_POPOVER_GAP + size.height;
2189
2190 measured_hover_popovers.push(MeasuredHoverPopover {
2191 element: hover_popover,
2192 size,
2193 horizontal_offset,
2194 });
2195 }
2196 overall_height += HOVER_POPOVER_GAP;
2197
2198 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
2199 let mut occlusion = div()
2200 .size_full()
2201 .occlude()
2202 .on_mouse_move(|_, cx| cx.stop_propagation())
2203 .into_any_element();
2204 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
2205 cx.defer_draw(occlusion, origin, 2);
2206 }
2207
2208 if hovered_point.y > overall_height {
2209 // There is enough space above. Render popovers above the hovered point
2210 let mut current_y = hovered_point.y;
2211 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2212 let size = popover.size;
2213 let popover_origin = point(
2214 hovered_point.x + popover.horizontal_offset,
2215 current_y - size.height,
2216 );
2217
2218 cx.defer_draw(popover.element, popover_origin, 2);
2219 if position != itertools::Position::Last {
2220 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
2221 draw_occluder(size.width, origin, cx);
2222 }
2223
2224 current_y = popover_origin.y - HOVER_POPOVER_GAP;
2225 }
2226 } else {
2227 // There is not enough space above. Render popovers below the hovered point
2228 let mut current_y = hovered_point.y + line_height;
2229 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2230 let size = popover.size;
2231 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2232
2233 cx.defer_draw(popover.element, popover_origin, 2);
2234 if position != itertools::Position::Last {
2235 let origin = point(popover_origin.x, popover_origin.y + size.height);
2236 draw_occluder(size.width, origin, cx);
2237 }
2238
2239 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2240 }
2241 }
2242 }
2243
2244 fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2245 cx.paint_layer(layout.hitbox.bounds, |cx| {
2246 let scroll_top = layout.position_map.snapshot.scroll_position().y;
2247 let gutter_bg = cx.theme().colors().editor_gutter_background;
2248 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2249 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2250
2251 if let EditorMode::Full = layout.mode {
2252 let mut active_rows = layout.active_rows.iter().peekable();
2253 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2254 let mut end_row = *start_row;
2255 while active_rows.peek().map_or(false, |r| {
2256 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
2257 }) {
2258 active_rows.next().unwrap();
2259 end_row += 1;
2260 }
2261
2262 if !contains_non_empty_selection {
2263 let origin = point(
2264 layout.hitbox.origin.x,
2265 layout.hitbox.origin.y
2266 + (*start_row as f32 - scroll_top)
2267 * layout.position_map.line_height,
2268 );
2269 let size = size(
2270 layout.hitbox.size.width,
2271 layout.position_map.line_height * (end_row - start_row + 1) as f32,
2272 );
2273 let active_line_bg = cx.theme().colors().editor_active_line_background;
2274 cx.paint_quad(fill(Bounds { origin, size }, active_line_bg));
2275 }
2276 }
2277
2278 let mut paint_highlight =
2279 |highlight_row_start: u32, highlight_row_end: u32, color| {
2280 let origin = point(
2281 layout.hitbox.origin.x,
2282 layout.hitbox.origin.y
2283 + (highlight_row_start as f32 - scroll_top)
2284 * layout.position_map.line_height,
2285 );
2286 let size = size(
2287 layout.hitbox.size.width,
2288 layout.position_map.line_height
2289 * (highlight_row_end + 1 - highlight_row_start) as f32,
2290 );
2291 cx.paint_quad(fill(Bounds { origin, size }, color));
2292 };
2293
2294 let mut current_paint: Option<(Hsla, Range<u32>)> = None;
2295 for (&new_row, &new_color) in &layout.highlighted_rows {
2296 match &mut current_paint {
2297 Some((current_color, current_range)) => {
2298 let current_color = *current_color;
2299 let new_range_started =
2300 current_color != new_color || current_range.end + 1 != new_row;
2301 if new_range_started {
2302 paint_highlight(
2303 current_range.start,
2304 current_range.end,
2305 current_color,
2306 );
2307 current_paint = Some((new_color, new_row..new_row));
2308 continue;
2309 } else {
2310 current_range.end += 1;
2311 }
2312 }
2313 None => current_paint = Some((new_color, new_row..new_row)),
2314 };
2315 }
2316 if let Some((color, range)) = current_paint {
2317 paint_highlight(range.start, range.end, color);
2318 }
2319
2320 let scroll_left =
2321 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2322
2323 for (wrap_position, active) in layout.wrap_guides.iter() {
2324 let x = (layout.text_hitbox.origin.x
2325 + *wrap_position
2326 + layout.position_map.em_width / 2.)
2327 - scroll_left;
2328
2329 let show_scrollbars = layout
2330 .scrollbar_layout
2331 .as_ref()
2332 .map_or(false, |scrollbar| scrollbar.visible);
2333 if x < layout.text_hitbox.origin.x
2334 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2335 {
2336 continue;
2337 }
2338
2339 let color = if *active {
2340 cx.theme().colors().editor_active_wrap_guide
2341 } else {
2342 cx.theme().colors().editor_wrap_guide
2343 };
2344 cx.paint_quad(fill(
2345 Bounds {
2346 origin: point(x, layout.text_hitbox.origin.y),
2347 size: size(px(1.), layout.text_hitbox.size.height),
2348 },
2349 color,
2350 ));
2351 }
2352 }
2353 })
2354 }
2355
2356 fn paint_gutter(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2357 let line_height = layout.position_map.line_height;
2358
2359 let scroll_position = layout.position_map.snapshot.scroll_position();
2360 let scroll_top = scroll_position.y * line_height;
2361
2362 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2363 for (_, hunk_hitbox) in &layout.display_hunks {
2364 if let Some(hunk_hitbox) = hunk_hitbox {
2365 cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
2366 }
2367 }
2368
2369 let show_git_gutter = matches!(
2370 ProjectSettings::get_global(cx).git.git_gutter,
2371 Some(GitGutterSetting::TrackedFiles)
2372 );
2373 if show_git_gutter {
2374 Self::paint_diff_hunks(layout.gutter_hitbox.bounds, layout, cx)
2375 }
2376
2377 if layout.blamed_display_rows.is_some() {
2378 self.paint_blamed_display_rows(layout, cx);
2379 }
2380
2381 for (ix, line) in layout.line_numbers.iter().enumerate() {
2382 if let Some(line) = line {
2383 let line_origin = layout.gutter_hitbox.origin
2384 + point(
2385 layout.gutter_hitbox.size.width
2386 - line.width
2387 - layout.gutter_dimensions.right_padding,
2388 ix as f32 * line_height - (scroll_top % line_height),
2389 );
2390
2391 line.paint(line_origin, line_height, cx).log_err();
2392 }
2393 }
2394
2395 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2396 cx.with_element_namespace("gutter_fold_indicators", |cx| {
2397 for fold_indicator in layout.fold_indicators.iter_mut().flatten() {
2398 fold_indicator.paint(cx);
2399 }
2400 });
2401
2402 for test_indicators in layout.test_indicators.iter_mut() {
2403 test_indicators.paint(cx);
2404 }
2405
2406 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2407 indicator.paint(cx);
2408 }
2409 });
2410 }
2411
2412 fn paint_diff_hunks(
2413 gutter_bounds: Bounds<Pixels>,
2414 layout: &EditorLayout,
2415 cx: &mut WindowContext,
2416 ) {
2417 if layout.display_hunks.is_empty() {
2418 return;
2419 }
2420
2421 let line_height = layout.position_map.line_height;
2422 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2423 for (hunk, hitbox) in &layout.display_hunks {
2424 let hunk_to_paint = match hunk {
2425 DisplayDiffHunk::Folded { .. } => {
2426 let hunk_bounds = Self::diff_hunk_bounds(
2427 &layout.position_map.snapshot,
2428 line_height,
2429 gutter_bounds,
2430 &hunk,
2431 );
2432 Some((
2433 hunk_bounds,
2434 cx.theme().status().modified,
2435 Corners::all(1. * line_height),
2436 ))
2437 }
2438 DisplayDiffHunk::Unfolded { status, .. } => {
2439 hitbox.as_ref().map(|hunk_hitbox| match status {
2440 DiffHunkStatus::Added => (
2441 hunk_hitbox.bounds,
2442 cx.theme().status().created,
2443 Corners::all(0.05 * line_height),
2444 ),
2445 DiffHunkStatus::Modified => (
2446 hunk_hitbox.bounds,
2447 cx.theme().status().modified,
2448 Corners::all(0.05 * line_height),
2449 ),
2450 DiffHunkStatus::Removed => (
2451 hunk_hitbox.bounds,
2452 cx.theme().status().deleted,
2453 Corners::all(1. * line_height),
2454 ),
2455 })
2456 }
2457 };
2458
2459 if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
2460 cx.paint_quad(quad(
2461 hunk_bounds,
2462 corner_radii,
2463 background_color,
2464 Edges::default(),
2465 transparent_black(),
2466 ));
2467 }
2468 }
2469 });
2470 }
2471
2472 fn diff_hunk_bounds(
2473 snapshot: &EditorSnapshot,
2474 line_height: Pixels,
2475 bounds: Bounds<Pixels>,
2476 hunk: &DisplayDiffHunk,
2477 ) -> Bounds<Pixels> {
2478 let scroll_position = snapshot.scroll_position();
2479 let scroll_top = scroll_position.y * line_height;
2480
2481 match hunk {
2482 DisplayDiffHunk::Folded { display_row, .. } => {
2483 let start_y = *display_row as f32 * line_height - scroll_top;
2484 let end_y = start_y + line_height;
2485
2486 let width = 0.275 * line_height;
2487 let highlight_origin = bounds.origin + point(-width, start_y);
2488 let highlight_size = size(width * 2., end_y - start_y);
2489 Bounds::new(highlight_origin, highlight_size)
2490 }
2491 DisplayDiffHunk::Unfolded {
2492 display_row_range,
2493 status,
2494 ..
2495 } => match status {
2496 DiffHunkStatus::Added | DiffHunkStatus::Modified => {
2497 let start_row = display_row_range.start;
2498 let end_row = display_row_range.end;
2499 // If we're in a multibuffer, row range span might include an
2500 // excerpt header, so if we were to draw the marker straight away,
2501 // the hunk might include the rows of that header.
2502 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2503 // Instead, we simply check whether the range we're dealing with includes
2504 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2505 let end_row_in_current_excerpt = snapshot
2506 .blocks_in_range(start_row..end_row)
2507 .find_map(|(start_row, block)| {
2508 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2509 Some(start_row)
2510 } else {
2511 None
2512 }
2513 })
2514 .unwrap_or(end_row);
2515
2516 let start_y = start_row as f32 * line_height - scroll_top;
2517 let end_y = end_row_in_current_excerpt as f32 * line_height - scroll_top;
2518
2519 let width = 0.275 * line_height;
2520 let highlight_origin = bounds.origin + point(-width, start_y);
2521 let highlight_size = size(width * 2., end_y - start_y);
2522 Bounds::new(highlight_origin, highlight_size)
2523 }
2524 DiffHunkStatus::Removed => {
2525 let row = display_row_range.start;
2526
2527 let offset = line_height / 2.;
2528 let start_y = row as f32 * line_height - offset - scroll_top;
2529 let end_y = start_y + line_height;
2530
2531 let width = 0.35 * line_height;
2532 let highlight_origin = bounds.origin + point(-width, start_y);
2533 let highlight_size = size(width * 2., end_y - start_y);
2534 Bounds::new(highlight_origin, highlight_size)
2535 }
2536 },
2537 }
2538 }
2539
2540 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2541 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
2542 return;
2543 };
2544
2545 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2546 for mut blame_element in blamed_display_rows.into_iter() {
2547 blame_element.paint(cx);
2548 }
2549 })
2550 }
2551
2552 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2553 cx.with_content_mask(
2554 Some(ContentMask {
2555 bounds: layout.text_hitbox.bounds,
2556 }),
2557 |cx| {
2558 let cursor_style = if self
2559 .editor
2560 .read(cx)
2561 .hovered_link_state
2562 .as_ref()
2563 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
2564 {
2565 CursorStyle::PointingHand
2566 } else {
2567 CursorStyle::IBeam
2568 };
2569 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
2570
2571 cx.with_element_namespace("folds", |cx| self.paint_folds(layout, cx));
2572 let invisible_display_ranges = self.paint_highlights(layout, cx);
2573 self.paint_lines(&invisible_display_ranges, layout, cx);
2574 self.paint_redactions(layout, cx);
2575 self.paint_cursors(layout, cx);
2576 self.paint_inline_blame(layout, cx);
2577 },
2578 )
2579 }
2580
2581 fn paint_highlights(
2582 &mut self,
2583 layout: &mut EditorLayout,
2584 cx: &mut WindowContext,
2585 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
2586 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2587 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
2588 let line_end_overshoot = 0.15 * layout.position_map.line_height;
2589 for (range, color) in &layout.highlighted_ranges {
2590 self.paint_highlighted_range(
2591 range.clone(),
2592 *color,
2593 Pixels::ZERO,
2594 line_end_overshoot,
2595 layout,
2596 cx,
2597 );
2598 }
2599
2600 let corner_radius = 0.15 * layout.position_map.line_height;
2601
2602 for (player_color, selections) in &layout.selections {
2603 for selection in selections.into_iter() {
2604 self.paint_highlighted_range(
2605 selection.range.clone(),
2606 player_color.selection,
2607 corner_radius,
2608 corner_radius * 2.,
2609 layout,
2610 cx,
2611 );
2612
2613 if selection.is_local && !selection.range.is_empty() {
2614 invisible_display_ranges.push(selection.range.clone());
2615 }
2616 }
2617 }
2618 invisible_display_ranges
2619 })
2620 }
2621
2622 fn paint_lines(
2623 &mut self,
2624 invisible_display_ranges: &[Range<DisplayPoint>],
2625 layout: &EditorLayout,
2626 cx: &mut WindowContext,
2627 ) {
2628 let whitespace_setting = self
2629 .editor
2630 .read(cx)
2631 .buffer
2632 .read(cx)
2633 .settings_at(0, cx)
2634 .show_whitespaces;
2635
2636 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
2637 let row = layout.visible_display_row_range.start + ix as u32;
2638 line_with_invisibles.draw(
2639 layout,
2640 row,
2641 layout.content_origin,
2642 whitespace_setting,
2643 invisible_display_ranges,
2644 cx,
2645 )
2646 }
2647 }
2648
2649 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
2650 if layout.redacted_ranges.is_empty() {
2651 return;
2652 }
2653
2654 let line_end_overshoot = layout.line_end_overshoot();
2655
2656 // A softer than perfect black
2657 let redaction_color = gpui::rgb(0x0e1111);
2658
2659 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2660 for range in layout.redacted_ranges.iter() {
2661 self.paint_highlighted_range(
2662 range.clone(),
2663 redaction_color.into(),
2664 Pixels::ZERO,
2665 line_end_overshoot,
2666 layout,
2667 cx,
2668 );
2669 }
2670 });
2671 }
2672
2673 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2674 for cursor in &mut layout.visible_cursors {
2675 cursor.paint(layout.content_origin, cx);
2676 }
2677 }
2678
2679 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
2680 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
2681 return;
2682 };
2683
2684 let thumb_bounds = scrollbar_layout.thumb_bounds();
2685 if scrollbar_layout.visible {
2686 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
2687 cx.paint_quad(quad(
2688 scrollbar_layout.hitbox.bounds,
2689 Corners::default(),
2690 cx.theme().colors().scrollbar_track_background,
2691 Edges {
2692 top: Pixels::ZERO,
2693 right: Pixels::ZERO,
2694 bottom: Pixels::ZERO,
2695 left: ScrollbarLayout::BORDER_WIDTH,
2696 },
2697 cx.theme().colors().scrollbar_track_border,
2698 ));
2699
2700 let fast_markers =
2701 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
2702 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
2703 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
2704
2705 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
2706 for marker in markers.iter().chain(&fast_markers) {
2707 let mut marker = marker.clone();
2708 marker.bounds.origin += scrollbar_layout.hitbox.origin;
2709 cx.paint_quad(marker);
2710 }
2711
2712 cx.paint_quad(quad(
2713 thumb_bounds,
2714 Corners::default(),
2715 cx.theme().colors().scrollbar_thumb_background,
2716 Edges {
2717 top: Pixels::ZERO,
2718 right: Pixels::ZERO,
2719 bottom: Pixels::ZERO,
2720 left: ScrollbarLayout::BORDER_WIDTH,
2721 },
2722 cx.theme().colors().scrollbar_thumb_border,
2723 ));
2724 });
2725 }
2726
2727 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2728
2729 let row_height = scrollbar_layout.row_height;
2730 let row_range = scrollbar_layout.visible_row_range.clone();
2731
2732 cx.on_mouse_event({
2733 let editor = self.editor.clone();
2734 let hitbox = scrollbar_layout.hitbox.clone();
2735 let mut mouse_position = cx.mouse_position();
2736 move |event: &MouseMoveEvent, phase, cx| {
2737 if phase == DispatchPhase::Capture {
2738 return;
2739 }
2740
2741 editor.update(cx, |editor, cx| {
2742 if event.pressed_button == Some(MouseButton::Left)
2743 && editor.scroll_manager.is_dragging_scrollbar()
2744 {
2745 let y = mouse_position.y;
2746 let new_y = event.position.y;
2747 if (hitbox.top()..hitbox.bottom()).contains(&y) {
2748 let mut position = editor.scroll_position(cx);
2749 position.y += (new_y - y) / row_height;
2750 if position.y < 0.0 {
2751 position.y = 0.0;
2752 }
2753 editor.set_scroll_position(position, cx);
2754 }
2755
2756 cx.stop_propagation();
2757 } else {
2758 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2759 if hitbox.is_hovered(cx) {
2760 editor.scroll_manager.show_scrollbar(cx);
2761 }
2762 }
2763 mouse_position = event.position;
2764 })
2765 }
2766 });
2767
2768 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2769 cx.on_mouse_event({
2770 let editor = self.editor.clone();
2771 move |_: &MouseUpEvent, phase, cx| {
2772 if phase == DispatchPhase::Capture {
2773 return;
2774 }
2775
2776 editor.update(cx, |editor, cx| {
2777 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2778 cx.stop_propagation();
2779 });
2780 }
2781 });
2782 } else {
2783 cx.on_mouse_event({
2784 let editor = self.editor.clone();
2785 let hitbox = scrollbar_layout.hitbox.clone();
2786 move |event: &MouseDownEvent, phase, cx| {
2787 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2788 return;
2789 }
2790
2791 editor.update(cx, |editor, cx| {
2792 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2793
2794 let y = event.position.y;
2795 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2796 let center_row = ((y - hitbox.top()) / row_height).round() as u32;
2797 let top_row = center_row
2798 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2799 let mut position = editor.scroll_position(cx);
2800 position.y = top_row as f32;
2801 editor.set_scroll_position(position, cx);
2802 } else {
2803 editor.scroll_manager.show_scrollbar(cx);
2804 }
2805
2806 cx.stop_propagation();
2807 });
2808 }
2809 });
2810 }
2811 }
2812
2813 fn collect_fast_scrollbar_markers(
2814 &self,
2815 layout: &EditorLayout,
2816 scrollbar_layout: &ScrollbarLayout,
2817 cx: &mut WindowContext,
2818 ) -> Vec<PaintQuad> {
2819 const LIMIT: usize = 100;
2820 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
2821 return vec![];
2822 }
2823 let cursor_ranges = layout
2824 .cursors
2825 .iter()
2826 .map(|(point, color)| ColoredRange {
2827 start: point.row(),
2828 end: point.row(),
2829 color: *color,
2830 })
2831 .collect_vec();
2832 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
2833 }
2834
2835 fn refresh_slow_scrollbar_markers(
2836 &self,
2837 layout: &EditorLayout,
2838 scrollbar_layout: &ScrollbarLayout,
2839 cx: &mut WindowContext,
2840 ) {
2841 self.editor.update(cx, |editor, cx| {
2842 if !editor.is_singleton(cx)
2843 || !editor
2844 .scrollbar_marker_state
2845 .should_refresh(scrollbar_layout.hitbox.size)
2846 {
2847 return;
2848 }
2849
2850 let scrollbar_layout = scrollbar_layout.clone();
2851 let background_highlights = editor.background_highlights.clone();
2852 let snapshot = layout.position_map.snapshot.clone();
2853 let theme = cx.theme().clone();
2854 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
2855 let max_row = layout.max_row;
2856
2857 editor.scrollbar_marker_state.dirty = false;
2858 editor.scrollbar_marker_state.pending_refresh =
2859 Some(cx.spawn(|editor, mut cx| async move {
2860 let scrollbar_size = scrollbar_layout.hitbox.size;
2861 let scrollbar_markers = cx
2862 .background_executor()
2863 .spawn(async move {
2864 let mut marker_quads = Vec::new();
2865
2866 if scrollbar_settings.git_diff {
2867 let marker_row_ranges = snapshot
2868 .buffer_snapshot
2869 .git_diff_hunks_in_range(0..max_row)
2870 .map(|hunk| {
2871 let start_display_row =
2872 Point::new(hunk.associated_range.start, 0)
2873 .to_display_point(&snapshot.display_snapshot)
2874 .row();
2875 let mut end_display_row =
2876 Point::new(hunk.associated_range.end, 0)
2877 .to_display_point(&snapshot.display_snapshot)
2878 .row();
2879 if end_display_row != start_display_row {
2880 end_display_row -= 1;
2881 }
2882 let color = match hunk.status() {
2883 DiffHunkStatus::Added => theme.status().created,
2884 DiffHunkStatus::Modified => theme.status().modified,
2885 DiffHunkStatus::Removed => theme.status().deleted,
2886 };
2887 ColoredRange {
2888 start: start_display_row,
2889 end: end_display_row,
2890 color,
2891 }
2892 });
2893
2894 marker_quads.extend(
2895 scrollbar_layout
2896 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
2897 );
2898 }
2899
2900 for (background_highlight_id, (_, background_ranges)) in
2901 background_highlights.iter()
2902 {
2903 let is_search_highlights = *background_highlight_id
2904 == TypeId::of::<BufferSearchHighlights>();
2905 let is_symbol_occurrences = *background_highlight_id
2906 == TypeId::of::<DocumentHighlightRead>()
2907 || *background_highlight_id
2908 == TypeId::of::<DocumentHighlightWrite>();
2909 if (is_search_highlights && scrollbar_settings.search_results)
2910 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
2911 {
2912 let mut color = theme.status().info;
2913 if is_symbol_occurrences {
2914 color.fade_out(0.5);
2915 }
2916 let marker_row_ranges =
2917 background_ranges.into_iter().map(|range| {
2918 let display_start = range
2919 .start
2920 .to_display_point(&snapshot.display_snapshot);
2921 let display_end = range
2922 .end
2923 .to_display_point(&snapshot.display_snapshot);
2924 ColoredRange {
2925 start: display_start.row(),
2926 end: display_end.row(),
2927 color,
2928 }
2929 });
2930 marker_quads.extend(
2931 scrollbar_layout
2932 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
2933 );
2934 }
2935 }
2936
2937 if scrollbar_settings.diagnostics {
2938 let max_point =
2939 snapshot.display_snapshot.buffer_snapshot.max_point();
2940
2941 let diagnostics = snapshot
2942 .buffer_snapshot
2943 .diagnostics_in_range::<_, Point>(
2944 Point::zero()..max_point,
2945 false,
2946 )
2947 // We want to sort by severity, in order to paint the most severe diagnostics last.
2948 .sorted_by_key(|diagnostic| {
2949 std::cmp::Reverse(diagnostic.diagnostic.severity)
2950 });
2951
2952 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
2953 let start_display = diagnostic
2954 .range
2955 .start
2956 .to_display_point(&snapshot.display_snapshot);
2957 let end_display = diagnostic
2958 .range
2959 .end
2960 .to_display_point(&snapshot.display_snapshot);
2961 let color = match diagnostic.diagnostic.severity {
2962 DiagnosticSeverity::ERROR => theme.status().error,
2963 DiagnosticSeverity::WARNING => theme.status().warning,
2964 DiagnosticSeverity::INFORMATION => theme.status().info,
2965 _ => theme.status().hint,
2966 };
2967 ColoredRange {
2968 start: start_display.row(),
2969 end: end_display.row(),
2970 color,
2971 }
2972 });
2973 marker_quads.extend(
2974 scrollbar_layout
2975 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
2976 );
2977 }
2978
2979 Arc::from(marker_quads)
2980 })
2981 .await;
2982
2983 editor.update(&mut cx, |editor, cx| {
2984 editor.scrollbar_marker_state.markers = scrollbar_markers;
2985 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
2986 editor.scrollbar_marker_state.pending_refresh = None;
2987 cx.notify();
2988 })?;
2989
2990 Ok(())
2991 }));
2992 });
2993 }
2994
2995 #[allow(clippy::too_many_arguments)]
2996 fn paint_highlighted_range(
2997 &self,
2998 range: Range<DisplayPoint>,
2999 color: Hsla,
3000 corner_radius: Pixels,
3001 line_end_overshoot: Pixels,
3002 layout: &EditorLayout,
3003 cx: &mut WindowContext,
3004 ) {
3005 let start_row = layout.visible_display_row_range.start;
3006 let end_row = layout.visible_display_row_range.end;
3007 if range.start != range.end {
3008 let row_range = if range.end.column() == 0 {
3009 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3010 } else {
3011 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
3012 };
3013
3014 let highlighted_range = HighlightedRange {
3015 color,
3016 line_height: layout.position_map.line_height,
3017 corner_radius,
3018 start_y: layout.content_origin.y
3019 + row_range.start as f32 * layout.position_map.line_height
3020 - layout.position_map.scroll_pixel_position.y,
3021 lines: row_range
3022 .into_iter()
3023 .map(|row| {
3024 let line_layout =
3025 &layout.position_map.line_layouts[(row - start_row) as usize].line;
3026 HighlightedRangeLine {
3027 start_x: if row == range.start.row() {
3028 layout.content_origin.x
3029 + line_layout.x_for_index(range.start.column() as usize)
3030 - layout.position_map.scroll_pixel_position.x
3031 } else {
3032 layout.content_origin.x
3033 - layout.position_map.scroll_pixel_position.x
3034 },
3035 end_x: if row == range.end.row() {
3036 layout.content_origin.x
3037 + line_layout.x_for_index(range.end.column() as usize)
3038 - layout.position_map.scroll_pixel_position.x
3039 } else {
3040 layout.content_origin.x + line_layout.width + line_end_overshoot
3041 - layout.position_map.scroll_pixel_position.x
3042 },
3043 }
3044 })
3045 .collect(),
3046 };
3047
3048 highlighted_range.paint(layout.text_hitbox.bounds, cx);
3049 }
3050 }
3051
3052 fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3053 if layout.folds.is_empty() {
3054 return;
3055 }
3056
3057 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3058 let fold_corner_radius = 0.15 * layout.position_map.line_height;
3059 for mut fold in mem::take(&mut layout.folds) {
3060 fold.hover_element.paint(cx);
3061
3062 let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
3063 let fold_background = if hover_element.interactivity().active.unwrap() {
3064 cx.theme().colors().ghost_element_active
3065 } else if hover_element.interactivity().hovered.unwrap() {
3066 cx.theme().colors().ghost_element_hover
3067 } else {
3068 cx.theme().colors().ghost_element_background
3069 };
3070
3071 self.paint_highlighted_range(
3072 fold.display_range.clone(),
3073 fold_background,
3074 fold_corner_radius,
3075 fold_corner_radius * 2.,
3076 layout,
3077 cx,
3078 );
3079 }
3080 })
3081 }
3082
3083 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3084 if let Some(mut inline_blame) = layout.inline_blame.take() {
3085 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3086 inline_blame.paint(cx);
3087 })
3088 }
3089 }
3090
3091 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3092 for mut block in layout.blocks.drain(..) {
3093 block.element.paint(cx);
3094 }
3095 }
3096
3097 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3098 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3099 mouse_context_menu.paint(cx);
3100 }
3101 }
3102
3103 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3104 cx.on_mouse_event({
3105 let position_map = layout.position_map.clone();
3106 let editor = self.editor.clone();
3107 let hitbox = layout.hitbox.clone();
3108 let mut delta = ScrollDelta::default();
3109
3110 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3111 // accidentally turn off their scrolling.
3112 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3113
3114 move |event: &ScrollWheelEvent, phase, cx| {
3115 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3116 delta = delta.coalesce(event.delta);
3117 editor.update(cx, |editor, cx| {
3118 let position_map: &PositionMap = &position_map;
3119
3120 let line_height = position_map.line_height;
3121 let max_glyph_width = position_map.em_width;
3122 let (delta, axis) = match delta {
3123 gpui::ScrollDelta::Pixels(mut pixels) => {
3124 //Trackpad
3125 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3126 (pixels, axis)
3127 }
3128
3129 gpui::ScrollDelta::Lines(lines) => {
3130 //Not trackpad
3131 let pixels =
3132 point(lines.x * max_glyph_width, lines.y * line_height);
3133 (pixels, None)
3134 }
3135 };
3136
3137 let current_scroll_position = position_map.snapshot.scroll_position();
3138 let x = (current_scroll_position.x * max_glyph_width
3139 - (delta.x * scroll_sensitivity))
3140 / max_glyph_width;
3141 let y = (current_scroll_position.y * line_height
3142 - (delta.y * scroll_sensitivity))
3143 / line_height;
3144 let mut scroll_position =
3145 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3146 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3147 if forbid_vertical_scroll {
3148 scroll_position.y = current_scroll_position.y;
3149 if scroll_position == current_scroll_position {
3150 return;
3151 }
3152 }
3153 editor.scroll(scroll_position, axis, cx);
3154 cx.stop_propagation();
3155 });
3156 }
3157 }
3158 });
3159 }
3160
3161 fn paint_mouse_listeners(
3162 &mut self,
3163 layout: &EditorLayout,
3164 hovered_hunk: Option<HunkToExpand>,
3165 cx: &mut WindowContext,
3166 ) {
3167 self.paint_scroll_wheel_listener(layout, cx);
3168
3169 cx.on_mouse_event({
3170 let position_map = layout.position_map.clone();
3171 let editor = self.editor.clone();
3172 let text_hitbox = layout.text_hitbox.clone();
3173 let gutter_hitbox = layout.gutter_hitbox.clone();
3174
3175 move |event: &MouseDownEvent, phase, cx| {
3176 if phase == DispatchPhase::Bubble {
3177 match event.button {
3178 MouseButton::Left => editor.update(cx, |editor, cx| {
3179 Self::mouse_left_down(
3180 editor,
3181 event,
3182 hovered_hunk.as_ref(),
3183 &position_map,
3184 &text_hitbox,
3185 &gutter_hitbox,
3186 cx,
3187 );
3188 }),
3189 MouseButton::Right => editor.update(cx, |editor, cx| {
3190 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3191 }),
3192 MouseButton::Middle => editor.update(cx, |editor, cx| {
3193 Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3194 }),
3195 _ => {}
3196 };
3197 }
3198 }
3199 });
3200
3201 cx.on_mouse_event({
3202 let editor = self.editor.clone();
3203 let position_map = layout.position_map.clone();
3204 let text_hitbox = layout.text_hitbox.clone();
3205
3206 move |event: &MouseUpEvent, phase, cx| {
3207 if phase == DispatchPhase::Bubble {
3208 editor.update(cx, |editor, cx| {
3209 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3210 });
3211 }
3212 }
3213 });
3214 cx.on_mouse_event({
3215 let position_map = layout.position_map.clone();
3216 let editor = self.editor.clone();
3217 let text_hitbox = layout.text_hitbox.clone();
3218 let gutter_hitbox = layout.gutter_hitbox.clone();
3219
3220 move |event: &MouseMoveEvent, phase, cx| {
3221 if phase == DispatchPhase::Bubble {
3222 editor.update(cx, |editor, cx| {
3223 if event.pressed_button == Some(MouseButton::Left) {
3224 Self::mouse_dragged(
3225 editor,
3226 event,
3227 &position_map,
3228 text_hitbox.bounds,
3229 cx,
3230 )
3231 }
3232
3233 Self::mouse_moved(
3234 editor,
3235 event,
3236 &position_map,
3237 &text_hitbox,
3238 &gutter_hitbox,
3239 cx,
3240 )
3241 });
3242 }
3243 }
3244 });
3245 }
3246
3247 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3248 bounds.upper_right().x - self.style.scrollbar_width
3249 }
3250
3251 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3252 let style = &self.style;
3253 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3254 let layout = cx
3255 .text_system()
3256 .shape_line(
3257 SharedString::from(" ".repeat(column)),
3258 font_size,
3259 &[TextRun {
3260 len: column,
3261 font: style.text.font(),
3262 color: Hsla::default(),
3263 background_color: None,
3264 underline: None,
3265 strikethrough: None,
3266 }],
3267 )
3268 .unwrap();
3269
3270 layout.width
3271 }
3272
3273 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3274 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
3275 self.column_pixels(digit_count, cx)
3276 }
3277}
3278
3279fn prepaint_gutter_button(
3280 button: IconButton,
3281 row: u32,
3282 line_height: Pixels,
3283 gutter_dimensions: &GutterDimensions,
3284 scroll_pixel_position: gpui::Point<Pixels>,
3285 gutter_hitbox: &Hitbox,
3286 cx: &mut WindowContext<'_>,
3287) -> AnyElement {
3288 let mut button = button.into_any_element();
3289 let available_space = size(
3290 AvailableSpace::MinContent,
3291 AvailableSpace::Definite(line_height),
3292 );
3293 let indicator_size = button.layout_as_root(available_space, cx);
3294
3295 let blame_width = gutter_dimensions
3296 .git_blame_entries_width
3297 .unwrap_or(Pixels::ZERO);
3298
3299 let mut x = blame_width;
3300 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
3301 - indicator_size.width
3302 - blame_width;
3303 x += available_width / 2.;
3304
3305 let mut y = row as f32 * line_height - scroll_pixel_position.y;
3306 y += (line_height - indicator_size.height) / 2.;
3307
3308 button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
3309 button
3310}
3311
3312fn render_inline_blame_entry(
3313 blame: &gpui::Model<GitBlame>,
3314 blame_entry: BlameEntry,
3315 style: &EditorStyle,
3316 workspace: Option<WeakView<Workspace>>,
3317 cx: &mut WindowContext<'_>,
3318) -> AnyElement {
3319 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3320
3321 let author = blame_entry.author.as_deref().unwrap_or_default();
3322 let text = format!("{}, {}", author, relative_timestamp);
3323
3324 let details = blame.read(cx).details_for_entry(&blame_entry);
3325
3326 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3327
3328 h_flex()
3329 .id("inline-blame")
3330 .w_full()
3331 .font_family(style.text.font().family)
3332 .text_color(cx.theme().status().hint)
3333 .line_height(style.text.line_height)
3334 .child(Icon::new(IconName::FileGit).color(Color::Hint))
3335 .child(text)
3336 .gap_2()
3337 .hoverable_tooltip(move |_| tooltip.clone().into())
3338 .into_any()
3339}
3340
3341fn render_blame_entry(
3342 ix: usize,
3343 blame: &gpui::Model<GitBlame>,
3344 blame_entry: BlameEntry,
3345 style: &EditorStyle,
3346 last_used_color: &mut Option<(PlayerColor, Oid)>,
3347 editor: View<Editor>,
3348 cx: &mut WindowContext<'_>,
3349) -> AnyElement {
3350 let mut sha_color = cx
3351 .theme()
3352 .players()
3353 .color_for_participant(blame_entry.sha.into());
3354 // If the last color we used is the same as the one we get for this line, but
3355 // the commit SHAs are different, then we try again to get a different color.
3356 match *last_used_color {
3357 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3358 let index: u32 = blame_entry.sha.into();
3359 sha_color = cx.theme().players().color_for_participant(index + 1);
3360 }
3361 _ => {}
3362 };
3363 last_used_color.replace((sha_color, blame_entry.sha));
3364
3365 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3366
3367 let pretty_commit_id = format!("{}", blame_entry.sha);
3368 let short_commit_id = pretty_commit_id.chars().take(6).collect::<String>();
3369
3370 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3371 let name = util::truncate_and_trailoff(author_name, 20);
3372
3373 let details = blame.read(cx).details_for_entry(&blame_entry);
3374
3375 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3376
3377 let tooltip = cx.new_view(|_| {
3378 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3379 });
3380
3381 h_flex()
3382 .w_full()
3383 .font_family(style.text.font().family)
3384 .line_height(style.text.line_height)
3385 .id(("blame", ix))
3386 .children([
3387 div()
3388 .text_color(sha_color.cursor)
3389 .child(short_commit_id)
3390 .mr_2(),
3391 div()
3392 .w_full()
3393 .h_flex()
3394 .justify_between()
3395 .text_color(cx.theme().status().hint)
3396 .child(name)
3397 .child(relative_timestamp),
3398 ])
3399 .on_mouse_down(MouseButton::Right, {
3400 let blame_entry = blame_entry.clone();
3401 move |event, cx| {
3402 deploy_blame_entry_context_menu(&blame_entry, editor.clone(), event.position, cx);
3403 }
3404 })
3405 .hover(|style| style.bg(cx.theme().colors().element_hover))
3406 .when_some(
3407 details.and_then(|details| details.permalink),
3408 |this, url| {
3409 let url = url.clone();
3410 this.cursor_pointer().on_click(move |_, cx| {
3411 cx.stop_propagation();
3412 cx.open_url(url.as_str())
3413 })
3414 },
3415 )
3416 .hoverable_tooltip(move |_| tooltip.clone().into())
3417 .into_any()
3418}
3419
3420fn deploy_blame_entry_context_menu(
3421 blame_entry: &BlameEntry,
3422 editor: View<Editor>,
3423 position: gpui::Point<Pixels>,
3424 cx: &mut WindowContext<'_>,
3425) {
3426 let context_menu = ContextMenu::build(cx, move |this, _| {
3427 let sha = format!("{}", blame_entry.sha);
3428 this.entry("Copy commit SHA", None, move |cx| {
3429 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3430 })
3431 });
3432
3433 editor.update(cx, move |editor, cx| {
3434 editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3435 cx.notify();
3436 });
3437}
3438
3439#[derive(Debug)]
3440pub(crate) struct LineWithInvisibles {
3441 pub line: ShapedLine,
3442 invisibles: Vec<Invisible>,
3443}
3444
3445impl LineWithInvisibles {
3446 fn from_chunks<'a>(
3447 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3448 text_style: &TextStyle,
3449 max_line_len: usize,
3450 max_line_count: usize,
3451 line_number_layouts: &[Option<ShapedLine>],
3452 editor_mode: EditorMode,
3453 cx: &WindowContext,
3454 ) -> Vec<Self> {
3455 let mut layouts = Vec::with_capacity(max_line_count);
3456 let mut line = String::new();
3457 let mut invisibles = Vec::new();
3458 let mut styles = Vec::new();
3459 let mut non_whitespace_added = false;
3460 let mut row = 0;
3461 let mut line_exceeded_max_len = false;
3462 let font_size = text_style.font_size.to_pixels(cx.rem_size());
3463
3464 for highlighted_chunk in chunks.chain([HighlightedChunk {
3465 chunk: "\n",
3466 style: None,
3467 is_tab: false,
3468 }]) {
3469 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
3470 if ix > 0 {
3471 let shaped_line = cx
3472 .text_system()
3473 .shape_line(line.clone().into(), font_size, &styles)
3474 .unwrap();
3475 layouts.push(Self {
3476 line: shaped_line,
3477 invisibles: std::mem::take(&mut invisibles),
3478 });
3479
3480 line.clear();
3481 styles.clear();
3482 row += 1;
3483 line_exceeded_max_len = false;
3484 non_whitespace_added = false;
3485 if row == max_line_count {
3486 return layouts;
3487 }
3488 }
3489
3490 if !line_chunk.is_empty() && !line_exceeded_max_len {
3491 let text_style = if let Some(style) = highlighted_chunk.style {
3492 Cow::Owned(text_style.clone().highlight(style))
3493 } else {
3494 Cow::Borrowed(text_style)
3495 };
3496
3497 if line.len() + line_chunk.len() > max_line_len {
3498 let mut chunk_len = max_line_len - line.len();
3499 while !line_chunk.is_char_boundary(chunk_len) {
3500 chunk_len -= 1;
3501 }
3502 line_chunk = &line_chunk[..chunk_len];
3503 line_exceeded_max_len = true;
3504 }
3505
3506 styles.push(TextRun {
3507 len: line_chunk.len(),
3508 font: text_style.font(),
3509 color: text_style.color,
3510 background_color: text_style.background_color,
3511 underline: text_style.underline,
3512 strikethrough: text_style.strikethrough,
3513 });
3514
3515 if editor_mode == EditorMode::Full {
3516 // Line wrap pads its contents with fake whitespaces,
3517 // avoid printing them
3518 let inside_wrapped_string = line_number_layouts
3519 .get(row)
3520 .and_then(|layout| layout.as_ref())
3521 .is_none();
3522 if highlighted_chunk.is_tab {
3523 if non_whitespace_added || !inside_wrapped_string {
3524 invisibles.push(Invisible::Tab {
3525 line_start_offset: line.len(),
3526 });
3527 }
3528 } else {
3529 invisibles.extend(
3530 line_chunk
3531 .chars()
3532 .enumerate()
3533 .filter(|(_, line_char)| {
3534 let is_whitespace = line_char.is_whitespace();
3535 non_whitespace_added |= !is_whitespace;
3536 is_whitespace
3537 && (non_whitespace_added || !inside_wrapped_string)
3538 })
3539 .map(|(whitespace_index, _)| Invisible::Whitespace {
3540 line_offset: line.len() + whitespace_index,
3541 }),
3542 )
3543 }
3544 }
3545
3546 line.push_str(line_chunk);
3547 }
3548 }
3549 }
3550
3551 layouts
3552 }
3553
3554 fn draw(
3555 &self,
3556 layout: &EditorLayout,
3557 row: u32,
3558 content_origin: gpui::Point<Pixels>,
3559 whitespace_setting: ShowWhitespaceSetting,
3560 selection_ranges: &[Range<DisplayPoint>],
3561 cx: &mut WindowContext,
3562 ) {
3563 let line_height = layout.position_map.line_height;
3564 let line_y =
3565 line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
3566
3567 let line_origin =
3568 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
3569 self.line.paint(line_origin, line_height, cx).log_err();
3570
3571 self.draw_invisibles(
3572 &selection_ranges,
3573 layout,
3574 content_origin,
3575 line_y,
3576 row,
3577 line_height,
3578 whitespace_setting,
3579 cx,
3580 );
3581 }
3582
3583 #[allow(clippy::too_many_arguments)]
3584 fn draw_invisibles(
3585 &self,
3586 selection_ranges: &[Range<DisplayPoint>],
3587 layout: &EditorLayout,
3588 content_origin: gpui::Point<Pixels>,
3589 line_y: Pixels,
3590 row: u32,
3591 line_height: Pixels,
3592 whitespace_setting: ShowWhitespaceSetting,
3593 cx: &mut WindowContext,
3594 ) {
3595 let allowed_invisibles_regions = match whitespace_setting {
3596 ShowWhitespaceSetting::None => return,
3597 ShowWhitespaceSetting::Selection => Some(selection_ranges),
3598 ShowWhitespaceSetting::All => None,
3599 };
3600
3601 for invisible in &self.invisibles {
3602 let (&token_offset, invisible_symbol) = match invisible {
3603 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
3604 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
3605 };
3606
3607 let x_offset = self.line.x_for_index(token_offset);
3608 let invisible_offset =
3609 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
3610 let origin = content_origin
3611 + gpui::point(
3612 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
3613 line_y,
3614 );
3615
3616 if let Some(allowed_regions) = allowed_invisibles_regions {
3617 let invisible_point = DisplayPoint::new(row, token_offset as u32);
3618 if !allowed_regions
3619 .iter()
3620 .any(|region| region.start <= invisible_point && invisible_point < region.end)
3621 {
3622 continue;
3623 }
3624 }
3625 invisible_symbol.paint(origin, line_height, cx).log_err();
3626 }
3627 }
3628}
3629
3630#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3631enum Invisible {
3632 Tab { line_start_offset: usize },
3633 Whitespace { line_offset: usize },
3634}
3635
3636impl Element for EditorElement {
3637 type RequestLayoutState = ();
3638 type PrepaintState = EditorLayout;
3639
3640 fn id(&self) -> Option<ElementId> {
3641 None
3642 }
3643
3644 fn request_layout(
3645 &mut self,
3646 _: Option<&GlobalElementId>,
3647 cx: &mut WindowContext,
3648 ) -> (gpui::LayoutId, ()) {
3649 self.editor.update(cx, |editor, cx| {
3650 editor.set_style(self.style.clone(), cx);
3651
3652 let layout_id = match editor.mode {
3653 EditorMode::SingleLine => {
3654 let rem_size = cx.rem_size();
3655 let mut style = Style::default();
3656 style.size.width = relative(1.).into();
3657 style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
3658 cx.request_layout(&style, None)
3659 }
3660 EditorMode::AutoHeight { max_lines } => {
3661 let editor_handle = cx.view().clone();
3662 let max_line_number_width =
3663 self.max_line_number_width(&editor.snapshot(cx), cx);
3664 cx.request_measured_layout(Style::default(), move |known_dimensions, _, cx| {
3665 editor_handle
3666 .update(cx, |editor, cx| {
3667 compute_auto_height_layout(
3668 editor,
3669 max_lines,
3670 max_line_number_width,
3671 known_dimensions,
3672 cx,
3673 )
3674 })
3675 .unwrap_or_default()
3676 })
3677 }
3678 EditorMode::Full => {
3679 let mut style = Style::default();
3680 style.size.width = relative(1.).into();
3681 style.size.height = relative(1.).into();
3682 cx.request_layout(&style, None)
3683 }
3684 };
3685
3686 (layout_id, ())
3687 })
3688 }
3689
3690 fn prepaint(
3691 &mut self,
3692 _: Option<&GlobalElementId>,
3693 bounds: Bounds<Pixels>,
3694 _: &mut Self::RequestLayoutState,
3695 cx: &mut WindowContext,
3696 ) -> Self::PrepaintState {
3697 let text_style = TextStyleRefinement {
3698 font_size: Some(self.style.text.font_size),
3699 line_height: Some(self.style.text.line_height),
3700 ..Default::default()
3701 };
3702 cx.set_view_id(self.editor.entity_id());
3703 cx.with_text_style(Some(text_style), |cx| {
3704 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3705 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3706 let style = self.style.clone();
3707
3708 let font_id = cx.text_system().resolve_font(&style.text.font());
3709 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3710 let line_height = style.text.line_height_in_pixels(cx.rem_size());
3711 let em_width = cx
3712 .text_system()
3713 .typographic_bounds(font_id, font_size, 'm')
3714 .unwrap()
3715 .size
3716 .width;
3717 let em_advance = cx
3718 .text_system()
3719 .advance(font_id, font_size, 'm')
3720 .unwrap()
3721 .width;
3722
3723 let gutter_dimensions = snapshot.gutter_dimensions(
3724 font_id,
3725 font_size,
3726 em_width,
3727 self.max_line_number_width(&snapshot, cx),
3728 cx,
3729 );
3730 let text_width = bounds.size.width - gutter_dimensions.width;
3731 let overscroll = size(em_width, px(0.));
3732
3733 snapshot = self.editor.update(cx, |editor, cx| {
3734 editor.last_bounds = Some(bounds);
3735 editor.gutter_dimensions = gutter_dimensions;
3736 editor.set_visible_line_count(bounds.size.height / line_height, cx);
3737
3738 let editor_width =
3739 text_width - gutter_dimensions.margin - overscroll.width - em_width;
3740 let wrap_width = match editor.soft_wrap_mode(cx) {
3741 SoftWrap::None => None,
3742 SoftWrap::PreferLine => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
3743 SoftWrap::EditorWidth => Some(editor_width),
3744 SoftWrap::Column(column) => {
3745 Some(editor_width.min(column as f32 * em_advance))
3746 }
3747 };
3748
3749 if editor.set_wrap_width(wrap_width, cx) {
3750 editor.snapshot(cx)
3751 } else {
3752 snapshot
3753 }
3754 });
3755
3756 let wrap_guides = self
3757 .editor
3758 .read(cx)
3759 .wrap_guides(cx)
3760 .iter()
3761 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
3762 .collect::<SmallVec<[_; 2]>>();
3763
3764 let hitbox = cx.insert_hitbox(bounds, false);
3765 let gutter_hitbox = cx.insert_hitbox(
3766 Bounds {
3767 origin: bounds.origin,
3768 size: size(gutter_dimensions.width, bounds.size.height),
3769 },
3770 false,
3771 );
3772 let text_hitbox = cx.insert_hitbox(
3773 Bounds {
3774 origin: gutter_hitbox.upper_right(),
3775 size: size(text_width, bounds.size.height),
3776 },
3777 false,
3778 );
3779 // Offset the content_bounds from the text_bounds by the gutter margin (which
3780 // is roughly half a character wide) to make hit testing work more like how we want.
3781 let content_origin =
3782 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
3783
3784 let mut autoscroll_containing_element = false;
3785 let mut autoscroll_horizontally = false;
3786 self.editor.update(cx, |editor, cx| {
3787 autoscroll_containing_element =
3788 editor.autoscroll_requested() || editor.has_pending_selection();
3789 autoscroll_horizontally = editor.autoscroll_vertically(bounds, line_height, cx);
3790 snapshot = editor.snapshot(cx);
3791 });
3792
3793 let mut scroll_position = snapshot.scroll_position();
3794 // The scroll position is a fractional point, the whole number of which represents
3795 // the top of the window in terms of display rows.
3796 let start_row = scroll_position.y as u32;
3797 let height_in_lines = bounds.size.height / line_height;
3798 let max_row = snapshot.max_point().row();
3799 let end_row = cmp::min(
3800 (scroll_position.y + height_in_lines).ceil() as u32,
3801 max_row + 1,
3802 );
3803
3804 let buffer_rows = snapshot
3805 .buffer_rows(start_row)
3806 .take((start_row..end_row).len());
3807
3808 let start_anchor = if start_row == 0 {
3809 Anchor::min()
3810 } else {
3811 snapshot.buffer_snapshot.anchor_before(
3812 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3813 )
3814 };
3815 let end_anchor = if end_row > max_row {
3816 Anchor::max()
3817 } else {
3818 snapshot.buffer_snapshot.anchor_before(
3819 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3820 )
3821 };
3822
3823 let highlighted_rows = self.editor.update(cx, |editor, cx| {
3824 editor.highlighted_display_rows(HashSet::default(), cx)
3825 });
3826 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3827 start_anchor..end_anchor,
3828 &snapshot.display_snapshot,
3829 cx.theme().colors(),
3830 );
3831
3832 let redacted_ranges = self.editor.read(cx).redacted_ranges(
3833 start_anchor..end_anchor,
3834 &snapshot.display_snapshot,
3835 cx,
3836 );
3837
3838 let test_lines = self.editor.read(cx).runnable_display_rows(
3839 start_anchor..end_anchor,
3840 &snapshot.display_snapshot,
3841 cx,
3842 );
3843
3844 let (selections, active_rows, newest_selection_head) = self.layout_selections(
3845 start_anchor,
3846 end_anchor,
3847 &snapshot,
3848 start_row,
3849 end_row,
3850 cx,
3851 );
3852
3853 let (line_numbers, fold_statuses) = self.layout_line_numbers(
3854 start_row..end_row,
3855 buffer_rows.clone(),
3856 &active_rows,
3857 newest_selection_head,
3858 &snapshot,
3859 cx,
3860 );
3861
3862 let display_hunks = self.layout_git_gutters(
3863 line_height,
3864 &gutter_hitbox,
3865 start_row..end_row,
3866 &snapshot,
3867 cx,
3868 );
3869
3870 let mut max_visible_line_width = Pixels::ZERO;
3871 let line_layouts =
3872 self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3873 for line_with_invisibles in &line_layouts {
3874 if line_with_invisibles.line.width > max_visible_line_width {
3875 max_visible_line_width = line_with_invisibles.line.width;
3876 }
3877 }
3878
3879 let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3880 .unwrap()
3881 .width;
3882 let mut scroll_width =
3883 longest_line_width.max(max_visible_line_width) + overscroll.width;
3884
3885 let mut blocks = cx.with_element_namespace("blocks", |cx| {
3886 self.build_blocks(
3887 start_row..end_row,
3888 &snapshot,
3889 &hitbox,
3890 &text_hitbox,
3891 &mut scroll_width,
3892 &gutter_dimensions,
3893 em_width,
3894 gutter_dimensions.width + gutter_dimensions.margin,
3895 line_height,
3896 &line_layouts,
3897 cx,
3898 )
3899 });
3900
3901 let scroll_pixel_position = point(
3902 scroll_position.x * em_width,
3903 scroll_position.y * line_height,
3904 );
3905
3906 let mut inline_blame = None;
3907 if let Some(newest_selection_head) = newest_selection_head {
3908 let display_row = newest_selection_head.row();
3909 if (start_row..end_row).contains(&display_row) {
3910 let line_layout = &line_layouts[(display_row - start_row) as usize];
3911 inline_blame = self.layout_inline_blame(
3912 display_row,
3913 &snapshot.display_snapshot,
3914 line_layout,
3915 em_width,
3916 content_origin,
3917 scroll_pixel_position,
3918 line_height,
3919 cx,
3920 );
3921 }
3922 }
3923
3924 let blamed_display_rows = self.layout_blame_entries(
3925 buffer_rows,
3926 em_width,
3927 scroll_position,
3928 line_height,
3929 &gutter_hitbox,
3930 gutter_dimensions.git_blame_entries_width,
3931 cx,
3932 );
3933
3934 let scroll_max = point(
3935 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3936 max_row as f32,
3937 );
3938
3939 self.editor.update(cx, |editor, cx| {
3940 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3941
3942 let autoscrolled = if autoscroll_horizontally {
3943 editor.autoscroll_horizontally(
3944 start_row,
3945 text_hitbox.size.width,
3946 scroll_width,
3947 em_width,
3948 &line_layouts,
3949 cx,
3950 )
3951 } else {
3952 false
3953 };
3954
3955 if clamped || autoscrolled {
3956 snapshot = editor.snapshot(cx);
3957 scroll_position = snapshot.scroll_position();
3958 }
3959 });
3960
3961 cx.with_element_namespace("blocks", |cx| {
3962 self.layout_blocks(
3963 &mut blocks,
3964 &hitbox,
3965 line_height,
3966 scroll_pixel_position,
3967 cx,
3968 );
3969 });
3970
3971 let cursors = self.collect_cursors(&snapshot, cx);
3972 let visible_row_range = start_row..end_row;
3973 let non_visible_cursors = cursors
3974 .iter()
3975 .any(move |c| !visible_row_range.contains(&c.0.row()));
3976
3977 let visible_cursors = self.layout_visible_cursors(
3978 &snapshot,
3979 &selections,
3980 start_row..end_row,
3981 &line_layouts,
3982 &text_hitbox,
3983 content_origin,
3984 scroll_position,
3985 scroll_pixel_position,
3986 line_height,
3987 em_width,
3988 autoscroll_containing_element,
3989 cx,
3990 );
3991
3992 let scrollbar_layout = self.layout_scrollbar(
3993 &snapshot,
3994 bounds,
3995 scroll_position,
3996 height_in_lines,
3997 non_visible_cursors,
3998 cx,
3999 );
4000
4001 let folds = cx.with_element_namespace("folds", |cx| {
4002 self.layout_folds(
4003 &snapshot,
4004 content_origin,
4005 start_anchor..end_anchor,
4006 start_row..end_row,
4007 scroll_pixel_position,
4008 line_height,
4009 &line_layouts,
4010 cx,
4011 )
4012 });
4013
4014 let gutter_settings = EditorSettings::get_global(cx).gutter;
4015
4016 let mut context_menu_visible = false;
4017 let mut code_actions_indicator = None;
4018 if let Some(newest_selection_head) = newest_selection_head {
4019 if (start_row..end_row).contains(&newest_selection_head.row()) {
4020 context_menu_visible = self.layout_context_menu(
4021 line_height,
4022 &hitbox,
4023 &text_hitbox,
4024 content_origin,
4025 start_row,
4026 scroll_pixel_position,
4027 &line_layouts,
4028 newest_selection_head,
4029 gutter_dimensions.width - gutter_dimensions.left_padding,
4030 cx,
4031 );
4032 if gutter_settings.code_actions {
4033 let has_test_indicator = test_lines
4034 .iter()
4035 .any(|(line, _)| *line == newest_selection_head.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 test_lines,
4052 line_height,
4053 scroll_pixel_position,
4054 &gutter_dimensions,
4055 &gutter_hitbox,
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}