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