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