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 let max_row = layout.max_row;
2870
2871 editor.scrollbar_marker_state.dirty = false;
2872 editor.scrollbar_marker_state.pending_refresh =
2873 Some(cx.spawn(|editor, mut cx| async move {
2874 let scrollbar_size = scrollbar_layout.hitbox.size;
2875 let scrollbar_markers = cx
2876 .background_executor()
2877 .spawn(async move {
2878 let mut marker_quads = Vec::new();
2879
2880 if scrollbar_settings.git_diff {
2881 let marker_row_ranges = snapshot
2882 .buffer_snapshot
2883 .git_diff_hunks_in_range(0..max_row)
2884 .map(|hunk| {
2885 let start_display_row =
2886 Point::new(hunk.associated_range.start, 0)
2887 .to_display_point(&snapshot.display_snapshot)
2888 .row();
2889 let mut end_display_row =
2890 Point::new(hunk.associated_range.end, 0)
2891 .to_display_point(&snapshot.display_snapshot)
2892 .row();
2893 if end_display_row != start_display_row {
2894 end_display_row -= 1;
2895 }
2896 let color = match hunk.status() {
2897 DiffHunkStatus::Added => theme.status().created,
2898 DiffHunkStatus::Modified => theme.status().modified,
2899 DiffHunkStatus::Removed => theme.status().deleted,
2900 };
2901 ColoredRange {
2902 start: start_display_row,
2903 end: end_display_row,
2904 color,
2905 }
2906 });
2907
2908 marker_quads.extend(
2909 scrollbar_layout
2910 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
2911 );
2912 }
2913
2914 for (background_highlight_id, (_, background_ranges)) in
2915 background_highlights.iter()
2916 {
2917 let is_search_highlights = *background_highlight_id
2918 == TypeId::of::<BufferSearchHighlights>();
2919 let is_symbol_occurrences = *background_highlight_id
2920 == TypeId::of::<DocumentHighlightRead>()
2921 || *background_highlight_id
2922 == TypeId::of::<DocumentHighlightWrite>();
2923 if (is_search_highlights && scrollbar_settings.search_results)
2924 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
2925 {
2926 let mut color = theme.status().info;
2927 if is_symbol_occurrences {
2928 color.fade_out(0.5);
2929 }
2930 let marker_row_ranges =
2931 background_ranges.into_iter().map(|range| {
2932 let display_start = range
2933 .start
2934 .to_display_point(&snapshot.display_snapshot);
2935 let display_end = range
2936 .end
2937 .to_display_point(&snapshot.display_snapshot);
2938 ColoredRange {
2939 start: display_start.row(),
2940 end: display_end.row(),
2941 color,
2942 }
2943 });
2944 marker_quads.extend(
2945 scrollbar_layout
2946 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
2947 );
2948 }
2949 }
2950
2951 if scrollbar_settings.diagnostics {
2952 let max_point =
2953 snapshot.display_snapshot.buffer_snapshot.max_point();
2954
2955 let diagnostics = snapshot
2956 .buffer_snapshot
2957 .diagnostics_in_range::<_, Point>(
2958 Point::zero()..max_point,
2959 false,
2960 )
2961 // We want to sort by severity, in order to paint the most severe diagnostics last.
2962 .sorted_by_key(|diagnostic| {
2963 std::cmp::Reverse(diagnostic.diagnostic.severity)
2964 });
2965
2966 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
2967 let start_display = diagnostic
2968 .range
2969 .start
2970 .to_display_point(&snapshot.display_snapshot);
2971 let end_display = diagnostic
2972 .range
2973 .end
2974 .to_display_point(&snapshot.display_snapshot);
2975 let color = match diagnostic.diagnostic.severity {
2976 DiagnosticSeverity::ERROR => theme.status().error,
2977 DiagnosticSeverity::WARNING => theme.status().warning,
2978 DiagnosticSeverity::INFORMATION => theme.status().info,
2979 _ => theme.status().hint,
2980 };
2981 ColoredRange {
2982 start: start_display.row(),
2983 end: end_display.row(),
2984 color,
2985 }
2986 });
2987 marker_quads.extend(
2988 scrollbar_layout
2989 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
2990 );
2991 }
2992
2993 Arc::from(marker_quads)
2994 })
2995 .await;
2996
2997 editor.update(&mut cx, |editor, cx| {
2998 editor.scrollbar_marker_state.markers = scrollbar_markers;
2999 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
3000 editor.scrollbar_marker_state.pending_refresh = None;
3001 cx.notify();
3002 })?;
3003
3004 Ok(())
3005 }));
3006 });
3007 }
3008
3009 #[allow(clippy::too_many_arguments)]
3010 fn paint_highlighted_range(
3011 &self,
3012 range: Range<DisplayPoint>,
3013 color: Hsla,
3014 corner_radius: Pixels,
3015 line_end_overshoot: Pixels,
3016 layout: &EditorLayout,
3017 cx: &mut WindowContext,
3018 ) {
3019 let start_row = layout.visible_display_row_range.start;
3020 let end_row = layout.visible_display_row_range.end;
3021 if range.start != range.end {
3022 let row_range = if range.end.column() == 0 {
3023 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3024 } else {
3025 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
3026 };
3027
3028 let highlighted_range = HighlightedRange {
3029 color,
3030 line_height: layout.position_map.line_height,
3031 corner_radius,
3032 start_y: layout.content_origin.y
3033 + row_range.start as f32 * layout.position_map.line_height
3034 - layout.position_map.scroll_pixel_position.y,
3035 lines: row_range
3036 .into_iter()
3037 .map(|row| {
3038 let line_layout =
3039 &layout.position_map.line_layouts[(row - start_row) as usize].line;
3040 HighlightedRangeLine {
3041 start_x: if row == range.start.row() {
3042 layout.content_origin.x
3043 + line_layout.x_for_index(range.start.column() as usize)
3044 - layout.position_map.scroll_pixel_position.x
3045 } else {
3046 layout.content_origin.x
3047 - layout.position_map.scroll_pixel_position.x
3048 },
3049 end_x: if row == range.end.row() {
3050 layout.content_origin.x
3051 + line_layout.x_for_index(range.end.column() as usize)
3052 - layout.position_map.scroll_pixel_position.x
3053 } else {
3054 layout.content_origin.x + line_layout.width + line_end_overshoot
3055 - layout.position_map.scroll_pixel_position.x
3056 },
3057 }
3058 })
3059 .collect(),
3060 };
3061
3062 highlighted_range.paint(layout.text_hitbox.bounds, cx);
3063 }
3064 }
3065
3066 fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3067 if layout.folds.is_empty() {
3068 return;
3069 }
3070
3071 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3072 let fold_corner_radius = 0.15 * layout.position_map.line_height;
3073 for mut fold in mem::take(&mut layout.folds) {
3074 fold.hover_element.paint(cx);
3075
3076 let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
3077 let fold_background = if hover_element.interactivity().active.unwrap() {
3078 cx.theme().colors().ghost_element_active
3079 } else if hover_element.interactivity().hovered.unwrap() {
3080 cx.theme().colors().ghost_element_hover
3081 } else {
3082 cx.theme().colors().ghost_element_background
3083 };
3084
3085 self.paint_highlighted_range(
3086 fold.display_range.clone(),
3087 fold_background,
3088 fold_corner_radius,
3089 fold_corner_radius * 2.,
3090 layout,
3091 cx,
3092 );
3093 }
3094 })
3095 }
3096
3097 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3098 if let Some(mut inline_blame) = layout.inline_blame.take() {
3099 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3100 inline_blame.paint(cx);
3101 })
3102 }
3103 }
3104
3105 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3106 for mut block in layout.blocks.drain(..) {
3107 block.element.paint(cx);
3108 }
3109 }
3110
3111 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3112 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3113 mouse_context_menu.paint(cx);
3114 }
3115 }
3116
3117 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3118 cx.on_mouse_event({
3119 let position_map = layout.position_map.clone();
3120 let editor = self.editor.clone();
3121 let hitbox = layout.hitbox.clone();
3122 let mut delta = ScrollDelta::default();
3123
3124 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3125 // accidentally turn off their scrolling.
3126 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3127
3128 move |event: &ScrollWheelEvent, phase, cx| {
3129 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3130 delta = delta.coalesce(event.delta);
3131 editor.update(cx, |editor, cx| {
3132 let position_map: &PositionMap = &position_map;
3133
3134 let line_height = position_map.line_height;
3135 let max_glyph_width = position_map.em_width;
3136 let (delta, axis) = match delta {
3137 gpui::ScrollDelta::Pixels(mut pixels) => {
3138 //Trackpad
3139 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3140 (pixels, axis)
3141 }
3142
3143 gpui::ScrollDelta::Lines(lines) => {
3144 //Not trackpad
3145 let pixels =
3146 point(lines.x * max_glyph_width, lines.y * line_height);
3147 (pixels, None)
3148 }
3149 };
3150
3151 let current_scroll_position = position_map.snapshot.scroll_position();
3152 let x = (current_scroll_position.x * max_glyph_width
3153 - (delta.x * scroll_sensitivity))
3154 / max_glyph_width;
3155 let y = (current_scroll_position.y * line_height
3156 - (delta.y * scroll_sensitivity))
3157 / line_height;
3158 let mut scroll_position =
3159 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3160 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3161 if forbid_vertical_scroll {
3162 scroll_position.y = current_scroll_position.y;
3163 if scroll_position == current_scroll_position {
3164 return;
3165 }
3166 }
3167 editor.scroll(scroll_position, axis, cx);
3168 cx.stop_propagation();
3169 });
3170 }
3171 }
3172 });
3173 }
3174
3175 fn paint_mouse_listeners(
3176 &mut self,
3177 layout: &EditorLayout,
3178 hovered_hunk: Option<HunkToExpand>,
3179 cx: &mut WindowContext,
3180 ) {
3181 self.paint_scroll_wheel_listener(layout, cx);
3182
3183 cx.on_mouse_event({
3184 let position_map = layout.position_map.clone();
3185 let editor = self.editor.clone();
3186 let text_hitbox = layout.text_hitbox.clone();
3187 let gutter_hitbox = layout.gutter_hitbox.clone();
3188
3189 move |event: &MouseDownEvent, phase, cx| {
3190 if phase == DispatchPhase::Bubble {
3191 match event.button {
3192 MouseButton::Left => editor.update(cx, |editor, cx| {
3193 Self::mouse_left_down(
3194 editor,
3195 event,
3196 hovered_hunk.as_ref(),
3197 &position_map,
3198 &text_hitbox,
3199 &gutter_hitbox,
3200 cx,
3201 );
3202 }),
3203 MouseButton::Right => editor.update(cx, |editor, cx| {
3204 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3205 }),
3206 MouseButton::Middle => editor.update(cx, |editor, cx| {
3207 Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3208 }),
3209 _ => {}
3210 };
3211 }
3212 }
3213 });
3214
3215 cx.on_mouse_event({
3216 let editor = self.editor.clone();
3217 let position_map = layout.position_map.clone();
3218 let text_hitbox = layout.text_hitbox.clone();
3219
3220 move |event: &MouseUpEvent, phase, cx| {
3221 if phase == DispatchPhase::Bubble {
3222 editor.update(cx, |editor, cx| {
3223 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3224 });
3225 }
3226 }
3227 });
3228 cx.on_mouse_event({
3229 let position_map = layout.position_map.clone();
3230 let editor = self.editor.clone();
3231 let text_hitbox = layout.text_hitbox.clone();
3232 let gutter_hitbox = layout.gutter_hitbox.clone();
3233
3234 move |event: &MouseMoveEvent, phase, cx| {
3235 if phase == DispatchPhase::Bubble {
3236 editor.update(cx, |editor, cx| {
3237 if event.pressed_button == Some(MouseButton::Left) {
3238 Self::mouse_dragged(
3239 editor,
3240 event,
3241 &position_map,
3242 text_hitbox.bounds,
3243 cx,
3244 )
3245 }
3246
3247 Self::mouse_moved(
3248 editor,
3249 event,
3250 &position_map,
3251 &text_hitbox,
3252 &gutter_hitbox,
3253 cx,
3254 )
3255 });
3256 }
3257 }
3258 });
3259 }
3260
3261 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
3262 bounds.upper_right().x - self.style.scrollbar_width
3263 }
3264
3265 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
3266 let style = &self.style;
3267 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3268 let layout = cx
3269 .text_system()
3270 .shape_line(
3271 SharedString::from(" ".repeat(column)),
3272 font_size,
3273 &[TextRun {
3274 len: column,
3275 font: style.text.font(),
3276 color: Hsla::default(),
3277 background_color: None,
3278 underline: None,
3279 strikethrough: None,
3280 }],
3281 )
3282 .unwrap();
3283
3284 layout.width
3285 }
3286
3287 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
3288 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
3289 self.column_pixels(digit_count, cx)
3290 }
3291}
3292
3293fn prepaint_gutter_button(
3294 button: IconButton,
3295 row: u32,
3296 line_height: Pixels,
3297 gutter_dimensions: &GutterDimensions,
3298 scroll_pixel_position: gpui::Point<Pixels>,
3299 gutter_hitbox: &Hitbox,
3300 cx: &mut WindowContext<'_>,
3301) -> AnyElement {
3302 let mut button = button.into_any_element();
3303 let available_space = size(
3304 AvailableSpace::MinContent,
3305 AvailableSpace::Definite(line_height),
3306 );
3307 let indicator_size = button.layout_as_root(available_space, cx);
3308
3309 let blame_width = gutter_dimensions
3310 .git_blame_entries_width
3311 .unwrap_or(Pixels::ZERO);
3312
3313 let mut x = blame_width;
3314 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
3315 - indicator_size.width
3316 - blame_width;
3317 x += available_width / 2.;
3318
3319 let mut y = row as f32 * line_height - scroll_pixel_position.y;
3320 y += (line_height - indicator_size.height) / 2.;
3321
3322 button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
3323 button
3324}
3325
3326fn render_inline_blame_entry(
3327 blame: &gpui::Model<GitBlame>,
3328 blame_entry: BlameEntry,
3329 style: &EditorStyle,
3330 workspace: Option<WeakView<Workspace>>,
3331 cx: &mut WindowContext<'_>,
3332) -> AnyElement {
3333 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3334
3335 let author = blame_entry.author.as_deref().unwrap_or_default();
3336 let text = format!("{}, {}", author, relative_timestamp);
3337
3338 let details = blame.read(cx).details_for_entry(&blame_entry);
3339
3340 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
3341
3342 h_flex()
3343 .id("inline-blame")
3344 .w_full()
3345 .font_family(style.text.font().family)
3346 .text_color(cx.theme().status().hint)
3347 .line_height(style.text.line_height)
3348 .child(Icon::new(IconName::FileGit).color(Color::Hint))
3349 .child(text)
3350 .gap_2()
3351 .hoverable_tooltip(move |_| tooltip.clone().into())
3352 .into_any()
3353}
3354
3355fn render_blame_entry(
3356 ix: usize,
3357 blame: &gpui::Model<GitBlame>,
3358 blame_entry: BlameEntry,
3359 style: &EditorStyle,
3360 last_used_color: &mut Option<(PlayerColor, Oid)>,
3361 editor: View<Editor>,
3362 cx: &mut WindowContext<'_>,
3363) -> AnyElement {
3364 let mut sha_color = cx
3365 .theme()
3366 .players()
3367 .color_for_participant(blame_entry.sha.into());
3368 // If the last color we used is the same as the one we get for this line, but
3369 // the commit SHAs are different, then we try again to get a different color.
3370 match *last_used_color {
3371 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
3372 let index: u32 = blame_entry.sha.into();
3373 sha_color = cx.theme().players().color_for_participant(index + 1);
3374 }
3375 _ => {}
3376 };
3377 last_used_color.replace((sha_color, blame_entry.sha));
3378
3379 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry, cx);
3380
3381 let short_commit_id = blame_entry.sha.display_short();
3382
3383 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
3384 let name = util::truncate_and_trailoff(author_name, 20);
3385
3386 let details = blame.read(cx).details_for_entry(&blame_entry);
3387
3388 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
3389
3390 let tooltip = cx.new_view(|_| {
3391 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
3392 });
3393
3394 h_flex()
3395 .w_full()
3396 .font_family(style.text.font().family)
3397 .line_height(style.text.line_height)
3398 .id(("blame", ix))
3399 .children([
3400 div()
3401 .text_color(sha_color.cursor)
3402 .child(short_commit_id)
3403 .mr_2(),
3404 div()
3405 .w_full()
3406 .h_flex()
3407 .justify_between()
3408 .text_color(cx.theme().status().hint)
3409 .child(name)
3410 .child(relative_timestamp),
3411 ])
3412 .on_mouse_down(MouseButton::Right, {
3413 let blame_entry = blame_entry.clone();
3414 move |event, cx| {
3415 deploy_blame_entry_context_menu(&blame_entry, editor.clone(), event.position, cx);
3416 }
3417 })
3418 .hover(|style| style.bg(cx.theme().colors().element_hover))
3419 .when_some(
3420 details.and_then(|details| details.permalink),
3421 |this, url| {
3422 let url = url.clone();
3423 this.cursor_pointer().on_click(move |_, cx| {
3424 cx.stop_propagation();
3425 cx.open_url(url.as_str())
3426 })
3427 },
3428 )
3429 .hoverable_tooltip(move |_| tooltip.clone().into())
3430 .into_any()
3431}
3432
3433fn deploy_blame_entry_context_menu(
3434 blame_entry: &BlameEntry,
3435 editor: View<Editor>,
3436 position: gpui::Point<Pixels>,
3437 cx: &mut WindowContext<'_>,
3438) {
3439 let context_menu = ContextMenu::build(cx, move |this, _| {
3440 let sha = format!("{}", blame_entry.sha);
3441 this.entry("Copy commit SHA", None, move |cx| {
3442 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
3443 })
3444 });
3445
3446 editor.update(cx, move |editor, cx| {
3447 editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
3448 cx.notify();
3449 });
3450}
3451
3452#[derive(Debug)]
3453pub(crate) struct LineWithInvisibles {
3454 pub line: ShapedLine,
3455 invisibles: Vec<Invisible>,
3456}
3457
3458impl LineWithInvisibles {
3459 fn from_chunks<'a>(
3460 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3461 text_style: &TextStyle,
3462 max_line_len: usize,
3463 max_line_count: usize,
3464 line_number_layouts: &[Option<ShapedLine>],
3465 editor_mode: EditorMode,
3466 cx: &WindowContext,
3467 ) -> Vec<Self> {
3468 let mut layouts = Vec::with_capacity(max_line_count);
3469 let mut line = String::new();
3470 let mut invisibles = Vec::new();
3471 let mut styles = Vec::new();
3472 let mut non_whitespace_added = false;
3473 let mut row = 0;
3474 let mut line_exceeded_max_len = false;
3475 let font_size = text_style.font_size.to_pixels(cx.rem_size());
3476
3477 for highlighted_chunk in chunks.chain([HighlightedChunk {
3478 chunk: "\n",
3479 style: None,
3480 is_tab: false,
3481 }]) {
3482 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
3483 if ix > 0 {
3484 let shaped_line = cx
3485 .text_system()
3486 .shape_line(line.clone().into(), font_size, &styles)
3487 .unwrap();
3488 layouts.push(Self {
3489 line: shaped_line,
3490 invisibles: std::mem::take(&mut invisibles),
3491 });
3492
3493 line.clear();
3494 styles.clear();
3495 row += 1;
3496 line_exceeded_max_len = false;
3497 non_whitespace_added = false;
3498 if row == max_line_count {
3499 return layouts;
3500 }
3501 }
3502
3503 if !line_chunk.is_empty() && !line_exceeded_max_len {
3504 let text_style = if let Some(style) = highlighted_chunk.style {
3505 Cow::Owned(text_style.clone().highlight(style))
3506 } else {
3507 Cow::Borrowed(text_style)
3508 };
3509
3510 if line.len() + line_chunk.len() > max_line_len {
3511 let mut chunk_len = max_line_len - line.len();
3512 while !line_chunk.is_char_boundary(chunk_len) {
3513 chunk_len -= 1;
3514 }
3515 line_chunk = &line_chunk[..chunk_len];
3516 line_exceeded_max_len = true;
3517 }
3518
3519 styles.push(TextRun {
3520 len: line_chunk.len(),
3521 font: text_style.font(),
3522 color: text_style.color,
3523 background_color: text_style.background_color,
3524 underline: text_style.underline,
3525 strikethrough: text_style.strikethrough,
3526 });
3527
3528 if editor_mode == EditorMode::Full {
3529 // Line wrap pads its contents with fake whitespaces,
3530 // avoid printing them
3531 let inside_wrapped_string = line_number_layouts
3532 .get(row)
3533 .and_then(|layout| layout.as_ref())
3534 .is_none();
3535 if highlighted_chunk.is_tab {
3536 if non_whitespace_added || !inside_wrapped_string {
3537 invisibles.push(Invisible::Tab {
3538 line_start_offset: line.len(),
3539 });
3540 }
3541 } else {
3542 invisibles.extend(
3543 line_chunk
3544 .chars()
3545 .enumerate()
3546 .filter(|(_, line_char)| {
3547 let is_whitespace = line_char.is_whitespace();
3548 non_whitespace_added |= !is_whitespace;
3549 is_whitespace
3550 && (non_whitespace_added || !inside_wrapped_string)
3551 })
3552 .map(|(whitespace_index, _)| Invisible::Whitespace {
3553 line_offset: line.len() + whitespace_index,
3554 }),
3555 )
3556 }
3557 }
3558
3559 line.push_str(line_chunk);
3560 }
3561 }
3562 }
3563
3564 layouts
3565 }
3566
3567 fn draw(
3568 &self,
3569 layout: &EditorLayout,
3570 row: u32,
3571 content_origin: gpui::Point<Pixels>,
3572 whitespace_setting: ShowWhitespaceSetting,
3573 selection_ranges: &[Range<DisplayPoint>],
3574 cx: &mut WindowContext,
3575 ) {
3576 let line_height = layout.position_map.line_height;
3577 let line_y =
3578 line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
3579
3580 let line_origin =
3581 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
3582 self.line.paint(line_origin, line_height, cx).log_err();
3583
3584 self.draw_invisibles(
3585 &selection_ranges,
3586 layout,
3587 content_origin,
3588 line_y,
3589 row,
3590 line_height,
3591 whitespace_setting,
3592 cx,
3593 );
3594 }
3595
3596 #[allow(clippy::too_many_arguments)]
3597 fn draw_invisibles(
3598 &self,
3599 selection_ranges: &[Range<DisplayPoint>],
3600 layout: &EditorLayout,
3601 content_origin: gpui::Point<Pixels>,
3602 line_y: Pixels,
3603 row: u32,
3604 line_height: Pixels,
3605 whitespace_setting: ShowWhitespaceSetting,
3606 cx: &mut WindowContext,
3607 ) {
3608 let allowed_invisibles_regions = match whitespace_setting {
3609 ShowWhitespaceSetting::None => return,
3610 ShowWhitespaceSetting::Selection => Some(selection_ranges),
3611 ShowWhitespaceSetting::All => None,
3612 };
3613
3614 for invisible in &self.invisibles {
3615 let (&token_offset, invisible_symbol) = match invisible {
3616 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
3617 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
3618 };
3619
3620 let x_offset = self.line.x_for_index(token_offset);
3621 let invisible_offset =
3622 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
3623 let origin = content_origin
3624 + gpui::point(
3625 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
3626 line_y,
3627 );
3628
3629 if let Some(allowed_regions) = allowed_invisibles_regions {
3630 let invisible_point = DisplayPoint::new(row, token_offset as u32);
3631 if !allowed_regions
3632 .iter()
3633 .any(|region| region.start <= invisible_point && invisible_point < region.end)
3634 {
3635 continue;
3636 }
3637 }
3638 invisible_symbol.paint(origin, line_height, cx).log_err();
3639 }
3640 }
3641}
3642
3643#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3644enum Invisible {
3645 Tab { line_start_offset: usize },
3646 Whitespace { line_offset: usize },
3647}
3648
3649impl Element for EditorElement {
3650 type RequestLayoutState = ();
3651 type PrepaintState = EditorLayout;
3652
3653 fn id(&self) -> Option<ElementId> {
3654 None
3655 }
3656
3657 fn request_layout(
3658 &mut self,
3659 _: Option<&GlobalElementId>,
3660 cx: &mut WindowContext,
3661 ) -> (gpui::LayoutId, ()) {
3662 self.editor.update(cx, |editor, cx| {
3663 editor.set_style(self.style.clone(), cx);
3664
3665 let layout_id = match editor.mode {
3666 EditorMode::SingleLine => {
3667 let rem_size = cx.rem_size();
3668 let mut style = Style::default();
3669 style.size.width = relative(1.).into();
3670 style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
3671 cx.request_layout(style, None)
3672 }
3673 EditorMode::AutoHeight { max_lines } => {
3674 let editor_handle = cx.view().clone();
3675 let max_line_number_width =
3676 self.max_line_number_width(&editor.snapshot(cx), cx);
3677 cx.request_measured_layout(Style::default(), move |known_dimensions, _, cx| {
3678 editor_handle
3679 .update(cx, |editor, cx| {
3680 compute_auto_height_layout(
3681 editor,
3682 max_lines,
3683 max_line_number_width,
3684 known_dimensions,
3685 cx,
3686 )
3687 })
3688 .unwrap_or_default()
3689 })
3690 }
3691 EditorMode::Full => {
3692 let mut style = Style::default();
3693 style.size.width = relative(1.).into();
3694 style.size.height = relative(1.).into();
3695 cx.request_layout(style, None)
3696 }
3697 };
3698
3699 (layout_id, ())
3700 })
3701 }
3702
3703 fn prepaint(
3704 &mut self,
3705 _: Option<&GlobalElementId>,
3706 bounds: Bounds<Pixels>,
3707 _: &mut Self::RequestLayoutState,
3708 cx: &mut WindowContext,
3709 ) -> Self::PrepaintState {
3710 let text_style = TextStyleRefinement {
3711 font_size: Some(self.style.text.font_size),
3712 line_height: Some(self.style.text.line_height),
3713 ..Default::default()
3714 };
3715 cx.set_view_id(self.editor.entity_id());
3716 cx.with_text_style(Some(text_style), |cx| {
3717 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3718 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3719 let style = self.style.clone();
3720
3721 let font_id = cx.text_system().resolve_font(&style.text.font());
3722 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3723 let line_height = style.text.line_height_in_pixels(cx.rem_size());
3724 let em_width = cx
3725 .text_system()
3726 .typographic_bounds(font_id, font_size, 'm')
3727 .unwrap()
3728 .size
3729 .width;
3730 let em_advance = cx
3731 .text_system()
3732 .advance(font_id, font_size, 'm')
3733 .unwrap()
3734 .width;
3735
3736 let gutter_dimensions = snapshot.gutter_dimensions(
3737 font_id,
3738 font_size,
3739 em_width,
3740 self.max_line_number_width(&snapshot, cx),
3741 cx,
3742 );
3743 let text_width = bounds.size.width - gutter_dimensions.width;
3744 let overscroll = size(em_width, px(0.));
3745
3746 snapshot = self.editor.update(cx, |editor, cx| {
3747 editor.last_bounds = Some(bounds);
3748 editor.gutter_dimensions = gutter_dimensions;
3749 editor.set_visible_line_count(bounds.size.height / line_height, cx);
3750
3751 let editor_width =
3752 text_width - gutter_dimensions.margin - overscroll.width - em_width;
3753 let wrap_width = match editor.soft_wrap_mode(cx) {
3754 SoftWrap::None => None,
3755 SoftWrap::PreferLine => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
3756 SoftWrap::EditorWidth => Some(editor_width),
3757 SoftWrap::Column(column) => {
3758 Some(editor_width.min(column as f32 * em_advance))
3759 }
3760 };
3761
3762 if editor.set_wrap_width(wrap_width, cx) {
3763 editor.snapshot(cx)
3764 } else {
3765 snapshot
3766 }
3767 });
3768
3769 let wrap_guides = self
3770 .editor
3771 .read(cx)
3772 .wrap_guides(cx)
3773 .iter()
3774 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
3775 .collect::<SmallVec<[_; 2]>>();
3776
3777 let hitbox = cx.insert_hitbox(bounds, false);
3778 let gutter_hitbox = cx.insert_hitbox(
3779 Bounds {
3780 origin: bounds.origin,
3781 size: size(gutter_dimensions.width, bounds.size.height),
3782 },
3783 false,
3784 );
3785 let text_hitbox = cx.insert_hitbox(
3786 Bounds {
3787 origin: gutter_hitbox.upper_right(),
3788 size: size(text_width, bounds.size.height),
3789 },
3790 false,
3791 );
3792 // Offset the content_bounds from the text_bounds by the gutter margin (which
3793 // is roughly half a character wide) to make hit testing work more like how we want.
3794 let content_origin =
3795 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
3796
3797 let mut autoscroll_containing_element = false;
3798 let mut autoscroll_horizontally = false;
3799 self.editor.update(cx, |editor, cx| {
3800 autoscroll_containing_element =
3801 editor.autoscroll_requested() || editor.has_pending_selection();
3802 autoscroll_horizontally = editor.autoscroll_vertically(bounds, line_height, cx);
3803 snapshot = editor.snapshot(cx);
3804 });
3805
3806 let mut scroll_position = snapshot.scroll_position();
3807 // The scroll position is a fractional point, the whole number of which represents
3808 // the top of the window in terms of display rows.
3809 let start_row = scroll_position.y as u32;
3810 let height_in_lines = bounds.size.height / line_height;
3811 let max_row = snapshot.max_point().row();
3812 let end_row = cmp::min(
3813 (scroll_position.y + height_in_lines).ceil() as u32,
3814 max_row + 1,
3815 );
3816
3817 let buffer_rows = snapshot
3818 .buffer_rows(start_row)
3819 .take((start_row..end_row).len());
3820
3821 let start_anchor = if start_row == 0 {
3822 Anchor::min()
3823 } else {
3824 snapshot.buffer_snapshot.anchor_before(
3825 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3826 )
3827 };
3828 let end_anchor = if end_row > max_row {
3829 Anchor::max()
3830 } else {
3831 snapshot.buffer_snapshot.anchor_before(
3832 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3833 )
3834 };
3835
3836 let highlighted_rows = self.editor.update(cx, |editor, cx| {
3837 editor.highlighted_display_rows(HashSet::default(), cx)
3838 });
3839 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3840 start_anchor..end_anchor,
3841 &snapshot.display_snapshot,
3842 cx.theme().colors(),
3843 );
3844
3845 let redacted_ranges = self.editor.read(cx).redacted_ranges(
3846 start_anchor..end_anchor,
3847 &snapshot.display_snapshot,
3848 cx,
3849 );
3850
3851 let (selections, active_rows, newest_selection_head) = self.layout_selections(
3852 start_anchor,
3853 end_anchor,
3854 &snapshot,
3855 start_row,
3856 end_row,
3857 cx,
3858 );
3859
3860 let (line_numbers, fold_statuses) = self.layout_line_numbers(
3861 start_row..end_row,
3862 buffer_rows.clone(),
3863 &active_rows,
3864 newest_selection_head,
3865 &snapshot,
3866 cx,
3867 );
3868
3869 let display_hunks = self.layout_git_gutters(
3870 line_height,
3871 &gutter_hitbox,
3872 start_row..end_row,
3873 &snapshot,
3874 cx,
3875 );
3876
3877 let mut max_visible_line_width = Pixels::ZERO;
3878 let line_layouts =
3879 self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3880 for line_with_invisibles in &line_layouts {
3881 if line_with_invisibles.line.width > max_visible_line_width {
3882 max_visible_line_width = line_with_invisibles.line.width;
3883 }
3884 }
3885
3886 let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3887 .unwrap()
3888 .width;
3889 let mut scroll_width =
3890 longest_line_width.max(max_visible_line_width) + overscroll.width;
3891
3892 let mut blocks = cx.with_element_namespace("blocks", |cx| {
3893 self.build_blocks(
3894 start_row..end_row,
3895 &snapshot,
3896 &hitbox,
3897 &text_hitbox,
3898 &mut scroll_width,
3899 &gutter_dimensions,
3900 em_width,
3901 gutter_dimensions.width + gutter_dimensions.margin,
3902 line_height,
3903 &line_layouts,
3904 cx,
3905 )
3906 });
3907
3908 let scroll_pixel_position = point(
3909 scroll_position.x * em_width,
3910 scroll_position.y * line_height,
3911 );
3912
3913 let mut inline_blame = None;
3914 if let Some(newest_selection_head) = newest_selection_head {
3915 let display_row = newest_selection_head.row();
3916 if (start_row..end_row).contains(&display_row) {
3917 let line_layout = &line_layouts[(display_row - start_row) as usize];
3918 inline_blame = self.layout_inline_blame(
3919 display_row,
3920 &snapshot.display_snapshot,
3921 line_layout,
3922 em_width,
3923 content_origin,
3924 scroll_pixel_position,
3925 line_height,
3926 cx,
3927 );
3928 }
3929 }
3930
3931 let blamed_display_rows = self.layout_blame_entries(
3932 buffer_rows,
3933 em_width,
3934 scroll_position,
3935 line_height,
3936 &gutter_hitbox,
3937 gutter_dimensions.git_blame_entries_width,
3938 cx,
3939 );
3940
3941 let scroll_max = point(
3942 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3943 max_row as f32,
3944 );
3945
3946 self.editor.update(cx, |editor, cx| {
3947 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3948
3949 let autoscrolled = if autoscroll_horizontally {
3950 editor.autoscroll_horizontally(
3951 start_row,
3952 text_hitbox.size.width,
3953 scroll_width,
3954 em_width,
3955 &line_layouts,
3956 cx,
3957 )
3958 } else {
3959 false
3960 };
3961
3962 if clamped || autoscrolled {
3963 snapshot = editor.snapshot(cx);
3964 scroll_position = snapshot.scroll_position();
3965 }
3966 });
3967
3968 cx.with_element_namespace("blocks", |cx| {
3969 self.layout_blocks(
3970 &mut blocks,
3971 &hitbox,
3972 line_height,
3973 scroll_pixel_position,
3974 cx,
3975 );
3976 });
3977
3978 let cursors = self.collect_cursors(&snapshot, cx);
3979 let visible_row_range = start_row..end_row;
3980 let non_visible_cursors = cursors
3981 .iter()
3982 .any(move |c| !visible_row_range.contains(&c.0.row()));
3983
3984 let visible_cursors = self.layout_visible_cursors(
3985 &snapshot,
3986 &selections,
3987 start_row..end_row,
3988 &line_layouts,
3989 &text_hitbox,
3990 content_origin,
3991 scroll_position,
3992 scroll_pixel_position,
3993 line_height,
3994 em_width,
3995 autoscroll_containing_element,
3996 cx,
3997 );
3998
3999 let scrollbar_layout = self.layout_scrollbar(
4000 &snapshot,
4001 bounds,
4002 scroll_position,
4003 height_in_lines,
4004 non_visible_cursors,
4005 cx,
4006 );
4007
4008 let folds = cx.with_element_namespace("folds", |cx| {
4009 self.layout_folds(
4010 &snapshot,
4011 content_origin,
4012 start_anchor..end_anchor,
4013 start_row..end_row,
4014 scroll_pixel_position,
4015 line_height,
4016 &line_layouts,
4017 cx,
4018 )
4019 });
4020
4021 let gutter_settings = EditorSettings::get_global(cx).gutter;
4022
4023 let mut context_menu_visible = false;
4024 let mut code_actions_indicator = None;
4025 if let Some(newest_selection_head) = newest_selection_head {
4026 if (start_row..end_row).contains(&newest_selection_head.row()) {
4027 context_menu_visible = self.layout_context_menu(
4028 line_height,
4029 &hitbox,
4030 &text_hitbox,
4031 content_origin,
4032 start_row,
4033 scroll_pixel_position,
4034 &line_layouts,
4035 newest_selection_head,
4036 gutter_dimensions.width - gutter_dimensions.left_padding,
4037 cx,
4038 );
4039 if gutter_settings.code_actions {
4040 let newest_selection_point =
4041 newest_selection_head.to_point(&snapshot.display_snapshot);
4042 let buffer = snapshot
4043 .buffer_snapshot
4044 .buffer_line_for_row(newest_selection_point.row);
4045 if let Some((buffer, range)) = buffer {
4046 let buffer_id = buffer.remote_id();
4047 let row = range.start.row;
4048 let has_test_indicator =
4049 self.editor.read(cx).tasks.contains_key(&(buffer_id, row));
4050
4051 if !has_test_indicator {
4052 code_actions_indicator = self.layout_code_actions_indicator(
4053 line_height,
4054 newest_selection_head,
4055 scroll_pixel_position,
4056 &gutter_dimensions,
4057 &gutter_hitbox,
4058 cx,
4059 );
4060 }
4061 }
4062 }
4063 }
4064 }
4065
4066 let test_indicators = self.layout_run_indicators(
4067 line_height,
4068 scroll_pixel_position,
4069 &gutter_dimensions,
4070 &gutter_hitbox,
4071 &snapshot,
4072 cx,
4073 );
4074
4075 if !context_menu_visible && !cx.has_active_drag() {
4076 self.layout_hover_popovers(
4077 &snapshot,
4078 &hitbox,
4079 &text_hitbox,
4080 start_row..end_row,
4081 content_origin,
4082 scroll_pixel_position,
4083 &line_layouts,
4084 line_height,
4085 em_width,
4086 cx,
4087 );
4088 }
4089
4090 let mouse_context_menu = self.layout_mouse_context_menu(cx);
4091
4092 let fold_indicators = if gutter_settings.folds {
4093 cx.with_element_namespace("gutter_fold_indicators", |cx| {
4094 self.layout_gutter_fold_indicators(
4095 fold_statuses,
4096 line_height,
4097 &gutter_dimensions,
4098 gutter_settings,
4099 scroll_pixel_position,
4100 &gutter_hitbox,
4101 cx,
4102 )
4103 })
4104 } else {
4105 Vec::new()
4106 };
4107
4108 let invisible_symbol_font_size = font_size / 2.;
4109 let tab_invisible = cx
4110 .text_system()
4111 .shape_line(
4112 "→".into(),
4113 invisible_symbol_font_size,
4114 &[TextRun {
4115 len: "→".len(),
4116 font: self.style.text.font(),
4117 color: cx.theme().colors().editor_invisible,
4118 background_color: None,
4119 underline: None,
4120 strikethrough: None,
4121 }],
4122 )
4123 .unwrap();
4124 let space_invisible = cx
4125 .text_system()
4126 .shape_line(
4127 "•".into(),
4128 invisible_symbol_font_size,
4129 &[TextRun {
4130 len: "•".len(),
4131 font: self.style.text.font(),
4132 color: cx.theme().colors().editor_invisible,
4133 background_color: None,
4134 underline: None,
4135 strikethrough: None,
4136 }],
4137 )
4138 .unwrap();
4139
4140 EditorLayout {
4141 mode: snapshot.mode,
4142 position_map: Arc::new(PositionMap {
4143 size: bounds.size,
4144 scroll_pixel_position,
4145 scroll_max,
4146 line_layouts,
4147 line_height,
4148 em_width,
4149 em_advance,
4150 snapshot,
4151 }),
4152 visible_display_row_range: start_row..end_row,
4153 wrap_guides,
4154 hitbox,
4155 text_hitbox,
4156 gutter_hitbox,
4157 gutter_dimensions,
4158 content_origin,
4159 scrollbar_layout,
4160 max_row,
4161 active_rows,
4162 highlighted_rows,
4163 highlighted_ranges,
4164 redacted_ranges,
4165 line_numbers,
4166 display_hunks,
4167 blamed_display_rows,
4168 inline_blame,
4169 folds,
4170 blocks,
4171 cursors,
4172 visible_cursors,
4173 selections,
4174 mouse_context_menu,
4175 test_indicators,
4176 code_actions_indicator,
4177 fold_indicators,
4178 tab_invisible,
4179 space_invisible,
4180 }
4181 })
4182 })
4183 }
4184
4185 fn paint(
4186 &mut self,
4187 _: Option<&GlobalElementId>,
4188 bounds: Bounds<gpui::Pixels>,
4189 _: &mut Self::RequestLayoutState,
4190 layout: &mut Self::PrepaintState,
4191 cx: &mut WindowContext,
4192 ) {
4193 let focus_handle = self.editor.focus_handle(cx);
4194 let key_context = self.editor.read(cx).key_context(cx);
4195 cx.set_focus_handle(&focus_handle);
4196 cx.set_key_context(key_context);
4197 cx.handle_input(
4198 &focus_handle,
4199 ElementInputHandler::new(bounds, self.editor.clone()),
4200 );
4201 self.register_actions(cx);
4202 self.register_key_listeners(cx, layout);
4203
4204 let text_style = TextStyleRefinement {
4205 font_size: Some(self.style.text.font_size),
4206 line_height: Some(self.style.text.line_height),
4207 ..Default::default()
4208 };
4209 let mouse_position = cx.mouse_position();
4210 let hovered_hunk = layout
4211 .display_hunks
4212 .iter()
4213 .find_map(|(hunk, hunk_hitbox)| match hunk {
4214 DisplayDiffHunk::Folded { .. } => None,
4215 DisplayDiffHunk::Unfolded {
4216 diff_base_byte_range,
4217 multi_buffer_range,
4218 status,
4219 ..
4220 } => {
4221 if hunk_hitbox
4222 .as_ref()
4223 .map(|hitbox| hitbox.contains(&mouse_position))
4224 .unwrap_or(false)
4225 {
4226 Some(HunkToExpand {
4227 status: *status,
4228 multi_buffer_range: multi_buffer_range.clone(),
4229 diff_base_byte_range: diff_base_byte_range.clone(),
4230 })
4231 } else {
4232 None
4233 }
4234 }
4235 });
4236 cx.with_text_style(Some(text_style), |cx| {
4237 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4238 self.paint_mouse_listeners(layout, hovered_hunk, cx);
4239 self.paint_background(layout, cx);
4240 if layout.gutter_hitbox.size.width > Pixels::ZERO {
4241 self.paint_gutter(layout, cx)
4242 }
4243
4244 self.paint_text(layout, cx);
4245
4246 if !layout.blocks.is_empty() {
4247 cx.with_element_namespace("blocks", |cx| {
4248 self.paint_blocks(layout, cx);
4249 });
4250 }
4251
4252 self.paint_scrollbar(layout, cx);
4253 self.paint_mouse_context_menu(layout, cx);
4254 });
4255 })
4256 }
4257}
4258
4259impl IntoElement for EditorElement {
4260 type Element = Self;
4261
4262 fn into_element(self) -> Self::Element {
4263 self
4264 }
4265}
4266
4267type BufferRow = u32;
4268
4269pub struct EditorLayout {
4270 position_map: Arc<PositionMap>,
4271 hitbox: Hitbox,
4272 text_hitbox: Hitbox,
4273 gutter_hitbox: Hitbox,
4274 gutter_dimensions: GutterDimensions,
4275 content_origin: gpui::Point<Pixels>,
4276 scrollbar_layout: Option<ScrollbarLayout>,
4277 mode: EditorMode,
4278 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
4279 visible_display_row_range: Range<u32>,
4280 active_rows: BTreeMap<u32, bool>,
4281 highlighted_rows: BTreeMap<u32, Hsla>,
4282 line_numbers: Vec<Option<ShapedLine>>,
4283 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
4284 blamed_display_rows: Option<Vec<AnyElement>>,
4285 inline_blame: Option<AnyElement>,
4286 folds: Vec<FoldLayout>,
4287 blocks: Vec<BlockLayout>,
4288 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
4289 redacted_ranges: Vec<Range<DisplayPoint>>,
4290 cursors: Vec<(DisplayPoint, Hsla)>,
4291 visible_cursors: Vec<CursorLayout>,
4292 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
4293 max_row: u32,
4294 code_actions_indicator: Option<AnyElement>,
4295 test_indicators: Vec<AnyElement>,
4296 fold_indicators: Vec<Option<AnyElement>>,
4297 mouse_context_menu: Option<AnyElement>,
4298 tab_invisible: ShapedLine,
4299 space_invisible: ShapedLine,
4300}
4301
4302impl EditorLayout {
4303 fn line_end_overshoot(&self) -> Pixels {
4304 0.15 * self.position_map.line_height
4305 }
4306}
4307
4308struct ColoredRange<T> {
4309 start: T,
4310 end: T,
4311 color: Hsla,
4312}
4313
4314#[derive(Clone)]
4315struct ScrollbarLayout {
4316 hitbox: Hitbox,
4317 visible_row_range: Range<f32>,
4318 visible: bool,
4319 row_height: Pixels,
4320 thumb_height: Pixels,
4321}
4322
4323impl ScrollbarLayout {
4324 const BORDER_WIDTH: Pixels = px(1.0);
4325 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
4326 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
4327 const MIN_THUMB_HEIGHT: Pixels = px(20.0);
4328
4329 fn thumb_bounds(&self) -> Bounds<Pixels> {
4330 let thumb_top = self.y_for_row(self.visible_row_range.start);
4331 let thumb_bottom = thumb_top + self.thumb_height;
4332 Bounds::from_corners(
4333 point(self.hitbox.left(), thumb_top),
4334 point(self.hitbox.right(), thumb_bottom),
4335 )
4336 }
4337
4338 fn y_for_row(&self, row: f32) -> Pixels {
4339 self.hitbox.top() + row * self.row_height
4340 }
4341
4342 fn marker_quads_for_ranges(
4343 &self,
4344 row_ranges: impl IntoIterator<Item = ColoredRange<u32>>,
4345 column: Option<usize>,
4346 ) -> Vec<PaintQuad> {
4347 struct MinMax {
4348 min: Pixels,
4349 max: Pixels,
4350 }
4351 let (x_range, height_limit) = if let Some(column) = column {
4352 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
4353 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
4354 let end = start + column_width;
4355 (
4356 Range { start, end },
4357 MinMax {
4358 min: Self::MIN_MARKER_HEIGHT,
4359 max: px(f32::MAX),
4360 },
4361 )
4362 } else {
4363 (
4364 Range {
4365 start: Self::BORDER_WIDTH,
4366 end: self.hitbox.size.width,
4367 },
4368 MinMax {
4369 min: Self::LINE_MARKER_HEIGHT,
4370 max: Self::LINE_MARKER_HEIGHT,
4371 },
4372 )
4373 };
4374
4375 let row_to_y = |row: u32| row as f32 * self.row_height;
4376 let mut pixel_ranges = row_ranges
4377 .into_iter()
4378 .map(|range| {
4379 let start_y = row_to_y(range.start);
4380 let end_y = row_to_y(range.end)
4381 + self.row_height.max(height_limit.min).min(height_limit.max);
4382 ColoredRange {
4383 start: start_y,
4384 end: end_y,
4385 color: range.color,
4386 }
4387 })
4388 .peekable();
4389
4390 let mut quads = Vec::new();
4391 while let Some(mut pixel_range) = pixel_ranges.next() {
4392 while let Some(next_pixel_range) = pixel_ranges.peek() {
4393 if pixel_range.end >= next_pixel_range.start - px(1.0)
4394 && pixel_range.color == next_pixel_range.color
4395 {
4396 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
4397 pixel_ranges.next();
4398 } else {
4399 break;
4400 }
4401 }
4402
4403 let bounds = Bounds::from_corners(
4404 point(x_range.start, pixel_range.start),
4405 point(x_range.end, pixel_range.end),
4406 );
4407 quads.push(quad(
4408 bounds,
4409 Corners::default(),
4410 pixel_range.color,
4411 Edges::default(),
4412 Hsla::transparent_black(),
4413 ));
4414 }
4415
4416 quads
4417 }
4418}
4419
4420struct FoldLayout {
4421 display_range: Range<DisplayPoint>,
4422 hover_element: AnyElement,
4423}
4424
4425struct PositionMap {
4426 size: Size<Pixels>,
4427 line_height: Pixels,
4428 scroll_pixel_position: gpui::Point<Pixels>,
4429 scroll_max: gpui::Point<f32>,
4430 em_width: Pixels,
4431 em_advance: Pixels,
4432 line_layouts: Vec<LineWithInvisibles>,
4433 snapshot: EditorSnapshot,
4434}
4435
4436#[derive(Debug, Copy, Clone)]
4437pub struct PointForPosition {
4438 pub previous_valid: DisplayPoint,
4439 pub next_valid: DisplayPoint,
4440 pub exact_unclipped: DisplayPoint,
4441 pub column_overshoot_after_line_end: u32,
4442}
4443
4444impl PointForPosition {
4445 pub fn as_valid(&self) -> Option<DisplayPoint> {
4446 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
4447 Some(self.previous_valid)
4448 } else {
4449 None
4450 }
4451 }
4452}
4453
4454impl PositionMap {
4455 fn point_for_position(
4456 &self,
4457 text_bounds: Bounds<Pixels>,
4458 position: gpui::Point<Pixels>,
4459 ) -> PointForPosition {
4460 let scroll_position = self.snapshot.scroll_position();
4461 let position = position - text_bounds.origin;
4462 let y = position.y.max(px(0.)).min(self.size.height);
4463 let x = position.x + (scroll_position.x * self.em_width);
4464 let row = ((y / self.line_height) + scroll_position.y) as u32;
4465
4466 let (column, x_overshoot_after_line_end) = if let Some(line) = self
4467 .line_layouts
4468 .get(row as usize - scroll_position.y as usize)
4469 .map(|LineWithInvisibles { line, .. }| line)
4470 {
4471 if let Some(ix) = line.index_for_x(x) {
4472 (ix as u32, px(0.))
4473 } else {
4474 (line.len as u32, px(0.).max(x - line.width))
4475 }
4476 } else {
4477 (0, x)
4478 };
4479
4480 let mut exact_unclipped = DisplayPoint::new(row, column);
4481 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
4482 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
4483
4484 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
4485 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
4486 PointForPosition {
4487 previous_valid,
4488 next_valid,
4489 exact_unclipped,
4490 column_overshoot_after_line_end,
4491 }
4492 }
4493}
4494
4495struct BlockLayout {
4496 row: u32,
4497 element: AnyElement,
4498 available_space: Size<AvailableSpace>,
4499 style: BlockStyle,
4500}
4501
4502fn layout_line(
4503 row: u32,
4504 snapshot: &EditorSnapshot,
4505 style: &EditorStyle,
4506 cx: &WindowContext,
4507) -> Result<ShapedLine> {
4508 let mut line = snapshot.line(row);
4509
4510 let len = {
4511 let line_len = line.len();
4512 if line_len > MAX_LINE_LEN {
4513 let mut len = MAX_LINE_LEN;
4514 while !line.is_char_boundary(len) {
4515 len -= 1;
4516 }
4517
4518 line.truncate(len);
4519 len
4520 } else {
4521 line_len
4522 }
4523 };
4524
4525 cx.text_system().shape_line(
4526 line.into(),
4527 style.text.font_size.to_pixels(cx.rem_size()),
4528 &[TextRun {
4529 len,
4530 font: style.text.font(),
4531 color: Hsla::default(),
4532 background_color: None,
4533 underline: None,
4534 strikethrough: None,
4535 }],
4536 )
4537}
4538
4539pub struct CursorLayout {
4540 origin: gpui::Point<Pixels>,
4541 block_width: Pixels,
4542 line_height: Pixels,
4543 color: Hsla,
4544 shape: CursorShape,
4545 block_text: Option<ShapedLine>,
4546 cursor_name: Option<AnyElement>,
4547}
4548
4549#[derive(Debug)]
4550pub struct CursorName {
4551 string: SharedString,
4552 color: Hsla,
4553 is_top_row: bool,
4554}
4555
4556impl CursorLayout {
4557 pub fn new(
4558 origin: gpui::Point<Pixels>,
4559 block_width: Pixels,
4560 line_height: Pixels,
4561 color: Hsla,
4562 shape: CursorShape,
4563 block_text: Option<ShapedLine>,
4564 ) -> CursorLayout {
4565 CursorLayout {
4566 origin,
4567 block_width,
4568 line_height,
4569 color,
4570 shape,
4571 block_text,
4572 cursor_name: None,
4573 }
4574 }
4575
4576 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4577 Bounds {
4578 origin: self.origin + origin,
4579 size: size(self.block_width, self.line_height),
4580 }
4581 }
4582
4583 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4584 match self.shape {
4585 CursorShape::Bar => Bounds {
4586 origin: self.origin + origin,
4587 size: size(px(2.0), self.line_height),
4588 },
4589 CursorShape::Block | CursorShape::Hollow => Bounds {
4590 origin: self.origin + origin,
4591 size: size(self.block_width, self.line_height),
4592 },
4593 CursorShape::Underscore => Bounds {
4594 origin: self.origin
4595 + origin
4596 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
4597 size: size(self.block_width, px(2.0)),
4598 },
4599 }
4600 }
4601
4602 pub fn layout(
4603 &mut self,
4604 origin: gpui::Point<Pixels>,
4605 cursor_name: Option<CursorName>,
4606 cx: &mut WindowContext,
4607 ) {
4608 if let Some(cursor_name) = cursor_name {
4609 let bounds = self.bounds(origin);
4610 let text_size = self.line_height / 1.5;
4611
4612 let name_origin = if cursor_name.is_top_row {
4613 point(bounds.right() - px(1.), bounds.top())
4614 } else {
4615 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
4616 };
4617 let mut name_element = div()
4618 .bg(self.color)
4619 .text_size(text_size)
4620 .px_0p5()
4621 .line_height(text_size + px(2.))
4622 .text_color(cursor_name.color)
4623 .child(cursor_name.string.clone())
4624 .into_any_element();
4625
4626 name_element.prepaint_as_root(
4627 name_origin,
4628 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
4629 cx,
4630 );
4631
4632 self.cursor_name = Some(name_element);
4633 }
4634 }
4635
4636 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
4637 let bounds = self.bounds(origin);
4638
4639 //Draw background or border quad
4640 let cursor = if matches!(self.shape, CursorShape::Hollow) {
4641 outline(bounds, self.color)
4642 } else {
4643 fill(bounds, self.color)
4644 };
4645
4646 if let Some(name) = &mut self.cursor_name {
4647 name.paint(cx);
4648 }
4649
4650 cx.paint_quad(cursor);
4651
4652 if let Some(block_text) = &self.block_text {
4653 block_text
4654 .paint(self.origin + origin, self.line_height, cx)
4655 .log_err();
4656 }
4657 }
4658
4659 pub fn shape(&self) -> CursorShape {
4660 self.shape
4661 }
4662}
4663
4664#[derive(Debug)]
4665pub struct HighlightedRange {
4666 pub start_y: Pixels,
4667 pub line_height: Pixels,
4668 pub lines: Vec<HighlightedRangeLine>,
4669 pub color: Hsla,
4670 pub corner_radius: Pixels,
4671}
4672
4673#[derive(Debug)]
4674pub struct HighlightedRangeLine {
4675 pub start_x: Pixels,
4676 pub end_x: Pixels,
4677}
4678
4679impl HighlightedRange {
4680 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
4681 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
4682 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
4683 self.paint_lines(
4684 self.start_y + self.line_height,
4685 &self.lines[1..],
4686 bounds,
4687 cx,
4688 );
4689 } else {
4690 self.paint_lines(self.start_y, &self.lines, bounds, cx);
4691 }
4692 }
4693
4694 fn paint_lines(
4695 &self,
4696 start_y: Pixels,
4697 lines: &[HighlightedRangeLine],
4698 _bounds: Bounds<Pixels>,
4699 cx: &mut WindowContext,
4700 ) {
4701 if lines.is_empty() {
4702 return;
4703 }
4704
4705 let first_line = lines.first().unwrap();
4706 let last_line = lines.last().unwrap();
4707
4708 let first_top_left = point(first_line.start_x, start_y);
4709 let first_top_right = point(first_line.end_x, start_y);
4710
4711 let curve_height = point(Pixels::ZERO, self.corner_radius);
4712 let curve_width = |start_x: Pixels, end_x: Pixels| {
4713 let max = (end_x - start_x) / 2.;
4714 let width = if max < self.corner_radius {
4715 max
4716 } else {
4717 self.corner_radius
4718 };
4719
4720 point(width, Pixels::ZERO)
4721 };
4722
4723 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
4724 let mut path = gpui::Path::new(first_top_right - top_curve_width);
4725 path.curve_to(first_top_right + curve_height, first_top_right);
4726
4727 let mut iter = lines.iter().enumerate().peekable();
4728 while let Some((ix, line)) = iter.next() {
4729 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
4730
4731 if let Some((_, next_line)) = iter.peek() {
4732 let next_top_right = point(next_line.end_x, bottom_right.y);
4733
4734 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
4735 Ordering::Equal => {
4736 path.line_to(bottom_right);
4737 }
4738 Ordering::Less => {
4739 let curve_width = curve_width(next_top_right.x, bottom_right.x);
4740 path.line_to(bottom_right - curve_height);
4741 if self.corner_radius > Pixels::ZERO {
4742 path.curve_to(bottom_right - curve_width, bottom_right);
4743 }
4744 path.line_to(next_top_right + curve_width);
4745 if self.corner_radius > Pixels::ZERO {
4746 path.curve_to(next_top_right + curve_height, next_top_right);
4747 }
4748 }
4749 Ordering::Greater => {
4750 let curve_width = curve_width(bottom_right.x, next_top_right.x);
4751 path.line_to(bottom_right - curve_height);
4752 if self.corner_radius > Pixels::ZERO {
4753 path.curve_to(bottom_right + curve_width, bottom_right);
4754 }
4755 path.line_to(next_top_right - curve_width);
4756 if self.corner_radius > Pixels::ZERO {
4757 path.curve_to(next_top_right + curve_height, next_top_right);
4758 }
4759 }
4760 }
4761 } else {
4762 let curve_width = curve_width(line.start_x, line.end_x);
4763 path.line_to(bottom_right - curve_height);
4764 if self.corner_radius > Pixels::ZERO {
4765 path.curve_to(bottom_right - curve_width, bottom_right);
4766 }
4767
4768 let bottom_left = point(line.start_x, bottom_right.y);
4769 path.line_to(bottom_left + curve_width);
4770 if self.corner_radius > Pixels::ZERO {
4771 path.curve_to(bottom_left - curve_height, bottom_left);
4772 }
4773 }
4774 }
4775
4776 if first_line.start_x > last_line.start_x {
4777 let curve_width = curve_width(last_line.start_x, first_line.start_x);
4778 let second_top_left = point(last_line.start_x, start_y + self.line_height);
4779 path.line_to(second_top_left + curve_height);
4780 if self.corner_radius > Pixels::ZERO {
4781 path.curve_to(second_top_left + curve_width, second_top_left);
4782 }
4783 let first_bottom_left = point(first_line.start_x, second_top_left.y);
4784 path.line_to(first_bottom_left - curve_width);
4785 if self.corner_radius > Pixels::ZERO {
4786 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
4787 }
4788 }
4789
4790 path.line_to(first_top_left + curve_height);
4791 if self.corner_radius > Pixels::ZERO {
4792 path.curve_to(first_top_left + top_curve_width, first_top_left);
4793 }
4794 path.line_to(first_top_right - top_curve_width);
4795
4796 cx.paint_path(path, self.color);
4797 }
4798}
4799
4800pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4801 (delta.pow(1.5) / 100.0).into()
4802}
4803
4804fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4805 (delta.pow(1.2) / 300.0).into()
4806}
4807
4808#[cfg(test)]
4809mod tests {
4810 use super::*;
4811 use crate::{
4812 display_map::{BlockDisposition, BlockProperties},
4813 editor_tests::{init_test, update_test_language_settings},
4814 Editor, MultiBuffer,
4815 };
4816 use gpui::{TestAppContext, VisualTestContext};
4817 use language::language_settings;
4818 use log::info;
4819 use std::num::NonZeroU32;
4820 use ui::Context;
4821 use util::test::sample_text;
4822
4823 #[gpui::test]
4824 fn test_shape_line_numbers(cx: &mut TestAppContext) {
4825 init_test(cx, |_| {});
4826 let window = cx.add_window(|cx| {
4827 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4828 Editor::new(EditorMode::Full, buffer, None, cx)
4829 });
4830
4831 let editor = window.root(cx).unwrap();
4832 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4833 let element = EditorElement::new(&editor, style);
4834 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
4835
4836 let layouts = cx
4837 .update_window(*window, |_, cx| {
4838 element
4839 .layout_line_numbers(
4840 0..6,
4841 (0..6).map(Some),
4842 &Default::default(),
4843 Some(DisplayPoint::new(0, 0)),
4844 &snapshot,
4845 cx,
4846 )
4847 .0
4848 })
4849 .unwrap();
4850 assert_eq!(layouts.len(), 6);
4851
4852 let relative_rows = window
4853 .update(cx, |editor, cx| {
4854 let snapshot = editor.snapshot(cx);
4855 element.calculate_relative_line_numbers(&snapshot, &(0..6), Some(3))
4856 })
4857 .unwrap();
4858 assert_eq!(relative_rows[&0], 3);
4859 assert_eq!(relative_rows[&1], 2);
4860 assert_eq!(relative_rows[&2], 1);
4861 // current line has no relative number
4862 assert_eq!(relative_rows[&4], 1);
4863 assert_eq!(relative_rows[&5], 2);
4864
4865 // works if cursor is before screen
4866 let relative_rows = window
4867 .update(cx, |editor, cx| {
4868 let snapshot = editor.snapshot(cx);
4869 element.calculate_relative_line_numbers(&snapshot, &(3..6), Some(1))
4870 })
4871 .unwrap();
4872 assert_eq!(relative_rows.len(), 3);
4873 assert_eq!(relative_rows[&3], 2);
4874 assert_eq!(relative_rows[&4], 3);
4875 assert_eq!(relative_rows[&5], 4);
4876
4877 // works if cursor is after screen
4878 let relative_rows = window
4879 .update(cx, |editor, cx| {
4880 let snapshot = editor.snapshot(cx);
4881 element.calculate_relative_line_numbers(&snapshot, &(0..3), Some(6))
4882 })
4883 .unwrap();
4884 assert_eq!(relative_rows.len(), 3);
4885 assert_eq!(relative_rows[&0], 5);
4886 assert_eq!(relative_rows[&1], 4);
4887 assert_eq!(relative_rows[&2], 3);
4888 }
4889
4890 #[gpui::test]
4891 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
4892 init_test(cx, |_| {});
4893
4894 let window = cx.add_window(|cx| {
4895 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
4896 Editor::new(EditorMode::Full, buffer, None, cx)
4897 });
4898 let cx = &mut VisualTestContext::from_window(*window, cx);
4899 let editor = window.root(cx).unwrap();
4900 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4901
4902 window
4903 .update(cx, |editor, cx| {
4904 editor.cursor_shape = CursorShape::Block;
4905 editor.change_selections(None, cx, |s| {
4906 s.select_ranges([
4907 Point::new(0, 0)..Point::new(1, 0),
4908 Point::new(3, 2)..Point::new(3, 3),
4909 Point::new(5, 6)..Point::new(6, 0),
4910 ]);
4911 });
4912 })
4913 .unwrap();
4914
4915 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
4916 EditorElement::new(&editor, style)
4917 });
4918
4919 assert_eq!(state.selections.len(), 1);
4920 let local_selections = &state.selections[0].1;
4921 assert_eq!(local_selections.len(), 3);
4922 // moves cursor back one line
4923 assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
4924 assert_eq!(
4925 local_selections[0].range,
4926 DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
4927 );
4928
4929 // moves cursor back one column
4930 assert_eq!(
4931 local_selections[1].range,
4932 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
4933 );
4934 assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
4935
4936 // leaves cursor on the max point
4937 assert_eq!(
4938 local_selections[2].range,
4939 DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
4940 );
4941 assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
4942
4943 // active lines does not include 1 (even though the range of the selection does)
4944 assert_eq!(
4945 state.active_rows.keys().cloned().collect::<Vec<u32>>(),
4946 vec![0, 3, 5, 6]
4947 );
4948
4949 // multi-buffer support
4950 // in DisplayPoint coordinates, this is what we're dealing with:
4951 // 0: [[file
4952 // 1: header]]
4953 // 2: aaaaaa
4954 // 3: bbbbbb
4955 // 4: cccccc
4956 // 5:
4957 // 6: ...
4958 // 7: ffffff
4959 // 8: gggggg
4960 // 9: hhhhhh
4961 // 10:
4962 // 11: [[file
4963 // 12: header]]
4964 // 13: bbbbbb
4965 // 14: cccccc
4966 // 15: dddddd
4967 let window = cx.add_window(|cx| {
4968 let buffer = MultiBuffer::build_multi(
4969 [
4970 (
4971 &(sample_text(8, 6, 'a') + "\n"),
4972 vec![
4973 Point::new(0, 0)..Point::new(3, 0),
4974 Point::new(4, 0)..Point::new(7, 0),
4975 ],
4976 ),
4977 (
4978 &(sample_text(8, 6, 'a') + "\n"),
4979 vec![Point::new(1, 0)..Point::new(3, 0)],
4980 ),
4981 ],
4982 cx,
4983 );
4984 Editor::new(EditorMode::Full, buffer, None, cx)
4985 });
4986 let editor = window.root(cx).unwrap();
4987 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4988 let _state = window.update(cx, |editor, cx| {
4989 editor.cursor_shape = CursorShape::Block;
4990 editor.change_selections(None, cx, |s| {
4991 s.select_display_ranges([
4992 DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4993 DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4994 ]);
4995 });
4996 });
4997
4998 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
4999 EditorElement::new(&editor, style)
5000 });
5001 assert_eq!(state.selections.len(), 1);
5002 let local_selections = &state.selections[0].1;
5003 assert_eq!(local_selections.len(), 2);
5004
5005 // moves cursor on excerpt boundary back a line
5006 // and doesn't allow selection to bleed through
5007 assert_eq!(
5008 local_selections[0].range,
5009 DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
5010 );
5011 assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
5012 // moves cursor on buffer boundary back two lines
5013 // and doesn't allow selection to bleed through
5014 assert_eq!(
5015 local_selections[1].range,
5016 DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
5017 );
5018 assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
5019 }
5020
5021 #[gpui::test]
5022 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
5023 init_test(cx, |_| {});
5024
5025 let window = cx.add_window(|cx| {
5026 let buffer = MultiBuffer::build_simple("", cx);
5027 Editor::new(EditorMode::Full, buffer, None, cx)
5028 });
5029 let cx = &mut VisualTestContext::from_window(*window, cx);
5030 let editor = window.root(cx).unwrap();
5031 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5032 window
5033 .update(cx, |editor, cx| {
5034 editor.set_placeholder_text("hello", cx);
5035 editor.insert_blocks(
5036 [BlockProperties {
5037 style: BlockStyle::Fixed,
5038 disposition: BlockDisposition::Above,
5039 height: 3,
5040 position: Anchor::min(),
5041 render: Box::new(|_| div().into_any()),
5042 }],
5043 None,
5044 cx,
5045 );
5046
5047 // Blur the editor so that it displays placeholder text.
5048 cx.blur();
5049 })
5050 .unwrap();
5051
5052 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5053 EditorElement::new(&editor, style)
5054 });
5055 assert_eq!(state.position_map.line_layouts.len(), 4);
5056 assert_eq!(
5057 state
5058 .line_numbers
5059 .iter()
5060 .map(Option::is_some)
5061 .collect::<Vec<_>>(),
5062 &[false, false, false, true]
5063 );
5064 }
5065
5066 #[gpui::test]
5067 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
5068 const TAB_SIZE: u32 = 4;
5069
5070 let input_text = "\t \t|\t| a b";
5071 let expected_invisibles = vec![
5072 Invisible::Tab {
5073 line_start_offset: 0,
5074 },
5075 Invisible::Whitespace {
5076 line_offset: TAB_SIZE as usize,
5077 },
5078 Invisible::Tab {
5079 line_start_offset: TAB_SIZE as usize + 1,
5080 },
5081 Invisible::Tab {
5082 line_start_offset: TAB_SIZE as usize * 2 + 1,
5083 },
5084 Invisible::Whitespace {
5085 line_offset: TAB_SIZE as usize * 3 + 1,
5086 },
5087 Invisible::Whitespace {
5088 line_offset: TAB_SIZE as usize * 3 + 3,
5089 },
5090 ];
5091 assert_eq!(
5092 expected_invisibles.len(),
5093 input_text
5094 .chars()
5095 .filter(|initial_char| initial_char.is_whitespace())
5096 .count(),
5097 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
5098 );
5099
5100 init_test(cx, |s| {
5101 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
5102 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
5103 });
5104
5105 let actual_invisibles =
5106 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
5107
5108 assert_eq!(expected_invisibles, actual_invisibles);
5109 }
5110
5111 #[gpui::test]
5112 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
5113 init_test(cx, |s| {
5114 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
5115 s.defaults.tab_size = NonZeroU32::new(4);
5116 });
5117
5118 for editor_mode_without_invisibles in [
5119 EditorMode::SingleLine,
5120 EditorMode::AutoHeight { max_lines: 100 },
5121 ] {
5122 let invisibles = collect_invisibles_from_new_editor(
5123 cx,
5124 editor_mode_without_invisibles,
5125 "\t\t\t| | a b",
5126 px(500.0),
5127 );
5128 assert!(invisibles.is_empty(),
5129 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
5130 }
5131 }
5132
5133 #[gpui::test]
5134 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
5135 let tab_size = 4;
5136 let input_text = "a\tbcd ".repeat(9);
5137 let repeated_invisibles = [
5138 Invisible::Tab {
5139 line_start_offset: 1,
5140 },
5141 Invisible::Whitespace {
5142 line_offset: tab_size as usize + 3,
5143 },
5144 Invisible::Whitespace {
5145 line_offset: tab_size as usize + 4,
5146 },
5147 Invisible::Whitespace {
5148 line_offset: tab_size as usize + 5,
5149 },
5150 ];
5151 let expected_invisibles = std::iter::once(repeated_invisibles)
5152 .cycle()
5153 .take(9)
5154 .flatten()
5155 .collect::<Vec<_>>();
5156 assert_eq!(
5157 expected_invisibles.len(),
5158 input_text
5159 .chars()
5160 .filter(|initial_char| initial_char.is_whitespace())
5161 .count(),
5162 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
5163 );
5164 info!("Expected invisibles: {expected_invisibles:?}");
5165
5166 init_test(cx, |_| {});
5167
5168 // Put the same string with repeating whitespace pattern into editors of various size,
5169 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
5170 let resize_step = 10.0;
5171 let mut editor_width = 200.0;
5172 while editor_width <= 1000.0 {
5173 update_test_language_settings(cx, |s| {
5174 s.defaults.tab_size = NonZeroU32::new(tab_size);
5175 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
5176 s.defaults.preferred_line_length = Some(editor_width as u32);
5177 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
5178 });
5179
5180 let actual_invisibles = collect_invisibles_from_new_editor(
5181 cx,
5182 EditorMode::Full,
5183 &input_text,
5184 px(editor_width),
5185 );
5186
5187 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
5188 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
5189 let mut i = 0;
5190 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
5191 i = actual_index;
5192 match expected_invisibles.get(i) {
5193 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
5194 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
5195 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
5196 _ => {
5197 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
5198 }
5199 },
5200 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
5201 }
5202 }
5203 let missing_expected_invisibles = &expected_invisibles[i + 1..];
5204 assert!(
5205 missing_expected_invisibles.is_empty(),
5206 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
5207 );
5208
5209 editor_width += resize_step;
5210 }
5211 }
5212
5213 fn collect_invisibles_from_new_editor(
5214 cx: &mut TestAppContext,
5215 editor_mode: EditorMode,
5216 input_text: &str,
5217 editor_width: Pixels,
5218 ) -> Vec<Invisible> {
5219 info!(
5220 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
5221 editor_width.0
5222 );
5223 let window = cx.add_window(|cx| {
5224 let buffer = MultiBuffer::build_simple(&input_text, cx);
5225 Editor::new(editor_mode, buffer, None, cx)
5226 });
5227 let cx = &mut VisualTestContext::from_window(*window, cx);
5228 let editor = window.root(cx).unwrap();
5229 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
5230 window
5231 .update(cx, |editor, cx| {
5232 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
5233 editor.set_wrap_width(Some(editor_width), cx);
5234 })
5235 .unwrap();
5236 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
5237 EditorElement::new(&editor, style)
5238 });
5239 state
5240 .position_map
5241 .line_layouts
5242 .iter()
5243 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
5244 .cloned()
5245 .collect()
5246 }
5247}
5248
5249pub fn register_action<T: Action>(
5250 view: &View<Editor>,
5251 cx: &mut WindowContext,
5252 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
5253) {
5254 let view = view.clone();
5255 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
5256 let action = action.downcast_ref().unwrap();
5257 if phase == DispatchPhase::Bubble {
5258 view.update(cx, |editor, cx| {
5259 listener(editor, action, cx);
5260 })
5261 }
5262 })
5263}
5264
5265fn compute_auto_height_layout(
5266 editor: &mut Editor,
5267 max_lines: usize,
5268 max_line_number_width: Pixels,
5269 known_dimensions: Size<Option<Pixels>>,
5270 cx: &mut ViewContext<Editor>,
5271) -> Option<Size<Pixels>> {
5272 let width = known_dimensions.width?;
5273 if let Some(height) = known_dimensions.height {
5274 return Some(size(width, height));
5275 }
5276
5277 let style = editor.style.as_ref().unwrap();
5278 let font_id = cx.text_system().resolve_font(&style.text.font());
5279 let font_size = style.text.font_size.to_pixels(cx.rem_size());
5280 let line_height = style.text.line_height_in_pixels(cx.rem_size());
5281 let em_width = cx
5282 .text_system()
5283 .typographic_bounds(font_id, font_size, 'm')
5284 .unwrap()
5285 .size
5286 .width;
5287
5288 let mut snapshot = editor.snapshot(cx);
5289 let gutter_dimensions =
5290 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
5291
5292 editor.gutter_dimensions = gutter_dimensions;
5293 let text_width = width - gutter_dimensions.width;
5294 let overscroll = size(em_width, px(0.));
5295
5296 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
5297 if editor.set_wrap_width(Some(editor_width), cx) {
5298 snapshot = editor.snapshot(cx);
5299 }
5300
5301 let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
5302 let height = scroll_height
5303 .max(line_height)
5304 .min(line_height * max_lines as f32);
5305
5306 Some(size(width, height))
5307}