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