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