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