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