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