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