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 let text_style = &self.style.text;
1115
1116 let shaped_lines = blamed_rows
1117 .into_iter()
1118 .enumerate()
1119 .flat_map(|(ix, blame_entry)| {
1120 if let Some(blame_entry) = blame_entry {
1121 let mut element = render_blame_entry(
1122 ix,
1123 &blame,
1124 blame_entry,
1125 text_style,
1126 &mut last_used_color,
1127 self.editor.clone(),
1128 cx,
1129 );
1130
1131 let start_y = ix as f32 * line_height - (scroll_top % line_height);
1132 let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1133
1134 element.layout(absolute_offset, size(width, AvailableSpace::MinContent), cx);
1135
1136 Some(element)
1137 } else {
1138 None
1139 }
1140 })
1141 .collect();
1142
1143 Some(shaped_lines)
1144 }
1145
1146 fn layout_code_actions_indicator(
1147 &self,
1148 line_height: Pixels,
1149 newest_selection_head: DisplayPoint,
1150 scroll_pixel_position: gpui::Point<Pixels>,
1151 gutter_dimensions: &GutterDimensions,
1152 gutter_hitbox: &Hitbox,
1153 cx: &mut ElementContext,
1154 ) -> Option<AnyElement> {
1155 let mut active = false;
1156 let mut button = None;
1157 self.editor.update(cx, |editor, cx| {
1158 active = matches!(
1159 editor.context_menu.read().as_ref(),
1160 Some(crate::ContextMenu::CodeActions(_))
1161 );
1162 button = editor.render_code_actions_indicator(&self.style, active, cx);
1163 });
1164
1165 let mut button = button?.into_any_element();
1166 let available_space = size(
1167 AvailableSpace::MinContent,
1168 AvailableSpace::Definite(line_height),
1169 );
1170 let indicator_size = button.measure(available_space, cx);
1171
1172 let blame_width = gutter_dimensions
1173 .git_blame_entries_width
1174 .unwrap_or(Pixels::ZERO);
1175
1176 let mut x = blame_width;
1177 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
1178 - indicator_size.width
1179 - blame_width;
1180 x += available_width / 2.;
1181
1182 let mut y = newest_selection_head.row() as f32 * line_height - scroll_pixel_position.y;
1183 y += (line_height - indicator_size.height) / 2.;
1184
1185 button.layout(gutter_hitbox.origin + point(x, y), available_space, cx);
1186 Some(button)
1187 }
1188
1189 fn calculate_relative_line_numbers(
1190 &self,
1191 buffer_rows: Vec<Option<u32>>,
1192 rows: &Range<u32>,
1193 relative_to: Option<u32>,
1194 ) -> HashMap<u32, u32> {
1195 let mut relative_rows: HashMap<u32, u32> = Default::default();
1196 let Some(relative_to) = relative_to else {
1197 return relative_rows;
1198 };
1199
1200 let start = rows.start.min(relative_to);
1201
1202 let head_idx = relative_to - start;
1203 let mut delta = 1;
1204 let mut i = head_idx + 1;
1205 while i < buffer_rows.len() as u32 {
1206 if buffer_rows[i as usize].is_some() {
1207 if rows.contains(&(i + start)) {
1208 relative_rows.insert(i + start, delta);
1209 }
1210 delta += 1;
1211 }
1212 i += 1;
1213 }
1214 delta = 1;
1215 i = head_idx.min(buffer_rows.len() as u32 - 1);
1216 while i > 0 && buffer_rows[i as usize].is_none() {
1217 i -= 1;
1218 }
1219
1220 while i > 0 {
1221 i -= 1;
1222 if buffer_rows[i as usize].is_some() {
1223 if rows.contains(&(i + start)) {
1224 relative_rows.insert(i + start, delta);
1225 }
1226 delta += 1;
1227 }
1228 }
1229
1230 relative_rows
1231 }
1232
1233 fn layout_line_numbers(
1234 &self,
1235 rows: Range<u32>,
1236 buffer_rows: impl Iterator<Item = Option<u32>>,
1237 active_rows: &BTreeMap<u32, bool>,
1238 newest_selection_head: Option<DisplayPoint>,
1239 snapshot: &EditorSnapshot,
1240 cx: &ElementContext,
1241 ) -> (
1242 Vec<Option<ShapedLine>>,
1243 Vec<Option<(FoldStatus, BufferRow, bool)>>,
1244 ) {
1245 let editor = self.editor.read(cx);
1246 let is_singleton = editor.is_singleton(cx);
1247 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
1248 let newest = editor.selections.newest::<Point>(cx);
1249 SelectionLayout::new(
1250 newest,
1251 editor.selections.line_mode,
1252 editor.cursor_shape,
1253 &snapshot.display_snapshot,
1254 true,
1255 true,
1256 None,
1257 )
1258 .head
1259 });
1260 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1261 let include_line_numbers =
1262 EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full;
1263 let include_fold_statuses =
1264 EditorSettings::get_global(cx).gutter.folds && snapshot.mode == EditorMode::Full;
1265 let mut shaped_line_numbers = Vec::with_capacity(rows.len());
1266 let mut fold_statuses = Vec::with_capacity(rows.len());
1267 let mut line_number = String::new();
1268 let is_relative = EditorSettings::get_global(cx).relative_line_numbers;
1269 let relative_to = if is_relative {
1270 Some(newest_selection_head.row())
1271 } else {
1272 None
1273 };
1274
1275 let buffer_rows = buffer_rows.collect::<Vec<_>>();
1276 let relative_rows =
1277 self.calculate_relative_line_numbers(buffer_rows.clone(), &rows, relative_to);
1278
1279 for (ix, row) in buffer_rows.into_iter().enumerate() {
1280 let display_row = rows.start + ix as u32;
1281 let (active, color) = if active_rows.contains_key(&display_row) {
1282 (true, cx.theme().colors().editor_active_line_number)
1283 } else {
1284 (false, cx.theme().colors().editor_line_number)
1285 };
1286 if let Some(buffer_row) = row {
1287 if include_line_numbers {
1288 line_number.clear();
1289 let default_number = buffer_row + 1;
1290 let number = relative_rows
1291 .get(&(ix as u32 + rows.start))
1292 .unwrap_or(&default_number);
1293 write!(&mut line_number, "{}", number).unwrap();
1294 let run = TextRun {
1295 len: line_number.len(),
1296 font: self.style.text.font(),
1297 color,
1298 background_color: None,
1299 underline: None,
1300 strikethrough: None,
1301 };
1302 let shaped_line = cx
1303 .text_system()
1304 .shape_line(line_number.clone().into(), font_size, &[run])
1305 .unwrap();
1306 shaped_line_numbers.push(Some(shaped_line));
1307 }
1308 if include_fold_statuses {
1309 fold_statuses.push(
1310 is_singleton
1311 .then(|| {
1312 snapshot
1313 .fold_for_line(buffer_row)
1314 .map(|fold_status| (fold_status, buffer_row, active))
1315 })
1316 .flatten(),
1317 )
1318 }
1319 } else {
1320 fold_statuses.push(None);
1321 shaped_line_numbers.push(None);
1322 }
1323 }
1324
1325 (shaped_line_numbers, fold_statuses)
1326 }
1327
1328 fn layout_lines(
1329 &self,
1330 rows: Range<u32>,
1331 line_number_layouts: &[Option<ShapedLine>],
1332 snapshot: &EditorSnapshot,
1333 cx: &ElementContext,
1334 ) -> Vec<LineWithInvisibles> {
1335 if rows.start >= rows.end {
1336 return Vec::new();
1337 }
1338
1339 // Show the placeholder when the editor is empty
1340 if snapshot.is_empty() {
1341 let font_size = self.style.text.font_size.to_pixels(cx.rem_size());
1342 let placeholder_color = cx.theme().colors().text_placeholder;
1343 let placeholder_text = snapshot.placeholder_text();
1344
1345 let placeholder_lines = placeholder_text
1346 .as_ref()
1347 .map_or("", AsRef::as_ref)
1348 .split('\n')
1349 .skip(rows.start as usize)
1350 .chain(iter::repeat(""))
1351 .take(rows.len());
1352 placeholder_lines
1353 .filter_map(move |line| {
1354 let run = TextRun {
1355 len: line.len(),
1356 font: self.style.text.font(),
1357 color: placeholder_color,
1358 background_color: None,
1359 underline: Default::default(),
1360 strikethrough: None,
1361 };
1362 cx.text_system()
1363 .shape_line(line.to_string().into(), font_size, &[run])
1364 .log_err()
1365 })
1366 .map(|line| LineWithInvisibles {
1367 line,
1368 invisibles: Vec::new(),
1369 })
1370 .collect()
1371 } else {
1372 let chunks = snapshot.highlighted_chunks(rows.clone(), true, &self.style);
1373 LineWithInvisibles::from_chunks(
1374 chunks,
1375 &self.style.text,
1376 MAX_LINE_LEN,
1377 rows.len(),
1378 line_number_layouts,
1379 snapshot.mode,
1380 cx,
1381 )
1382 }
1383 }
1384
1385 #[allow(clippy::too_many_arguments)]
1386 fn build_blocks(
1387 &self,
1388 rows: Range<u32>,
1389 snapshot: &EditorSnapshot,
1390 hitbox: &Hitbox,
1391 text_hitbox: &Hitbox,
1392 scroll_width: &mut Pixels,
1393 gutter_dimensions: &GutterDimensions,
1394 em_width: Pixels,
1395 text_x: Pixels,
1396 line_height: Pixels,
1397 line_layouts: &[LineWithInvisibles],
1398 cx: &mut ElementContext,
1399 ) -> Vec<BlockLayout> {
1400 let mut block_id = 0;
1401 let (fixed_blocks, non_fixed_blocks) = snapshot
1402 .blocks_in_range(rows.clone())
1403 .partition::<Vec<_>, _>(|(_, block)| match block {
1404 TransformBlock::ExcerptHeader { .. } => false,
1405 TransformBlock::Custom(block) => block.style() == BlockStyle::Fixed,
1406 });
1407
1408 let render_block = |block: &TransformBlock,
1409 available_space: Size<AvailableSpace>,
1410 block_id: usize,
1411 block_row_start: u32,
1412 cx: &mut ElementContext| {
1413 let mut element = match block {
1414 TransformBlock::Custom(block) => {
1415 let align_to = block
1416 .position()
1417 .to_point(&snapshot.buffer_snapshot)
1418 .to_display_point(snapshot);
1419 let anchor_x = text_x
1420 + if rows.contains(&align_to.row()) {
1421 line_layouts[(align_to.row() - rows.start) as usize]
1422 .line
1423 .x_for_index(align_to.column() as usize)
1424 } else {
1425 layout_line(align_to.row(), snapshot, &self.style, cx)
1426 .unwrap()
1427 .x_for_index(align_to.column() as usize)
1428 };
1429
1430 block.render(&mut BlockContext {
1431 context: cx,
1432 anchor_x,
1433 gutter_dimensions,
1434 line_height,
1435 em_width,
1436 block_id,
1437 max_width: text_hitbox.size.width.max(*scroll_width),
1438 editor_style: &self.style,
1439 })
1440 }
1441
1442 TransformBlock::ExcerptHeader {
1443 buffer,
1444 range,
1445 starts_new_buffer,
1446 height,
1447 ..
1448 } => {
1449 let include_root = self
1450 .editor
1451 .read(cx)
1452 .project
1453 .as_ref()
1454 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1455 .unwrap_or_default();
1456
1457 #[derive(Clone)]
1458 struct JumpData {
1459 position: Point,
1460 anchor: text::Anchor,
1461 path: ProjectPath,
1462 line_offset_from_top: u32,
1463 }
1464
1465 let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
1466 let jump_path = ProjectPath {
1467 worktree_id: file.worktree_id(cx),
1468 path: file.path.clone(),
1469 };
1470 let jump_anchor = range
1471 .primary
1472 .as_ref()
1473 .map_or(range.context.start, |primary| primary.start);
1474
1475 let excerpt_start = range.context.start;
1476 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
1477 let offset_from_excerpt_start = if jump_anchor == excerpt_start {
1478 0
1479 } else {
1480 let excerpt_start_row =
1481 language::ToPoint::to_point(&jump_anchor, buffer).row;
1482 jump_position.row - excerpt_start_row
1483 };
1484
1485 let line_offset_from_top =
1486 block_row_start + *height as u32 + offset_from_excerpt_start
1487 - snapshot
1488 .scroll_anchor
1489 .scroll_position(&snapshot.display_snapshot)
1490 .y as u32;
1491
1492 JumpData {
1493 position: jump_position,
1494 anchor: jump_anchor,
1495 path: jump_path,
1496 line_offset_from_top,
1497 }
1498 });
1499
1500 let element = if *starts_new_buffer {
1501 let path = buffer.resolve_file_path(cx, include_root);
1502 let mut filename = None;
1503 let mut parent_path = None;
1504 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
1505 if let Some(path) = path {
1506 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
1507 parent_path = path
1508 .parent()
1509 .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
1510 }
1511
1512 v_flex()
1513 .id(("path header container", block_id))
1514 .size_full()
1515 .justify_center()
1516 .p(gpui::px(6.))
1517 .child(
1518 h_flex()
1519 .id("path header block")
1520 .size_full()
1521 .pl(gpui::px(12.))
1522 .pr(gpui::px(8.))
1523 .rounded_md()
1524 .shadow_md()
1525 .border()
1526 .border_color(cx.theme().colors().border)
1527 .bg(cx.theme().colors().editor_subheader_background)
1528 .justify_between()
1529 .hover(|style| style.bg(cx.theme().colors().element_hover))
1530 .child(
1531 h_flex().gap_3().child(
1532 h_flex()
1533 .gap_2()
1534 .child(
1535 filename
1536 .map(SharedString::from)
1537 .unwrap_or_else(|| "untitled".into()),
1538 )
1539 .when_some(parent_path, |then, path| {
1540 then.child(
1541 div().child(path).text_color(
1542 cx.theme().colors().text_muted,
1543 ),
1544 )
1545 }),
1546 ),
1547 )
1548 .when_some(jump_data.clone(), |this, jump_data| {
1549 this.cursor_pointer()
1550 .tooltip(|cx| {
1551 Tooltip::for_action(
1552 "Jump to File",
1553 &OpenExcerpts,
1554 cx,
1555 )
1556 })
1557 .on_mouse_down(MouseButton::Left, |_, cx| {
1558 cx.stop_propagation()
1559 })
1560 .on_click(cx.listener_for(&self.editor, {
1561 move |editor, _, cx| {
1562 editor.jump(
1563 jump_data.path.clone(),
1564 jump_data.position,
1565 jump_data.anchor,
1566 jump_data.line_offset_from_top,
1567 cx,
1568 );
1569 }
1570 }))
1571 }),
1572 )
1573 } else {
1574 v_flex()
1575 .id(("collapsed context", block_id))
1576 .size_full()
1577 .child(
1578 div()
1579 .flex()
1580 .v_flex()
1581 .justify_start()
1582 .id("jump to collapsed context")
1583 .w(relative(1.0))
1584 .h_full()
1585 .child(
1586 div()
1587 .h_px()
1588 .w_full()
1589 .bg(cx.theme().colors().border_variant)
1590 .group_hover("excerpt-jump-action", |style| {
1591 style.bg(cx.theme().colors().border)
1592 }),
1593 ),
1594 )
1595 .child(
1596 h_flex()
1597 .justify_end()
1598 .flex_none()
1599 .w(
1600 gutter_dimensions.width - (gutter_dimensions.left_padding), // + gutter_dimensions.right_padding)
1601 )
1602 .h_full()
1603 .child(
1604 ButtonLike::new("jump-icon")
1605 .style(ButtonStyle::Transparent)
1606 .child(
1607 svg()
1608 .path(IconName::ArrowUpRight.path())
1609 .size(IconSize::XSmall.rems())
1610 .text_color(cx.theme().colors().border)
1611 .group_hover("excerpt-jump-action", |style| {
1612 style.text_color(
1613 cx.theme().colors().editor_line_number,
1614 )
1615 }),
1616 )
1617 .when_some(jump_data.clone(), |this, jump_data| {
1618 this.on_click(cx.listener_for(&self.editor, {
1619 let path = jump_data.path.clone();
1620 move |editor, _, cx| {
1621 editor.jump(
1622 path.clone(),
1623 jump_data.position,
1624 jump_data.anchor,
1625 jump_data.line_offset_from_top,
1626 cx,
1627 );
1628 }
1629 }))
1630 .tooltip({
1631 move |cx| {
1632 Tooltip::for_action(
1633 format!(
1634 "Jump to {}:L{}",
1635 jump_data.path.path.display(),
1636 jump_data.position.row + 1
1637 ),
1638 &OpenExcerpts,
1639 cx,
1640 )
1641 }
1642 })
1643 }),
1644 ),
1645 )
1646 .group("excerpt-jump-action")
1647 .cursor_pointer()
1648 .when_some(jump_data.clone(), |this, jump_data| {
1649 this.on_click(cx.listener_for(&self.editor, {
1650 let path = jump_data.path.clone();
1651 move |editor, _, cx| {
1652 cx.stop_propagation();
1653
1654 editor.jump(
1655 path.clone(),
1656 jump_data.position,
1657 jump_data.anchor,
1658 jump_data.line_offset_from_top,
1659 cx,
1660 );
1661 }
1662 }))
1663 .tooltip(move |cx| {
1664 Tooltip::for_action(
1665 format!(
1666 "Jump to {}:L{}",
1667 jump_data.path.path.display(),
1668 jump_data.position.row + 1
1669 ),
1670 &OpenExcerpts,
1671 cx,
1672 )
1673 })
1674 })
1675 };
1676 element.into_any()
1677 }
1678 };
1679
1680 let size = element.measure(available_space, cx);
1681 (element, size)
1682 };
1683
1684 let mut fixed_block_max_width = Pixels::ZERO;
1685 let mut blocks = Vec::new();
1686 for (row, block) in fixed_blocks {
1687 let available_space = size(
1688 AvailableSpace::MinContent,
1689 AvailableSpace::Definite(block.height() as f32 * line_height),
1690 );
1691 let (element, element_size) = render_block(block, available_space, block_id, row, cx);
1692 block_id += 1;
1693 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
1694 blocks.push(BlockLayout {
1695 row,
1696 element,
1697 available_space,
1698 style: BlockStyle::Fixed,
1699 });
1700 }
1701 for (row, block) in non_fixed_blocks {
1702 let style = match block {
1703 TransformBlock::Custom(block) => block.style(),
1704 TransformBlock::ExcerptHeader { .. } => BlockStyle::Sticky,
1705 };
1706 let width = match style {
1707 BlockStyle::Sticky => hitbox.size.width,
1708 BlockStyle::Flex => hitbox
1709 .size
1710 .width
1711 .max(fixed_block_max_width)
1712 .max(gutter_dimensions.width + *scroll_width),
1713 BlockStyle::Fixed => unreachable!(),
1714 };
1715 let available_space = size(
1716 AvailableSpace::Definite(width),
1717 AvailableSpace::Definite(block.height() as f32 * line_height),
1718 );
1719 let (element, _) = render_block(block, available_space, block_id, row, cx);
1720 block_id += 1;
1721 blocks.push(BlockLayout {
1722 row,
1723 element,
1724 available_space,
1725 style,
1726 });
1727 }
1728
1729 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
1730 blocks
1731 }
1732
1733 fn layout_blocks(
1734 &self,
1735 blocks: &mut Vec<BlockLayout>,
1736 hitbox: &Hitbox,
1737 line_height: Pixels,
1738 scroll_pixel_position: gpui::Point<Pixels>,
1739 cx: &mut ElementContext,
1740 ) {
1741 for block in blocks {
1742 let mut origin = hitbox.origin
1743 + point(
1744 Pixels::ZERO,
1745 block.row as f32 * line_height - scroll_pixel_position.y,
1746 );
1747 if !matches!(block.style, BlockStyle::Sticky) {
1748 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
1749 }
1750 block.element.layout(origin, block.available_space, cx);
1751 }
1752 }
1753
1754 #[allow(clippy::too_many_arguments)]
1755 fn layout_context_menu(
1756 &self,
1757 line_height: Pixels,
1758 hitbox: &Hitbox,
1759 text_hitbox: &Hitbox,
1760 content_origin: gpui::Point<Pixels>,
1761 start_row: u32,
1762 scroll_pixel_position: gpui::Point<Pixels>,
1763 line_layouts: &[LineWithInvisibles],
1764 newest_selection_head: DisplayPoint,
1765 cx: &mut ElementContext,
1766 ) -> bool {
1767 let max_height = cmp::min(
1768 12. * line_height,
1769 cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
1770 );
1771 let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
1772 if editor.context_menu_visible() {
1773 editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
1774 } else {
1775 None
1776 }
1777 }) else {
1778 return false;
1779 };
1780
1781 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1782 let context_menu_size = context_menu.measure(available_space, cx);
1783
1784 let cursor_row_layout = &line_layouts[(position.row() - start_row) as usize].line;
1785 let x = cursor_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1786 let y = (position.row() + 1) as f32 * line_height - scroll_pixel_position.y;
1787 let mut list_origin = content_origin + point(x, y);
1788 let list_width = context_menu_size.width;
1789 let list_height = context_menu_size.height;
1790
1791 // Snap the right edge of the list to the right edge of the window if
1792 // its horizontal bounds overflow.
1793 if list_origin.x + list_width > cx.viewport_size().width {
1794 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
1795 }
1796
1797 if list_origin.y + list_height > text_hitbox.lower_right().y {
1798 list_origin.y -= line_height + list_height;
1799 }
1800
1801 cx.defer_draw(context_menu, list_origin, 1);
1802 true
1803 }
1804
1805 fn layout_mouse_context_menu(&self, cx: &mut ElementContext) -> Option<AnyElement> {
1806 let mouse_context_menu = self.editor.read(cx).mouse_context_menu.as_ref()?;
1807 let mut element = overlay()
1808 .position(mouse_context_menu.position)
1809 .child(mouse_context_menu.context_menu.clone())
1810 .anchor(AnchorCorner::TopLeft)
1811 .snap_to_window()
1812 .into_any();
1813 element.layout(gpui::Point::default(), AvailableSpace::min_size(), cx);
1814 Some(element)
1815 }
1816
1817 #[allow(clippy::too_many_arguments)]
1818 fn layout_hover_popovers(
1819 &self,
1820 snapshot: &EditorSnapshot,
1821 hitbox: &Hitbox,
1822 text_hitbox: &Hitbox,
1823 visible_display_row_range: Range<u32>,
1824 content_origin: gpui::Point<Pixels>,
1825 scroll_pixel_position: gpui::Point<Pixels>,
1826 line_layouts: &[LineWithInvisibles],
1827 line_height: Pixels,
1828 em_width: Pixels,
1829 cx: &mut ElementContext,
1830 ) {
1831 struct MeasuredHoverPopover {
1832 element: AnyElement,
1833 size: Size<Pixels>,
1834 horizontal_offset: Pixels,
1835 }
1836
1837 let max_size = size(
1838 (120. * em_width) // Default size
1839 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
1840 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
1841 (16. * line_height) // Default size
1842 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
1843 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
1844 );
1845
1846 let hover_popovers = self.editor.update(cx, |editor, cx| {
1847 editor.hover_state.render(
1848 &snapshot,
1849 &self.style,
1850 visible_display_row_range.clone(),
1851 max_size,
1852 editor.workspace.as_ref().map(|(w, _)| w.clone()),
1853 cx,
1854 )
1855 });
1856 let Some((position, hover_popovers)) = hover_popovers else {
1857 return;
1858 };
1859
1860 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
1861
1862 // This is safe because we check on layout whether the required row is available
1863 let hovered_row_layout =
1864 &line_layouts[(position.row() - visible_display_row_range.start) as usize].line;
1865
1866 // Compute Hovered Point
1867 let x =
1868 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
1869 let y = position.row() as f32 * line_height - scroll_pixel_position.y;
1870 let hovered_point = content_origin + point(x, y);
1871
1872 let mut overall_height = Pixels::ZERO;
1873 let mut measured_hover_popovers = Vec::new();
1874 for mut hover_popover in hover_popovers {
1875 let size = hover_popover.measure(available_space, cx);
1876 let horizontal_offset =
1877 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
1878
1879 overall_height += HOVER_POPOVER_GAP + size.height;
1880
1881 measured_hover_popovers.push(MeasuredHoverPopover {
1882 element: hover_popover,
1883 size,
1884 horizontal_offset,
1885 });
1886 }
1887 overall_height += HOVER_POPOVER_GAP;
1888
1889 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
1890 let mut occlusion = div()
1891 .size_full()
1892 .occlude()
1893 .on_mouse_move(|_, cx| cx.stop_propagation())
1894 .into_any_element();
1895 occlusion.measure(size(width, HOVER_POPOVER_GAP).into(), cx);
1896 cx.defer_draw(occlusion, origin, 2);
1897 }
1898
1899 if hovered_point.y > overall_height {
1900 // There is enough space above. Render popovers above the hovered point
1901 let mut current_y = hovered_point.y;
1902 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
1903 let size = popover.size;
1904 let popover_origin = point(
1905 hovered_point.x + popover.horizontal_offset,
1906 current_y - size.height,
1907 );
1908
1909 cx.defer_draw(popover.element, popover_origin, 2);
1910 if position != itertools::Position::Last {
1911 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
1912 draw_occluder(size.width, origin, cx);
1913 }
1914
1915 current_y = popover_origin.y - HOVER_POPOVER_GAP;
1916 }
1917 } else {
1918 // There is not enough space above. Render popovers below the hovered point
1919 let mut current_y = hovered_point.y + line_height;
1920 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
1921 let size = popover.size;
1922 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
1923
1924 cx.defer_draw(popover.element, popover_origin, 2);
1925 if position != itertools::Position::Last {
1926 let origin = point(popover_origin.x, popover_origin.y + size.height);
1927 draw_occluder(size.width, origin, cx);
1928 }
1929
1930 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
1931 }
1932 }
1933 }
1934
1935 fn paint_background(&self, layout: &EditorLayout, cx: &mut ElementContext) {
1936 cx.paint_layer(layout.hitbox.bounds, |cx| {
1937 let scroll_top = layout.position_map.snapshot.scroll_position().y;
1938 let gutter_bg = cx.theme().colors().editor_gutter_background;
1939 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
1940 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
1941
1942 if let EditorMode::Full = layout.mode {
1943 let mut active_rows = layout.active_rows.iter().peekable();
1944 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
1945 let mut end_row = *start_row;
1946 while active_rows.peek().map_or(false, |r| {
1947 *r.0 == end_row + 1 && r.1 == contains_non_empty_selection
1948 }) {
1949 active_rows.next().unwrap();
1950 end_row += 1;
1951 }
1952
1953 if !contains_non_empty_selection {
1954 let origin = point(
1955 layout.hitbox.origin.x,
1956 layout.hitbox.origin.y
1957 + (*start_row as f32 - scroll_top)
1958 * layout.position_map.line_height,
1959 );
1960 let size = size(
1961 layout.hitbox.size.width,
1962 layout.position_map.line_height * (end_row - start_row + 1) as f32,
1963 );
1964 let active_line_bg = cx.theme().colors().editor_active_line_background;
1965 cx.paint_quad(fill(Bounds { origin, size }, active_line_bg));
1966 }
1967 }
1968
1969 let mut paint_highlight =
1970 |highlight_row_start: u32, highlight_row_end: u32, color| {
1971 let origin = point(
1972 layout.hitbox.origin.x,
1973 layout.hitbox.origin.y
1974 + (highlight_row_start as f32 - scroll_top)
1975 * layout.position_map.line_height,
1976 );
1977 let size = size(
1978 layout.hitbox.size.width,
1979 layout.position_map.line_height
1980 * (highlight_row_end + 1 - highlight_row_start) as f32,
1981 );
1982 cx.paint_quad(fill(Bounds { origin, size }, color));
1983 };
1984
1985 let mut last_row = None;
1986 let mut highlight_row_start = 0u32;
1987 let mut highlight_row_end = 0u32;
1988 for (&row, &color) in &layout.highlighted_rows {
1989 let paint = last_row.map_or(false, |(last_row, last_color)| {
1990 last_color != color || last_row + 1 < row
1991 });
1992
1993 if paint {
1994 let paint_range_is_unfinished = highlight_row_end == 0;
1995 if paint_range_is_unfinished {
1996 highlight_row_end = row;
1997 last_row = None;
1998 }
1999 paint_highlight(highlight_row_start, highlight_row_end, color);
2000 highlight_row_start = 0;
2001 highlight_row_end = 0;
2002 if !paint_range_is_unfinished {
2003 highlight_row_start = row;
2004 last_row = Some((row, color));
2005 }
2006 } else {
2007 if last_row.is_none() {
2008 highlight_row_start = row;
2009 } else {
2010 highlight_row_end = row;
2011 }
2012 last_row = Some((row, color));
2013 }
2014 }
2015 if let Some((row, hsla)) = last_row {
2016 highlight_row_end = row;
2017 paint_highlight(highlight_row_start, highlight_row_end, hsla);
2018 }
2019
2020 let scroll_left =
2021 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
2022
2023 for (wrap_position, active) in layout.wrap_guides.iter() {
2024 let x = (layout.text_hitbox.origin.x
2025 + *wrap_position
2026 + layout.position_map.em_width / 2.)
2027 - scroll_left;
2028
2029 let show_scrollbars = layout
2030 .scrollbar_layout
2031 .as_ref()
2032 .map_or(false, |scrollbar| scrollbar.visible);
2033 if x < layout.text_hitbox.origin.x
2034 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
2035 {
2036 continue;
2037 }
2038
2039 let color = if *active {
2040 cx.theme().colors().editor_active_wrap_guide
2041 } else {
2042 cx.theme().colors().editor_wrap_guide
2043 };
2044 cx.paint_quad(fill(
2045 Bounds {
2046 origin: point(x, layout.text_hitbox.origin.y),
2047 size: size(px(1.), layout.text_hitbox.size.height),
2048 },
2049 color,
2050 ));
2051 }
2052 }
2053 })
2054 }
2055
2056 fn paint_gutter(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2057 let line_height = layout.position_map.line_height;
2058
2059 let scroll_position = layout.position_map.snapshot.scroll_position();
2060 let scroll_top = scroll_position.y * line_height;
2061
2062 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
2063
2064 let show_git_gutter = matches!(
2065 ProjectSettings::get_global(cx).git.git_gutter,
2066 Some(GitGutterSetting::TrackedFiles)
2067 );
2068
2069 if show_git_gutter {
2070 Self::paint_diff_hunks(layout, cx);
2071 }
2072
2073 if layout.blamed_display_rows.is_some() {
2074 self.paint_blamed_display_rows(layout, cx);
2075 }
2076
2077 for (ix, line) in layout.line_numbers.iter().enumerate() {
2078 if let Some(line) = line {
2079 let line_origin = layout.gutter_hitbox.origin
2080 + point(
2081 layout.gutter_hitbox.size.width
2082 - line.width
2083 - layout.gutter_dimensions.right_padding,
2084 ix as f32 * line_height - (scroll_top % line_height),
2085 );
2086
2087 line.paint(line_origin, line_height, cx).log_err();
2088 }
2089 }
2090
2091 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2092 cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
2093 for fold_indicator in layout.fold_indicators.iter_mut().flatten() {
2094 fold_indicator.paint(cx);
2095 }
2096 });
2097
2098 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
2099 indicator.paint(cx);
2100 }
2101 })
2102 }
2103
2104 fn paint_diff_hunks(layout: &EditorLayout, cx: &mut ElementContext) {
2105 if layout.display_hunks.is_empty() {
2106 return;
2107 }
2108
2109 let line_height = layout.position_map.line_height;
2110
2111 let scroll_position = layout.position_map.snapshot.scroll_position();
2112 let scroll_top = scroll_position.y * line_height;
2113
2114 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2115 for hunk in &layout.display_hunks {
2116 let (display_row_range, status) = match hunk {
2117 //TODO: This rendering is entirely a horrible hack
2118 &DisplayDiffHunk::Folded { display_row: row } => {
2119 let start_y = row as f32 * line_height - scroll_top;
2120 let end_y = start_y + line_height;
2121
2122 let width = 0.275 * line_height;
2123 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2124 let highlight_size = size(width * 2., end_y - start_y);
2125 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2126 cx.paint_quad(quad(
2127 highlight_bounds,
2128 Corners::all(1. * line_height),
2129 cx.theme().status().modified,
2130 Edges::default(),
2131 transparent_black(),
2132 ));
2133
2134 continue;
2135 }
2136
2137 DisplayDiffHunk::Unfolded {
2138 display_row_range,
2139 status,
2140 } => (display_row_range, status),
2141 };
2142
2143 let color = match status {
2144 DiffHunkStatus::Added => cx.theme().status().created,
2145 DiffHunkStatus::Modified => cx.theme().status().modified,
2146
2147 //TODO: This rendering is entirely a horrible hack
2148 DiffHunkStatus::Removed => {
2149 let row = display_row_range.start;
2150
2151 let offset = line_height / 2.;
2152 let start_y = row as f32 * line_height - offset - scroll_top;
2153 let end_y = start_y + line_height;
2154
2155 let width = 0.275 * line_height;
2156 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2157 let highlight_size = size(width * 2., end_y - start_y);
2158 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2159 cx.paint_quad(quad(
2160 highlight_bounds,
2161 Corners::all(1. * line_height),
2162 cx.theme().status().deleted,
2163 Edges::default(),
2164 transparent_black(),
2165 ));
2166
2167 continue;
2168 }
2169 };
2170
2171 let start_row = display_row_range.start;
2172 let end_row = display_row_range.end;
2173 // If we're in a multibuffer, row range span might include an
2174 // excerpt header, so if we were to draw the marker straight away,
2175 // the hunk might include the rows of that header.
2176 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
2177 // Instead, we simply check whether the range we're dealing with includes
2178 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
2179 let end_row_in_current_excerpt = layout
2180 .position_map
2181 .snapshot
2182 .blocks_in_range(start_row..end_row)
2183 .find_map(|(start_row, block)| {
2184 if matches!(block, TransformBlock::ExcerptHeader { .. }) {
2185 Some(start_row)
2186 } else {
2187 None
2188 }
2189 })
2190 .unwrap_or(end_row);
2191
2192 let start_y = start_row as f32 * line_height - scroll_top;
2193 let end_y = end_row_in_current_excerpt as f32 * line_height - scroll_top;
2194
2195 let width = 0.275 * line_height;
2196 let highlight_origin = layout.gutter_hitbox.origin + point(-width, start_y);
2197 let highlight_size = size(width * 2., end_y - start_y);
2198 let highlight_bounds = Bounds::new(highlight_origin, highlight_size);
2199 cx.paint_quad(quad(
2200 highlight_bounds,
2201 Corners::all(0.05 * line_height),
2202 color,
2203 Edges::default(),
2204 transparent_black(),
2205 ));
2206 }
2207 })
2208 }
2209
2210 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2211 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
2212 return;
2213 };
2214
2215 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
2216 for mut blame_element in blamed_display_rows.into_iter() {
2217 blame_element.paint(cx);
2218 }
2219 })
2220 }
2221
2222 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2223 cx.with_content_mask(
2224 Some(ContentMask {
2225 bounds: layout.text_hitbox.bounds,
2226 }),
2227 |cx| {
2228 let cursor_style = if self
2229 .editor
2230 .read(cx)
2231 .hovered_link_state
2232 .as_ref()
2233 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
2234 {
2235 CursorStyle::PointingHand
2236 } else {
2237 CursorStyle::IBeam
2238 };
2239 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
2240
2241 cx.with_element_id(Some("folds"), |cx| self.paint_folds(layout, cx));
2242 let invisible_display_ranges = self.paint_highlights(layout, cx);
2243 self.paint_lines(&invisible_display_ranges, layout, cx);
2244 self.paint_redactions(layout, cx);
2245 self.paint_cursors(layout, cx);
2246 },
2247 )
2248 }
2249
2250 fn paint_highlights(
2251 &mut self,
2252 layout: &mut EditorLayout,
2253 cx: &mut ElementContext,
2254 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
2255 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2256 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
2257 let line_end_overshoot = 0.15 * layout.position_map.line_height;
2258 for (range, color) in &layout.highlighted_ranges {
2259 self.paint_highlighted_range(
2260 range.clone(),
2261 *color,
2262 Pixels::ZERO,
2263 line_end_overshoot,
2264 layout,
2265 cx,
2266 );
2267 }
2268
2269 let corner_radius = 0.15 * layout.position_map.line_height;
2270
2271 for (player_color, selections) in &layout.selections {
2272 for selection in selections.into_iter() {
2273 self.paint_highlighted_range(
2274 selection.range.clone(),
2275 player_color.selection,
2276 corner_radius,
2277 corner_radius * 2.,
2278 layout,
2279 cx,
2280 );
2281
2282 if selection.is_local && !selection.range.is_empty() {
2283 invisible_display_ranges.push(selection.range.clone());
2284 }
2285 }
2286 }
2287 invisible_display_ranges
2288 })
2289 }
2290
2291 fn paint_lines(
2292 &mut self,
2293 invisible_display_ranges: &[Range<DisplayPoint>],
2294 layout: &EditorLayout,
2295 cx: &mut ElementContext,
2296 ) {
2297 let whitespace_setting = self
2298 .editor
2299 .read(cx)
2300 .buffer
2301 .read(cx)
2302 .settings_at(0, cx)
2303 .show_whitespaces;
2304
2305 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
2306 let row = layout.visible_display_row_range.start + ix as u32;
2307 line_with_invisibles.draw(
2308 layout,
2309 row,
2310 layout.content_origin,
2311 whitespace_setting,
2312 invisible_display_ranges,
2313 cx,
2314 )
2315 }
2316 }
2317
2318 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2319 if layout.redacted_ranges.is_empty() {
2320 return;
2321 }
2322
2323 let line_end_overshoot = layout.line_end_overshoot();
2324
2325 // A softer than perfect black
2326 let redaction_color = gpui::rgb(0x0e1111);
2327
2328 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2329 for range in layout.redacted_ranges.iter() {
2330 self.paint_highlighted_range(
2331 range.clone(),
2332 redaction_color.into(),
2333 Pixels::ZERO,
2334 line_end_overshoot,
2335 layout,
2336 cx,
2337 );
2338 }
2339 });
2340 }
2341
2342 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2343 for cursor in &mut layout.cursors {
2344 cursor.paint(layout.content_origin, cx);
2345 }
2346 }
2347
2348 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2349 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
2350 return;
2351 };
2352
2353 let thumb_bounds = scrollbar_layout.thumb_bounds();
2354 if scrollbar_layout.visible {
2355 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
2356 cx.paint_quad(quad(
2357 scrollbar_layout.hitbox.bounds,
2358 Corners::default(),
2359 cx.theme().colors().scrollbar_track_background,
2360 Edges {
2361 top: Pixels::ZERO,
2362 right: Pixels::ZERO,
2363 bottom: Pixels::ZERO,
2364 left: ScrollbarLayout::BORDER_WIDTH,
2365 },
2366 cx.theme().colors().scrollbar_track_border,
2367 ));
2368 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
2369 let is_singleton = self.editor.read(cx).is_singleton(cx);
2370 let left = scrollbar_layout.hitbox.left();
2371 let right = scrollbar_layout.hitbox.right();
2372 let column_width =
2373 px(((right - left - ScrollbarLayout::BORDER_WIDTH).0 / 3.0).floor());
2374 if is_singleton && scrollbar_settings.selections {
2375 let start_anchor = Anchor::min();
2376 let end_anchor = Anchor::max();
2377 let background_ranges = self
2378 .editor
2379 .read(cx)
2380 .background_highlight_row_ranges::<BufferSearchHighlights>(
2381 start_anchor..end_anchor,
2382 &layout.position_map.snapshot,
2383 50000,
2384 );
2385 let left_x = left + ScrollbarLayout::BORDER_WIDTH + column_width;
2386 let right_x = left_x + column_width;
2387 for range in background_ranges {
2388 let (start_y, end_y) =
2389 scrollbar_layout.ys_for_marker(range.start().row(), range.end().row());
2390 let bounds =
2391 Bounds::from_corners(point(left_x, start_y), point(right_x, end_y));
2392 cx.paint_quad(quad(
2393 bounds,
2394 Corners::default(),
2395 cx.theme().status().info,
2396 Edges::default(),
2397 cx.theme().colors().scrollbar_thumb_border,
2398 ));
2399 }
2400 }
2401
2402 if is_singleton && scrollbar_settings.symbols_selections {
2403 let selection_ranges = self.editor.read(cx).background_highlights_in_range(
2404 Anchor::min()..Anchor::max(),
2405 &layout.position_map.snapshot,
2406 cx.theme().colors(),
2407 );
2408 let left_x = left + ScrollbarLayout::BORDER_WIDTH + column_width;
2409 let right_x = left_x + column_width;
2410 for hunk in selection_ranges {
2411 let start_display = Point::new(hunk.0.start.row(), 0)
2412 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2413 let end_display = Point::new(hunk.0.end.row(), 0)
2414 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2415 let (start_y, end_y) =
2416 scrollbar_layout.ys_for_marker(start_display.row(), end_display.row());
2417 let bounds =
2418 Bounds::from_corners(point(left_x, start_y), point(right_x, end_y));
2419 cx.paint_quad(quad(
2420 bounds,
2421 Corners::default(),
2422 cx.theme().status().info,
2423 Edges::default(),
2424 cx.theme().colors().scrollbar_thumb_border,
2425 ));
2426 }
2427 }
2428
2429 if is_singleton && scrollbar_settings.git_diff {
2430 let left_x = left + ScrollbarLayout::BORDER_WIDTH;
2431 let right_x = left_x + column_width;
2432 for hunk in layout
2433 .position_map
2434 .snapshot
2435 .buffer_snapshot
2436 .git_diff_hunks_in_range(0..layout.max_row)
2437 {
2438 let start_display_row = Point::new(hunk.associated_range.start, 0)
2439 .to_display_point(&layout.position_map.snapshot.display_snapshot)
2440 .row();
2441 let mut end_display_row = Point::new(hunk.associated_range.end, 0)
2442 .to_display_point(&layout.position_map.snapshot.display_snapshot)
2443 .row();
2444 if end_display_row != start_display_row {
2445 end_display_row -= 1;
2446 }
2447 let (start_y, end_y) =
2448 scrollbar_layout.ys_for_marker(start_display_row, end_display_row);
2449 let bounds =
2450 Bounds::from_corners(point(left_x, start_y), point(right_x, end_y));
2451 let color = match hunk.status() {
2452 DiffHunkStatus::Added => cx.theme().status().created,
2453 DiffHunkStatus::Modified => cx.theme().status().modified,
2454 DiffHunkStatus::Removed => cx.theme().status().deleted,
2455 };
2456 cx.paint_quad(quad(
2457 bounds,
2458 Corners::default(),
2459 color,
2460 Edges::default(),
2461 cx.theme().colors().scrollbar_thumb_border,
2462 ));
2463 }
2464 }
2465
2466 if is_singleton && scrollbar_settings.diagnostics {
2467 let max_point = layout
2468 .position_map
2469 .snapshot
2470 .display_snapshot
2471 .buffer_snapshot
2472 .max_point();
2473
2474 let diagnostics = layout
2475 .position_map
2476 .snapshot
2477 .buffer_snapshot
2478 .diagnostics_in_range::<_, Point>(Point::zero()..max_point, false)
2479 // We want to sort by severity, in order to paint the most severe diagnostics last.
2480 .sorted_by_key(|diagnostic| {
2481 std::cmp::Reverse(diagnostic.diagnostic.severity)
2482 });
2483
2484 let left_x = left + ScrollbarLayout::BORDER_WIDTH + 2.0 * column_width;
2485 for diagnostic in diagnostics {
2486 let start_display = diagnostic
2487 .range
2488 .start
2489 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2490 let end_display = diagnostic
2491 .range
2492 .end
2493 .to_display_point(&layout.position_map.snapshot.display_snapshot);
2494 let (start_y, end_y) =
2495 scrollbar_layout.ys_for_marker(start_display.row(), end_display.row());
2496 let bounds =
2497 Bounds::from_corners(point(left_x, start_y), point(right, end_y));
2498 let color = match diagnostic.diagnostic.severity {
2499 DiagnosticSeverity::ERROR => cx.theme().status().error,
2500 DiagnosticSeverity::WARNING => cx.theme().status().warning,
2501 DiagnosticSeverity::INFORMATION => cx.theme().status().info,
2502 _ => cx.theme().status().hint,
2503 };
2504 cx.paint_quad(quad(
2505 bounds,
2506 Corners::default(),
2507 color,
2508 Edges::default(),
2509 cx.theme().colors().scrollbar_thumb_border,
2510 ));
2511 }
2512 }
2513
2514 cx.paint_quad(quad(
2515 thumb_bounds,
2516 Corners::default(),
2517 cx.theme().colors().scrollbar_thumb_background,
2518 Edges {
2519 top: Pixels::ZERO,
2520 right: Pixels::ZERO,
2521 bottom: Pixels::ZERO,
2522 left: ScrollbarLayout::BORDER_WIDTH,
2523 },
2524 cx.theme().colors().scrollbar_thumb_border,
2525 ));
2526 });
2527 }
2528
2529 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
2530
2531 let scroll_height = scrollbar_layout.scroll_height;
2532 let height = scrollbar_layout.height;
2533 let row_range = scrollbar_layout.visible_row_range.clone();
2534
2535 cx.on_mouse_event({
2536 let editor = self.editor.clone();
2537 let hitbox = scrollbar_layout.hitbox.clone();
2538 let mut mouse_position = cx.mouse_position();
2539 move |event: &MouseMoveEvent, phase, cx| {
2540 if phase == DispatchPhase::Capture {
2541 return;
2542 }
2543
2544 editor.update(cx, |editor, cx| {
2545 if event.pressed_button == Some(MouseButton::Left)
2546 && editor.scroll_manager.is_dragging_scrollbar()
2547 {
2548 let y = mouse_position.y;
2549 let new_y = event.position.y;
2550 if (hitbox.top()..hitbox.bottom()).contains(&y) {
2551 let mut position = editor.scroll_position(cx);
2552 position.y += (new_y - y) * scroll_height / height;
2553 if position.y < 0.0 {
2554 position.y = 0.0;
2555 }
2556 editor.set_scroll_position(position, cx);
2557 }
2558
2559 mouse_position = event.position;
2560 cx.stop_propagation();
2561 } else {
2562 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2563 if hitbox.is_hovered(cx) {
2564 editor.scroll_manager.show_scrollbar(cx);
2565 }
2566 }
2567 })
2568 }
2569 });
2570
2571 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
2572 cx.on_mouse_event({
2573 let editor = self.editor.clone();
2574 move |_: &MouseUpEvent, phase, cx| {
2575 if phase == DispatchPhase::Capture {
2576 return;
2577 }
2578
2579 editor.update(cx, |editor, cx| {
2580 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
2581 cx.stop_propagation();
2582 });
2583 }
2584 });
2585 } else {
2586 cx.on_mouse_event({
2587 let editor = self.editor.clone();
2588 let hitbox = scrollbar_layout.hitbox.clone();
2589 move |event: &MouseDownEvent, phase, cx| {
2590 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
2591 return;
2592 }
2593
2594 editor.update(cx, |editor, cx| {
2595 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
2596
2597 let y = event.position.y;
2598 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
2599 let center_row =
2600 ((y - hitbox.top()) * scroll_height / height).round() as u32;
2601 let top_row = center_row
2602 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
2603 let mut position = editor.scroll_position(cx);
2604 position.y = top_row as f32;
2605 editor.set_scroll_position(position, cx);
2606 } else {
2607 editor.scroll_manager.show_scrollbar(cx);
2608 }
2609
2610 cx.stop_propagation();
2611 });
2612 }
2613 });
2614 }
2615 }
2616
2617 #[allow(clippy::too_many_arguments)]
2618 fn paint_highlighted_range(
2619 &self,
2620 range: Range<DisplayPoint>,
2621 color: Hsla,
2622 corner_radius: Pixels,
2623 line_end_overshoot: Pixels,
2624 layout: &EditorLayout,
2625 cx: &mut ElementContext,
2626 ) {
2627 let start_row = layout.visible_display_row_range.start;
2628 let end_row = layout.visible_display_row_range.end;
2629 if range.start != range.end {
2630 let row_range = if range.end.column() == 0 {
2631 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
2632 } else {
2633 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row() + 1, end_row)
2634 };
2635
2636 let highlighted_range = HighlightedRange {
2637 color,
2638 line_height: layout.position_map.line_height,
2639 corner_radius,
2640 start_y: layout.content_origin.y
2641 + row_range.start as f32 * layout.position_map.line_height
2642 - layout.position_map.scroll_pixel_position.y,
2643 lines: row_range
2644 .into_iter()
2645 .map(|row| {
2646 let line_layout =
2647 &layout.position_map.line_layouts[(row - start_row) as usize].line;
2648 HighlightedRangeLine {
2649 start_x: if row == range.start.row() {
2650 layout.content_origin.x
2651 + line_layout.x_for_index(range.start.column() as usize)
2652 - layout.position_map.scroll_pixel_position.x
2653 } else {
2654 layout.content_origin.x
2655 - layout.position_map.scroll_pixel_position.x
2656 },
2657 end_x: if row == range.end.row() {
2658 layout.content_origin.x
2659 + line_layout.x_for_index(range.end.column() as usize)
2660 - layout.position_map.scroll_pixel_position.x
2661 } else {
2662 layout.content_origin.x + line_layout.width + line_end_overshoot
2663 - layout.position_map.scroll_pixel_position.x
2664 },
2665 }
2666 })
2667 .collect(),
2668 };
2669
2670 highlighted_range.paint(layout.text_hitbox.bounds, cx);
2671 }
2672 }
2673
2674 fn paint_folds(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2675 if layout.folds.is_empty() {
2676 return;
2677 }
2678
2679 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
2680 let fold_corner_radius = 0.15 * layout.position_map.line_height;
2681 for mut fold in mem::take(&mut layout.folds) {
2682 fold.hover_element.paint(cx);
2683
2684 let hover_element = fold.hover_element.downcast_mut::<Stateful<Div>>().unwrap();
2685 let fold_background = if hover_element.interactivity().active.unwrap() {
2686 cx.theme().colors().ghost_element_active
2687 } else if hover_element.interactivity().hovered.unwrap() {
2688 cx.theme().colors().ghost_element_hover
2689 } else {
2690 cx.theme().colors().ghost_element_background
2691 };
2692
2693 self.paint_highlighted_range(
2694 fold.display_range.clone(),
2695 fold_background,
2696 fold_corner_radius,
2697 fold_corner_radius * 2.,
2698 layout,
2699 cx,
2700 );
2701 }
2702 })
2703 }
2704
2705 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2706 for mut block in layout.blocks.drain(..) {
2707 block.element.paint(cx);
2708 }
2709 }
2710
2711 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut ElementContext) {
2712 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
2713 mouse_context_menu.paint(cx);
2714 }
2715 }
2716
2717 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2718 cx.on_mouse_event({
2719 let position_map = layout.position_map.clone();
2720 let editor = self.editor.clone();
2721 let hitbox = layout.hitbox.clone();
2722 let mut delta = ScrollDelta::default();
2723
2724 move |event: &ScrollWheelEvent, phase, cx| {
2725 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
2726 delta = delta.coalesce(event.delta);
2727 editor.update(cx, |editor, cx| {
2728 let position_map: &PositionMap = &position_map;
2729
2730 let line_height = position_map.line_height;
2731 let max_glyph_width = position_map.em_width;
2732 let (delta, axis) = match delta {
2733 gpui::ScrollDelta::Pixels(mut pixels) => {
2734 //Trackpad
2735 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
2736 (pixels, axis)
2737 }
2738
2739 gpui::ScrollDelta::Lines(lines) => {
2740 //Not trackpad
2741 let pixels =
2742 point(lines.x * max_glyph_width, lines.y * line_height);
2743 (pixels, None)
2744 }
2745 };
2746
2747 let scroll_position = position_map.snapshot.scroll_position();
2748 let x = (scroll_position.x * max_glyph_width - delta.x) / max_glyph_width;
2749 let y = (scroll_position.y * line_height - delta.y) / line_height;
2750 let scroll_position =
2751 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
2752 editor.scroll(scroll_position, axis, cx);
2753 cx.stop_propagation();
2754 });
2755 }
2756 }
2757 });
2758 }
2759
2760 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, cx: &mut ElementContext) {
2761 self.paint_scroll_wheel_listener(layout, cx);
2762
2763 cx.on_mouse_event({
2764 let position_map = layout.position_map.clone();
2765 let editor = self.editor.clone();
2766 let text_hitbox = layout.text_hitbox.clone();
2767 let gutter_hitbox = layout.gutter_hitbox.clone();
2768
2769 move |event: &MouseDownEvent, phase, cx| {
2770 if phase == DispatchPhase::Bubble {
2771 match event.button {
2772 MouseButton::Left => editor.update(cx, |editor, cx| {
2773 Self::mouse_left_down(
2774 editor,
2775 event,
2776 &position_map,
2777 &text_hitbox,
2778 &gutter_hitbox,
2779 cx,
2780 );
2781 }),
2782 MouseButton::Right => editor.update(cx, |editor, cx| {
2783 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
2784 }),
2785 _ => {}
2786 };
2787 }
2788 }
2789 });
2790
2791 cx.on_mouse_event({
2792 let editor = self.editor.clone();
2793 let position_map = layout.position_map.clone();
2794 let text_hitbox = layout.text_hitbox.clone();
2795
2796 move |event: &MouseUpEvent, phase, cx| {
2797 if phase == DispatchPhase::Bubble {
2798 editor.update(cx, |editor, cx| {
2799 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
2800 });
2801 }
2802 }
2803 });
2804 cx.on_mouse_event({
2805 let position_map = layout.position_map.clone();
2806 let editor = self.editor.clone();
2807 let text_hitbox = layout.text_hitbox.clone();
2808 let gutter_hitbox = layout.gutter_hitbox.clone();
2809
2810 move |event: &MouseMoveEvent, phase, cx| {
2811 if phase == DispatchPhase::Bubble {
2812 editor.update(cx, |editor, cx| {
2813 if event.pressed_button == Some(MouseButton::Left) {
2814 Self::mouse_dragged(
2815 editor,
2816 event,
2817 &position_map,
2818 text_hitbox.bounds,
2819 cx,
2820 )
2821 }
2822
2823 Self::mouse_moved(
2824 editor,
2825 event,
2826 &position_map,
2827 &text_hitbox,
2828 &gutter_hitbox,
2829 cx,
2830 )
2831 });
2832 }
2833 }
2834 });
2835 }
2836
2837 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
2838 bounds.upper_right().x - self.style.scrollbar_width
2839 }
2840
2841 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
2842 let style = &self.style;
2843 let font_size = style.text.font_size.to_pixels(cx.rem_size());
2844 let layout = cx
2845 .text_system()
2846 .shape_line(
2847 SharedString::from(" ".repeat(column)),
2848 font_size,
2849 &[TextRun {
2850 len: column,
2851 font: style.text.font(),
2852 color: Hsla::default(),
2853 background_color: None,
2854 underline: None,
2855 strikethrough: None,
2856 }],
2857 )
2858 .unwrap();
2859
2860 layout.width
2861 }
2862
2863 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
2864 let digit_count = (snapshot.max_buffer_row() as f32 + 1.).log10().floor() as usize + 1;
2865 self.column_pixels(digit_count, cx)
2866 }
2867}
2868
2869fn render_blame_entry(
2870 ix: usize,
2871 blame: &gpui::Model<GitBlame>,
2872 blame_entry: BlameEntry,
2873 text_style: &TextStyle,
2874 last_used_color: &mut Option<(PlayerColor, Oid)>,
2875 editor: View<Editor>,
2876 cx: &mut ElementContext<'_>,
2877) -> AnyElement {
2878 let mut sha_color = cx
2879 .theme()
2880 .players()
2881 .color_for_participant(blame_entry.sha.into());
2882 // If the last color we used is the same as the one we get for this line, but
2883 // the commit SHAs are different, then we try again to get a different color.
2884 match *last_used_color {
2885 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
2886 let index: u32 = blame_entry.sha.into();
2887 sha_color = cx.theme().players().color_for_participant(index + 1);
2888 }
2889 _ => {}
2890 };
2891 last_used_color.replace((sha_color, blame_entry.sha));
2892
2893 let relative_timestamp = match blame_entry.author_offset_date_time() {
2894 Ok(timestamp) => time_format::format_localized_timestamp(
2895 timestamp,
2896 time::OffsetDateTime::now_utc(),
2897 cx.local_timezone(),
2898 time_format::TimestampFormat::Relative,
2899 ),
2900 Err(_) => "Error parsing date".to_string(),
2901 };
2902
2903 let pretty_commit_id = format!("{}", blame_entry.sha);
2904 let short_commit_id = pretty_commit_id.clone().chars().take(6).collect::<String>();
2905
2906 let name = blame_entry.author.as_deref().unwrap_or("<no name>");
2907 let name = if name.len() > 20 {
2908 format!("{}...", &name[..16])
2909 } else {
2910 name.to_string()
2911 };
2912
2913 let permalink = blame.read(cx).permalink_for_entry(&blame_entry);
2914 let commit_message = blame.read(cx).message_for_entry(&blame_entry);
2915
2916 h_flex()
2917 .font(text_style.font().family)
2918 .line_height(text_style.line_height)
2919 .id(("blame", ix))
2920 .children([
2921 div()
2922 .text_color(sha_color.cursor)
2923 .child(short_commit_id)
2924 .mr_2(),
2925 div()
2926 .text_color(cx.theme().status().hint)
2927 .child(format!("{:20} {: >14}", name, relative_timestamp)),
2928 ])
2929 .on_mouse_down(MouseButton::Right, {
2930 let blame_entry = blame_entry.clone();
2931 move |event, cx| {
2932 deploy_blame_entry_context_menu(&blame_entry, editor.clone(), event.position, cx);
2933 }
2934 })
2935 .hover(|style| style.bg(cx.theme().colors().element_hover))
2936 .when_some(permalink, |this, url| {
2937 let url = url.clone();
2938 this.cursor_pointer().on_click(move |_, cx| {
2939 cx.stop_propagation();
2940 cx.open_url(url.as_str())
2941 })
2942 })
2943 .tooltip(move |cx| {
2944 BlameEntryTooltip::new(
2945 sha_color.cursor,
2946 commit_message.clone(),
2947 blame_entry.clone(),
2948 cx,
2949 )
2950 })
2951 .into_any()
2952}
2953
2954fn deploy_blame_entry_context_menu(
2955 blame_entry: &BlameEntry,
2956 editor: View<Editor>,
2957 position: gpui::Point<Pixels>,
2958 cx: &mut WindowContext<'_>,
2959) {
2960 let context_menu = ContextMenu::build(cx, move |this, _| {
2961 let sha = format!("{}", blame_entry.sha);
2962 this.entry("Copy commit SHA", None, move |cx| {
2963 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
2964 })
2965 });
2966
2967 editor.update(cx, move |editor, cx| {
2968 editor.mouse_context_menu = Some(MouseContextMenu::new(position, context_menu, cx));
2969 cx.notify();
2970 });
2971}
2972
2973struct BlameEntryTooltip {
2974 color: Hsla,
2975 commit_message: Option<String>,
2976 blame_entry: BlameEntry,
2977}
2978
2979impl BlameEntryTooltip {
2980 fn new(
2981 color: Hsla,
2982 commit_message: Option<String>,
2983 blame_entry: BlameEntry,
2984 cx: &mut WindowContext,
2985 ) -> AnyView {
2986 cx.new_view(|_cx| Self {
2987 color,
2988 commit_message,
2989 blame_entry,
2990 })
2991 .into()
2992 }
2993}
2994
2995impl Render for BlameEntryTooltip {
2996 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2997 let author = self
2998 .blame_entry
2999 .author
3000 .clone()
3001 .unwrap_or("<no name>".to_string());
3002 let author_email = self.blame_entry.author_mail.clone().unwrap_or_default();
3003 let absolute_timestamp = match self.blame_entry.author_offset_date_time() {
3004 Ok(timestamp) => time_format::format_localized_timestamp(
3005 timestamp,
3006 time::OffsetDateTime::now_utc(),
3007 cx.local_timezone(),
3008 time_format::TimestampFormat::Absolute,
3009 ),
3010 Err(_) => "Error parsing date".to_string(),
3011 };
3012
3013 let message = match &self.commit_message {
3014 Some(message) => util::truncate_lines_and_trailoff(message, 15),
3015 None => self.blame_entry.summary.clone().unwrap_or_default(),
3016 };
3017
3018 let pretty_commit_id = format!("{}", self.blame_entry.sha);
3019
3020 tooltip_container(cx, move |this, cx| {
3021 this.occlude()
3022 .on_mouse_move(|_, cx| cx.stop_propagation())
3023 .child(
3024 v_flex()
3025 .child(
3026 h_flex()
3027 .child(
3028 div()
3029 .text_color(cx.theme().colors().text_muted)
3030 .child("Commit")
3031 .pr_2(),
3032 )
3033 .child(
3034 div().text_color(self.color).child(pretty_commit_id.clone()),
3035 ),
3036 )
3037 .child(
3038 div()
3039 .child(format!(
3040 "{} {} - {}",
3041 author, author_email, absolute_timestamp
3042 ))
3043 .text_color(cx.theme().colors().text_muted),
3044 )
3045 .child(div().child(message)),
3046 )
3047 })
3048 }
3049}
3050
3051#[derive(Debug)]
3052pub(crate) struct LineWithInvisibles {
3053 pub line: ShapedLine,
3054 invisibles: Vec<Invisible>,
3055}
3056
3057impl LineWithInvisibles {
3058 fn from_chunks<'a>(
3059 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
3060 text_style: &TextStyle,
3061 max_line_len: usize,
3062 max_line_count: usize,
3063 line_number_layouts: &[Option<ShapedLine>],
3064 editor_mode: EditorMode,
3065 cx: &WindowContext,
3066 ) -> Vec<Self> {
3067 let mut layouts = Vec::with_capacity(max_line_count);
3068 let mut line = String::new();
3069 let mut invisibles = Vec::new();
3070 let mut styles = Vec::new();
3071 let mut non_whitespace_added = false;
3072 let mut row = 0;
3073 let mut line_exceeded_max_len = false;
3074 let font_size = text_style.font_size.to_pixels(cx.rem_size());
3075
3076 for highlighted_chunk in chunks.chain([HighlightedChunk {
3077 chunk: "\n",
3078 style: None,
3079 is_tab: false,
3080 }]) {
3081 for (ix, mut line_chunk) in highlighted_chunk.chunk.split('\n').enumerate() {
3082 if ix > 0 {
3083 let shaped_line = cx
3084 .text_system()
3085 .shape_line(line.clone().into(), font_size, &styles)
3086 .unwrap();
3087 layouts.push(Self {
3088 line: shaped_line,
3089 invisibles: std::mem::take(&mut invisibles),
3090 });
3091
3092 line.clear();
3093 styles.clear();
3094 row += 1;
3095 line_exceeded_max_len = false;
3096 non_whitespace_added = false;
3097 if row == max_line_count {
3098 return layouts;
3099 }
3100 }
3101
3102 if !line_chunk.is_empty() && !line_exceeded_max_len {
3103 let text_style = if let Some(style) = highlighted_chunk.style {
3104 Cow::Owned(text_style.clone().highlight(style))
3105 } else {
3106 Cow::Borrowed(text_style)
3107 };
3108
3109 if line.len() + line_chunk.len() > max_line_len {
3110 let mut chunk_len = max_line_len - line.len();
3111 while !line_chunk.is_char_boundary(chunk_len) {
3112 chunk_len -= 1;
3113 }
3114 line_chunk = &line_chunk[..chunk_len];
3115 line_exceeded_max_len = true;
3116 }
3117
3118 styles.push(TextRun {
3119 len: line_chunk.len(),
3120 font: text_style.font(),
3121 color: text_style.color,
3122 background_color: text_style.background_color,
3123 underline: text_style.underline,
3124 strikethrough: text_style.strikethrough,
3125 });
3126
3127 if editor_mode == EditorMode::Full {
3128 // Line wrap pads its contents with fake whitespaces,
3129 // avoid printing them
3130 let inside_wrapped_string = line_number_layouts
3131 .get(row)
3132 .and_then(|layout| layout.as_ref())
3133 .is_none();
3134 if highlighted_chunk.is_tab {
3135 if non_whitespace_added || !inside_wrapped_string {
3136 invisibles.push(Invisible::Tab {
3137 line_start_offset: line.len(),
3138 });
3139 }
3140 } else {
3141 invisibles.extend(
3142 line_chunk
3143 .chars()
3144 .enumerate()
3145 .filter(|(_, line_char)| {
3146 let is_whitespace = line_char.is_whitespace();
3147 non_whitespace_added |= !is_whitespace;
3148 is_whitespace
3149 && (non_whitespace_added || !inside_wrapped_string)
3150 })
3151 .map(|(whitespace_index, _)| Invisible::Whitespace {
3152 line_offset: line.len() + whitespace_index,
3153 }),
3154 )
3155 }
3156 }
3157
3158 line.push_str(line_chunk);
3159 }
3160 }
3161 }
3162
3163 layouts
3164 }
3165
3166 fn draw(
3167 &self,
3168 layout: &EditorLayout,
3169 row: u32,
3170 content_origin: gpui::Point<Pixels>,
3171 whitespace_setting: ShowWhitespaceSetting,
3172 selection_ranges: &[Range<DisplayPoint>],
3173 cx: &mut ElementContext,
3174 ) {
3175 let line_height = layout.position_map.line_height;
3176 let line_y =
3177 line_height * (row as f32 - layout.position_map.scroll_pixel_position.y / line_height);
3178
3179 self.line
3180 .paint(
3181 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y),
3182 line_height,
3183 cx,
3184 )
3185 .log_err();
3186
3187 self.draw_invisibles(
3188 &selection_ranges,
3189 layout,
3190 content_origin,
3191 line_y,
3192 row,
3193 line_height,
3194 whitespace_setting,
3195 cx,
3196 );
3197 }
3198
3199 #[allow(clippy::too_many_arguments)]
3200 fn draw_invisibles(
3201 &self,
3202 selection_ranges: &[Range<DisplayPoint>],
3203 layout: &EditorLayout,
3204 content_origin: gpui::Point<Pixels>,
3205 line_y: Pixels,
3206 row: u32,
3207 line_height: Pixels,
3208 whitespace_setting: ShowWhitespaceSetting,
3209 cx: &mut ElementContext,
3210 ) {
3211 let allowed_invisibles_regions = match whitespace_setting {
3212 ShowWhitespaceSetting::None => return,
3213 ShowWhitespaceSetting::Selection => Some(selection_ranges),
3214 ShowWhitespaceSetting::All => None,
3215 };
3216
3217 for invisible in &self.invisibles {
3218 let (&token_offset, invisible_symbol) = match invisible {
3219 Invisible::Tab { line_start_offset } => (line_start_offset, &layout.tab_invisible),
3220 Invisible::Whitespace { line_offset } => (line_offset, &layout.space_invisible),
3221 };
3222
3223 let x_offset = self.line.x_for_index(token_offset);
3224 let invisible_offset =
3225 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
3226 let origin = content_origin
3227 + gpui::point(
3228 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
3229 line_y,
3230 );
3231
3232 if let Some(allowed_regions) = allowed_invisibles_regions {
3233 let invisible_point = DisplayPoint::new(row, token_offset as u32);
3234 if !allowed_regions
3235 .iter()
3236 .any(|region| region.start <= invisible_point && invisible_point < region.end)
3237 {
3238 continue;
3239 }
3240 }
3241 invisible_symbol.paint(origin, line_height, cx).log_err();
3242 }
3243 }
3244}
3245
3246#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3247enum Invisible {
3248 Tab { line_start_offset: usize },
3249 Whitespace { line_offset: usize },
3250}
3251
3252impl Element for EditorElement {
3253 type BeforeLayout = ();
3254 type AfterLayout = EditorLayout;
3255
3256 fn before_layout(&mut self, cx: &mut ElementContext) -> (gpui::LayoutId, ()) {
3257 self.editor.update(cx, |editor, cx| {
3258 editor.set_style(self.style.clone(), cx);
3259
3260 let layout_id = match editor.mode {
3261 EditorMode::SingleLine => {
3262 let rem_size = cx.rem_size();
3263 let mut style = Style::default();
3264 style.size.width = relative(1.).into();
3265 style.size.height = self.style.text.line_height_in_pixels(rem_size).into();
3266 cx.with_element_context(|cx| cx.request_layout(&style, None))
3267 }
3268 EditorMode::AutoHeight { max_lines } => {
3269 let editor_handle = cx.view().clone();
3270 let max_line_number_width =
3271 self.max_line_number_width(&editor.snapshot(cx), cx);
3272 cx.with_element_context(|cx| {
3273 cx.request_measured_layout(
3274 Style::default(),
3275 move |known_dimensions, _, cx| {
3276 editor_handle
3277 .update(cx, |editor, cx| {
3278 compute_auto_height_layout(
3279 editor,
3280 max_lines,
3281 max_line_number_width,
3282 known_dimensions,
3283 cx,
3284 )
3285 })
3286 .unwrap_or_default()
3287 },
3288 )
3289 })
3290 }
3291 EditorMode::Full => {
3292 let mut style = Style::default();
3293 style.size.width = relative(1.).into();
3294 style.size.height = relative(1.).into();
3295 cx.with_element_context(|cx| cx.request_layout(&style, None))
3296 }
3297 };
3298
3299 (layout_id, ())
3300 })
3301 }
3302
3303 fn after_layout(
3304 &mut self,
3305 bounds: Bounds<Pixels>,
3306 _: &mut Self::BeforeLayout,
3307 cx: &mut ElementContext,
3308 ) -> Self::AfterLayout {
3309 let text_style = TextStyleRefinement {
3310 font_size: Some(self.style.text.font_size),
3311 line_height: Some(self.style.text.line_height),
3312 ..Default::default()
3313 };
3314 cx.with_text_style(Some(text_style), |cx| {
3315 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3316 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
3317 let style = self.style.clone();
3318
3319 let font_id = cx.text_system().resolve_font(&style.text.font());
3320 let font_size = style.text.font_size.to_pixels(cx.rem_size());
3321 let line_height = style.text.line_height_in_pixels(cx.rem_size());
3322 let em_width = cx
3323 .text_system()
3324 .typographic_bounds(font_id, font_size, 'm')
3325 .unwrap()
3326 .size
3327 .width;
3328 let em_advance = cx
3329 .text_system()
3330 .advance(font_id, font_size, 'm')
3331 .unwrap()
3332 .width;
3333
3334 let gutter_dimensions = snapshot.gutter_dimensions(
3335 font_id,
3336 font_size,
3337 em_width,
3338 self.max_line_number_width(&snapshot, cx),
3339 cx,
3340 );
3341 let text_width = bounds.size.width - gutter_dimensions.width;
3342 let overscroll = size(em_width, px(0.));
3343
3344 snapshot = self.editor.update(cx, |editor, cx| {
3345 editor.gutter_width = gutter_dimensions.width;
3346 editor.set_visible_line_count(bounds.size.height / line_height, cx);
3347
3348 let editor_width =
3349 text_width - gutter_dimensions.margin - overscroll.width - em_width;
3350 let wrap_width = match editor.soft_wrap_mode(cx) {
3351 SoftWrap::None => (MAX_LINE_LEN / 2) as f32 * em_advance,
3352 SoftWrap::EditorWidth => editor_width,
3353 SoftWrap::Column(column) => editor_width.min(column as f32 * em_advance),
3354 };
3355
3356 if editor.set_wrap_width(Some(wrap_width), cx) {
3357 editor.snapshot(cx)
3358 } else {
3359 snapshot
3360 }
3361 });
3362
3363 let wrap_guides = self
3364 .editor
3365 .read(cx)
3366 .wrap_guides(cx)
3367 .iter()
3368 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
3369 .collect::<SmallVec<[_; 2]>>();
3370
3371 let hitbox = cx.insert_hitbox(bounds, false);
3372 let gutter_hitbox = cx.insert_hitbox(
3373 Bounds {
3374 origin: bounds.origin,
3375 size: size(gutter_dimensions.width, bounds.size.height),
3376 },
3377 false,
3378 );
3379 let text_hitbox = cx.insert_hitbox(
3380 Bounds {
3381 origin: gutter_hitbox.upper_right(),
3382 size: size(text_width, bounds.size.height),
3383 },
3384 false,
3385 );
3386 // Offset the content_bounds from the text_bounds by the gutter margin (which
3387 // is roughly half a character wide) to make hit testing work more like how we want.
3388 let content_origin =
3389 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
3390
3391 let autoscroll_horizontally = self.editor.update(cx, |editor, cx| {
3392 let autoscroll_horizontally =
3393 editor.autoscroll_vertically(bounds.size.height, line_height, cx);
3394 snapshot = editor.snapshot(cx);
3395 autoscroll_horizontally
3396 });
3397
3398 let mut scroll_position = snapshot.scroll_position();
3399 // The scroll position is a fractional point, the whole number of which represents
3400 // the top of the window in terms of display rows.
3401 let start_row = scroll_position.y as u32;
3402 let height_in_lines = bounds.size.height / line_height;
3403 let max_row = snapshot.max_point().row();
3404
3405 // Add 1 to ensure selections bleed off screen
3406 let end_row =
3407 1 + cmp::min((scroll_position.y + height_in_lines).ceil() as u32, max_row);
3408
3409 let buffer_rows = snapshot
3410 .buffer_rows(start_row)
3411 .take((start_row..end_row).len());
3412
3413 let start_anchor = if start_row == 0 {
3414 Anchor::min()
3415 } else {
3416 snapshot.buffer_snapshot.anchor_before(
3417 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
3418 )
3419 };
3420 let end_anchor = if end_row > max_row {
3421 Anchor::max()
3422 } else {
3423 snapshot.buffer_snapshot.anchor_before(
3424 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
3425 )
3426 };
3427
3428 let highlighted_rows = self
3429 .editor
3430 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
3431 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
3432 start_anchor..end_anchor,
3433 &snapshot.display_snapshot,
3434 cx.theme().colors(),
3435 );
3436
3437 let redacted_ranges = self.editor.read(cx).redacted_ranges(
3438 start_anchor..end_anchor,
3439 &snapshot.display_snapshot,
3440 cx,
3441 );
3442
3443 let (selections, active_rows, newest_selection_head) = self.layout_selections(
3444 start_anchor,
3445 end_anchor,
3446 &snapshot,
3447 start_row,
3448 end_row,
3449 cx,
3450 );
3451
3452 let (line_numbers, fold_statuses) = self.layout_line_numbers(
3453 start_row..end_row,
3454 buffer_rows.clone(),
3455 &active_rows,
3456 newest_selection_head,
3457 &snapshot,
3458 cx,
3459 );
3460
3461 let display_hunks = self.layout_git_gutters(start_row..end_row, &snapshot);
3462
3463 let blamed_display_rows = self.layout_blame_entries(
3464 buffer_rows,
3465 em_width,
3466 scroll_position,
3467 line_height,
3468 &gutter_hitbox,
3469 gutter_dimensions.git_blame_entries_width,
3470 cx,
3471 );
3472
3473 let mut max_visible_line_width = Pixels::ZERO;
3474 let line_layouts =
3475 self.layout_lines(start_row..end_row, &line_numbers, &snapshot, cx);
3476 for line_with_invisibles in &line_layouts {
3477 if line_with_invisibles.line.width > max_visible_line_width {
3478 max_visible_line_width = line_with_invisibles.line.width;
3479 }
3480 }
3481
3482 let longest_line_width = layout_line(snapshot.longest_row(), &snapshot, &style, cx)
3483 .unwrap()
3484 .width;
3485 let mut scroll_width =
3486 longest_line_width.max(max_visible_line_width) + overscroll.width;
3487 let mut blocks = self.build_blocks(
3488 start_row..end_row,
3489 &snapshot,
3490 &hitbox,
3491 &text_hitbox,
3492 &mut scroll_width,
3493 &gutter_dimensions,
3494 em_width,
3495 gutter_dimensions.width + gutter_dimensions.margin,
3496 line_height,
3497 &line_layouts,
3498 cx,
3499 );
3500
3501 let scroll_max = point(
3502 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
3503 max_row as f32,
3504 );
3505
3506 self.editor.update(cx, |editor, cx| {
3507 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
3508
3509 let autoscrolled = if autoscroll_horizontally {
3510 editor.autoscroll_horizontally(
3511 start_row,
3512 text_hitbox.size.width,
3513 scroll_width,
3514 em_width,
3515 &line_layouts,
3516 cx,
3517 )
3518 } else {
3519 false
3520 };
3521
3522 if clamped || autoscrolled {
3523 snapshot = editor.snapshot(cx);
3524 scroll_position = snapshot.scroll_position();
3525 }
3526 });
3527
3528 let scroll_pixel_position = point(
3529 scroll_position.x * em_width,
3530 scroll_position.y * line_height,
3531 );
3532
3533 cx.with_element_id(Some("blocks"), |cx| {
3534 self.layout_blocks(
3535 &mut blocks,
3536 &hitbox,
3537 line_height,
3538 scroll_pixel_position,
3539 cx,
3540 );
3541 });
3542
3543 let cursors = self.layout_cursors(
3544 &snapshot,
3545 &selections,
3546 start_row..end_row,
3547 &line_layouts,
3548 &text_hitbox,
3549 content_origin,
3550 scroll_pixel_position,
3551 line_height,
3552 em_width,
3553 cx,
3554 );
3555
3556 let scrollbar_layout = self.layout_scrollbar(
3557 &snapshot,
3558 bounds,
3559 scroll_position,
3560 line_height,
3561 height_in_lines,
3562 cx,
3563 );
3564
3565 let folds = cx.with_element_id(Some("folds"), |cx| {
3566 self.layout_folds(
3567 &snapshot,
3568 content_origin,
3569 start_anchor..end_anchor,
3570 start_row..end_row,
3571 scroll_pixel_position,
3572 line_height,
3573 &line_layouts,
3574 cx,
3575 )
3576 });
3577
3578 let gutter_settings = EditorSettings::get_global(cx).gutter;
3579
3580 let mut context_menu_visible = false;
3581 let mut code_actions_indicator = None;
3582 if let Some(newest_selection_head) = newest_selection_head {
3583 if (start_row..end_row).contains(&newest_selection_head.row()) {
3584 context_menu_visible = self.layout_context_menu(
3585 line_height,
3586 &hitbox,
3587 &text_hitbox,
3588 content_origin,
3589 start_row,
3590 scroll_pixel_position,
3591 &line_layouts,
3592 newest_selection_head,
3593 cx,
3594 );
3595 if gutter_settings.code_actions {
3596 code_actions_indicator = self.layout_code_actions_indicator(
3597 line_height,
3598 newest_selection_head,
3599 scroll_pixel_position,
3600 &gutter_dimensions,
3601 &gutter_hitbox,
3602 cx,
3603 );
3604 }
3605 }
3606 }
3607
3608 if !context_menu_visible && !cx.has_active_drag() {
3609 self.layout_hover_popovers(
3610 &snapshot,
3611 &hitbox,
3612 &text_hitbox,
3613 start_row..end_row,
3614 content_origin,
3615 scroll_pixel_position,
3616 &line_layouts,
3617 line_height,
3618 em_width,
3619 cx,
3620 );
3621 }
3622
3623 let mouse_context_menu = self.layout_mouse_context_menu(cx);
3624
3625 let fold_indicators = if gutter_settings.folds {
3626 cx.with_element_id(Some("gutter_fold_indicators"), |cx| {
3627 self.layout_gutter_fold_indicators(
3628 fold_statuses,
3629 line_height,
3630 &gutter_dimensions,
3631 gutter_settings,
3632 scroll_pixel_position,
3633 &gutter_hitbox,
3634 cx,
3635 )
3636 })
3637 } else {
3638 Vec::new()
3639 };
3640
3641 let invisible_symbol_font_size = font_size / 2.;
3642 let tab_invisible = cx
3643 .text_system()
3644 .shape_line(
3645 "→".into(),
3646 invisible_symbol_font_size,
3647 &[TextRun {
3648 len: "→".len(),
3649 font: self.style.text.font(),
3650 color: cx.theme().colors().editor_invisible,
3651 background_color: None,
3652 underline: None,
3653 strikethrough: None,
3654 }],
3655 )
3656 .unwrap();
3657 let space_invisible = cx
3658 .text_system()
3659 .shape_line(
3660 "•".into(),
3661 invisible_symbol_font_size,
3662 &[TextRun {
3663 len: "•".len(),
3664 font: self.style.text.font(),
3665 color: cx.theme().colors().editor_invisible,
3666 background_color: None,
3667 underline: None,
3668 strikethrough: None,
3669 }],
3670 )
3671 .unwrap();
3672
3673 EditorLayout {
3674 mode: snapshot.mode,
3675 position_map: Arc::new(PositionMap {
3676 size: bounds.size,
3677 scroll_pixel_position,
3678 scroll_max,
3679 line_layouts,
3680 line_height,
3681 em_width,
3682 em_advance,
3683 snapshot,
3684 }),
3685 visible_display_row_range: start_row..end_row,
3686 wrap_guides,
3687 hitbox,
3688 text_hitbox,
3689 gutter_hitbox,
3690 gutter_dimensions,
3691 content_origin,
3692 scrollbar_layout,
3693 max_row,
3694 active_rows,
3695 highlighted_rows,
3696 highlighted_ranges,
3697 redacted_ranges,
3698 line_numbers,
3699 display_hunks,
3700 blamed_display_rows,
3701 folds,
3702 blocks,
3703 cursors,
3704 selections,
3705 mouse_context_menu,
3706 code_actions_indicator,
3707 fold_indicators,
3708 tab_invisible,
3709 space_invisible,
3710 }
3711 })
3712 })
3713 }
3714
3715 fn paint(
3716 &mut self,
3717 bounds: Bounds<gpui::Pixels>,
3718 _: &mut Self::BeforeLayout,
3719 layout: &mut Self::AfterLayout,
3720 cx: &mut ElementContext,
3721 ) {
3722 let focus_handle = self.editor.focus_handle(cx);
3723 let key_context = self.editor.read(cx).key_context(cx);
3724 cx.set_focus_handle(&focus_handle);
3725 cx.set_key_context(key_context);
3726 cx.set_view_id(self.editor.entity_id());
3727 cx.handle_input(
3728 &focus_handle,
3729 ElementInputHandler::new(bounds, self.editor.clone()),
3730 );
3731 self.register_actions(cx);
3732 self.register_key_listeners(cx, layout);
3733
3734 let text_style = TextStyleRefinement {
3735 font_size: Some(self.style.text.font_size),
3736 line_height: Some(self.style.text.line_height),
3737 ..Default::default()
3738 };
3739 cx.with_text_style(Some(text_style), |cx| {
3740 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
3741 self.paint_mouse_listeners(layout, cx);
3742
3743 self.paint_background(layout, cx);
3744 if layout.gutter_hitbox.size.width > Pixels::ZERO {
3745 self.paint_gutter(layout, cx);
3746 }
3747 self.paint_text(layout, cx);
3748
3749 if !layout.blocks.is_empty() {
3750 cx.with_element_id(Some("blocks"), |cx| {
3751 self.paint_blocks(layout, cx);
3752 });
3753 }
3754
3755 self.paint_scrollbar(layout, cx);
3756 self.paint_mouse_context_menu(layout, cx);
3757 });
3758 })
3759 }
3760}
3761
3762impl IntoElement for EditorElement {
3763 type Element = Self;
3764
3765 fn into_element(self) -> Self::Element {
3766 self
3767 }
3768}
3769
3770type BufferRow = u32;
3771
3772pub struct EditorLayout {
3773 position_map: Arc<PositionMap>,
3774 hitbox: Hitbox,
3775 text_hitbox: Hitbox,
3776 gutter_hitbox: Hitbox,
3777 gutter_dimensions: GutterDimensions,
3778 content_origin: gpui::Point<Pixels>,
3779 scrollbar_layout: Option<ScrollbarLayout>,
3780 mode: EditorMode,
3781 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
3782 visible_display_row_range: Range<u32>,
3783 active_rows: BTreeMap<u32, bool>,
3784 highlighted_rows: BTreeMap<u32, Hsla>,
3785 line_numbers: Vec<Option<ShapedLine>>,
3786 display_hunks: Vec<DisplayDiffHunk>,
3787 blamed_display_rows: Option<Vec<AnyElement>>,
3788 folds: Vec<FoldLayout>,
3789 blocks: Vec<BlockLayout>,
3790 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3791 redacted_ranges: Vec<Range<DisplayPoint>>,
3792 cursors: Vec<CursorLayout>,
3793 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
3794 max_row: u32,
3795 code_actions_indicator: Option<AnyElement>,
3796 fold_indicators: Vec<Option<AnyElement>>,
3797 mouse_context_menu: Option<AnyElement>,
3798 tab_invisible: ShapedLine,
3799 space_invisible: ShapedLine,
3800}
3801
3802impl EditorLayout {
3803 fn line_end_overshoot(&self) -> Pixels {
3804 0.15 * self.position_map.line_height
3805 }
3806}
3807
3808struct ScrollbarLayout {
3809 hitbox: Hitbox,
3810 visible_row_range: Range<f32>,
3811 visible: bool,
3812 height: Pixels,
3813 scroll_height: f32,
3814 first_row_y_offset: Pixels,
3815 row_height: Pixels,
3816}
3817
3818impl ScrollbarLayout {
3819 const BORDER_WIDTH: Pixels = px(1.0);
3820 const MIN_MARKER_HEIGHT: Pixels = px(2.0);
3821
3822 fn thumb_bounds(&self) -> Bounds<Pixels> {
3823 let thumb_top = self.y_for_row(self.visible_row_range.start) - self.first_row_y_offset;
3824 let thumb_bottom = self.y_for_row(self.visible_row_range.end) + self.first_row_y_offset;
3825 Bounds::from_corners(
3826 point(self.hitbox.left(), thumb_top),
3827 point(self.hitbox.right(), thumb_bottom),
3828 )
3829 }
3830
3831 fn y_for_row(&self, row: f32) -> Pixels {
3832 self.hitbox.top() + self.first_row_y_offset + row * self.row_height
3833 }
3834
3835 fn ys_for_marker(&self, start_row: u32, end_row: u32) -> (Pixels, Pixels) {
3836 let start_y = self.y_for_row(start_row as f32);
3837 let mut end_y = self.y_for_row((end_row + 1) as f32);
3838 if end_y - start_y < Self::MIN_MARKER_HEIGHT {
3839 end_y = start_y + Self::MIN_MARKER_HEIGHT;
3840 }
3841 (start_y, end_y)
3842 }
3843}
3844
3845struct FoldLayout {
3846 display_range: Range<DisplayPoint>,
3847 hover_element: AnyElement,
3848}
3849
3850struct PositionMap {
3851 size: Size<Pixels>,
3852 line_height: Pixels,
3853 scroll_pixel_position: gpui::Point<Pixels>,
3854 scroll_max: gpui::Point<f32>,
3855 em_width: Pixels,
3856 em_advance: Pixels,
3857 line_layouts: Vec<LineWithInvisibles>,
3858 snapshot: EditorSnapshot,
3859}
3860
3861#[derive(Debug, Copy, Clone)]
3862pub struct PointForPosition {
3863 pub previous_valid: DisplayPoint,
3864 pub next_valid: DisplayPoint,
3865 pub exact_unclipped: DisplayPoint,
3866 pub column_overshoot_after_line_end: u32,
3867}
3868
3869impl PointForPosition {
3870 pub fn as_valid(&self) -> Option<DisplayPoint> {
3871 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
3872 Some(self.previous_valid)
3873 } else {
3874 None
3875 }
3876 }
3877}
3878
3879impl PositionMap {
3880 fn point_for_position(
3881 &self,
3882 text_bounds: Bounds<Pixels>,
3883 position: gpui::Point<Pixels>,
3884 ) -> PointForPosition {
3885 let scroll_position = self.snapshot.scroll_position();
3886 let position = position - text_bounds.origin;
3887 let y = position.y.max(px(0.)).min(self.size.height);
3888 let x = position.x + (scroll_position.x * self.em_width);
3889 let row = ((y / self.line_height) + scroll_position.y) as u32;
3890
3891 let (column, x_overshoot_after_line_end) = if let Some(line) = self
3892 .line_layouts
3893 .get(row as usize - scroll_position.y as usize)
3894 .map(|LineWithInvisibles { line, .. }| line)
3895 {
3896 if let Some(ix) = line.index_for_x(x) {
3897 (ix as u32, px(0.))
3898 } else {
3899 (line.len as u32, px(0.).max(x - line.width))
3900 }
3901 } else {
3902 (0, x)
3903 };
3904
3905 let mut exact_unclipped = DisplayPoint::new(row, column);
3906 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
3907 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
3908
3909 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
3910 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
3911 PointForPosition {
3912 previous_valid,
3913 next_valid,
3914 exact_unclipped,
3915 column_overshoot_after_line_end,
3916 }
3917 }
3918}
3919
3920struct BlockLayout {
3921 row: u32,
3922 element: AnyElement,
3923 available_space: Size<AvailableSpace>,
3924 style: BlockStyle,
3925}
3926
3927fn layout_line(
3928 row: u32,
3929 snapshot: &EditorSnapshot,
3930 style: &EditorStyle,
3931 cx: &WindowContext,
3932) -> Result<ShapedLine> {
3933 let mut line = snapshot.line(row);
3934
3935 if line.len() > MAX_LINE_LEN {
3936 let mut len = MAX_LINE_LEN;
3937 while !line.is_char_boundary(len) {
3938 len -= 1;
3939 }
3940
3941 line.truncate(len);
3942 }
3943
3944 cx.text_system().shape_line(
3945 line.into(),
3946 style.text.font_size.to_pixels(cx.rem_size()),
3947 &[TextRun {
3948 len: snapshot.line_len(row) as usize,
3949 font: style.text.font(),
3950 color: Hsla::default(),
3951 background_color: None,
3952 underline: None,
3953 strikethrough: None,
3954 }],
3955 )
3956}
3957
3958pub struct CursorLayout {
3959 origin: gpui::Point<Pixels>,
3960 block_width: Pixels,
3961 line_height: Pixels,
3962 color: Hsla,
3963 shape: CursorShape,
3964 block_text: Option<ShapedLine>,
3965 cursor_name: Option<AnyElement>,
3966}
3967
3968#[derive(Debug)]
3969pub struct CursorName {
3970 string: SharedString,
3971 color: Hsla,
3972 is_top_row: bool,
3973}
3974
3975impl CursorLayout {
3976 pub fn new(
3977 origin: gpui::Point<Pixels>,
3978 block_width: Pixels,
3979 line_height: Pixels,
3980 color: Hsla,
3981 shape: CursorShape,
3982 block_text: Option<ShapedLine>,
3983 ) -> CursorLayout {
3984 CursorLayout {
3985 origin,
3986 block_width,
3987 line_height,
3988 color,
3989 shape,
3990 block_text,
3991 cursor_name: None,
3992 }
3993 }
3994
3995 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
3996 Bounds {
3997 origin: self.origin + origin,
3998 size: size(self.block_width, self.line_height),
3999 }
4000 }
4001
4002 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
4003 match self.shape {
4004 CursorShape::Bar => Bounds {
4005 origin: self.origin + origin,
4006 size: size(px(2.0), self.line_height),
4007 },
4008 CursorShape::Block | CursorShape::Hollow => Bounds {
4009 origin: self.origin + origin,
4010 size: size(self.block_width, self.line_height),
4011 },
4012 CursorShape::Underscore => Bounds {
4013 origin: self.origin
4014 + origin
4015 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
4016 size: size(self.block_width, px(2.0)),
4017 },
4018 }
4019 }
4020
4021 pub fn layout(
4022 &mut self,
4023 origin: gpui::Point<Pixels>,
4024 cursor_name: Option<CursorName>,
4025 cx: &mut ElementContext,
4026 ) {
4027 if let Some(cursor_name) = cursor_name {
4028 let bounds = self.bounds(origin);
4029 let text_size = self.line_height / 1.5;
4030
4031 let name_origin = if cursor_name.is_top_row {
4032 point(bounds.right() - px(1.), bounds.top())
4033 } else {
4034 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
4035 };
4036 let mut name_element = div()
4037 .bg(self.color)
4038 .text_size(text_size)
4039 .px_0p5()
4040 .line_height(text_size + px(2.))
4041 .text_color(cursor_name.color)
4042 .child(cursor_name.string.clone())
4043 .into_any_element();
4044
4045 name_element.layout(
4046 name_origin,
4047 size(AvailableSpace::MinContent, AvailableSpace::MinContent),
4048 cx,
4049 );
4050
4051 self.cursor_name = Some(name_element);
4052 }
4053 }
4054
4055 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut ElementContext) {
4056 let bounds = self.bounds(origin);
4057
4058 //Draw background or border quad
4059 let cursor = if matches!(self.shape, CursorShape::Hollow) {
4060 outline(bounds, self.color)
4061 } else {
4062 fill(bounds, self.color)
4063 };
4064
4065 if let Some(name) = &mut self.cursor_name {
4066 name.paint(cx);
4067 }
4068
4069 cx.paint_quad(cursor);
4070
4071 if let Some(block_text) = &self.block_text {
4072 block_text
4073 .paint(self.origin + origin, self.line_height, cx)
4074 .log_err();
4075 }
4076 }
4077
4078 pub fn shape(&self) -> CursorShape {
4079 self.shape
4080 }
4081}
4082
4083#[derive(Debug)]
4084pub struct HighlightedRange {
4085 pub start_y: Pixels,
4086 pub line_height: Pixels,
4087 pub lines: Vec<HighlightedRangeLine>,
4088 pub color: Hsla,
4089 pub corner_radius: Pixels,
4090}
4091
4092#[derive(Debug)]
4093pub struct HighlightedRangeLine {
4094 pub start_x: Pixels,
4095 pub end_x: Pixels,
4096}
4097
4098impl HighlightedRange {
4099 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut ElementContext) {
4100 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
4101 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
4102 self.paint_lines(
4103 self.start_y + self.line_height,
4104 &self.lines[1..],
4105 bounds,
4106 cx,
4107 );
4108 } else {
4109 self.paint_lines(self.start_y, &self.lines, bounds, cx);
4110 }
4111 }
4112
4113 fn paint_lines(
4114 &self,
4115 start_y: Pixels,
4116 lines: &[HighlightedRangeLine],
4117 _bounds: Bounds<Pixels>,
4118 cx: &mut ElementContext,
4119 ) {
4120 if lines.is_empty() {
4121 return;
4122 }
4123
4124 let first_line = lines.first().unwrap();
4125 let last_line = lines.last().unwrap();
4126
4127 let first_top_left = point(first_line.start_x, start_y);
4128 let first_top_right = point(first_line.end_x, start_y);
4129
4130 let curve_height = point(Pixels::ZERO, self.corner_radius);
4131 let curve_width = |start_x: Pixels, end_x: Pixels| {
4132 let max = (end_x - start_x) / 2.;
4133 let width = if max < self.corner_radius {
4134 max
4135 } else {
4136 self.corner_radius
4137 };
4138
4139 point(width, Pixels::ZERO)
4140 };
4141
4142 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
4143 let mut path = gpui::Path::new(first_top_right - top_curve_width);
4144 path.curve_to(first_top_right + curve_height, first_top_right);
4145
4146 let mut iter = lines.iter().enumerate().peekable();
4147 while let Some((ix, line)) = iter.next() {
4148 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
4149
4150 if let Some((_, next_line)) = iter.peek() {
4151 let next_top_right = point(next_line.end_x, bottom_right.y);
4152
4153 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
4154 Ordering::Equal => {
4155 path.line_to(bottom_right);
4156 }
4157 Ordering::Less => {
4158 let curve_width = curve_width(next_top_right.x, bottom_right.x);
4159 path.line_to(bottom_right - curve_height);
4160 if self.corner_radius > Pixels::ZERO {
4161 path.curve_to(bottom_right - curve_width, bottom_right);
4162 }
4163 path.line_to(next_top_right + curve_width);
4164 if self.corner_radius > Pixels::ZERO {
4165 path.curve_to(next_top_right + curve_height, next_top_right);
4166 }
4167 }
4168 Ordering::Greater => {
4169 let curve_width = curve_width(bottom_right.x, next_top_right.x);
4170 path.line_to(bottom_right - curve_height);
4171 if self.corner_radius > Pixels::ZERO {
4172 path.curve_to(bottom_right + curve_width, bottom_right);
4173 }
4174 path.line_to(next_top_right - curve_width);
4175 if self.corner_radius > Pixels::ZERO {
4176 path.curve_to(next_top_right + curve_height, next_top_right);
4177 }
4178 }
4179 }
4180 } else {
4181 let curve_width = curve_width(line.start_x, line.end_x);
4182 path.line_to(bottom_right - curve_height);
4183 if self.corner_radius > Pixels::ZERO {
4184 path.curve_to(bottom_right - curve_width, bottom_right);
4185 }
4186
4187 let bottom_left = point(line.start_x, bottom_right.y);
4188 path.line_to(bottom_left + curve_width);
4189 if self.corner_radius > Pixels::ZERO {
4190 path.curve_to(bottom_left - curve_height, bottom_left);
4191 }
4192 }
4193 }
4194
4195 if first_line.start_x > last_line.start_x {
4196 let curve_width = curve_width(last_line.start_x, first_line.start_x);
4197 let second_top_left = point(last_line.start_x, start_y + self.line_height);
4198 path.line_to(second_top_left + curve_height);
4199 if self.corner_radius > Pixels::ZERO {
4200 path.curve_to(second_top_left + curve_width, second_top_left);
4201 }
4202 let first_bottom_left = point(first_line.start_x, second_top_left.y);
4203 path.line_to(first_bottom_left - curve_width);
4204 if self.corner_radius > Pixels::ZERO {
4205 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
4206 }
4207 }
4208
4209 path.line_to(first_top_left + curve_height);
4210 if self.corner_radius > Pixels::ZERO {
4211 path.curve_to(first_top_left + top_curve_width, first_top_left);
4212 }
4213 path.line_to(first_top_right - top_curve_width);
4214
4215 cx.paint_path(path, self.color);
4216 }
4217}
4218
4219pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4220 (delta.pow(1.5) / 100.0).into()
4221}
4222
4223fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
4224 (delta.pow(1.2) / 300.0).into()
4225}
4226
4227#[cfg(test)]
4228mod tests {
4229 use super::*;
4230 use crate::{
4231 display_map::{BlockDisposition, BlockProperties},
4232 editor_tests::{init_test, update_test_language_settings},
4233 Editor, MultiBuffer,
4234 };
4235 use gpui::TestAppContext;
4236 use language::language_settings;
4237 use log::info;
4238 use std::{num::NonZeroU32, sync::Arc};
4239 use util::test::sample_text;
4240
4241 #[gpui::test]
4242 fn test_shape_line_numbers(cx: &mut TestAppContext) {
4243 init_test(cx, |_| {});
4244 let window = cx.add_window(|cx| {
4245 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4246 Editor::new(EditorMode::Full, buffer, None, cx)
4247 });
4248
4249 let editor = window.root(cx).unwrap();
4250 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4251 let element = EditorElement::new(&editor, style);
4252 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
4253
4254 let layouts = cx
4255 .update_window(*window, |_, cx| {
4256 cx.with_element_context(|cx| {
4257 element
4258 .layout_line_numbers(
4259 0..6,
4260 (0..6).map(Some),
4261 &Default::default(),
4262 Some(DisplayPoint::new(0, 0)),
4263 &snapshot,
4264 cx,
4265 )
4266 .0
4267 })
4268 })
4269 .unwrap();
4270 assert_eq!(layouts.len(), 6);
4271
4272 let relative_rows =
4273 element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(0..6), Some(3));
4274 assert_eq!(relative_rows[&0], 3);
4275 assert_eq!(relative_rows[&1], 2);
4276 assert_eq!(relative_rows[&2], 1);
4277 // current line has no relative number
4278 assert_eq!(relative_rows[&4], 1);
4279 assert_eq!(relative_rows[&5], 2);
4280
4281 // works if cursor is before screen
4282 let relative_rows =
4283 element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(3..6), Some(1));
4284 assert_eq!(relative_rows.len(), 3);
4285 assert_eq!(relative_rows[&3], 2);
4286 assert_eq!(relative_rows[&4], 3);
4287 assert_eq!(relative_rows[&5], 4);
4288
4289 // works if cursor is after screen
4290 let relative_rows =
4291 element.calculate_relative_line_numbers((0..6).map(Some).collect(), &(0..3), Some(6));
4292 assert_eq!(relative_rows.len(), 3);
4293 assert_eq!(relative_rows[&0], 5);
4294 assert_eq!(relative_rows[&1], 4);
4295 assert_eq!(relative_rows[&2], 3);
4296 }
4297
4298 #[gpui::test]
4299 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
4300 init_test(cx, |_| {});
4301
4302 let window = cx.add_window(|cx| {
4303 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
4304 Editor::new(EditorMode::Full, buffer, None, cx)
4305 });
4306 let editor = window.root(cx).unwrap();
4307 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4308 let mut element = EditorElement::new(&editor, style);
4309
4310 window
4311 .update(cx, |editor, cx| {
4312 editor.cursor_shape = CursorShape::Block;
4313 editor.change_selections(None, cx, |s| {
4314 s.select_ranges([
4315 Point::new(0, 0)..Point::new(1, 0),
4316 Point::new(3, 2)..Point::new(3, 3),
4317 Point::new(5, 6)..Point::new(6, 0),
4318 ]);
4319 });
4320 })
4321 .unwrap();
4322 let state = cx
4323 .update_window(window.into(), |_view, cx| {
4324 cx.with_element_context(|cx| {
4325 element.after_layout(
4326 Bounds {
4327 origin: point(px(500.), px(500.)),
4328 size: size(px(500.), px(500.)),
4329 },
4330 &mut (),
4331 cx,
4332 )
4333 })
4334 })
4335 .unwrap();
4336
4337 assert_eq!(state.selections.len(), 1);
4338 let local_selections = &state.selections[0].1;
4339 assert_eq!(local_selections.len(), 3);
4340 // moves cursor back one line
4341 assert_eq!(local_selections[0].head, DisplayPoint::new(0, 6));
4342 assert_eq!(
4343 local_selections[0].range,
4344 DisplayPoint::new(0, 0)..DisplayPoint::new(1, 0)
4345 );
4346
4347 // moves cursor back one column
4348 assert_eq!(
4349 local_selections[1].range,
4350 DisplayPoint::new(3, 2)..DisplayPoint::new(3, 3)
4351 );
4352 assert_eq!(local_selections[1].head, DisplayPoint::new(3, 2));
4353
4354 // leaves cursor on the max point
4355 assert_eq!(
4356 local_selections[2].range,
4357 DisplayPoint::new(5, 6)..DisplayPoint::new(6, 0)
4358 );
4359 assert_eq!(local_selections[2].head, DisplayPoint::new(6, 0));
4360
4361 // active lines does not include 1 (even though the range of the selection does)
4362 assert_eq!(
4363 state.active_rows.keys().cloned().collect::<Vec<u32>>(),
4364 vec![0, 3, 5, 6]
4365 );
4366
4367 // multi-buffer support
4368 // in DisplayPoint coordinates, this is what we're dealing with:
4369 // 0: [[file
4370 // 1: header]]
4371 // 2: aaaaaa
4372 // 3: bbbbbb
4373 // 4: cccccc
4374 // 5:
4375 // 6: ...
4376 // 7: ffffff
4377 // 8: gggggg
4378 // 9: hhhhhh
4379 // 10:
4380 // 11: [[file
4381 // 12: header]]
4382 // 13: bbbbbb
4383 // 14: cccccc
4384 // 15: dddddd
4385 let window = cx.add_window(|cx| {
4386 let buffer = MultiBuffer::build_multi(
4387 [
4388 (
4389 &(sample_text(8, 6, 'a') + "\n"),
4390 vec![
4391 Point::new(0, 0)..Point::new(3, 0),
4392 Point::new(4, 0)..Point::new(7, 0),
4393 ],
4394 ),
4395 (
4396 &(sample_text(8, 6, 'a') + "\n"),
4397 vec![Point::new(1, 0)..Point::new(3, 0)],
4398 ),
4399 ],
4400 cx,
4401 );
4402 Editor::new(EditorMode::Full, buffer, None, cx)
4403 });
4404 let editor = window.root(cx).unwrap();
4405 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4406 let mut element = EditorElement::new(&editor, style);
4407 let _state = window.update(cx, |editor, cx| {
4408 editor.cursor_shape = CursorShape::Block;
4409 editor.change_selections(None, cx, |s| {
4410 s.select_display_ranges([
4411 DisplayPoint::new(4, 0)..DisplayPoint::new(7, 0),
4412 DisplayPoint::new(10, 0)..DisplayPoint::new(13, 0),
4413 ]);
4414 });
4415 });
4416
4417 let state = cx
4418 .update_window(window.into(), |_view, cx| {
4419 cx.with_element_context(|cx| {
4420 element.after_layout(
4421 Bounds {
4422 origin: point(px(500.), px(500.)),
4423 size: size(px(500.), px(500.)),
4424 },
4425 &mut (),
4426 cx,
4427 )
4428 })
4429 })
4430 .unwrap();
4431 assert_eq!(state.selections.len(), 1);
4432 let local_selections = &state.selections[0].1;
4433 assert_eq!(local_selections.len(), 2);
4434
4435 // moves cursor on excerpt boundary back a line
4436 // and doesn't allow selection to bleed through
4437 assert_eq!(
4438 local_selections[0].range,
4439 DisplayPoint::new(4, 0)..DisplayPoint::new(6, 0)
4440 );
4441 assert_eq!(local_selections[0].head, DisplayPoint::new(5, 0));
4442 // moves cursor on buffer boundary back two lines
4443 // and doesn't allow selection to bleed through
4444 assert_eq!(
4445 local_selections[1].range,
4446 DisplayPoint::new(10, 0)..DisplayPoint::new(11, 0)
4447 );
4448 assert_eq!(local_selections[1].head, DisplayPoint::new(10, 0));
4449 }
4450
4451 #[gpui::test]
4452 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
4453 init_test(cx, |_| {});
4454
4455 let window = cx.add_window(|cx| {
4456 let buffer = MultiBuffer::build_simple("", cx);
4457 Editor::new(EditorMode::Full, buffer, None, cx)
4458 });
4459 let editor = window.root(cx).unwrap();
4460 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4461 window
4462 .update(cx, |editor, cx| {
4463 editor.set_placeholder_text("hello", cx);
4464 editor.insert_blocks(
4465 [BlockProperties {
4466 style: BlockStyle::Fixed,
4467 disposition: BlockDisposition::Above,
4468 height: 3,
4469 position: Anchor::min(),
4470 render: Arc::new(|_| div().into_any()),
4471 }],
4472 None,
4473 cx,
4474 );
4475
4476 // Blur the editor so that it displays placeholder text.
4477 cx.blur();
4478 })
4479 .unwrap();
4480
4481 let mut element = EditorElement::new(&editor, style);
4482 let state = cx
4483 .update_window(window.into(), |_view, cx| {
4484 cx.with_element_context(|cx| {
4485 element.after_layout(
4486 Bounds {
4487 origin: point(px(500.), px(500.)),
4488 size: size(px(500.), px(500.)),
4489 },
4490 &mut (),
4491 cx,
4492 )
4493 })
4494 })
4495 .unwrap();
4496
4497 assert_eq!(state.position_map.line_layouts.len(), 4);
4498 assert_eq!(
4499 state
4500 .line_numbers
4501 .iter()
4502 .map(Option::is_some)
4503 .collect::<Vec<_>>(),
4504 &[false, false, false, true]
4505 );
4506 }
4507
4508 #[gpui::test]
4509 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
4510 const TAB_SIZE: u32 = 4;
4511
4512 let input_text = "\t \t|\t| a b";
4513 let expected_invisibles = vec![
4514 Invisible::Tab {
4515 line_start_offset: 0,
4516 },
4517 Invisible::Whitespace {
4518 line_offset: TAB_SIZE as usize,
4519 },
4520 Invisible::Tab {
4521 line_start_offset: TAB_SIZE as usize + 1,
4522 },
4523 Invisible::Tab {
4524 line_start_offset: TAB_SIZE as usize * 2 + 1,
4525 },
4526 Invisible::Whitespace {
4527 line_offset: TAB_SIZE as usize * 3 + 1,
4528 },
4529 Invisible::Whitespace {
4530 line_offset: TAB_SIZE as usize * 3 + 3,
4531 },
4532 ];
4533 assert_eq!(
4534 expected_invisibles.len(),
4535 input_text
4536 .chars()
4537 .filter(|initial_char| initial_char.is_whitespace())
4538 .count(),
4539 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4540 );
4541
4542 init_test(cx, |s| {
4543 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4544 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
4545 });
4546
4547 let actual_invisibles =
4548 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
4549
4550 assert_eq!(expected_invisibles, actual_invisibles);
4551 }
4552
4553 #[gpui::test]
4554 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
4555 init_test(cx, |s| {
4556 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4557 s.defaults.tab_size = NonZeroU32::new(4);
4558 });
4559
4560 for editor_mode_without_invisibles in [
4561 EditorMode::SingleLine,
4562 EditorMode::AutoHeight { max_lines: 100 },
4563 ] {
4564 let invisibles = collect_invisibles_from_new_editor(
4565 cx,
4566 editor_mode_without_invisibles,
4567 "\t\t\t| | a b",
4568 px(500.0),
4569 );
4570 assert!(invisibles.is_empty(),
4571 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
4572 }
4573 }
4574
4575 #[gpui::test]
4576 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
4577 let tab_size = 4;
4578 let input_text = "a\tbcd ".repeat(9);
4579 let repeated_invisibles = [
4580 Invisible::Tab {
4581 line_start_offset: 1,
4582 },
4583 Invisible::Whitespace {
4584 line_offset: tab_size as usize + 3,
4585 },
4586 Invisible::Whitespace {
4587 line_offset: tab_size as usize + 4,
4588 },
4589 Invisible::Whitespace {
4590 line_offset: tab_size as usize + 5,
4591 },
4592 ];
4593 let expected_invisibles = std::iter::once(repeated_invisibles)
4594 .cycle()
4595 .take(9)
4596 .flatten()
4597 .collect::<Vec<_>>();
4598 assert_eq!(
4599 expected_invisibles.len(),
4600 input_text
4601 .chars()
4602 .filter(|initial_char| initial_char.is_whitespace())
4603 .count(),
4604 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
4605 );
4606 info!("Expected invisibles: {expected_invisibles:?}");
4607
4608 init_test(cx, |_| {});
4609
4610 // Put the same string with repeating whitespace pattern into editors of various size,
4611 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
4612 let resize_step = 10.0;
4613 let mut editor_width = 200.0;
4614 while editor_width <= 1000.0 {
4615 update_test_language_settings(cx, |s| {
4616 s.defaults.tab_size = NonZeroU32::new(tab_size);
4617 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
4618 s.defaults.preferred_line_length = Some(editor_width as u32);
4619 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
4620 });
4621
4622 let actual_invisibles = collect_invisibles_from_new_editor(
4623 cx,
4624 EditorMode::Full,
4625 &input_text,
4626 px(editor_width),
4627 );
4628
4629 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
4630 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
4631 let mut i = 0;
4632 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
4633 i = actual_index;
4634 match expected_invisibles.get(i) {
4635 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
4636 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
4637 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
4638 _ => {
4639 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
4640 }
4641 },
4642 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
4643 }
4644 }
4645 let missing_expected_invisibles = &expected_invisibles[i + 1..];
4646 assert!(
4647 missing_expected_invisibles.is_empty(),
4648 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
4649 );
4650
4651 editor_width += resize_step;
4652 }
4653 }
4654
4655 fn collect_invisibles_from_new_editor(
4656 cx: &mut TestAppContext,
4657 editor_mode: EditorMode,
4658 input_text: &str,
4659 editor_width: Pixels,
4660 ) -> Vec<Invisible> {
4661 info!(
4662 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
4663 editor_width.0
4664 );
4665 let window = cx.add_window(|cx| {
4666 let buffer = MultiBuffer::build_simple(&input_text, cx);
4667 Editor::new(editor_mode, buffer, None, cx)
4668 });
4669 let editor = window.root(cx).unwrap();
4670 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
4671 let mut element = EditorElement::new(&editor, style);
4672 window
4673 .update(cx, |editor, cx| {
4674 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
4675 editor.set_wrap_width(Some(editor_width), cx);
4676 })
4677 .unwrap();
4678 let layout_state = cx
4679 .update_window(window.into(), |_, cx| {
4680 cx.with_element_context(|cx| {
4681 element.after_layout(
4682 Bounds {
4683 origin: point(px(500.), px(500.)),
4684 size: size(px(500.), px(500.)),
4685 },
4686 &mut (),
4687 cx,
4688 )
4689 })
4690 })
4691 .unwrap();
4692
4693 layout_state
4694 .position_map
4695 .line_layouts
4696 .iter()
4697 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
4698 .cloned()
4699 .collect()
4700 }
4701}
4702
4703pub fn register_action<T: Action>(
4704 view: &View<Editor>,
4705 cx: &mut WindowContext,
4706 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
4707) {
4708 let view = view.clone();
4709 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
4710 let action = action.downcast_ref().unwrap();
4711 if phase == DispatchPhase::Bubble {
4712 view.update(cx, |editor, cx| {
4713 listener(editor, action, cx);
4714 })
4715 }
4716 })
4717}
4718
4719fn compute_auto_height_layout(
4720 editor: &mut Editor,
4721 max_lines: usize,
4722 max_line_number_width: Pixels,
4723 known_dimensions: Size<Option<Pixels>>,
4724 cx: &mut ViewContext<Editor>,
4725) -> Option<Size<Pixels>> {
4726 let width = known_dimensions.width?;
4727 if let Some(height) = known_dimensions.height {
4728 return Some(size(width, height));
4729 }
4730
4731 let style = editor.style.as_ref().unwrap();
4732 let font_id = cx.text_system().resolve_font(&style.text.font());
4733 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4734 let line_height = style.text.line_height_in_pixels(cx.rem_size());
4735 let em_width = cx
4736 .text_system()
4737 .typographic_bounds(font_id, font_size, 'm')
4738 .unwrap()
4739 .size
4740 .width;
4741
4742 let mut snapshot = editor.snapshot(cx);
4743 let gutter_dimensions =
4744 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
4745
4746 editor.gutter_width = gutter_dimensions.width;
4747 let text_width = width - gutter_dimensions.width;
4748 let overscroll = size(em_width, px(0.));
4749
4750 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
4751 if editor.set_wrap_width(Some(editor_width), cx) {
4752 snapshot = editor.snapshot(cx);
4753 }
4754
4755 let scroll_height = Pixels::from(snapshot.max_point().row() + 1) * line_height;
4756 let height = scroll_height
4757 .max(line_height)
4758 .min(line_height * max_lines as f32);
4759
4760 Some(size(width, height))
4761}