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