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::{self, MenuPosition, MouseContextMenu},
21 scroll::scroll_amount::ScrollAmount,
22 BlockId, CodeActionsMenu, CursorShape, CustomBlockId, DisplayPoint, DisplayRow,
23 DocumentHighlightRead, DocumentHighlightWrite, Editor, EditorMode, EditorSettings,
24 EditorSnapshot, EditorStyle, ExpandExcerpts, FocusedBlock, GutterDimensions, HalfPageDown,
25 HalfPageUp, HoveredCursor, HoveredHunk, LineDown, LineUp, OpenExcerpts, PageDown, PageUp,
26 Point, RangeToAnchorExt, RowExt, RowRangeExt, SelectPhase, Selection, SoftWrap, ToPoint,
27 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_width: 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 resized_blocks: &mut HashMap<CustomBlockId, u32>,
1945 cx: &mut WindowContext,
1946 ) -> (AnyElement, Size<Pixels>) {
1947 let mut element = match block {
1948 Block::Custom(block) => {
1949 let align_to = block
1950 .position()
1951 .to_point(&snapshot.buffer_snapshot)
1952 .to_display_point(snapshot);
1953 let anchor_x = text_x
1954 + if rows.contains(&align_to.row()) {
1955 line_layouts[align_to.row().minus(rows.start) as usize]
1956 .x_for_index(align_to.column() as usize)
1957 } else {
1958 layout_line(align_to.row(), snapshot, &self.style, cx)
1959 .x_for_index(align_to.column() as usize)
1960 };
1961
1962 div()
1963 .size_full()
1964 .child(block.render(&mut BlockContext {
1965 context: cx,
1966 anchor_x,
1967 gutter_dimensions,
1968 line_height,
1969 em_width,
1970 block_id,
1971 max_width: text_hitbox.size.width.max(*scroll_width),
1972 editor_style: &self.style,
1973 }))
1974 .cursor(CursorStyle::Arrow)
1975 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1976 .into_any_element()
1977 }
1978
1979 Block::ExcerptHeader {
1980 buffer,
1981 range,
1982 starts_new_buffer,
1983 height,
1984 id,
1985 show_excerpt_controls,
1986 ..
1987 } => {
1988 let include_root = self
1989 .editor
1990 .read(cx)
1991 .project
1992 .as_ref()
1993 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
1994 .unwrap_or_default();
1995
1996 #[derive(Clone)]
1997 struct JumpData {
1998 position: Point,
1999 anchor: text::Anchor,
2000 path: ProjectPath,
2001 line_offset_from_top: u32,
2002 }
2003
2004 let jump_data = project::File::from_dyn(buffer.file()).map(|file| {
2005 let jump_path = ProjectPath {
2006 worktree_id: file.worktree_id(cx),
2007 path: file.path.clone(),
2008 };
2009 let jump_anchor = range
2010 .primary
2011 .as_ref()
2012 .map_or(range.context.start, |primary| primary.start);
2013
2014 let excerpt_start = range.context.start;
2015 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
2016 let offset_from_excerpt_start = if jump_anchor == excerpt_start {
2017 0
2018 } else {
2019 let excerpt_start_row =
2020 language::ToPoint::to_point(&jump_anchor, buffer).row;
2021 jump_position.row - excerpt_start_row
2022 };
2023
2024 let line_offset_from_top =
2025 block_row_start.0 + *height + offset_from_excerpt_start
2026 - snapshot
2027 .scroll_anchor
2028 .scroll_position(&snapshot.display_snapshot)
2029 .y as u32;
2030
2031 JumpData {
2032 position: jump_position,
2033 anchor: jump_anchor,
2034 path: jump_path,
2035 line_offset_from_top,
2036 }
2037 });
2038
2039 let icon_offset = gutter_dimensions.width
2040 - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2041
2042 let element = if *starts_new_buffer {
2043 let path = buffer.resolve_file_path(cx, include_root);
2044 let mut filename = None;
2045 let mut parent_path = None;
2046 // Can't use .and_then() because `.file_name()` and `.parent()` return references :(
2047 if let Some(path) = path {
2048 filename = path.file_name().map(|f| f.to_string_lossy().to_string());
2049 parent_path = path
2050 .parent()
2051 .map(|p| SharedString::from(p.to_string_lossy().to_string() + "/"));
2052 }
2053
2054 let header_padding = px(6.0);
2055
2056 v_flex()
2057 .id(("path excerpt header", EntityId::from(block_id)))
2058 .w_full()
2059 .px(header_padding)
2060 .child(
2061 h_flex()
2062 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
2063 .id("path header block")
2064 .h(2. * cx.line_height())
2065 .pl(gpui::px(12.))
2066 .pr(gpui::px(8.))
2067 .rounded_md()
2068 .shadow_md()
2069 .border_1()
2070 .border_color(cx.theme().colors().border)
2071 .bg(cx.theme().colors().editor_subheader_background)
2072 .justify_between()
2073 .hover(|style| style.bg(cx.theme().colors().element_hover))
2074 .child(
2075 h_flex().gap_3().child(
2076 h_flex()
2077 .gap_2()
2078 .child(
2079 filename
2080 .map(SharedString::from)
2081 .unwrap_or_else(|| "untitled".into()),
2082 )
2083 .when_some(parent_path, |then, path| {
2084 then.child(
2085 div()
2086 .child(path)
2087 .text_color(cx.theme().colors().text_muted),
2088 )
2089 }),
2090 ),
2091 )
2092 .when_some(jump_data.clone(), |el, jump_data| {
2093 el.child(Icon::new(IconName::ArrowUpRight))
2094 .cursor_pointer()
2095 .tooltip(|cx| {
2096 Tooltip::for_action("Jump to File", &OpenExcerpts, cx)
2097 })
2098 .on_mouse_down(MouseButton::Left, |_, cx| {
2099 cx.stop_propagation()
2100 })
2101 .on_click(cx.listener_for(&self.editor, {
2102 move |editor, _, cx| {
2103 editor.jump(
2104 jump_data.path.clone(),
2105 jump_data.position,
2106 jump_data.anchor,
2107 jump_data.line_offset_from_top,
2108 cx,
2109 );
2110 }
2111 }))
2112 }),
2113 )
2114 .children(show_excerpt_controls.then(|| {
2115 h_flex()
2116 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.333)))
2117 .h(1. * cx.line_height())
2118 .pt_1()
2119 .justify_end()
2120 .flex_none()
2121 .w(icon_offset - header_padding)
2122 .child(
2123 ButtonLike::new("expand-icon")
2124 .style(ButtonStyle::Transparent)
2125 .child(
2126 svg()
2127 .path(IconName::ArrowUpFromLine.path())
2128 .size(IconSize::XSmall.rems())
2129 .text_color(cx.theme().colors().editor_line_number)
2130 .group("")
2131 .hover(|style| {
2132 style.text_color(
2133 cx.theme()
2134 .colors()
2135 .editor_active_line_number,
2136 )
2137 }),
2138 )
2139 .on_click(cx.listener_for(&self.editor, {
2140 let id = *id;
2141 move |editor, _, cx| {
2142 editor.expand_excerpt(
2143 id,
2144 multi_buffer::ExpandExcerptDirection::Up,
2145 cx,
2146 );
2147 }
2148 }))
2149 .tooltip({
2150 move |cx| {
2151 Tooltip::for_action(
2152 "Expand Excerpt",
2153 &ExpandExcerpts { lines: 0 },
2154 cx,
2155 )
2156 }
2157 }),
2158 )
2159 }))
2160 } else {
2161 v_flex()
2162 .id(("excerpt header", EntityId::from(block_id)))
2163 .w_full()
2164 .h(snapshot.excerpt_header_height() as f32 * cx.line_height())
2165 .child(
2166 div()
2167 .flex()
2168 .v_flex()
2169 .justify_start()
2170 .id("jump to collapsed context")
2171 .w(relative(1.0))
2172 .h_full()
2173 .child(
2174 div()
2175 .h_px()
2176 .w_full()
2177 .bg(cx.theme().colors().border_variant)
2178 .group_hover("excerpt-jump-action", |style| {
2179 style.bg(cx.theme().colors().border)
2180 }),
2181 ),
2182 )
2183 .child(
2184 h_flex()
2185 .justify_end()
2186 .flex_none()
2187 .w(icon_offset)
2188 .h_full()
2189 .child(
2190 show_excerpt_controls
2191 .then(|| {
2192 ButtonLike::new("expand-icon")
2193 .style(ButtonStyle::Transparent)
2194 .child(
2195 svg()
2196 .path(IconName::ArrowUpFromLine.path())
2197 .size(IconSize::XSmall.rems())
2198 .text_color(
2199 cx.theme().colors().editor_line_number,
2200 )
2201 .group("")
2202 .hover(|style| {
2203 style.text_color(
2204 cx.theme()
2205 .colors()
2206 .editor_active_line_number,
2207 )
2208 }),
2209 )
2210 .on_click(cx.listener_for(&self.editor, {
2211 let id = *id;
2212 move |editor, _, cx| {
2213 editor.expand_excerpt(
2214 id,
2215 multi_buffer::ExpandExcerptDirection::Up,
2216 cx,
2217 );
2218 }
2219 }))
2220 .tooltip({
2221 move |cx| {
2222 Tooltip::for_action(
2223 "Expand Excerpt",
2224 &ExpandExcerpts { lines: 0 },
2225 cx,
2226 )
2227 }
2228 })
2229 })
2230 .unwrap_or_else(|| {
2231 ButtonLike::new("jump-icon")
2232 .style(ButtonStyle::Transparent)
2233 .child(
2234 svg()
2235 .path(IconName::ArrowUpRight.path())
2236 .size(IconSize::XSmall.rems())
2237 .text_color(
2238 cx.theme().colors().border_variant,
2239 )
2240 .group("excerpt-jump-action")
2241 .group_hover(
2242 "excerpt-jump-action",
2243 |style| {
2244 style.text_color(
2245 cx.theme().colors().border,
2246 )
2247 },
2248 ),
2249 )
2250 .when_some(jump_data.clone(), |this, jump_data| {
2251 this.on_click(cx.listener_for(&self.editor, {
2252 let path = jump_data.path.clone();
2253 move |editor, _, cx| {
2254 cx.stop_propagation();
2255
2256 editor.jump(
2257 path.clone(),
2258 jump_data.position,
2259 jump_data.anchor,
2260 jump_data.line_offset_from_top,
2261 cx,
2262 );
2263 }
2264 }))
2265 .tooltip(move |cx| {
2266 Tooltip::for_action(
2267 format!(
2268 "Jump to {}:L{}",
2269 jump_data.path.path.display(),
2270 jump_data.position.row + 1
2271 ),
2272 &OpenExcerpts,
2273 cx,
2274 )
2275 })
2276 })
2277 }),
2278 ),
2279 )
2280 .group("excerpt-jump-action")
2281 .cursor_pointer()
2282 .when_some(jump_data.clone(), |this, jump_data| {
2283 this.on_click(cx.listener_for(&self.editor, {
2284 let path = jump_data.path.clone();
2285 move |editor, _, cx| {
2286 cx.stop_propagation();
2287
2288 editor.jump(
2289 path.clone(),
2290 jump_data.position,
2291 jump_data.anchor,
2292 jump_data.line_offset_from_top,
2293 cx,
2294 );
2295 }
2296 }))
2297 .tooltip(move |cx| {
2298 Tooltip::for_action(
2299 format!(
2300 "Jump to {}:L{}",
2301 jump_data.path.path.display(),
2302 jump_data.position.row + 1
2303 ),
2304 &OpenExcerpts,
2305 cx,
2306 )
2307 })
2308 })
2309 };
2310 element.into_any()
2311 }
2312
2313 Block::ExcerptFooter { id, .. } => {
2314 let element = v_flex()
2315 .id(("excerpt footer", EntityId::from(block_id)))
2316 .w_full()
2317 .h(snapshot.excerpt_footer_height() as f32 * cx.line_height())
2318 .child(
2319 h_flex()
2320 .justify_end()
2321 .flex_none()
2322 .w(gutter_dimensions.width
2323 - (gutter_dimensions.left_padding + gutter_dimensions.margin))
2324 .h_full()
2325 .child(
2326 ButtonLike::new("expand-icon")
2327 .style(ButtonStyle::Transparent)
2328 .child(
2329 svg()
2330 .path(IconName::ArrowDownFromLine.path())
2331 .size(IconSize::XSmall.rems())
2332 .text_color(cx.theme().colors().editor_line_number)
2333 .group("")
2334 .hover(|style| {
2335 style.text_color(
2336 cx.theme().colors().editor_active_line_number,
2337 )
2338 }),
2339 )
2340 .on_click(cx.listener_for(&self.editor, {
2341 let id = *id;
2342 move |editor, _, cx| {
2343 editor.expand_excerpt(
2344 id,
2345 multi_buffer::ExpandExcerptDirection::Down,
2346 cx,
2347 );
2348 }
2349 }))
2350 .tooltip({
2351 move |cx| {
2352 Tooltip::for_action(
2353 "Expand Excerpt",
2354 &ExpandExcerpts { lines: 0 },
2355 cx,
2356 )
2357 }
2358 }),
2359 ),
2360 );
2361 element.into_any()
2362 }
2363 };
2364
2365 // Discover the element's content height, then round up to the nearest multiple of line height.
2366 let preliminary_size =
2367 element.layout_as_root(size(available_width, AvailableSpace::MinContent), cx);
2368 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
2369 let final_size = if preliminary_size.height == quantized_height {
2370 preliminary_size
2371 } else {
2372 element.layout_as_root(size(available_width, quantized_height.into()), cx)
2373 };
2374
2375 if let BlockId::Custom(custom_block_id) = block_id {
2376 let element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
2377 if element_height_in_lines != block.height() {
2378 resized_blocks.insert(custom_block_id, element_height_in_lines);
2379 }
2380 }
2381
2382 (element, final_size)
2383 }
2384
2385 #[allow(clippy::too_many_arguments)]
2386 fn render_blocks(
2387 &self,
2388 rows: Range<DisplayRow>,
2389 snapshot: &EditorSnapshot,
2390 hitbox: &Hitbox,
2391 text_hitbox: &Hitbox,
2392 scroll_width: &mut Pixels,
2393 gutter_dimensions: &GutterDimensions,
2394 em_width: Pixels,
2395 text_x: Pixels,
2396 line_height: Pixels,
2397 line_layouts: &[LineWithInvisibles],
2398 cx: &mut WindowContext,
2399 ) -> Result<Vec<BlockLayout>, HashMap<CustomBlockId, u32>> {
2400 let (fixed_blocks, non_fixed_blocks) = snapshot
2401 .blocks_in_range(rows.clone())
2402 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
2403
2404 let mut focused_block = self
2405 .editor
2406 .update(cx, |editor, _| editor.take_focused_block());
2407 let mut fixed_block_max_width = Pixels::ZERO;
2408 let mut blocks = Vec::new();
2409 let mut resized_blocks = HashMap::default();
2410
2411 for (row, block) in fixed_blocks {
2412 let block_id = block.id();
2413
2414 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2415 focused_block = None;
2416 }
2417
2418 let (element, element_size) = self.render_block(
2419 block,
2420 AvailableSpace::MinContent,
2421 block_id,
2422 row,
2423 snapshot,
2424 text_x,
2425 &rows,
2426 line_layouts,
2427 gutter_dimensions,
2428 line_height,
2429 em_width,
2430 text_hitbox,
2431 scroll_width,
2432 &mut resized_blocks,
2433 cx,
2434 );
2435 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2436 blocks.push(BlockLayout {
2437 id: block_id,
2438 row: Some(row),
2439 element,
2440 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
2441 style: BlockStyle::Fixed,
2442 });
2443 }
2444 for (row, block) in non_fixed_blocks {
2445 let style = block.style();
2446 let width = match style {
2447 BlockStyle::Sticky => hitbox.size.width,
2448 BlockStyle::Flex => hitbox
2449 .size
2450 .width
2451 .max(fixed_block_max_width)
2452 .max(gutter_dimensions.width + *scroll_width),
2453 BlockStyle::Fixed => unreachable!(),
2454 };
2455 let block_id = block.id();
2456
2457 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2458 focused_block = None;
2459 }
2460
2461 let (element, element_size) = self.render_block(
2462 block,
2463 width.into(),
2464 block_id,
2465 row,
2466 snapshot,
2467 text_x,
2468 &rows,
2469 line_layouts,
2470 gutter_dimensions,
2471 line_height,
2472 em_width,
2473 text_hitbox,
2474 scroll_width,
2475 &mut resized_blocks,
2476 cx,
2477 );
2478
2479 blocks.push(BlockLayout {
2480 id: block_id,
2481 row: Some(row),
2482 element,
2483 available_space: size(width.into(), element_size.height.into()),
2484 style,
2485 });
2486 }
2487
2488 if let Some(focused_block) = focused_block {
2489 if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
2490 if focus_handle.is_focused(cx) {
2491 if let Some(block) = snapshot.block_for_id(focused_block.id) {
2492 let style = block.style();
2493 let width = match style {
2494 BlockStyle::Fixed => AvailableSpace::MinContent,
2495 BlockStyle::Flex => AvailableSpace::Definite(
2496 hitbox
2497 .size
2498 .width
2499 .max(fixed_block_max_width)
2500 .max(gutter_dimensions.width + *scroll_width),
2501 ),
2502 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
2503 };
2504
2505 let (element, element_size) = self.render_block(
2506 &block,
2507 width,
2508 focused_block.id,
2509 rows.end,
2510 snapshot,
2511 text_x,
2512 &rows,
2513 line_layouts,
2514 gutter_dimensions,
2515 line_height,
2516 em_width,
2517 text_hitbox,
2518 scroll_width,
2519 &mut resized_blocks,
2520 cx,
2521 );
2522
2523 blocks.push(BlockLayout {
2524 id: block.id(),
2525 row: None,
2526 element,
2527 available_space: size(width, element_size.height.into()),
2528 style,
2529 });
2530 }
2531 }
2532 }
2533 }
2534
2535 if resized_blocks.is_empty() {
2536 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2537 Ok(blocks)
2538 } else {
2539 Err(resized_blocks)
2540 }
2541 }
2542
2543 /// Returns true if any of the blocks changed size since the previous frame. This will trigger
2544 /// a restart of rendering for the editor based on the new sizes.
2545 fn layout_blocks(
2546 &self,
2547 blocks: &mut Vec<BlockLayout>,
2548 hitbox: &Hitbox,
2549 line_height: Pixels,
2550 scroll_pixel_position: gpui::Point<Pixels>,
2551 cx: &mut WindowContext,
2552 ) {
2553 for block in blocks {
2554 let mut origin = if let Some(row) = block.row {
2555 hitbox.origin
2556 + point(
2557 Pixels::ZERO,
2558 row.as_f32() * line_height - scroll_pixel_position.y,
2559 )
2560 } else {
2561 // Position the block outside the visible area
2562 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
2563 };
2564
2565 if !matches!(block.style, BlockStyle::Sticky) {
2566 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2567 }
2568
2569 let focus_handle = block
2570 .element
2571 .prepaint_as_root(origin, block.available_space, cx);
2572
2573 if let Some(focus_handle) = focus_handle {
2574 self.editor.update(cx, |editor, _cx| {
2575 editor.set_focused_block(FocusedBlock {
2576 id: block.id,
2577 focus_handle: focus_handle.downgrade(),
2578 });
2579 });
2580 }
2581 }
2582 }
2583
2584 #[allow(clippy::too_many_arguments)]
2585 fn layout_context_menu(
2586 &self,
2587 line_height: Pixels,
2588 hitbox: &Hitbox,
2589 text_hitbox: &Hitbox,
2590 content_origin: gpui::Point<Pixels>,
2591 start_row: DisplayRow,
2592 scroll_pixel_position: gpui::Point<Pixels>,
2593 line_layouts: &[LineWithInvisibles],
2594 newest_selection_head: DisplayPoint,
2595 gutter_overshoot: Pixels,
2596 cx: &mut WindowContext,
2597 ) -> bool {
2598 let max_height = cmp::min(
2599 12. * line_height,
2600 cmp::max(3. * line_height, (hitbox.size.height - line_height) / 2.),
2601 );
2602 let Some((position, mut context_menu)) = self.editor.update(cx, |editor, cx| {
2603 if editor.context_menu_visible() {
2604 editor.render_context_menu(newest_selection_head, &self.style, max_height, cx)
2605 } else {
2606 None
2607 }
2608 }) else {
2609 return false;
2610 };
2611
2612 let context_menu_size = context_menu.layout_as_root(AvailableSpace::min_size(), cx);
2613
2614 let (x, y) = match position {
2615 crate::ContextMenuOrigin::EditorPoint(point) => {
2616 let cursor_row_layout = &line_layouts[point.row().minus(start_row) as usize];
2617 let x = cursor_row_layout.x_for_index(point.column() as usize)
2618 - scroll_pixel_position.x;
2619 let y = point.row().next_row().as_f32() * line_height - scroll_pixel_position.y;
2620 (x, y)
2621 }
2622 crate::ContextMenuOrigin::GutterIndicator(row) => {
2623 // 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
2624 // text field.
2625 let x = -gutter_overshoot;
2626 let y = row.next_row().as_f32() * line_height - scroll_pixel_position.y;
2627 (x, y)
2628 }
2629 };
2630
2631 let mut list_origin = content_origin + point(x, y);
2632 let list_width = context_menu_size.width;
2633 let list_height = context_menu_size.height;
2634
2635 // Snap the right edge of the list to the right edge of the window if
2636 // its horizontal bounds overflow.
2637 if list_origin.x + list_width > cx.viewport_size().width {
2638 list_origin.x = (cx.viewport_size().width - list_width).max(Pixels::ZERO);
2639 }
2640
2641 if list_origin.y + list_height > text_hitbox.lower_right().y {
2642 list_origin.y -= line_height + list_height;
2643 }
2644
2645 cx.defer_draw(context_menu, list_origin, 1);
2646 true
2647 }
2648
2649 fn layout_mouse_context_menu(
2650 &self,
2651 editor_snapshot: &EditorSnapshot,
2652 visible_range: Range<DisplayRow>,
2653 cx: &mut WindowContext,
2654 ) -> Option<AnyElement> {
2655 let position = self.editor.update(cx, |editor, cx| {
2656 let visible_start_point = editor.display_to_pixel_point(
2657 DisplayPoint::new(visible_range.start, 0),
2658 editor_snapshot,
2659 cx,
2660 )?;
2661 let visible_end_point = editor.display_to_pixel_point(
2662 DisplayPoint::new(visible_range.end, 0),
2663 editor_snapshot,
2664 cx,
2665 )?;
2666
2667 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
2668 let (source_display_point, position) = match mouse_context_menu.position {
2669 MenuPosition::PinnedToScreen(point) => (None, point),
2670 MenuPosition::PinnedToEditor {
2671 source,
2672 offset_x,
2673 offset_y,
2674 } => {
2675 let source_display_point = source.to_display_point(editor_snapshot);
2676 let mut source_point = editor.to_pixel_point(source, editor_snapshot, cx)?;
2677 source_point.x += offset_x;
2678 source_point.y += offset_y;
2679 (Some(source_display_point), source_point)
2680 }
2681 };
2682
2683 let source_included = source_display_point.map_or(true, |source_display_point| {
2684 visible_range
2685 .to_inclusive()
2686 .contains(&source_display_point.row())
2687 });
2688 let position_included =
2689 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
2690 if !source_included && !position_included {
2691 None
2692 } else {
2693 Some(position)
2694 }
2695 })?;
2696
2697 let mut element = self.editor.update(cx, |editor, _| {
2698 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
2699 let context_menu = mouse_context_menu.context_menu.clone();
2700
2701 Some(
2702 deferred(
2703 anchored()
2704 .position(position)
2705 .child(context_menu)
2706 .anchor(AnchorCorner::TopLeft)
2707 .snap_to_window(),
2708 )
2709 .with_priority(1)
2710 .into_any(),
2711 )
2712 })?;
2713
2714 element.prepaint_as_root(position, AvailableSpace::min_size(), cx);
2715 Some(element)
2716 }
2717
2718 #[allow(clippy::too_many_arguments)]
2719 fn layout_hover_popovers(
2720 &self,
2721 snapshot: &EditorSnapshot,
2722 hitbox: &Hitbox,
2723 text_hitbox: &Hitbox,
2724 visible_display_row_range: Range<DisplayRow>,
2725 content_origin: gpui::Point<Pixels>,
2726 scroll_pixel_position: gpui::Point<Pixels>,
2727 line_layouts: &[LineWithInvisibles],
2728 line_height: Pixels,
2729 em_width: Pixels,
2730 cx: &mut WindowContext,
2731 ) {
2732 struct MeasuredHoverPopover {
2733 element: AnyElement,
2734 size: Size<Pixels>,
2735 horizontal_offset: Pixels,
2736 }
2737
2738 let max_size = size(
2739 (120. * em_width) // Default size
2740 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2741 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2742 (16. * line_height) // Default size
2743 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2744 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2745 );
2746
2747 let hover_popovers = self.editor.update(cx, |editor, cx| {
2748 editor
2749 .hover_state
2750 .render(&snapshot, visible_display_row_range.clone(), max_size, cx)
2751 });
2752 let Some((position, hover_popovers)) = hover_popovers else {
2753 return;
2754 };
2755
2756 // This is safe because we check on layout whether the required row is available
2757 let hovered_row_layout =
2758 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
2759
2760 // Compute Hovered Point
2761 let x =
2762 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
2763 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
2764 let hovered_point = content_origin + point(x, y);
2765
2766 let mut overall_height = Pixels::ZERO;
2767 let mut measured_hover_popovers = Vec::new();
2768 for mut hover_popover in hover_popovers {
2769 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), cx);
2770 let horizontal_offset =
2771 (text_hitbox.upper_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
2772
2773 overall_height += HOVER_POPOVER_GAP + size.height;
2774
2775 measured_hover_popovers.push(MeasuredHoverPopover {
2776 element: hover_popover,
2777 size,
2778 horizontal_offset,
2779 });
2780 }
2781 overall_height += HOVER_POPOVER_GAP;
2782
2783 fn draw_occluder(width: Pixels, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
2784 let mut occlusion = div()
2785 .size_full()
2786 .occlude()
2787 .on_mouse_move(|_, cx| cx.stop_propagation())
2788 .into_any_element();
2789 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), cx);
2790 cx.defer_draw(occlusion, origin, 2);
2791 }
2792
2793 if hovered_point.y > overall_height {
2794 // There is enough space above. Render popovers above the hovered point
2795 let mut current_y = hovered_point.y;
2796 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2797 let size = popover.size;
2798 let popover_origin = point(
2799 hovered_point.x + popover.horizontal_offset,
2800 current_y - size.height,
2801 );
2802
2803 cx.defer_draw(popover.element, popover_origin, 2);
2804 if position != itertools::Position::Last {
2805 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
2806 draw_occluder(size.width, origin, cx);
2807 }
2808
2809 current_y = popover_origin.y - HOVER_POPOVER_GAP;
2810 }
2811 } else {
2812 // There is not enough space above. Render popovers below the hovered point
2813 let mut current_y = hovered_point.y + line_height;
2814 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
2815 let size = popover.size;
2816 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
2817
2818 cx.defer_draw(popover.element, popover_origin, 2);
2819 if position != itertools::Position::Last {
2820 let origin = point(popover_origin.x, popover_origin.y + size.height);
2821 draw_occluder(size.width, origin, cx);
2822 }
2823
2824 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
2825 }
2826 }
2827 }
2828
2829 #[allow(clippy::too_many_arguments)]
2830 fn layout_signature_help(
2831 &self,
2832 hitbox: &Hitbox,
2833 content_origin: gpui::Point<Pixels>,
2834 scroll_pixel_position: gpui::Point<Pixels>,
2835 newest_selection_head: Option<DisplayPoint>,
2836 start_row: DisplayRow,
2837 line_layouts: &[LineWithInvisibles],
2838 line_height: Pixels,
2839 em_width: Pixels,
2840 cx: &mut WindowContext,
2841 ) {
2842 if !self.editor.focus_handle(cx).is_focused(cx) {
2843 return;
2844 }
2845 let Some(newest_selection_head) = newest_selection_head else {
2846 return;
2847 };
2848 let selection_row = newest_selection_head.row();
2849 if selection_row < start_row {
2850 return;
2851 }
2852 let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
2853 else {
2854 return;
2855 };
2856
2857 let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
2858 - scroll_pixel_position.x
2859 + content_origin.x;
2860 let start_y =
2861 selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
2862
2863 let max_size = size(
2864 (120. * em_width) // Default size
2865 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
2866 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
2867 (16. * line_height) // Default size
2868 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
2869 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
2870 );
2871
2872 let maybe_element = self.editor.update(cx, |editor, cx| {
2873 if let Some(popover) = editor.signature_help_state.popover_mut() {
2874 let element = popover.render(
2875 &self.style,
2876 max_size,
2877 editor.workspace.as_ref().map(|(w, _)| w.clone()),
2878 cx,
2879 );
2880 Some(element)
2881 } else {
2882 None
2883 }
2884 });
2885 if let Some(mut element) = maybe_element {
2886 let window_size = cx.viewport_size();
2887 let size = element.layout_as_root(Size::<AvailableSpace>::default(), cx);
2888 let mut point = point(start_x, start_y - size.height);
2889
2890 // Adjusting to ensure the popover does not overflow in the X-axis direction.
2891 if point.x + size.width >= window_size.width {
2892 point.x = window_size.width - size.width;
2893 }
2894
2895 cx.defer_draw(element, point, 1)
2896 }
2897 }
2898
2899 fn paint_background(&self, layout: &EditorLayout, cx: &mut WindowContext) {
2900 cx.paint_layer(layout.hitbox.bounds, |cx| {
2901 let scroll_top = layout.position_map.snapshot.scroll_position().y;
2902 let gutter_bg = cx.theme().colors().editor_gutter_background;
2903 cx.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
2904 cx.paint_quad(fill(layout.text_hitbox.bounds, self.style.background));
2905
2906 if let EditorMode::Full = layout.mode {
2907 let mut active_rows = layout.active_rows.iter().peekable();
2908 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
2909 let mut end_row = start_row.0;
2910 while active_rows
2911 .peek()
2912 .map_or(false, |(active_row, has_selection)| {
2913 active_row.0 == end_row + 1
2914 && *has_selection == contains_non_empty_selection
2915 })
2916 {
2917 active_rows.next().unwrap();
2918 end_row += 1;
2919 }
2920
2921 if !contains_non_empty_selection {
2922 let highlight_h_range =
2923 match layout.position_map.snapshot.current_line_highlight {
2924 CurrentLineHighlight::Gutter => Some(Range {
2925 start: layout.hitbox.left(),
2926 end: layout.gutter_hitbox.right(),
2927 }),
2928 CurrentLineHighlight::Line => Some(Range {
2929 start: layout.text_hitbox.bounds.left(),
2930 end: layout.text_hitbox.bounds.right(),
2931 }),
2932 CurrentLineHighlight::All => Some(Range {
2933 start: layout.hitbox.left(),
2934 end: layout.hitbox.right(),
2935 }),
2936 CurrentLineHighlight::None => None,
2937 };
2938 if let Some(range) = highlight_h_range {
2939 let active_line_bg = cx.theme().colors().editor_active_line_background;
2940 let bounds = Bounds {
2941 origin: point(
2942 range.start,
2943 layout.hitbox.origin.y
2944 + (start_row.as_f32() - scroll_top)
2945 * layout.position_map.line_height,
2946 ),
2947 size: size(
2948 range.end - range.start,
2949 layout.position_map.line_height
2950 * (end_row - start_row.0 + 1) as f32,
2951 ),
2952 };
2953 cx.paint_quad(fill(bounds, active_line_bg));
2954 }
2955 }
2956 }
2957
2958 let mut paint_highlight =
2959 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
2960 let origin = point(
2961 layout.hitbox.origin.x,
2962 layout.hitbox.origin.y
2963 + (highlight_row_start.as_f32() - scroll_top)
2964 * layout.position_map.line_height,
2965 );
2966 let size = size(
2967 layout.hitbox.size.width,
2968 layout.position_map.line_height
2969 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
2970 );
2971 cx.paint_quad(fill(Bounds { origin, size }, color));
2972 };
2973
2974 let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
2975 for (&new_row, &new_color) in &layout.highlighted_rows {
2976 match &mut current_paint {
2977 Some((current_color, current_range)) => {
2978 let current_color = *current_color;
2979 let new_range_started = current_color != new_color
2980 || current_range.end.next_row() != new_row;
2981 if new_range_started {
2982 paint_highlight(
2983 current_range.start,
2984 current_range.end,
2985 current_color,
2986 );
2987 current_paint = Some((new_color, new_row..new_row));
2988 continue;
2989 } else {
2990 current_range.end = current_range.end.next_row();
2991 }
2992 }
2993 None => current_paint = Some((new_color, new_row..new_row)),
2994 };
2995 }
2996 if let Some((color, range)) = current_paint {
2997 paint_highlight(range.start, range.end, color);
2998 }
2999
3000 let scroll_left =
3001 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
3002
3003 for (wrap_position, active) in layout.wrap_guides.iter() {
3004 let x = (layout.text_hitbox.origin.x
3005 + *wrap_position
3006 + layout.position_map.em_width / 2.)
3007 - scroll_left;
3008
3009 let show_scrollbars = layout
3010 .scrollbar_layout
3011 .as_ref()
3012 .map_or(false, |scrollbar| scrollbar.visible);
3013 if x < layout.text_hitbox.origin.x
3014 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
3015 {
3016 continue;
3017 }
3018
3019 let color = if *active {
3020 cx.theme().colors().editor_active_wrap_guide
3021 } else {
3022 cx.theme().colors().editor_wrap_guide
3023 };
3024 cx.paint_quad(fill(
3025 Bounds {
3026 origin: point(x, layout.text_hitbox.origin.y),
3027 size: size(px(1.), layout.text_hitbox.size.height),
3028 },
3029 color,
3030 ));
3031 }
3032 }
3033 })
3034 }
3035
3036 fn paint_indent_guides(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3037 let Some(indent_guides) = &layout.indent_guides else {
3038 return;
3039 };
3040
3041 let faded_color = |color: Hsla, alpha: f32| {
3042 let mut faded = color;
3043 faded.a = alpha;
3044 faded
3045 };
3046
3047 for indent_guide in indent_guides {
3048 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
3049 let settings = indent_guide.settings;
3050
3051 // TODO fixed for now, expose them through themes later
3052 const INDENT_AWARE_ALPHA: f32 = 0.2;
3053 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
3054 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
3055 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
3056
3057 let line_color = match (settings.coloring, indent_guide.active) {
3058 (IndentGuideColoring::Disabled, _) => None,
3059 (IndentGuideColoring::Fixed, false) => {
3060 Some(cx.theme().colors().editor_indent_guide)
3061 }
3062 (IndentGuideColoring::Fixed, true) => {
3063 Some(cx.theme().colors().editor_indent_guide_active)
3064 }
3065 (IndentGuideColoring::IndentAware, false) => {
3066 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
3067 }
3068 (IndentGuideColoring::IndentAware, true) => {
3069 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
3070 }
3071 };
3072
3073 let background_color = match (settings.background_coloring, indent_guide.active) {
3074 (IndentGuideBackgroundColoring::Disabled, _) => None,
3075 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
3076 indent_accent_colors,
3077 INDENT_AWARE_BACKGROUND_ALPHA,
3078 )),
3079 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
3080 indent_accent_colors,
3081 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
3082 )),
3083 };
3084
3085 let requested_line_width = if indent_guide.active {
3086 settings.active_line_width
3087 } else {
3088 settings.line_width
3089 }
3090 .clamp(1, 10);
3091 let mut line_indicator_width = 0.;
3092 if let Some(color) = line_color {
3093 cx.paint_quad(fill(
3094 Bounds {
3095 origin: indent_guide.origin,
3096 size: size(px(requested_line_width as f32), indent_guide.length),
3097 },
3098 color,
3099 ));
3100 line_indicator_width = requested_line_width as f32;
3101 }
3102
3103 if let Some(color) = background_color {
3104 let width = indent_guide.single_indent_width - px(line_indicator_width);
3105 cx.paint_quad(fill(
3106 Bounds {
3107 origin: point(
3108 indent_guide.origin.x + px(line_indicator_width),
3109 indent_guide.origin.y,
3110 ),
3111 size: size(width, indent_guide.length),
3112 },
3113 color,
3114 ));
3115 }
3116 }
3117 }
3118
3119 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3120 let line_height = layout.position_map.line_height;
3121 let scroll_position = layout.position_map.snapshot.scroll_position();
3122 let scroll_top = scroll_position.y * line_height;
3123
3124 cx.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
3125
3126 for (ix, line) in layout.line_numbers.iter().enumerate() {
3127 if let Some(line) = line {
3128 let line_origin = layout.gutter_hitbox.origin
3129 + point(
3130 layout.gutter_hitbox.size.width
3131 - line.width
3132 - layout.gutter_dimensions.right_padding,
3133 ix as f32 * line_height - (scroll_top % line_height),
3134 );
3135
3136 line.paint(line_origin, line_height, cx).log_err();
3137 }
3138 }
3139 }
3140
3141 fn paint_diff_hunks(layout: &mut EditorLayout, cx: &mut WindowContext) {
3142 if layout.display_hunks.is_empty() {
3143 return;
3144 }
3145
3146 let line_height = layout.position_map.line_height;
3147 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3148 for (hunk, hitbox) in &layout.display_hunks {
3149 let hunk_to_paint = match hunk {
3150 DisplayDiffHunk::Folded { .. } => {
3151 let hunk_bounds = Self::diff_hunk_bounds(
3152 &layout.position_map.snapshot,
3153 line_height,
3154 layout.gutter_hitbox.bounds,
3155 &hunk,
3156 );
3157 Some((
3158 hunk_bounds,
3159 cx.theme().status().modified,
3160 Corners::all(1. * line_height),
3161 ))
3162 }
3163 DisplayDiffHunk::Unfolded { status, .. } => {
3164 hitbox.as_ref().map(|hunk_hitbox| match status {
3165 DiffHunkStatus::Added => (
3166 hunk_hitbox.bounds,
3167 cx.theme().status().created,
3168 Corners::all(0.05 * line_height),
3169 ),
3170 DiffHunkStatus::Modified => (
3171 hunk_hitbox.bounds,
3172 cx.theme().status().modified,
3173 Corners::all(0.05 * line_height),
3174 ),
3175 DiffHunkStatus::Removed => (
3176 Bounds::new(
3177 point(
3178 hunk_hitbox.origin.x - hunk_hitbox.size.width,
3179 hunk_hitbox.origin.y,
3180 ),
3181 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
3182 ),
3183 cx.theme().status().deleted,
3184 Corners::all(1. * line_height),
3185 ),
3186 })
3187 }
3188 };
3189
3190 if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
3191 cx.paint_quad(quad(
3192 hunk_bounds,
3193 corner_radii,
3194 background_color,
3195 Edges::default(),
3196 transparent_black(),
3197 ));
3198 }
3199 }
3200 });
3201 }
3202
3203 pub(super) fn diff_hunk_bounds(
3204 snapshot: &EditorSnapshot,
3205 line_height: Pixels,
3206 gutter_bounds: Bounds<Pixels>,
3207 hunk: &DisplayDiffHunk,
3208 ) -> Bounds<Pixels> {
3209 let scroll_position = snapshot.scroll_position();
3210 let scroll_top = scroll_position.y * line_height;
3211
3212 match hunk {
3213 DisplayDiffHunk::Folded { display_row, .. } => {
3214 let start_y = display_row.as_f32() * line_height - scroll_top;
3215 let end_y = start_y + line_height;
3216
3217 let width = 0.275 * line_height;
3218 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3219 let highlight_size = size(width, end_y - start_y);
3220 Bounds::new(highlight_origin, highlight_size)
3221 }
3222 DisplayDiffHunk::Unfolded {
3223 display_row_range,
3224 status,
3225 ..
3226 } => match status {
3227 DiffHunkStatus::Added | DiffHunkStatus::Modified => {
3228 let start_row = display_row_range.start;
3229 let end_row = display_row_range.end;
3230 // If we're in a multibuffer, row range span might include an
3231 // excerpt header, so if we were to draw the marker straight away,
3232 // the hunk might include the rows of that header.
3233 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
3234 // Instead, we simply check whether the range we're dealing with includes
3235 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
3236 let end_row_in_current_excerpt = snapshot
3237 .blocks_in_range(start_row..end_row)
3238 .find_map(|(start_row, block)| {
3239 if matches!(block, Block::ExcerptHeader { .. }) {
3240 Some(start_row)
3241 } else {
3242 None
3243 }
3244 })
3245 .unwrap_or(end_row);
3246
3247 let start_y = start_row.as_f32() * line_height - scroll_top;
3248 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
3249
3250 let width = 0.275 * line_height;
3251 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3252 let highlight_size = size(width, end_y - start_y);
3253 Bounds::new(highlight_origin, highlight_size)
3254 }
3255 DiffHunkStatus::Removed => {
3256 let row = display_row_range.start;
3257
3258 let offset = line_height / 2.;
3259 let start_y = row.as_f32() * line_height - offset - scroll_top;
3260 let end_y = start_y + line_height;
3261
3262 let width = 0.35 * line_height;
3263 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
3264 let highlight_size = size(width, end_y - start_y);
3265 Bounds::new(highlight_origin, highlight_size)
3266 }
3267 },
3268 }
3269 }
3270
3271 fn paint_gutter_indicators(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3272 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3273 cx.with_element_namespace("gutter_fold_toggles", |cx| {
3274 for fold_indicator in layout.gutter_fold_toggles.iter_mut().flatten() {
3275 fold_indicator.paint(cx);
3276 }
3277 });
3278
3279 for test_indicator in layout.test_indicators.iter_mut() {
3280 test_indicator.paint(cx);
3281 }
3282 for close_indicator in layout.close_indicators.iter_mut() {
3283 close_indicator.paint(cx);
3284 }
3285
3286 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
3287 indicator.paint(cx);
3288 }
3289 });
3290 }
3291
3292 fn paint_gutter_highlights(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3293 for (_, hunk_hitbox) in &layout.display_hunks {
3294 if let Some(hunk_hitbox) = hunk_hitbox {
3295 cx.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
3296 }
3297 }
3298
3299 let show_git_gutter = layout
3300 .position_map
3301 .snapshot
3302 .show_git_diff_gutter
3303 .unwrap_or_else(|| {
3304 matches!(
3305 ProjectSettings::get_global(cx).git.git_gutter,
3306 Some(GitGutterSetting::TrackedFiles)
3307 )
3308 });
3309 if show_git_gutter {
3310 Self::paint_diff_hunks(layout, cx)
3311 }
3312
3313 let highlight_width = 0.275 * layout.position_map.line_height;
3314 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
3315 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3316 for (range, color) in &layout.highlighted_gutter_ranges {
3317 let start_row = if range.start.row() < layout.visible_display_row_range.start {
3318 layout.visible_display_row_range.start - DisplayRow(1)
3319 } else {
3320 range.start.row()
3321 };
3322 let end_row = if range.end.row() > layout.visible_display_row_range.end {
3323 layout.visible_display_row_range.end + DisplayRow(1)
3324 } else {
3325 range.end.row()
3326 };
3327
3328 let start_y = layout.gutter_hitbox.top()
3329 + start_row.0 as f32 * layout.position_map.line_height
3330 - layout.position_map.scroll_pixel_position.y;
3331 let end_y = layout.gutter_hitbox.top()
3332 + (end_row.0 + 1) as f32 * layout.position_map.line_height
3333 - layout.position_map.scroll_pixel_position.y;
3334 let bounds = Bounds::from_corners(
3335 point(layout.gutter_hitbox.left(), start_y),
3336 point(layout.gutter_hitbox.left() + highlight_width, end_y),
3337 );
3338 cx.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
3339 }
3340 });
3341 }
3342
3343 fn paint_blamed_display_rows(&self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3344 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
3345 return;
3346 };
3347
3348 cx.paint_layer(layout.gutter_hitbox.bounds, |cx| {
3349 for mut blame_element in blamed_display_rows.into_iter() {
3350 blame_element.paint(cx);
3351 }
3352 })
3353 }
3354
3355 fn paint_text(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3356 cx.with_content_mask(
3357 Some(ContentMask {
3358 bounds: layout.text_hitbox.bounds,
3359 }),
3360 |cx| {
3361 let cursor_style = if self
3362 .editor
3363 .read(cx)
3364 .hovered_link_state
3365 .as_ref()
3366 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
3367 {
3368 CursorStyle::PointingHand
3369 } else {
3370 CursorStyle::IBeam
3371 };
3372 cx.set_cursor_style(cursor_style, &layout.text_hitbox);
3373
3374 let invisible_display_ranges = self.paint_highlights(layout, cx);
3375 self.paint_lines(&invisible_display_ranges, layout, cx);
3376 self.paint_redactions(layout, cx);
3377 self.paint_cursors(layout, cx);
3378 self.paint_inline_blame(layout, cx);
3379 cx.with_element_namespace("crease_trailers", |cx| {
3380 for trailer in layout.crease_trailers.iter_mut().flatten() {
3381 trailer.element.paint(cx);
3382 }
3383 });
3384 },
3385 )
3386 }
3387
3388 fn paint_highlights(
3389 &mut self,
3390 layout: &mut EditorLayout,
3391 cx: &mut WindowContext,
3392 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
3393 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3394 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
3395 let line_end_overshoot = 0.15 * layout.position_map.line_height;
3396 for (range, color) in &layout.highlighted_ranges {
3397 self.paint_highlighted_range(
3398 range.clone(),
3399 *color,
3400 Pixels::ZERO,
3401 line_end_overshoot,
3402 layout,
3403 cx,
3404 );
3405 }
3406
3407 let corner_radius = 0.15 * layout.position_map.line_height;
3408
3409 for (player_color, selections) in &layout.selections {
3410 for selection in selections.into_iter() {
3411 self.paint_highlighted_range(
3412 selection.range.clone(),
3413 player_color.selection,
3414 corner_radius,
3415 corner_radius * 2.,
3416 layout,
3417 cx,
3418 );
3419
3420 if selection.is_local && !selection.range.is_empty() {
3421 invisible_display_ranges.push(selection.range.clone());
3422 }
3423 }
3424 }
3425 invisible_display_ranges
3426 })
3427 }
3428
3429 fn paint_lines(
3430 &mut self,
3431 invisible_display_ranges: &[Range<DisplayPoint>],
3432 layout: &mut EditorLayout,
3433 cx: &mut WindowContext,
3434 ) {
3435 let whitespace_setting = self
3436 .editor
3437 .read(cx)
3438 .buffer
3439 .read(cx)
3440 .settings_at(0, cx)
3441 .show_whitespaces;
3442
3443 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
3444 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
3445 line_with_invisibles.draw(
3446 layout,
3447 row,
3448 layout.content_origin,
3449 whitespace_setting,
3450 invisible_display_ranges,
3451 cx,
3452 )
3453 }
3454
3455 for line_element in &mut layout.line_elements {
3456 line_element.paint(cx);
3457 }
3458 }
3459
3460 fn paint_redactions(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3461 if layout.redacted_ranges.is_empty() {
3462 return;
3463 }
3464
3465 let line_end_overshoot = layout.line_end_overshoot();
3466
3467 // A softer than perfect black
3468 let redaction_color = gpui::rgb(0x0e1111);
3469
3470 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3471 for range in layout.redacted_ranges.iter() {
3472 self.paint_highlighted_range(
3473 range.clone(),
3474 redaction_color.into(),
3475 Pixels::ZERO,
3476 line_end_overshoot,
3477 layout,
3478 cx,
3479 );
3480 }
3481 });
3482 }
3483
3484 fn paint_cursors(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3485 for cursor in &mut layout.visible_cursors {
3486 cursor.paint(layout.content_origin, cx);
3487 }
3488 }
3489
3490 fn paint_scrollbar(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3491 let Some(scrollbar_layout) = layout.scrollbar_layout.as_ref() else {
3492 return;
3493 };
3494
3495 let thumb_bounds = scrollbar_layout.thumb_bounds();
3496 if scrollbar_layout.visible {
3497 cx.paint_layer(scrollbar_layout.hitbox.bounds, |cx| {
3498 cx.paint_quad(quad(
3499 scrollbar_layout.hitbox.bounds,
3500 Corners::default(),
3501 cx.theme().colors().scrollbar_track_background,
3502 Edges {
3503 top: Pixels::ZERO,
3504 right: Pixels::ZERO,
3505 bottom: Pixels::ZERO,
3506 left: ScrollbarLayout::BORDER_WIDTH,
3507 },
3508 cx.theme().colors().scrollbar_track_border,
3509 ));
3510
3511 let fast_markers =
3512 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
3513 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
3514 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, cx);
3515
3516 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
3517 for marker in markers.iter().chain(&fast_markers) {
3518 let mut marker = marker.clone();
3519 marker.bounds.origin += scrollbar_layout.hitbox.origin;
3520 cx.paint_quad(marker);
3521 }
3522
3523 cx.paint_quad(quad(
3524 thumb_bounds,
3525 Corners::default(),
3526 cx.theme().colors().scrollbar_thumb_background,
3527 Edges {
3528 top: Pixels::ZERO,
3529 right: Pixels::ZERO,
3530 bottom: Pixels::ZERO,
3531 left: ScrollbarLayout::BORDER_WIDTH,
3532 },
3533 cx.theme().colors().scrollbar_thumb_border,
3534 ));
3535 });
3536 }
3537
3538 cx.set_cursor_style(CursorStyle::Arrow, &scrollbar_layout.hitbox);
3539
3540 let row_height = scrollbar_layout.row_height;
3541 let row_range = scrollbar_layout.visible_row_range.clone();
3542
3543 cx.on_mouse_event({
3544 let editor = self.editor.clone();
3545 let hitbox = scrollbar_layout.hitbox.clone();
3546 let mut mouse_position = cx.mouse_position();
3547 move |event: &MouseMoveEvent, phase, cx| {
3548 if phase == DispatchPhase::Capture {
3549 return;
3550 }
3551
3552 editor.update(cx, |editor, cx| {
3553 if event.pressed_button == Some(MouseButton::Left)
3554 && editor.scroll_manager.is_dragging_scrollbar()
3555 {
3556 let y = mouse_position.y;
3557 let new_y = event.position.y;
3558 if (hitbox.top()..hitbox.bottom()).contains(&y) {
3559 let mut position = editor.scroll_position(cx);
3560 position.y += (new_y - y) / row_height;
3561 if position.y < 0.0 {
3562 position.y = 0.0;
3563 }
3564 editor.set_scroll_position(position, cx);
3565 }
3566
3567 cx.stop_propagation();
3568 } else {
3569 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3570 if hitbox.is_hovered(cx) {
3571 editor.scroll_manager.show_scrollbar(cx);
3572 }
3573 }
3574 mouse_position = event.position;
3575 })
3576 }
3577 });
3578
3579 if self.editor.read(cx).scroll_manager.is_dragging_scrollbar() {
3580 cx.on_mouse_event({
3581 let editor = self.editor.clone();
3582 move |_: &MouseUpEvent, phase, cx| {
3583 if phase == DispatchPhase::Capture {
3584 return;
3585 }
3586
3587 editor.update(cx, |editor, cx| {
3588 editor.scroll_manager.set_is_dragging_scrollbar(false, cx);
3589 cx.stop_propagation();
3590 });
3591 }
3592 });
3593 } else {
3594 cx.on_mouse_event({
3595 let editor = self.editor.clone();
3596 let hitbox = scrollbar_layout.hitbox.clone();
3597 move |event: &MouseDownEvent, phase, cx| {
3598 if phase == DispatchPhase::Capture || !hitbox.is_hovered(cx) {
3599 return;
3600 }
3601
3602 editor.update(cx, |editor, cx| {
3603 editor.scroll_manager.set_is_dragging_scrollbar(true, cx);
3604
3605 let y = event.position.y;
3606 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
3607 let center_row = ((y - hitbox.top()) / row_height).round() as u32;
3608 let top_row = center_row
3609 .saturating_sub((row_range.end - row_range.start) as u32 / 2);
3610 let mut position = editor.scroll_position(cx);
3611 position.y = top_row as f32;
3612 editor.set_scroll_position(position, cx);
3613 } else {
3614 editor.scroll_manager.show_scrollbar(cx);
3615 }
3616
3617 cx.stop_propagation();
3618 });
3619 }
3620 });
3621 }
3622 }
3623
3624 fn collect_fast_scrollbar_markers(
3625 &self,
3626 layout: &EditorLayout,
3627 scrollbar_layout: &ScrollbarLayout,
3628 cx: &mut WindowContext,
3629 ) -> Vec<PaintQuad> {
3630 const LIMIT: usize = 100;
3631 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
3632 return vec![];
3633 }
3634 let cursor_ranges = layout
3635 .cursors
3636 .iter()
3637 .map(|(point, color)| ColoredRange {
3638 start: point.row(),
3639 end: point.row(),
3640 color: *color,
3641 })
3642 .collect_vec();
3643 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
3644 }
3645
3646 fn refresh_slow_scrollbar_markers(
3647 &self,
3648 layout: &EditorLayout,
3649 scrollbar_layout: &ScrollbarLayout,
3650 cx: &mut WindowContext,
3651 ) {
3652 self.editor.update(cx, |editor, cx| {
3653 if !editor.is_singleton(cx)
3654 || !editor
3655 .scrollbar_marker_state
3656 .should_refresh(scrollbar_layout.hitbox.size)
3657 {
3658 return;
3659 }
3660
3661 let scrollbar_layout = scrollbar_layout.clone();
3662 let background_highlights = editor.background_highlights.clone();
3663 let snapshot = layout.position_map.snapshot.clone();
3664 let theme = cx.theme().clone();
3665 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
3666
3667 editor.scrollbar_marker_state.dirty = false;
3668 editor.scrollbar_marker_state.pending_refresh =
3669 Some(cx.spawn(|editor, mut cx| async move {
3670 let scrollbar_size = scrollbar_layout.hitbox.size;
3671 let scrollbar_markers = cx
3672 .background_executor()
3673 .spawn(async move {
3674 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
3675 let mut marker_quads = Vec::new();
3676 if scrollbar_settings.git_diff {
3677 let marker_row_ranges = snapshot
3678 .buffer_snapshot
3679 .git_diff_hunks_in_range(
3680 MultiBufferRow::MIN..MultiBufferRow::MAX,
3681 )
3682 .map(|hunk| {
3683 let start_display_row =
3684 MultiBufferPoint::new(hunk.associated_range.start.0, 0)
3685 .to_display_point(&snapshot.display_snapshot)
3686 .row();
3687 let mut end_display_row =
3688 MultiBufferPoint::new(hunk.associated_range.end.0, 0)
3689 .to_display_point(&snapshot.display_snapshot)
3690 .row();
3691 if end_display_row != start_display_row {
3692 end_display_row.0 -= 1;
3693 }
3694 let color = match hunk_status(&hunk) {
3695 DiffHunkStatus::Added => theme.status().created,
3696 DiffHunkStatus::Modified => theme.status().modified,
3697 DiffHunkStatus::Removed => theme.status().deleted,
3698 };
3699 ColoredRange {
3700 start: start_display_row,
3701 end: end_display_row,
3702 color,
3703 }
3704 });
3705
3706 marker_quads.extend(
3707 scrollbar_layout
3708 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
3709 );
3710 }
3711
3712 for (background_highlight_id, (_, background_ranges)) in
3713 background_highlights.iter()
3714 {
3715 let is_search_highlights = *background_highlight_id
3716 == TypeId::of::<BufferSearchHighlights>();
3717 let is_symbol_occurrences = *background_highlight_id
3718 == TypeId::of::<DocumentHighlightRead>()
3719 || *background_highlight_id
3720 == TypeId::of::<DocumentHighlightWrite>();
3721 if (is_search_highlights && scrollbar_settings.search_results)
3722 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
3723 {
3724 let mut color = theme.status().info;
3725 if is_symbol_occurrences {
3726 color.fade_out(0.5);
3727 }
3728 let marker_row_ranges =
3729 background_ranges.into_iter().map(|range| {
3730 let display_start = range
3731 .start
3732 .to_display_point(&snapshot.display_snapshot);
3733 let display_end = range
3734 .end
3735 .to_display_point(&snapshot.display_snapshot);
3736 ColoredRange {
3737 start: display_start.row(),
3738 end: display_end.row(),
3739 color,
3740 }
3741 });
3742 marker_quads.extend(
3743 scrollbar_layout
3744 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
3745 );
3746 }
3747 }
3748
3749 if scrollbar_settings.diagnostics {
3750 let diagnostics = snapshot
3751 .buffer_snapshot
3752 .diagnostics_in_range::<_, Point>(
3753 Point::zero()..max_point,
3754 false,
3755 )
3756 // We want to sort by severity, in order to paint the most severe diagnostics last.
3757 .sorted_by_key(|diagnostic| {
3758 std::cmp::Reverse(diagnostic.diagnostic.severity)
3759 });
3760
3761 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
3762 let start_display = diagnostic
3763 .range
3764 .start
3765 .to_display_point(&snapshot.display_snapshot);
3766 let end_display = diagnostic
3767 .range
3768 .end
3769 .to_display_point(&snapshot.display_snapshot);
3770 let color = match diagnostic.diagnostic.severity {
3771 DiagnosticSeverity::ERROR => theme.status().error,
3772 DiagnosticSeverity::WARNING => theme.status().warning,
3773 DiagnosticSeverity::INFORMATION => theme.status().info,
3774 _ => theme.status().hint,
3775 };
3776 ColoredRange {
3777 start: start_display.row(),
3778 end: end_display.row(),
3779 color,
3780 }
3781 });
3782 marker_quads.extend(
3783 scrollbar_layout
3784 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
3785 );
3786 }
3787
3788 Arc::from(marker_quads)
3789 })
3790 .await;
3791
3792 editor.update(&mut cx, |editor, cx| {
3793 editor.scrollbar_marker_state.markers = scrollbar_markers;
3794 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
3795 editor.scrollbar_marker_state.pending_refresh = None;
3796 cx.notify();
3797 })?;
3798
3799 Ok(())
3800 }));
3801 });
3802 }
3803
3804 #[allow(clippy::too_many_arguments)]
3805 fn paint_highlighted_range(
3806 &self,
3807 range: Range<DisplayPoint>,
3808 color: Hsla,
3809 corner_radius: Pixels,
3810 line_end_overshoot: Pixels,
3811 layout: &EditorLayout,
3812 cx: &mut WindowContext,
3813 ) {
3814 let start_row = layout.visible_display_row_range.start;
3815 let end_row = layout.visible_display_row_range.end;
3816 if range.start != range.end {
3817 let row_range = if range.end.column() == 0 {
3818 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
3819 } else {
3820 cmp::max(range.start.row(), start_row)
3821 ..cmp::min(range.end.row().next_row(), end_row)
3822 };
3823
3824 let highlighted_range = HighlightedRange {
3825 color,
3826 line_height: layout.position_map.line_height,
3827 corner_radius,
3828 start_y: layout.content_origin.y
3829 + row_range.start.as_f32() * layout.position_map.line_height
3830 - layout.position_map.scroll_pixel_position.y,
3831 lines: row_range
3832 .iter_rows()
3833 .map(|row| {
3834 let line_layout =
3835 &layout.position_map.line_layouts[row.minus(start_row) as usize];
3836 HighlightedRangeLine {
3837 start_x: if row == range.start.row() {
3838 layout.content_origin.x
3839 + line_layout.x_for_index(range.start.column() as usize)
3840 - layout.position_map.scroll_pixel_position.x
3841 } else {
3842 layout.content_origin.x
3843 - layout.position_map.scroll_pixel_position.x
3844 },
3845 end_x: if row == range.end.row() {
3846 layout.content_origin.x
3847 + line_layout.x_for_index(range.end.column() as usize)
3848 - layout.position_map.scroll_pixel_position.x
3849 } else {
3850 layout.content_origin.x + line_layout.width + line_end_overshoot
3851 - layout.position_map.scroll_pixel_position.x
3852 },
3853 }
3854 })
3855 .collect(),
3856 };
3857
3858 highlighted_range.paint(layout.text_hitbox.bounds, cx);
3859 }
3860 }
3861
3862 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3863 if let Some(mut inline_blame) = layout.inline_blame.take() {
3864 cx.paint_layer(layout.text_hitbox.bounds, |cx| {
3865 inline_blame.paint(cx);
3866 })
3867 }
3868 }
3869
3870 fn paint_blocks(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3871 for mut block in layout.blocks.drain(..) {
3872 block.element.paint(cx);
3873 }
3874 }
3875
3876 fn paint_mouse_context_menu(&mut self, layout: &mut EditorLayout, cx: &mut WindowContext) {
3877 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
3878 mouse_context_menu.paint(cx);
3879 }
3880 }
3881
3882 fn paint_scroll_wheel_listener(&mut self, layout: &EditorLayout, cx: &mut WindowContext) {
3883 cx.on_mouse_event({
3884 let position_map = layout.position_map.clone();
3885 let editor = self.editor.clone();
3886 let hitbox = layout.hitbox.clone();
3887 let mut delta = ScrollDelta::default();
3888
3889 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
3890 // accidentally turn off their scrolling.
3891 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
3892
3893 move |event: &ScrollWheelEvent, phase, cx| {
3894 if phase == DispatchPhase::Bubble && hitbox.is_hovered(cx) {
3895 delta = delta.coalesce(event.delta);
3896 editor.update(cx, |editor, cx| {
3897 let position_map: &PositionMap = &position_map;
3898
3899 let line_height = position_map.line_height;
3900 let max_glyph_width = position_map.em_width;
3901 let (delta, axis) = match delta {
3902 gpui::ScrollDelta::Pixels(mut pixels) => {
3903 //Trackpad
3904 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
3905 (pixels, axis)
3906 }
3907
3908 gpui::ScrollDelta::Lines(lines) => {
3909 //Not trackpad
3910 let pixels =
3911 point(lines.x * max_glyph_width, lines.y * line_height);
3912 (pixels, None)
3913 }
3914 };
3915
3916 let current_scroll_position = position_map.snapshot.scroll_position();
3917 let x = (current_scroll_position.x * max_glyph_width
3918 - (delta.x * scroll_sensitivity))
3919 / max_glyph_width;
3920 let y = (current_scroll_position.y * line_height
3921 - (delta.y * scroll_sensitivity))
3922 / line_height;
3923 let mut scroll_position =
3924 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
3925 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
3926 if forbid_vertical_scroll {
3927 scroll_position.y = current_scroll_position.y;
3928 }
3929
3930 if scroll_position != current_scroll_position {
3931 editor.scroll(scroll_position, axis, cx);
3932 cx.stop_propagation();
3933 } else if y < 0. {
3934 // Due to clamping, we may fail to detect cases of overscroll to the top;
3935 // We want the scroll manager to get an update in such cases and detect the change of direction
3936 // on the next frame.
3937 cx.notify();
3938 }
3939 });
3940 }
3941 }
3942 });
3943 }
3944
3945 fn paint_mouse_listeners(
3946 &mut self,
3947 layout: &EditorLayout,
3948 hovered_hunk: Option<HoveredHunk>,
3949 cx: &mut WindowContext,
3950 ) {
3951 self.paint_scroll_wheel_listener(layout, cx);
3952
3953 cx.on_mouse_event({
3954 let position_map = layout.position_map.clone();
3955 let editor = self.editor.clone();
3956 let text_hitbox = layout.text_hitbox.clone();
3957 let gutter_hitbox = layout.gutter_hitbox.clone();
3958
3959 move |event: &MouseDownEvent, phase, cx| {
3960 if phase == DispatchPhase::Bubble {
3961 match event.button {
3962 MouseButton::Left => editor.update(cx, |editor, cx| {
3963 Self::mouse_left_down(
3964 editor,
3965 event,
3966 hovered_hunk.clone(),
3967 &position_map,
3968 &text_hitbox,
3969 &gutter_hitbox,
3970 cx,
3971 );
3972 }),
3973 MouseButton::Right => editor.update(cx, |editor, cx| {
3974 Self::mouse_right_down(editor, event, &position_map, &text_hitbox, cx);
3975 }),
3976 MouseButton::Middle => editor.update(cx, |editor, cx| {
3977 Self::mouse_middle_down(editor, event, &position_map, &text_hitbox, cx);
3978 }),
3979 _ => {}
3980 };
3981 }
3982 }
3983 });
3984
3985 cx.on_mouse_event({
3986 let editor = self.editor.clone();
3987 let position_map = layout.position_map.clone();
3988 let text_hitbox = layout.text_hitbox.clone();
3989
3990 move |event: &MouseUpEvent, phase, cx| {
3991 if phase == DispatchPhase::Bubble {
3992 editor.update(cx, |editor, cx| {
3993 Self::mouse_up(editor, event, &position_map, &text_hitbox, cx)
3994 });
3995 }
3996 }
3997 });
3998 cx.on_mouse_event({
3999 let position_map = layout.position_map.clone();
4000 let editor = self.editor.clone();
4001 let text_hitbox = layout.text_hitbox.clone();
4002 let gutter_hitbox = layout.gutter_hitbox.clone();
4003
4004 move |event: &MouseMoveEvent, phase, cx| {
4005 if phase == DispatchPhase::Bubble {
4006 editor.update(cx, |editor, cx| {
4007 if editor.hover_state.focused(cx) {
4008 return;
4009 }
4010 if event.pressed_button == Some(MouseButton::Left)
4011 || event.pressed_button == Some(MouseButton::Middle)
4012 {
4013 Self::mouse_dragged(
4014 editor,
4015 event,
4016 &position_map,
4017 text_hitbox.bounds,
4018 cx,
4019 )
4020 }
4021
4022 Self::mouse_moved(
4023 editor,
4024 event,
4025 &position_map,
4026 &text_hitbox,
4027 &gutter_hitbox,
4028 cx,
4029 )
4030 });
4031 }
4032 }
4033 });
4034 }
4035
4036 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
4037 bounds.upper_right().x - self.style.scrollbar_width
4038 }
4039
4040 fn column_pixels(&self, column: usize, cx: &WindowContext) -> Pixels {
4041 let style = &self.style;
4042 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4043 let layout = cx
4044 .text_system()
4045 .shape_line(
4046 SharedString::from(" ".repeat(column)),
4047 font_size,
4048 &[TextRun {
4049 len: column,
4050 font: style.text.font(),
4051 color: Hsla::default(),
4052 background_color: None,
4053 underline: None,
4054 strikethrough: None,
4055 }],
4056 )
4057 .unwrap();
4058
4059 layout.width
4060 }
4061
4062 fn max_line_number_width(&self, snapshot: &EditorSnapshot, cx: &WindowContext) -> Pixels {
4063 let digit_count = snapshot
4064 .max_buffer_row()
4065 .next_row()
4066 .as_f32()
4067 .log10()
4068 .floor() as usize
4069 + 1;
4070 self.column_pixels(digit_count, cx)
4071 }
4072
4073 #[allow(clippy::too_many_arguments)]
4074 fn layout_hunk_diff_close_indicators(
4075 &self,
4076 line_height: Pixels,
4077 scroll_pixel_position: gpui::Point<Pixels>,
4078 gutter_dimensions: &GutterDimensions,
4079 gutter_hitbox: &Hitbox,
4080 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
4081 expanded_hunks_by_rows: HashMap<DisplayRow, ExpandedHunk>,
4082 cx: &mut WindowContext,
4083 ) -> Vec<AnyElement> {
4084 self.editor.update(cx, |editor, cx| {
4085 expanded_hunks_by_rows
4086 .into_iter()
4087 .map(|(display_row, hunk)| {
4088 let button = editor.close_hunk_diff_button(
4089 HoveredHunk {
4090 multi_buffer_range: hunk.hunk_range,
4091 status: hunk.status,
4092 diff_base_byte_range: hunk.diff_base_byte_range,
4093 },
4094 display_row,
4095 cx,
4096 );
4097
4098 prepaint_gutter_button(
4099 button,
4100 display_row,
4101 line_height,
4102 gutter_dimensions,
4103 scroll_pixel_position,
4104 gutter_hitbox,
4105 rows_with_hunk_bounds,
4106 cx,
4107 )
4108 })
4109 .collect()
4110 })
4111 }
4112}
4113
4114#[allow(clippy::too_many_arguments)]
4115fn prepaint_gutter_button(
4116 button: IconButton,
4117 row: DisplayRow,
4118 line_height: Pixels,
4119 gutter_dimensions: &GutterDimensions,
4120 scroll_pixel_position: gpui::Point<Pixels>,
4121 gutter_hitbox: &Hitbox,
4122 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
4123 cx: &mut WindowContext<'_>,
4124) -> AnyElement {
4125 let mut button = button.into_any_element();
4126 let available_space = size(
4127 AvailableSpace::MinContent,
4128 AvailableSpace::Definite(line_height),
4129 );
4130 let indicator_size = button.layout_as_root(available_space, cx);
4131
4132 let blame_width = gutter_dimensions.git_blame_entries_width;
4133 let gutter_width = rows_with_hunk_bounds
4134 .get(&row)
4135 .map(|bounds| bounds.size.width);
4136 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
4137
4138 let mut x = left_offset;
4139 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
4140 - indicator_size.width
4141 - left_offset;
4142 x += available_width / 2.;
4143
4144 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
4145 y += (line_height - indicator_size.height) / 2.;
4146
4147 button.prepaint_as_root(gutter_hitbox.origin + point(x, y), available_space, cx);
4148 button
4149}
4150
4151fn render_inline_blame_entry(
4152 blame: &gpui::Model<GitBlame>,
4153 blame_entry: BlameEntry,
4154 style: &EditorStyle,
4155 workspace: Option<WeakView<Workspace>>,
4156 cx: &mut WindowContext<'_>,
4157) -> AnyElement {
4158 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4159
4160 let author = blame_entry.author.as_deref().unwrap_or_default();
4161 let text = format!("{}, {}", author, relative_timestamp);
4162
4163 let details = blame.read(cx).details_for_entry(&blame_entry);
4164
4165 let tooltip = cx.new_view(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
4166
4167 h_flex()
4168 .id("inline-blame")
4169 .w_full()
4170 .font_family(style.text.font().family)
4171 .text_color(cx.theme().status().hint)
4172 .line_height(style.text.line_height)
4173 .child(Icon::new(IconName::FileGit).color(Color::Hint))
4174 .child(text)
4175 .gap_2()
4176 .hoverable_tooltip(move |_| tooltip.clone().into())
4177 .into_any()
4178}
4179
4180fn render_blame_entry(
4181 ix: usize,
4182 blame: &gpui::Model<GitBlame>,
4183 blame_entry: BlameEntry,
4184 style: &EditorStyle,
4185 last_used_color: &mut Option<(PlayerColor, Oid)>,
4186 editor: View<Editor>,
4187 cx: &mut WindowContext<'_>,
4188) -> AnyElement {
4189 let mut sha_color = cx
4190 .theme()
4191 .players()
4192 .color_for_participant(blame_entry.sha.into());
4193 // If the last color we used is the same as the one we get for this line, but
4194 // the commit SHAs are different, then we try again to get a different color.
4195 match *last_used_color {
4196 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
4197 let index: u32 = blame_entry.sha.into();
4198 sha_color = cx.theme().players().color_for_participant(index + 1);
4199 }
4200 _ => {}
4201 };
4202 last_used_color.replace((sha_color, blame_entry.sha));
4203
4204 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
4205
4206 let short_commit_id = blame_entry.sha.display_short();
4207
4208 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
4209 let name = util::truncate_and_trailoff(author_name, 20);
4210
4211 let details = blame.read(cx).details_for_entry(&blame_entry);
4212
4213 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
4214
4215 let tooltip = cx.new_view(|_| {
4216 BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace)
4217 });
4218
4219 h_flex()
4220 .w_full()
4221 .font_family(style.text.font().family)
4222 .line_height(style.text.line_height)
4223 .id(("blame", ix))
4224 .children([
4225 div()
4226 .text_color(sha_color.cursor)
4227 .child(short_commit_id)
4228 .mr_2(),
4229 div()
4230 .w_full()
4231 .h_flex()
4232 .justify_between()
4233 .text_color(cx.theme().status().hint)
4234 .child(name)
4235 .child(relative_timestamp),
4236 ])
4237 .on_mouse_down(MouseButton::Right, {
4238 let blame_entry = blame_entry.clone();
4239 let details = details.clone();
4240 move |event, cx| {
4241 deploy_blame_entry_context_menu(
4242 &blame_entry,
4243 details.as_ref(),
4244 editor.clone(),
4245 event.position,
4246 cx,
4247 );
4248 }
4249 })
4250 .hover(|style| style.bg(cx.theme().colors().element_hover))
4251 .when_some(
4252 details.and_then(|details| details.permalink),
4253 |this, url| {
4254 let url = url.clone();
4255 this.cursor_pointer().on_click(move |_, cx| {
4256 cx.stop_propagation();
4257 cx.open_url(url.as_str())
4258 })
4259 },
4260 )
4261 .hoverable_tooltip(move |_| tooltip.clone().into())
4262 .into_any()
4263}
4264
4265fn deploy_blame_entry_context_menu(
4266 blame_entry: &BlameEntry,
4267 details: Option<&CommitDetails>,
4268 editor: View<Editor>,
4269 position: gpui::Point<Pixels>,
4270 cx: &mut WindowContext<'_>,
4271) {
4272 let context_menu = ContextMenu::build(cx, move |menu, _| {
4273 let sha = format!("{}", blame_entry.sha);
4274 menu.on_blur_subscription(Subscription::new(|| {}))
4275 .entry("Copy commit SHA", None, move |cx| {
4276 cx.write_to_clipboard(ClipboardItem::new(sha.clone()));
4277 })
4278 .when_some(
4279 details.and_then(|details| details.permalink.clone()),
4280 |this, url| this.entry("Open permalink", None, move |cx| cx.open_url(url.as_str())),
4281 )
4282 });
4283
4284 editor.update(cx, move |editor, cx| {
4285 editor.mouse_context_menu = Some(MouseContextMenu::pinned_to_screen(
4286 position,
4287 context_menu,
4288 cx,
4289 ));
4290 cx.notify();
4291 });
4292}
4293
4294#[derive(Debug)]
4295pub(crate) struct LineWithInvisibles {
4296 fragments: SmallVec<[LineFragment; 1]>,
4297 invisibles: Vec<Invisible>,
4298 len: usize,
4299 width: Pixels,
4300 font_size: Pixels,
4301}
4302
4303#[allow(clippy::large_enum_variant)]
4304enum LineFragment {
4305 Text(ShapedLine),
4306 Element {
4307 element: Option<AnyElement>,
4308 size: Size<Pixels>,
4309 len: usize,
4310 },
4311}
4312
4313impl fmt::Debug for LineFragment {
4314 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4315 match self {
4316 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
4317 LineFragment::Element { size, len, .. } => f
4318 .debug_struct("Element")
4319 .field("size", size)
4320 .field("len", len)
4321 .finish(),
4322 }
4323 }
4324}
4325
4326impl LineWithInvisibles {
4327 fn from_chunks<'a>(
4328 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
4329 text_style: &TextStyle,
4330 max_line_len: usize,
4331 max_line_count: usize,
4332 line_number_layouts: &[Option<ShapedLine>],
4333 editor_mode: EditorMode,
4334 cx: &mut WindowContext,
4335 ) -> Vec<Self> {
4336 let mut layouts = Vec::with_capacity(max_line_count);
4337 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
4338 let mut line = String::new();
4339 let mut invisibles = Vec::new();
4340 let mut width = Pixels::ZERO;
4341 let mut len = 0;
4342 let mut styles = Vec::new();
4343 let mut non_whitespace_added = false;
4344 let mut row = 0;
4345 let mut line_exceeded_max_len = false;
4346 let font_size = text_style.font_size.to_pixels(cx.rem_size());
4347
4348 let ellipsis = SharedString::from("⋯");
4349
4350 for highlighted_chunk in chunks.chain([HighlightedChunk {
4351 text: "\n",
4352 style: None,
4353 is_tab: false,
4354 renderer: None,
4355 }]) {
4356 if let Some(renderer) = highlighted_chunk.renderer {
4357 if !line.is_empty() {
4358 let shaped_line = cx
4359 .text_system()
4360 .shape_line(line.clone().into(), font_size, &styles)
4361 .unwrap();
4362 width += shaped_line.width;
4363 len += shaped_line.len;
4364 fragments.push(LineFragment::Text(shaped_line));
4365 line.clear();
4366 styles.clear();
4367 }
4368
4369 let available_width = if renderer.constrain_width {
4370 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
4371 ellipsis.clone()
4372 } else {
4373 SharedString::from(Arc::from(highlighted_chunk.text))
4374 };
4375 let shaped_line = cx
4376 .text_system()
4377 .shape_line(
4378 chunk,
4379 font_size,
4380 &[text_style.to_run(highlighted_chunk.text.len())],
4381 )
4382 .unwrap();
4383 AvailableSpace::Definite(shaped_line.width)
4384 } else {
4385 AvailableSpace::MinContent
4386 };
4387
4388 let mut element = (renderer.render)(cx);
4389 let line_height = text_style.line_height_in_pixels(cx.rem_size());
4390 let size = element.layout_as_root(
4391 size(available_width, AvailableSpace::Definite(line_height)),
4392 cx,
4393 );
4394
4395 width += size.width;
4396 len += highlighted_chunk.text.len();
4397 fragments.push(LineFragment::Element {
4398 element: Some(element),
4399 size,
4400 len: highlighted_chunk.text.len(),
4401 });
4402 } else {
4403 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
4404 if ix > 0 {
4405 let shaped_line = cx
4406 .text_system()
4407 .shape_line(line.clone().into(), font_size, &styles)
4408 .unwrap();
4409 width += shaped_line.width;
4410 len += shaped_line.len;
4411 fragments.push(LineFragment::Text(shaped_line));
4412 layouts.push(Self {
4413 width: mem::take(&mut width),
4414 len: mem::take(&mut len),
4415 fragments: mem::take(&mut fragments),
4416 invisibles: std::mem::take(&mut invisibles),
4417 font_size,
4418 });
4419
4420 line.clear();
4421 styles.clear();
4422 row += 1;
4423 line_exceeded_max_len = false;
4424 non_whitespace_added = false;
4425 if row == max_line_count {
4426 return layouts;
4427 }
4428 }
4429
4430 if !line_chunk.is_empty() && !line_exceeded_max_len {
4431 let text_style = if let Some(style) = highlighted_chunk.style {
4432 Cow::Owned(text_style.clone().highlight(style))
4433 } else {
4434 Cow::Borrowed(text_style)
4435 };
4436
4437 if line.len() + line_chunk.len() > max_line_len {
4438 let mut chunk_len = max_line_len - line.len();
4439 while !line_chunk.is_char_boundary(chunk_len) {
4440 chunk_len -= 1;
4441 }
4442 line_chunk = &line_chunk[..chunk_len];
4443 line_exceeded_max_len = true;
4444 }
4445
4446 styles.push(TextRun {
4447 len: line_chunk.len(),
4448 font: text_style.font(),
4449 color: text_style.color,
4450 background_color: text_style.background_color,
4451 underline: text_style.underline,
4452 strikethrough: text_style.strikethrough,
4453 });
4454
4455 if editor_mode == EditorMode::Full {
4456 // Line wrap pads its contents with fake whitespaces,
4457 // avoid printing them
4458 let inside_wrapped_string = line_number_layouts
4459 .get(row)
4460 .and_then(|layout| layout.as_ref())
4461 .is_none();
4462 if highlighted_chunk.is_tab {
4463 if non_whitespace_added || !inside_wrapped_string {
4464 invisibles.push(Invisible::Tab {
4465 line_start_offset: line.len(),
4466 line_end_offset: line.len() + line_chunk.len(),
4467 });
4468 }
4469 } else {
4470 invisibles.extend(
4471 line_chunk
4472 .bytes()
4473 .enumerate()
4474 .filter(|(_, line_byte)| {
4475 let is_whitespace =
4476 (*line_byte as char).is_whitespace();
4477 non_whitespace_added |= !is_whitespace;
4478 is_whitespace
4479 && (non_whitespace_added || !inside_wrapped_string)
4480 })
4481 .map(|(whitespace_index, _)| Invisible::Whitespace {
4482 line_offset: line.len() + whitespace_index,
4483 }),
4484 )
4485 }
4486 }
4487
4488 line.push_str(line_chunk);
4489 }
4490 }
4491 }
4492 }
4493
4494 layouts
4495 }
4496
4497 fn prepaint(
4498 &mut self,
4499 line_height: Pixels,
4500 scroll_pixel_position: gpui::Point<Pixels>,
4501 row: DisplayRow,
4502 content_origin: gpui::Point<Pixels>,
4503 line_elements: &mut SmallVec<[AnyElement; 1]>,
4504 cx: &mut WindowContext,
4505 ) {
4506 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
4507 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
4508 for fragment in &mut self.fragments {
4509 match fragment {
4510 LineFragment::Text(line) => {
4511 fragment_origin.x += line.width;
4512 }
4513 LineFragment::Element { element, size, .. } => {
4514 let mut element = element
4515 .take()
4516 .expect("you can't prepaint LineWithInvisibles twice");
4517
4518 // Center the element vertically within the line.
4519 let mut element_origin = fragment_origin;
4520 element_origin.y += (line_height - size.height) / 2.;
4521 element.prepaint_at(element_origin, cx);
4522 line_elements.push(element);
4523
4524 fragment_origin.x += size.width;
4525 }
4526 }
4527 }
4528 }
4529
4530 fn draw(
4531 &self,
4532 layout: &EditorLayout,
4533 row: DisplayRow,
4534 content_origin: gpui::Point<Pixels>,
4535 whitespace_setting: ShowWhitespaceSetting,
4536 selection_ranges: &[Range<DisplayPoint>],
4537 cx: &mut WindowContext,
4538 ) {
4539 let line_height = layout.position_map.line_height;
4540 let line_y = line_height
4541 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
4542
4543 let mut fragment_origin =
4544 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
4545
4546 for fragment in &self.fragments {
4547 match fragment {
4548 LineFragment::Text(line) => {
4549 line.paint(fragment_origin, line_height, cx).log_err();
4550 fragment_origin.x += line.width;
4551 }
4552 LineFragment::Element { size, .. } => {
4553 fragment_origin.x += size.width;
4554 }
4555 }
4556 }
4557
4558 self.draw_invisibles(
4559 &selection_ranges,
4560 layout,
4561 content_origin,
4562 line_y,
4563 row,
4564 line_height,
4565 whitespace_setting,
4566 cx,
4567 );
4568 }
4569
4570 #[allow(clippy::too_many_arguments)]
4571 fn draw_invisibles(
4572 &self,
4573 selection_ranges: &[Range<DisplayPoint>],
4574 layout: &EditorLayout,
4575 content_origin: gpui::Point<Pixels>,
4576 line_y: Pixels,
4577 row: DisplayRow,
4578 line_height: Pixels,
4579 whitespace_setting: ShowWhitespaceSetting,
4580 cx: &mut WindowContext,
4581 ) {
4582 let extract_whitespace_info = |invisible: &Invisible| {
4583 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
4584 Invisible::Tab {
4585 line_start_offset,
4586 line_end_offset,
4587 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
4588 Invisible::Whitespace { line_offset } => {
4589 (*line_offset, line_offset + 1, &layout.space_invisible)
4590 }
4591 };
4592
4593 let x_offset = self.x_for_index(token_offset);
4594 let invisible_offset =
4595 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
4596 let origin = content_origin
4597 + gpui::point(
4598 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
4599 line_y,
4600 );
4601
4602 (
4603 [token_offset, token_end_offset],
4604 Box::new(move |cx: &mut WindowContext| {
4605 invisible_symbol.paint(origin, line_height, cx).log_err();
4606 }),
4607 )
4608 };
4609
4610 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
4611 match whitespace_setting {
4612 ShowWhitespaceSetting::None => return,
4613 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(cx)),
4614 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
4615 let invisible_point = DisplayPoint::new(row, start as u32);
4616 if !selection_ranges
4617 .iter()
4618 .any(|region| region.start <= invisible_point && invisible_point < region.end)
4619 {
4620 return;
4621 }
4622
4623 paint(cx);
4624 }),
4625
4626 // For a whitespace to be on a boundary, any of the following conditions need to be met:
4627 // - It is a tab
4628 // - It is adjacent to an edge (start or end)
4629 // - It is adjacent to a whitespace (left or right)
4630 ShowWhitespaceSetting::Boundary => {
4631 // 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
4632 // the above cases.
4633 // Note: We zip in the original `invisibles` to check for tab equality
4634 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut WindowContext)>)> = None;
4635 for (([start, end], paint), invisible) in
4636 invisible_iter.zip_eq(self.invisibles.iter())
4637 {
4638 let should_render = match (&last_seen, invisible) {
4639 (_, Invisible::Tab { .. }) => true,
4640 (Some((_, last_end, _)), _) => *last_end == start,
4641 _ => false,
4642 };
4643
4644 if should_render || start == 0 || end == self.len {
4645 paint(cx);
4646
4647 // Since we are scanning from the left, we will skip over the first available whitespace that is part
4648 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
4649 if let Some((should_render_last, last_end, paint_last)) = last_seen {
4650 // Note that we need to make sure that the last one is actually adjacent
4651 if !should_render_last && last_end == start {
4652 paint_last(cx);
4653 }
4654 }
4655 }
4656
4657 // Manually render anything within a selection
4658 let invisible_point = DisplayPoint::new(row, start as u32);
4659 if selection_ranges.iter().any(|region| {
4660 region.start <= invisible_point && invisible_point < region.end
4661 }) {
4662 paint(cx);
4663 }
4664
4665 last_seen = Some((should_render, end, paint));
4666 }
4667 }
4668 };
4669 }
4670
4671 pub fn x_for_index(&self, index: usize) -> Pixels {
4672 let mut fragment_start_x = Pixels::ZERO;
4673 let mut fragment_start_index = 0;
4674
4675 for fragment in &self.fragments {
4676 match fragment {
4677 LineFragment::Text(shaped_line) => {
4678 let fragment_end_index = fragment_start_index + shaped_line.len;
4679 if index < fragment_end_index {
4680 return fragment_start_x
4681 + shaped_line.x_for_index(index - fragment_start_index);
4682 }
4683 fragment_start_x += shaped_line.width;
4684 fragment_start_index = fragment_end_index;
4685 }
4686 LineFragment::Element { len, size, .. } => {
4687 let fragment_end_index = fragment_start_index + len;
4688 if index < fragment_end_index {
4689 return fragment_start_x;
4690 }
4691 fragment_start_x += size.width;
4692 fragment_start_index = fragment_end_index;
4693 }
4694 }
4695 }
4696
4697 fragment_start_x
4698 }
4699
4700 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
4701 let mut fragment_start_x = Pixels::ZERO;
4702 let mut fragment_start_index = 0;
4703
4704 for fragment in &self.fragments {
4705 match fragment {
4706 LineFragment::Text(shaped_line) => {
4707 let fragment_end_x = fragment_start_x + shaped_line.width;
4708 if x < fragment_end_x {
4709 return Some(
4710 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
4711 );
4712 }
4713 fragment_start_x = fragment_end_x;
4714 fragment_start_index += shaped_line.len;
4715 }
4716 LineFragment::Element { len, size, .. } => {
4717 let fragment_end_x = fragment_start_x + size.width;
4718 if x < fragment_end_x {
4719 return Some(fragment_start_index);
4720 }
4721 fragment_start_index += len;
4722 fragment_start_x = fragment_end_x;
4723 }
4724 }
4725 }
4726
4727 None
4728 }
4729
4730 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
4731 let mut fragment_start_index = 0;
4732
4733 for fragment in &self.fragments {
4734 match fragment {
4735 LineFragment::Text(shaped_line) => {
4736 let fragment_end_index = fragment_start_index + shaped_line.len;
4737 if index < fragment_end_index {
4738 return shaped_line.font_id_for_index(index - fragment_start_index);
4739 }
4740 fragment_start_index = fragment_end_index;
4741 }
4742 LineFragment::Element { len, .. } => {
4743 let fragment_end_index = fragment_start_index + len;
4744 if index < fragment_end_index {
4745 return None;
4746 }
4747 fragment_start_index = fragment_end_index;
4748 }
4749 }
4750 }
4751
4752 None
4753 }
4754}
4755
4756#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4757enum Invisible {
4758 /// A tab character
4759 ///
4760 /// A tab character is internally represented by spaces (configured by the user's tab width)
4761 /// aligned to the nearest column, so it's necessary to store the start and end offset for
4762 /// adjacency checks.
4763 Tab {
4764 line_start_offset: usize,
4765 line_end_offset: usize,
4766 },
4767 Whitespace {
4768 line_offset: usize,
4769 },
4770}
4771
4772impl EditorElement {
4773 /// Returns the rem size to use when rendering the [`EditorElement`].
4774 ///
4775 /// This allows UI elements to scale based on the `buffer_font_size`.
4776 fn rem_size(&self, cx: &WindowContext) -> Option<Pixels> {
4777 match self.editor.read(cx).mode {
4778 EditorMode::Full => {
4779 let buffer_font_size = self.style.text.font_size;
4780 match buffer_font_size {
4781 AbsoluteLength::Pixels(pixels) => {
4782 let rem_size_scale = {
4783 // Our default UI font size is 14px on a 16px base scale.
4784 // This means the default UI font size is 0.875rems.
4785 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
4786
4787 // We then determine the delta between a single rem and the default font
4788 // size scale.
4789 let default_font_size_delta = 1. - default_font_size_scale;
4790
4791 // Finally, we add this delta to 1rem to get the scale factor that
4792 // should be used to scale up the UI.
4793 1. + default_font_size_delta
4794 };
4795
4796 Some(pixels * rem_size_scale)
4797 }
4798 AbsoluteLength::Rems(rems) => {
4799 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
4800 }
4801 }
4802 }
4803 // We currently use single-line and auto-height editors in UI contexts,
4804 // so we don't want to scale everything with the buffer font size, as it
4805 // ends up looking off.
4806 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
4807 }
4808 }
4809}
4810
4811impl Element for EditorElement {
4812 type RequestLayoutState = ();
4813 type PrepaintState = EditorLayout;
4814
4815 fn id(&self) -> Option<ElementId> {
4816 None
4817 }
4818
4819 fn request_layout(
4820 &mut self,
4821 _: Option<&GlobalElementId>,
4822 cx: &mut WindowContext,
4823 ) -> (gpui::LayoutId, ()) {
4824 let rem_size = self.rem_size(cx);
4825 cx.with_rem_size(rem_size, |cx| {
4826 self.editor.update(cx, |editor, cx| {
4827 editor.set_style(self.style.clone(), cx);
4828
4829 let layout_id = match editor.mode {
4830 EditorMode::SingleLine { auto_width } => {
4831 let rem_size = cx.rem_size();
4832
4833 let height = self.style.text.line_height_in_pixels(rem_size);
4834 if auto_width {
4835 let editor_handle = cx.view().clone();
4836 let style = self.style.clone();
4837 cx.request_measured_layout(Style::default(), move |_, _, cx| {
4838 let editor_snapshot =
4839 editor_handle.update(cx, |editor, cx| editor.snapshot(cx));
4840 let line = Self::layout_lines(
4841 DisplayRow(0)..DisplayRow(1),
4842 &[],
4843 &editor_snapshot,
4844 &style,
4845 cx,
4846 )
4847 .pop()
4848 .unwrap();
4849
4850 let font_id = cx.text_system().resolve_font(&style.text.font());
4851 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4852 let em_width = cx
4853 .text_system()
4854 .typographic_bounds(font_id, font_size, 'm')
4855 .unwrap()
4856 .size
4857 .width;
4858
4859 size(line.width + em_width, height)
4860 })
4861 } else {
4862 let mut style = Style::default();
4863 style.size.height = height.into();
4864 style.size.width = relative(1.).into();
4865 cx.request_layout(style, None)
4866 }
4867 }
4868 EditorMode::AutoHeight { max_lines } => {
4869 let editor_handle = cx.view().clone();
4870 let max_line_number_width =
4871 self.max_line_number_width(&editor.snapshot(cx), cx);
4872 cx.request_measured_layout(
4873 Style::default(),
4874 move |known_dimensions, available_space, cx| {
4875 editor_handle
4876 .update(cx, |editor, cx| {
4877 compute_auto_height_layout(
4878 editor,
4879 max_lines,
4880 max_line_number_width,
4881 known_dimensions,
4882 available_space.width,
4883 cx,
4884 )
4885 })
4886 .unwrap_or_default()
4887 },
4888 )
4889 }
4890 EditorMode::Full => {
4891 let mut style = Style::default();
4892 style.size.width = relative(1.).into();
4893 style.size.height = relative(1.).into();
4894 cx.request_layout(style, None)
4895 }
4896 };
4897
4898 (layout_id, ())
4899 })
4900 })
4901 }
4902
4903 fn prepaint(
4904 &mut self,
4905 _: Option<&GlobalElementId>,
4906 bounds: Bounds<Pixels>,
4907 _: &mut Self::RequestLayoutState,
4908 cx: &mut WindowContext,
4909 ) -> Self::PrepaintState {
4910 let text_style = TextStyleRefinement {
4911 font_size: Some(self.style.text.font_size),
4912 line_height: Some(self.style.text.line_height),
4913 ..Default::default()
4914 };
4915 let focus_handle = self.editor.focus_handle(cx);
4916 cx.set_view_id(self.editor.entity_id());
4917 cx.set_focus_handle(&focus_handle);
4918
4919 let rem_size = self.rem_size(cx);
4920 cx.with_rem_size(rem_size, |cx| {
4921 cx.with_text_style(Some(text_style), |cx| {
4922 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
4923 let mut snapshot = self.editor.update(cx, |editor, cx| editor.snapshot(cx));
4924 let style = self.style.clone();
4925
4926 let font_id = cx.text_system().resolve_font(&style.text.font());
4927 let font_size = style.text.font_size.to_pixels(cx.rem_size());
4928 let line_height = style.text.line_height_in_pixels(cx.rem_size());
4929 let em_width = cx
4930 .text_system()
4931 .typographic_bounds(font_id, font_size, 'm')
4932 .unwrap()
4933 .size
4934 .width;
4935 let em_advance = cx
4936 .text_system()
4937 .advance(font_id, font_size, 'm')
4938 .unwrap()
4939 .width;
4940
4941 let gutter_dimensions = snapshot.gutter_dimensions(
4942 font_id,
4943 font_size,
4944 em_width,
4945 self.max_line_number_width(&snapshot, cx),
4946 cx,
4947 );
4948 let text_width = bounds.size.width - gutter_dimensions.width;
4949
4950 let right_margin = if snapshot.mode == EditorMode::Full {
4951 EditorElement::SCROLLBAR_WIDTH
4952 } else {
4953 px(0.)
4954 };
4955 let overscroll = size(em_width + right_margin, px(0.));
4956
4957 snapshot = self.editor.update(cx, |editor, cx| {
4958 editor.last_bounds = Some(bounds);
4959 editor.gutter_dimensions = gutter_dimensions;
4960 editor.set_visible_line_count(bounds.size.height / line_height, cx);
4961
4962 if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
4963 snapshot
4964 } else {
4965 let editor_width =
4966 text_width - gutter_dimensions.margin - overscroll.width - em_width;
4967 let wrap_width = match editor.soft_wrap_mode(cx) {
4968 SoftWrap::None => None,
4969 SoftWrap::PreferLine => {
4970 Some((MAX_LINE_LEN / 2) as f32 * em_advance)
4971 }
4972 SoftWrap::EditorWidth => Some(editor_width),
4973 SoftWrap::Column(column) => {
4974 Some(editor_width.min(column as f32 * em_advance))
4975 }
4976 };
4977
4978 if editor.set_wrap_width(wrap_width, cx) {
4979 editor.snapshot(cx)
4980 } else {
4981 snapshot
4982 }
4983 }
4984 });
4985
4986 let wrap_guides = self
4987 .editor
4988 .read(cx)
4989 .wrap_guides(cx)
4990 .iter()
4991 .map(|(guide, active)| (self.column_pixels(*guide, cx), *active))
4992 .collect::<SmallVec<[_; 2]>>();
4993
4994 let hitbox = cx.insert_hitbox(bounds, false);
4995 let gutter_hitbox =
4996 cx.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
4997 let text_hitbox = cx.insert_hitbox(
4998 Bounds {
4999 origin: gutter_hitbox.upper_right(),
5000 size: size(text_width, bounds.size.height),
5001 },
5002 false,
5003 );
5004 // Offset the content_bounds from the text_bounds by the gutter margin (which
5005 // is roughly half a character wide) to make hit testing work more like how we want.
5006 let content_origin =
5007 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
5008
5009 let height_in_lines = bounds.size.height / line_height;
5010 let max_row = snapshot.max_point().row().as_f32();
5011 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
5012 (max_row - height_in_lines + 1.).max(0.)
5013 } else {
5014 let settings = EditorSettings::get_global(cx);
5015 match settings.scroll_beyond_last_line {
5016 ScrollBeyondLastLine::OnePage => max_row,
5017 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
5018 ScrollBeyondLastLine::VerticalScrollMargin => {
5019 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
5020 .max(0.)
5021 }
5022 }
5023 };
5024
5025 let mut autoscroll_request = None;
5026 let mut autoscroll_containing_element = false;
5027 let mut autoscroll_horizontally = false;
5028 self.editor.update(cx, |editor, cx| {
5029 autoscroll_request = editor.autoscroll_request();
5030 autoscroll_containing_element =
5031 autoscroll_request.is_some() || editor.has_pending_selection();
5032 autoscroll_horizontally =
5033 editor.autoscroll_vertically(bounds, line_height, max_scroll_top, cx);
5034 snapshot = editor.snapshot(cx);
5035 });
5036
5037 let mut scroll_position = snapshot.scroll_position();
5038 // The scroll position is a fractional point, the whole number of which represents
5039 // the top of the window in terms of display rows.
5040 let start_row = DisplayRow(scroll_position.y as u32);
5041 let max_row = snapshot.max_point().row();
5042 let end_row = cmp::min(
5043 (scroll_position.y + height_in_lines).ceil() as u32,
5044 max_row.next_row().0,
5045 );
5046 let end_row = DisplayRow(end_row);
5047
5048 let buffer_rows = snapshot
5049 .buffer_rows(start_row)
5050 .take((start_row..end_row).len())
5051 .collect::<Vec<_>>();
5052
5053 let start_anchor = if start_row == Default::default() {
5054 Anchor::min()
5055 } else {
5056 snapshot.buffer_snapshot.anchor_before(
5057 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
5058 )
5059 };
5060 let end_anchor = if end_row > max_row {
5061 Anchor::max()
5062 } else {
5063 snapshot.buffer_snapshot.anchor_before(
5064 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
5065 )
5066 };
5067
5068 let highlighted_rows = self
5069 .editor
5070 .update(cx, |editor, cx| editor.highlighted_display_rows(cx));
5071 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
5072 start_anchor..end_anchor,
5073 &snapshot.display_snapshot,
5074 cx.theme().colors(),
5075 );
5076 let highlighted_gutter_ranges =
5077 self.editor.read(cx).gutter_highlights_in_range(
5078 start_anchor..end_anchor,
5079 &snapshot.display_snapshot,
5080 cx,
5081 );
5082
5083 let redacted_ranges = self.editor.read(cx).redacted_ranges(
5084 start_anchor..end_anchor,
5085 &snapshot.display_snapshot,
5086 cx,
5087 );
5088
5089 let (selections, active_rows, newest_selection_head) = self.layout_selections(
5090 start_anchor,
5091 end_anchor,
5092 &snapshot,
5093 start_row,
5094 end_row,
5095 cx,
5096 );
5097
5098 let line_numbers = self.layout_line_numbers(
5099 start_row..end_row,
5100 buffer_rows.iter().copied(),
5101 &active_rows,
5102 newest_selection_head,
5103 &snapshot,
5104 cx,
5105 );
5106
5107 let mut gutter_fold_toggles =
5108 cx.with_element_namespace("gutter_fold_toggles", |cx| {
5109 self.layout_gutter_fold_toggles(
5110 start_row..end_row,
5111 buffer_rows.iter().copied(),
5112 &active_rows,
5113 &snapshot,
5114 cx,
5115 )
5116 });
5117 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5118 self.layout_crease_trailers(buffer_rows.iter().copied(), &snapshot, cx)
5119 });
5120
5121 let display_hunks = self.layout_gutter_git_hunks(
5122 line_height,
5123 &gutter_hitbox,
5124 start_row..end_row,
5125 &snapshot,
5126 cx,
5127 );
5128
5129 let mut max_visible_line_width = Pixels::ZERO;
5130 let mut line_layouts = Self::layout_lines(
5131 start_row..end_row,
5132 &line_numbers,
5133 &snapshot,
5134 &self.style,
5135 cx,
5136 );
5137 for line_with_invisibles in &line_layouts {
5138 if line_with_invisibles.width > max_visible_line_width {
5139 max_visible_line_width = line_with_invisibles.width;
5140 }
5141 }
5142
5143 let longest_line_width =
5144 layout_line(snapshot.longest_row(), &snapshot, &style, cx).width;
5145 let mut scroll_width =
5146 longest_line_width.max(max_visible_line_width) + overscroll.width;
5147
5148 let blocks = cx.with_element_namespace("blocks", |cx| {
5149 self.render_blocks(
5150 start_row..end_row,
5151 &snapshot,
5152 &hitbox,
5153 &text_hitbox,
5154 &mut scroll_width,
5155 &gutter_dimensions,
5156 em_width,
5157 gutter_dimensions.full_width(),
5158 line_height,
5159 &line_layouts,
5160 cx,
5161 )
5162 });
5163 let mut blocks = match blocks {
5164 Ok(blocks) => blocks,
5165 Err(resized_blocks) => {
5166 self.editor.update(cx, |editor, cx| {
5167 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
5168 });
5169 return self.prepaint(None, bounds, &mut (), cx);
5170 }
5171 };
5172
5173 let start_buffer_row =
5174 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
5175 let end_buffer_row =
5176 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
5177
5178 let scroll_max = point(
5179 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5180 max_row.as_f32(),
5181 );
5182
5183 self.editor.update(cx, |editor, cx| {
5184 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5185
5186 let autoscrolled = if autoscroll_horizontally {
5187 editor.autoscroll_horizontally(
5188 start_row,
5189 text_hitbox.size.width,
5190 scroll_width,
5191 em_width,
5192 &line_layouts,
5193 cx,
5194 )
5195 } else {
5196 false
5197 };
5198
5199 if clamped || autoscrolled {
5200 snapshot = editor.snapshot(cx);
5201 scroll_position = snapshot.scroll_position();
5202 }
5203 });
5204
5205 let scroll_pixel_position = point(
5206 scroll_position.x * em_width,
5207 scroll_position.y * line_height,
5208 );
5209
5210 let indent_guides = self.layout_indent_guides(
5211 content_origin,
5212 text_hitbox.origin,
5213 start_buffer_row..end_buffer_row,
5214 scroll_pixel_position,
5215 line_height,
5216 &snapshot,
5217 cx,
5218 );
5219
5220 let crease_trailers = cx.with_element_namespace("crease_trailers", |cx| {
5221 self.prepaint_crease_trailers(
5222 crease_trailers,
5223 &line_layouts,
5224 line_height,
5225 content_origin,
5226 scroll_pixel_position,
5227 em_width,
5228 cx,
5229 )
5230 });
5231
5232 let mut inline_blame = None;
5233 if let Some(newest_selection_head) = newest_selection_head {
5234 let display_row = newest_selection_head.row();
5235 if (start_row..end_row).contains(&display_row) {
5236 let line_ix = display_row.minus(start_row) as usize;
5237 let line_layout = &line_layouts[line_ix];
5238 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
5239 inline_blame = self.layout_inline_blame(
5240 display_row,
5241 &snapshot.display_snapshot,
5242 line_layout,
5243 crease_trailer_layout,
5244 em_width,
5245 content_origin,
5246 scroll_pixel_position,
5247 line_height,
5248 cx,
5249 );
5250 }
5251 }
5252
5253 let blamed_display_rows = self.layout_blame_entries(
5254 buffer_rows.into_iter(),
5255 em_width,
5256 scroll_position,
5257 line_height,
5258 &gutter_hitbox,
5259 gutter_dimensions.git_blame_entries_width,
5260 cx,
5261 );
5262
5263 let scroll_max = point(
5264 ((scroll_width - text_hitbox.size.width) / em_width).max(0.0),
5265 max_scroll_top,
5266 );
5267
5268 self.editor.update(cx, |editor, cx| {
5269 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
5270
5271 let autoscrolled = if autoscroll_horizontally {
5272 editor.autoscroll_horizontally(
5273 start_row,
5274 text_hitbox.size.width,
5275 scroll_width,
5276 em_width,
5277 &line_layouts,
5278 cx,
5279 )
5280 } else {
5281 false
5282 };
5283
5284 if clamped || autoscrolled {
5285 snapshot = editor.snapshot(cx);
5286 scroll_position = snapshot.scroll_position();
5287 }
5288 });
5289
5290 let line_elements = self.prepaint_lines(
5291 start_row,
5292 &mut line_layouts,
5293 line_height,
5294 scroll_pixel_position,
5295 content_origin,
5296 cx,
5297 );
5298
5299 cx.with_element_namespace("blocks", |cx| {
5300 self.layout_blocks(
5301 &mut blocks,
5302 &hitbox,
5303 line_height,
5304 scroll_pixel_position,
5305 cx,
5306 );
5307 });
5308
5309 let cursors = self.collect_cursors(&snapshot, cx);
5310 let visible_row_range = start_row..end_row;
5311 let non_visible_cursors = cursors
5312 .iter()
5313 .any(move |c| !visible_row_range.contains(&c.0.row()));
5314
5315 let visible_cursors = self.layout_visible_cursors(
5316 &snapshot,
5317 &selections,
5318 start_row..end_row,
5319 &line_layouts,
5320 &text_hitbox,
5321 content_origin,
5322 scroll_position,
5323 scroll_pixel_position,
5324 line_height,
5325 em_width,
5326 autoscroll_containing_element,
5327 cx,
5328 );
5329
5330 let scrollbar_layout = self.layout_scrollbar(
5331 &snapshot,
5332 bounds,
5333 scroll_position,
5334 height_in_lines,
5335 non_visible_cursors,
5336 cx,
5337 );
5338
5339 let gutter_settings = EditorSettings::get_global(cx).gutter;
5340
5341 let expanded_add_hunks_by_rows = self.editor.update(cx, |editor, _| {
5342 editor
5343 .expanded_hunks
5344 .hunks(false)
5345 .filter(|hunk| hunk.status == DiffHunkStatus::Added)
5346 .map(|expanded_hunk| {
5347 let start_row = expanded_hunk
5348 .hunk_range
5349 .start
5350 .to_display_point(&snapshot)
5351 .row();
5352 (start_row, expanded_hunk.clone())
5353 })
5354 .collect::<HashMap<_, _>>()
5355 });
5356
5357 let rows_with_hunk_bounds = display_hunks
5358 .iter()
5359 .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
5360 .fold(
5361 HashMap::default(),
5362 |mut rows_with_hunk_bounds, (hunk, bounds)| {
5363 match hunk {
5364 DisplayDiffHunk::Folded { display_row } => {
5365 rows_with_hunk_bounds.insert(*display_row, bounds);
5366 }
5367 DisplayDiffHunk::Unfolded {
5368 display_row_range, ..
5369 } => {
5370 for display_row in display_row_range.iter_rows() {
5371 rows_with_hunk_bounds.insert(display_row, bounds);
5372 }
5373 }
5374 }
5375 rows_with_hunk_bounds
5376 },
5377 );
5378 let mut _context_menu_visible = false;
5379 let mut code_actions_indicator = None;
5380 if let Some(newest_selection_head) = newest_selection_head {
5381 if (start_row..end_row).contains(&newest_selection_head.row()) {
5382 _context_menu_visible = self.layout_context_menu(
5383 line_height,
5384 &hitbox,
5385 &text_hitbox,
5386 content_origin,
5387 start_row,
5388 scroll_pixel_position,
5389 &line_layouts,
5390 newest_selection_head,
5391 gutter_dimensions.width - gutter_dimensions.left_padding,
5392 cx,
5393 );
5394
5395 let show_code_actions = snapshot
5396 .show_code_actions
5397 .unwrap_or_else(|| gutter_settings.code_actions);
5398 if show_code_actions {
5399 let newest_selection_point =
5400 newest_selection_head.to_point(&snapshot.display_snapshot);
5401 let newest_selection_display_row =
5402 newest_selection_point.to_display_point(&snapshot).row();
5403 if !expanded_add_hunks_by_rows
5404 .contains_key(&newest_selection_display_row)
5405 {
5406 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
5407 MultiBufferRow(newest_selection_point.row),
5408 );
5409 if let Some((buffer, range)) = buffer {
5410 let buffer_id = buffer.remote_id();
5411 let row = range.start.row;
5412 let has_test_indicator = self
5413 .editor
5414 .read(cx)
5415 .tasks
5416 .contains_key(&(buffer_id, row));
5417
5418 if !has_test_indicator {
5419 code_actions_indicator = self
5420 .layout_code_actions_indicator(
5421 line_height,
5422 newest_selection_head,
5423 scroll_pixel_position,
5424 &gutter_dimensions,
5425 &gutter_hitbox,
5426 &rows_with_hunk_bounds,
5427 cx,
5428 );
5429 }
5430 }
5431 }
5432 }
5433 }
5434 }
5435
5436 let test_indicators = if gutter_settings.runnables {
5437 self.layout_run_indicators(
5438 line_height,
5439 scroll_pixel_position,
5440 &gutter_dimensions,
5441 &gutter_hitbox,
5442 &rows_with_hunk_bounds,
5443 &snapshot,
5444 cx,
5445 )
5446 } else {
5447 Vec::new()
5448 };
5449
5450 let close_indicators = self.layout_hunk_diff_close_indicators(
5451 line_height,
5452 scroll_pixel_position,
5453 &gutter_dimensions,
5454 &gutter_hitbox,
5455 &rows_with_hunk_bounds,
5456 expanded_add_hunks_by_rows,
5457 cx,
5458 );
5459
5460 self.layout_signature_help(
5461 &hitbox,
5462 content_origin,
5463 scroll_pixel_position,
5464 newest_selection_head,
5465 start_row,
5466 &line_layouts,
5467 line_height,
5468 em_width,
5469 cx,
5470 );
5471
5472 if !cx.has_active_drag() {
5473 self.layout_hover_popovers(
5474 &snapshot,
5475 &hitbox,
5476 &text_hitbox,
5477 start_row..end_row,
5478 content_origin,
5479 scroll_pixel_position,
5480 &line_layouts,
5481 line_height,
5482 em_width,
5483 cx,
5484 );
5485 }
5486
5487 let mouse_context_menu =
5488 self.layout_mouse_context_menu(&snapshot, start_row..end_row, cx);
5489
5490 cx.with_element_namespace("gutter_fold_toggles", |cx| {
5491 self.prepaint_gutter_fold_toggles(
5492 &mut gutter_fold_toggles,
5493 line_height,
5494 &gutter_dimensions,
5495 gutter_settings,
5496 scroll_pixel_position,
5497 &gutter_hitbox,
5498 cx,
5499 )
5500 });
5501
5502 let invisible_symbol_font_size = font_size / 2.;
5503 let tab_invisible = cx
5504 .text_system()
5505 .shape_line(
5506 "→".into(),
5507 invisible_symbol_font_size,
5508 &[TextRun {
5509 len: "→".len(),
5510 font: self.style.text.font(),
5511 color: cx.theme().colors().editor_invisible,
5512 background_color: None,
5513 underline: None,
5514 strikethrough: None,
5515 }],
5516 )
5517 .unwrap();
5518 let space_invisible = cx
5519 .text_system()
5520 .shape_line(
5521 "•".into(),
5522 invisible_symbol_font_size,
5523 &[TextRun {
5524 len: "•".len(),
5525 font: self.style.text.font(),
5526 color: cx.theme().colors().editor_invisible,
5527 background_color: None,
5528 underline: None,
5529 strikethrough: None,
5530 }],
5531 )
5532 .unwrap();
5533
5534 EditorLayout {
5535 mode: snapshot.mode,
5536 position_map: Rc::new(PositionMap {
5537 size: bounds.size,
5538 scroll_pixel_position,
5539 scroll_max,
5540 line_layouts,
5541 line_height,
5542 em_width,
5543 em_advance,
5544 snapshot,
5545 }),
5546 visible_display_row_range: start_row..end_row,
5547 wrap_guides,
5548 indent_guides,
5549 hitbox,
5550 text_hitbox,
5551 gutter_hitbox,
5552 gutter_dimensions,
5553 display_hunks,
5554 content_origin,
5555 scrollbar_layout,
5556 active_rows,
5557 highlighted_rows,
5558 highlighted_ranges,
5559 highlighted_gutter_ranges,
5560 redacted_ranges,
5561 line_elements,
5562 line_numbers,
5563 blamed_display_rows,
5564 inline_blame,
5565 blocks,
5566 cursors,
5567 visible_cursors,
5568 selections,
5569 mouse_context_menu,
5570 test_indicators,
5571 close_indicators,
5572 code_actions_indicator,
5573 gutter_fold_toggles,
5574 crease_trailers,
5575 tab_invisible,
5576 space_invisible,
5577 }
5578 })
5579 })
5580 })
5581 }
5582
5583 fn paint(
5584 &mut self,
5585 _: Option<&GlobalElementId>,
5586 bounds: Bounds<gpui::Pixels>,
5587 _: &mut Self::RequestLayoutState,
5588 layout: &mut Self::PrepaintState,
5589 cx: &mut WindowContext,
5590 ) {
5591 let focus_handle = self.editor.focus_handle(cx);
5592 let key_context = self.editor.read(cx).key_context(cx);
5593 cx.set_key_context(key_context);
5594 cx.handle_input(
5595 &focus_handle,
5596 ElementInputHandler::new(bounds, self.editor.clone()),
5597 );
5598 self.register_actions(cx);
5599 self.register_key_listeners(cx, layout);
5600
5601 let text_style = TextStyleRefinement {
5602 font_size: Some(self.style.text.font_size),
5603 line_height: Some(self.style.text.line_height),
5604 ..Default::default()
5605 };
5606 let mouse_position = cx.mouse_position();
5607 let hovered_hunk = layout
5608 .display_hunks
5609 .iter()
5610 .find_map(|(hunk, hunk_hitbox)| match hunk {
5611 DisplayDiffHunk::Folded { .. } => None,
5612 DisplayDiffHunk::Unfolded {
5613 diff_base_byte_range,
5614 multi_buffer_range,
5615 status,
5616 ..
5617 } => {
5618 if hunk_hitbox
5619 .as_ref()
5620 .map(|hitbox| hitbox.contains(&mouse_position))
5621 .unwrap_or(false)
5622 {
5623 Some(HoveredHunk {
5624 status: *status,
5625 multi_buffer_range: multi_buffer_range.clone(),
5626 diff_base_byte_range: diff_base_byte_range.clone(),
5627 })
5628 } else {
5629 None
5630 }
5631 }
5632 });
5633 let rem_size = self.rem_size(cx);
5634 cx.with_rem_size(rem_size, |cx| {
5635 cx.with_text_style(Some(text_style), |cx| {
5636 cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
5637 self.paint_mouse_listeners(layout, hovered_hunk, cx);
5638 self.paint_background(layout, cx);
5639 self.paint_indent_guides(layout, cx);
5640
5641 if layout.gutter_hitbox.size.width > Pixels::ZERO {
5642 self.paint_blamed_display_rows(layout, cx);
5643 self.paint_line_numbers(layout, cx);
5644 }
5645
5646 self.paint_text(layout, cx);
5647
5648 if layout.gutter_hitbox.size.width > Pixels::ZERO {
5649 self.paint_gutter_highlights(layout, cx);
5650 self.paint_gutter_indicators(layout, cx);
5651 }
5652
5653 if !layout.blocks.is_empty() {
5654 cx.with_element_namespace("blocks", |cx| {
5655 self.paint_blocks(layout, cx);
5656 });
5657 }
5658
5659 self.paint_scrollbar(layout, cx);
5660 self.paint_mouse_context_menu(layout, cx);
5661 });
5662 })
5663 })
5664 }
5665}
5666
5667pub(super) fn gutter_bounds(
5668 editor_bounds: Bounds<Pixels>,
5669 gutter_dimensions: GutterDimensions,
5670) -> Bounds<Pixels> {
5671 Bounds {
5672 origin: editor_bounds.origin,
5673 size: size(gutter_dimensions.width, editor_bounds.size.height),
5674 }
5675}
5676
5677impl IntoElement for EditorElement {
5678 type Element = Self;
5679
5680 fn into_element(self) -> Self::Element {
5681 self
5682 }
5683}
5684
5685pub struct EditorLayout {
5686 position_map: Rc<PositionMap>,
5687 hitbox: Hitbox,
5688 text_hitbox: Hitbox,
5689 gutter_hitbox: Hitbox,
5690 gutter_dimensions: GutterDimensions,
5691 content_origin: gpui::Point<Pixels>,
5692 scrollbar_layout: Option<ScrollbarLayout>,
5693 mode: EditorMode,
5694 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
5695 indent_guides: Option<Vec<IndentGuideLayout>>,
5696 visible_display_row_range: Range<DisplayRow>,
5697 active_rows: BTreeMap<DisplayRow, bool>,
5698 highlighted_rows: BTreeMap<DisplayRow, Hsla>,
5699 line_elements: SmallVec<[AnyElement; 1]>,
5700 line_numbers: Vec<Option<ShapedLine>>,
5701 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
5702 blamed_display_rows: Option<Vec<AnyElement>>,
5703 inline_blame: Option<AnyElement>,
5704 blocks: Vec<BlockLayout>,
5705 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5706 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
5707 redacted_ranges: Vec<Range<DisplayPoint>>,
5708 cursors: Vec<(DisplayPoint, Hsla)>,
5709 visible_cursors: Vec<CursorLayout>,
5710 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
5711 code_actions_indicator: Option<AnyElement>,
5712 test_indicators: Vec<AnyElement>,
5713 close_indicators: Vec<AnyElement>,
5714 gutter_fold_toggles: Vec<Option<AnyElement>>,
5715 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
5716 mouse_context_menu: Option<AnyElement>,
5717 tab_invisible: ShapedLine,
5718 space_invisible: ShapedLine,
5719}
5720
5721impl EditorLayout {
5722 fn line_end_overshoot(&self) -> Pixels {
5723 0.15 * self.position_map.line_height
5724 }
5725}
5726
5727struct ColoredRange<T> {
5728 start: T,
5729 end: T,
5730 color: Hsla,
5731}
5732
5733#[derive(Clone)]
5734struct ScrollbarLayout {
5735 hitbox: Hitbox,
5736 visible_row_range: Range<f32>,
5737 visible: bool,
5738 row_height: Pixels,
5739 thumb_height: Pixels,
5740}
5741
5742impl ScrollbarLayout {
5743 const BORDER_WIDTH: Pixels = px(1.0);
5744 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
5745 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
5746 const MIN_THUMB_HEIGHT: Pixels = px(20.0);
5747
5748 fn thumb_bounds(&self) -> Bounds<Pixels> {
5749 let thumb_top = self.y_for_row(self.visible_row_range.start);
5750 let thumb_bottom = thumb_top + self.thumb_height;
5751 Bounds::from_corners(
5752 point(self.hitbox.left(), thumb_top),
5753 point(self.hitbox.right(), thumb_bottom),
5754 )
5755 }
5756
5757 fn y_for_row(&self, row: f32) -> Pixels {
5758 self.hitbox.top() + row * self.row_height
5759 }
5760
5761 fn marker_quads_for_ranges(
5762 &self,
5763 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
5764 column: Option<usize>,
5765 ) -> Vec<PaintQuad> {
5766 struct MinMax {
5767 min: Pixels,
5768 max: Pixels,
5769 }
5770 let (x_range, height_limit) = if let Some(column) = column {
5771 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
5772 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
5773 let end = start + column_width;
5774 (
5775 Range { start, end },
5776 MinMax {
5777 min: Self::MIN_MARKER_HEIGHT,
5778 max: px(f32::MAX),
5779 },
5780 )
5781 } else {
5782 (
5783 Range {
5784 start: Self::BORDER_WIDTH,
5785 end: self.hitbox.size.width,
5786 },
5787 MinMax {
5788 min: Self::LINE_MARKER_HEIGHT,
5789 max: Self::LINE_MARKER_HEIGHT,
5790 },
5791 )
5792 };
5793
5794 let row_to_y = |row: DisplayRow| row.as_f32() * self.row_height;
5795 let mut pixel_ranges = row_ranges
5796 .into_iter()
5797 .map(|range| {
5798 let start_y = row_to_y(range.start);
5799 let end_y = row_to_y(range.end)
5800 + self.row_height.max(height_limit.min).min(height_limit.max);
5801 ColoredRange {
5802 start: start_y,
5803 end: end_y,
5804 color: range.color,
5805 }
5806 })
5807 .peekable();
5808
5809 let mut quads = Vec::new();
5810 while let Some(mut pixel_range) = pixel_ranges.next() {
5811 while let Some(next_pixel_range) = pixel_ranges.peek() {
5812 if pixel_range.end >= next_pixel_range.start - px(1.0)
5813 && pixel_range.color == next_pixel_range.color
5814 {
5815 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
5816 pixel_ranges.next();
5817 } else {
5818 break;
5819 }
5820 }
5821
5822 let bounds = Bounds::from_corners(
5823 point(x_range.start, pixel_range.start),
5824 point(x_range.end, pixel_range.end),
5825 );
5826 quads.push(quad(
5827 bounds,
5828 Corners::default(),
5829 pixel_range.color,
5830 Edges::default(),
5831 Hsla::transparent_black(),
5832 ));
5833 }
5834
5835 quads
5836 }
5837}
5838
5839struct CreaseTrailerLayout {
5840 element: AnyElement,
5841 bounds: Bounds<Pixels>,
5842}
5843
5844struct PositionMap {
5845 size: Size<Pixels>,
5846 line_height: Pixels,
5847 scroll_pixel_position: gpui::Point<Pixels>,
5848 scroll_max: gpui::Point<f32>,
5849 em_width: Pixels,
5850 em_advance: Pixels,
5851 line_layouts: Vec<LineWithInvisibles>,
5852 snapshot: EditorSnapshot,
5853}
5854
5855#[derive(Debug, Copy, Clone)]
5856pub struct PointForPosition {
5857 pub previous_valid: DisplayPoint,
5858 pub next_valid: DisplayPoint,
5859 pub exact_unclipped: DisplayPoint,
5860 pub column_overshoot_after_line_end: u32,
5861}
5862
5863impl PointForPosition {
5864 pub fn as_valid(&self) -> Option<DisplayPoint> {
5865 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
5866 Some(self.previous_valid)
5867 } else {
5868 None
5869 }
5870 }
5871}
5872
5873impl PositionMap {
5874 fn point_for_position(
5875 &self,
5876 text_bounds: Bounds<Pixels>,
5877 position: gpui::Point<Pixels>,
5878 ) -> PointForPosition {
5879 let scroll_position = self.snapshot.scroll_position();
5880 let position = position - text_bounds.origin;
5881 let y = position.y.max(px(0.)).min(self.size.height);
5882 let x = position.x + (scroll_position.x * self.em_width);
5883 let row = ((y / self.line_height) + scroll_position.y) as u32;
5884
5885 let (column, x_overshoot_after_line_end) = if let Some(line) = self
5886 .line_layouts
5887 .get(row as usize - scroll_position.y as usize)
5888 {
5889 if let Some(ix) = line.index_for_x(x) {
5890 (ix as u32, px(0.))
5891 } else {
5892 (line.len as u32, px(0.).max(x - line.width))
5893 }
5894 } else {
5895 (0, x)
5896 };
5897
5898 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
5899 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
5900 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
5901
5902 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
5903 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
5904 PointForPosition {
5905 previous_valid,
5906 next_valid,
5907 exact_unclipped,
5908 column_overshoot_after_line_end,
5909 }
5910 }
5911}
5912
5913struct BlockLayout {
5914 id: BlockId,
5915 row: Option<DisplayRow>,
5916 element: AnyElement,
5917 available_space: Size<AvailableSpace>,
5918 style: BlockStyle,
5919}
5920
5921fn layout_line(
5922 row: DisplayRow,
5923 snapshot: &EditorSnapshot,
5924 style: &EditorStyle,
5925 cx: &mut WindowContext,
5926) -> LineWithInvisibles {
5927 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
5928 LineWithInvisibles::from_chunks(chunks, &style.text, MAX_LINE_LEN, 1, &[], snapshot.mode, cx)
5929 .pop()
5930 .unwrap()
5931}
5932
5933#[derive(Debug)]
5934pub struct IndentGuideLayout {
5935 origin: gpui::Point<Pixels>,
5936 length: Pixels,
5937 single_indent_width: Pixels,
5938 depth: u32,
5939 active: bool,
5940 settings: IndentGuideSettings,
5941}
5942
5943pub struct CursorLayout {
5944 origin: gpui::Point<Pixels>,
5945 block_width: Pixels,
5946 line_height: Pixels,
5947 color: Hsla,
5948 shape: CursorShape,
5949 block_text: Option<ShapedLine>,
5950 cursor_name: Option<AnyElement>,
5951}
5952
5953#[derive(Debug)]
5954pub struct CursorName {
5955 string: SharedString,
5956 color: Hsla,
5957 is_top_row: bool,
5958}
5959
5960impl CursorLayout {
5961 pub fn new(
5962 origin: gpui::Point<Pixels>,
5963 block_width: Pixels,
5964 line_height: Pixels,
5965 color: Hsla,
5966 shape: CursorShape,
5967 block_text: Option<ShapedLine>,
5968 ) -> CursorLayout {
5969 CursorLayout {
5970 origin,
5971 block_width,
5972 line_height,
5973 color,
5974 shape,
5975 block_text,
5976 cursor_name: None,
5977 }
5978 }
5979
5980 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5981 Bounds {
5982 origin: self.origin + origin,
5983 size: size(self.block_width, self.line_height),
5984 }
5985 }
5986
5987 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
5988 match self.shape {
5989 CursorShape::Bar => Bounds {
5990 origin: self.origin + origin,
5991 size: size(px(2.0), self.line_height),
5992 },
5993 CursorShape::Block | CursorShape::Hollow => Bounds {
5994 origin: self.origin + origin,
5995 size: size(self.block_width, self.line_height),
5996 },
5997 CursorShape::Underscore => Bounds {
5998 origin: self.origin
5999 + origin
6000 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
6001 size: size(self.block_width, px(2.0)),
6002 },
6003 }
6004 }
6005
6006 pub fn layout(
6007 &mut self,
6008 origin: gpui::Point<Pixels>,
6009 cursor_name: Option<CursorName>,
6010 cx: &mut WindowContext,
6011 ) {
6012 if let Some(cursor_name) = cursor_name {
6013 let bounds = self.bounds(origin);
6014 let text_size = self.line_height / 1.5;
6015
6016 let name_origin = if cursor_name.is_top_row {
6017 point(bounds.right() - px(1.), bounds.top())
6018 } else {
6019 point(bounds.left(), bounds.top() - text_size / 2. - px(1.))
6020 };
6021 let mut name_element = div()
6022 .bg(self.color)
6023 .text_size(text_size)
6024 .px_0p5()
6025 .line_height(text_size + px(2.))
6026 .text_color(cursor_name.color)
6027 .child(cursor_name.string.clone())
6028 .into_any_element();
6029
6030 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), cx);
6031
6032 self.cursor_name = Some(name_element);
6033 }
6034 }
6035
6036 pub fn paint(&mut self, origin: gpui::Point<Pixels>, cx: &mut WindowContext) {
6037 let bounds = self.bounds(origin);
6038
6039 //Draw background or border quad
6040 let cursor = if matches!(self.shape, CursorShape::Hollow) {
6041 outline(bounds, self.color)
6042 } else {
6043 fill(bounds, self.color)
6044 };
6045
6046 if let Some(name) = &mut self.cursor_name {
6047 name.paint(cx);
6048 }
6049
6050 cx.paint_quad(cursor);
6051
6052 if let Some(block_text) = &self.block_text {
6053 block_text
6054 .paint(self.origin + origin, self.line_height, cx)
6055 .log_err();
6056 }
6057 }
6058
6059 pub fn shape(&self) -> CursorShape {
6060 self.shape
6061 }
6062}
6063
6064#[derive(Debug)]
6065pub struct HighlightedRange {
6066 pub start_y: Pixels,
6067 pub line_height: Pixels,
6068 pub lines: Vec<HighlightedRangeLine>,
6069 pub color: Hsla,
6070 pub corner_radius: Pixels,
6071}
6072
6073#[derive(Debug)]
6074pub struct HighlightedRangeLine {
6075 pub start_x: Pixels,
6076 pub end_x: Pixels,
6077}
6078
6079impl HighlightedRange {
6080 pub fn paint(&self, bounds: Bounds<Pixels>, cx: &mut WindowContext) {
6081 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
6082 self.paint_lines(self.start_y, &self.lines[0..1], bounds, cx);
6083 self.paint_lines(
6084 self.start_y + self.line_height,
6085 &self.lines[1..],
6086 bounds,
6087 cx,
6088 );
6089 } else {
6090 self.paint_lines(self.start_y, &self.lines, bounds, cx);
6091 }
6092 }
6093
6094 fn paint_lines(
6095 &self,
6096 start_y: Pixels,
6097 lines: &[HighlightedRangeLine],
6098 _bounds: Bounds<Pixels>,
6099 cx: &mut WindowContext,
6100 ) {
6101 if lines.is_empty() {
6102 return;
6103 }
6104
6105 let first_line = lines.first().unwrap();
6106 let last_line = lines.last().unwrap();
6107
6108 let first_top_left = point(first_line.start_x, start_y);
6109 let first_top_right = point(first_line.end_x, start_y);
6110
6111 let curve_height = point(Pixels::ZERO, self.corner_radius);
6112 let curve_width = |start_x: Pixels, end_x: Pixels| {
6113 let max = (end_x - start_x) / 2.;
6114 let width = if max < self.corner_radius {
6115 max
6116 } else {
6117 self.corner_radius
6118 };
6119
6120 point(width, Pixels::ZERO)
6121 };
6122
6123 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
6124 let mut path = gpui::Path::new(first_top_right - top_curve_width);
6125 path.curve_to(first_top_right + curve_height, first_top_right);
6126
6127 let mut iter = lines.iter().enumerate().peekable();
6128 while let Some((ix, line)) = iter.next() {
6129 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
6130
6131 if let Some((_, next_line)) = iter.peek() {
6132 let next_top_right = point(next_line.end_x, bottom_right.y);
6133
6134 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
6135 Ordering::Equal => {
6136 path.line_to(bottom_right);
6137 }
6138 Ordering::Less => {
6139 let curve_width = curve_width(next_top_right.x, bottom_right.x);
6140 path.line_to(bottom_right - curve_height);
6141 if self.corner_radius > Pixels::ZERO {
6142 path.curve_to(bottom_right - curve_width, bottom_right);
6143 }
6144 path.line_to(next_top_right + curve_width);
6145 if self.corner_radius > Pixels::ZERO {
6146 path.curve_to(next_top_right + curve_height, next_top_right);
6147 }
6148 }
6149 Ordering::Greater => {
6150 let curve_width = curve_width(bottom_right.x, next_top_right.x);
6151 path.line_to(bottom_right - curve_height);
6152 if self.corner_radius > Pixels::ZERO {
6153 path.curve_to(bottom_right + curve_width, bottom_right);
6154 }
6155 path.line_to(next_top_right - curve_width);
6156 if self.corner_radius > Pixels::ZERO {
6157 path.curve_to(next_top_right + curve_height, next_top_right);
6158 }
6159 }
6160 }
6161 } else {
6162 let curve_width = curve_width(line.start_x, line.end_x);
6163 path.line_to(bottom_right - curve_height);
6164 if self.corner_radius > Pixels::ZERO {
6165 path.curve_to(bottom_right - curve_width, bottom_right);
6166 }
6167
6168 let bottom_left = point(line.start_x, bottom_right.y);
6169 path.line_to(bottom_left + curve_width);
6170 if self.corner_radius > Pixels::ZERO {
6171 path.curve_to(bottom_left - curve_height, bottom_left);
6172 }
6173 }
6174 }
6175
6176 if first_line.start_x > last_line.start_x {
6177 let curve_width = curve_width(last_line.start_x, first_line.start_x);
6178 let second_top_left = point(last_line.start_x, start_y + self.line_height);
6179 path.line_to(second_top_left + curve_height);
6180 if self.corner_radius > Pixels::ZERO {
6181 path.curve_to(second_top_left + curve_width, second_top_left);
6182 }
6183 let first_bottom_left = point(first_line.start_x, second_top_left.y);
6184 path.line_to(first_bottom_left - curve_width);
6185 if self.corner_radius > Pixels::ZERO {
6186 path.curve_to(first_bottom_left - curve_height, first_bottom_left);
6187 }
6188 }
6189
6190 path.line_to(first_top_left + curve_height);
6191 if self.corner_radius > Pixels::ZERO {
6192 path.curve_to(first_top_left + top_curve_width, first_top_left);
6193 }
6194 path.line_to(first_top_right - top_curve_width);
6195
6196 cx.paint_path(path, self.color);
6197 }
6198}
6199
6200pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6201 (delta.pow(1.5) / 100.0).into()
6202}
6203
6204fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
6205 (delta.pow(1.2) / 300.0).into()
6206}
6207
6208#[cfg(test)]
6209mod tests {
6210 use super::*;
6211 use crate::{
6212 display_map::{BlockDisposition, BlockProperties},
6213 editor_tests::{init_test, update_test_language_settings},
6214 Editor, MultiBuffer,
6215 };
6216 use gpui::{TestAppContext, VisualTestContext};
6217 use language::language_settings;
6218 use log::info;
6219 use std::num::NonZeroU32;
6220 use ui::Context;
6221 use util::test::sample_text;
6222
6223 #[gpui::test]
6224 fn test_shape_line_numbers(cx: &mut TestAppContext) {
6225 init_test(cx, |_| {});
6226 let window = cx.add_window(|cx| {
6227 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
6228 Editor::new(EditorMode::Full, buffer, None, true, cx)
6229 });
6230
6231 let editor = window.root(cx).unwrap();
6232 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6233 let element = EditorElement::new(&editor, style);
6234 let snapshot = window.update(cx, |editor, cx| editor.snapshot(cx)).unwrap();
6235
6236 let layouts = cx
6237 .update_window(*window, |_, cx| {
6238 element.layout_line_numbers(
6239 DisplayRow(0)..DisplayRow(6),
6240 (0..6).map(MultiBufferRow).map(Some),
6241 &Default::default(),
6242 Some(DisplayPoint::new(DisplayRow(0), 0)),
6243 &snapshot,
6244 cx,
6245 )
6246 })
6247 .unwrap();
6248 assert_eq!(layouts.len(), 6);
6249
6250 let relative_rows = window
6251 .update(cx, |editor, cx| {
6252 let snapshot = editor.snapshot(cx);
6253 element.calculate_relative_line_numbers(
6254 &snapshot,
6255 &(DisplayRow(0)..DisplayRow(6)),
6256 Some(DisplayRow(3)),
6257 )
6258 })
6259 .unwrap();
6260 assert_eq!(relative_rows[&DisplayRow(0)], 3);
6261 assert_eq!(relative_rows[&DisplayRow(1)], 2);
6262 assert_eq!(relative_rows[&DisplayRow(2)], 1);
6263 // current line has no relative number
6264 assert_eq!(relative_rows[&DisplayRow(4)], 1);
6265 assert_eq!(relative_rows[&DisplayRow(5)], 2);
6266
6267 // works if cursor is before screen
6268 let relative_rows = window
6269 .update(cx, |editor, cx| {
6270 let snapshot = editor.snapshot(cx);
6271 element.calculate_relative_line_numbers(
6272 &snapshot,
6273 &(DisplayRow(3)..DisplayRow(6)),
6274 Some(DisplayRow(1)),
6275 )
6276 })
6277 .unwrap();
6278 assert_eq!(relative_rows.len(), 3);
6279 assert_eq!(relative_rows[&DisplayRow(3)], 2);
6280 assert_eq!(relative_rows[&DisplayRow(4)], 3);
6281 assert_eq!(relative_rows[&DisplayRow(5)], 4);
6282
6283 // works if cursor is after screen
6284 let relative_rows = window
6285 .update(cx, |editor, cx| {
6286 let snapshot = editor.snapshot(cx);
6287 element.calculate_relative_line_numbers(
6288 &snapshot,
6289 &(DisplayRow(0)..DisplayRow(3)),
6290 Some(DisplayRow(6)),
6291 )
6292 })
6293 .unwrap();
6294 assert_eq!(relative_rows.len(), 3);
6295 assert_eq!(relative_rows[&DisplayRow(0)], 5);
6296 assert_eq!(relative_rows[&DisplayRow(1)], 4);
6297 assert_eq!(relative_rows[&DisplayRow(2)], 3);
6298 }
6299
6300 #[gpui::test]
6301 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
6302 init_test(cx, |_| {});
6303
6304 let window = cx.add_window(|cx| {
6305 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
6306 Editor::new(EditorMode::Full, buffer, None, true, cx)
6307 });
6308 let cx = &mut VisualTestContext::from_window(*window, cx);
6309 let editor = window.root(cx).unwrap();
6310 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6311
6312 window
6313 .update(cx, |editor, cx| {
6314 editor.cursor_shape = CursorShape::Block;
6315 editor.change_selections(None, cx, |s| {
6316 s.select_ranges([
6317 Point::new(0, 0)..Point::new(1, 0),
6318 Point::new(3, 2)..Point::new(3, 3),
6319 Point::new(5, 6)..Point::new(6, 0),
6320 ]);
6321 });
6322 })
6323 .unwrap();
6324
6325 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6326 EditorElement::new(&editor, style)
6327 });
6328
6329 assert_eq!(state.selections.len(), 1);
6330 let local_selections = &state.selections[0].1;
6331 assert_eq!(local_selections.len(), 3);
6332 // moves cursor back one line
6333 assert_eq!(
6334 local_selections[0].head,
6335 DisplayPoint::new(DisplayRow(0), 6)
6336 );
6337 assert_eq!(
6338 local_selections[0].range,
6339 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
6340 );
6341
6342 // moves cursor back one column
6343 assert_eq!(
6344 local_selections[1].range,
6345 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
6346 );
6347 assert_eq!(
6348 local_selections[1].head,
6349 DisplayPoint::new(DisplayRow(3), 2)
6350 );
6351
6352 // leaves cursor on the max point
6353 assert_eq!(
6354 local_selections[2].range,
6355 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
6356 );
6357 assert_eq!(
6358 local_selections[2].head,
6359 DisplayPoint::new(DisplayRow(6), 0)
6360 );
6361
6362 // active lines does not include 1 (even though the range of the selection does)
6363 assert_eq!(
6364 state.active_rows.keys().cloned().collect::<Vec<_>>(),
6365 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
6366 );
6367
6368 // multi-buffer support
6369 // in DisplayPoint coordinates, this is what we're dealing with:
6370 // 0: [[file
6371 // 1: header
6372 // 2: section]]
6373 // 3: aaaaaa
6374 // 4: bbbbbb
6375 // 5: cccccc
6376 // 6:
6377 // 7: [[footer]]
6378 // 8: [[header]]
6379 // 9: ffffff
6380 // 10: gggggg
6381 // 11: hhhhhh
6382 // 12:
6383 // 13: [[footer]]
6384 // 14: [[file
6385 // 15: header
6386 // 16: section]]
6387 // 17: bbbbbb
6388 // 18: cccccc
6389 // 19: dddddd
6390 // 20: [[footer]]
6391 let window = cx.add_window(|cx| {
6392 let buffer = MultiBuffer::build_multi(
6393 [
6394 (
6395 &(sample_text(8, 6, 'a') + "\n"),
6396 vec![
6397 Point::new(0, 0)..Point::new(3, 0),
6398 Point::new(4, 0)..Point::new(7, 0),
6399 ],
6400 ),
6401 (
6402 &(sample_text(8, 6, 'a') + "\n"),
6403 vec![Point::new(1, 0)..Point::new(3, 0)],
6404 ),
6405 ],
6406 cx,
6407 );
6408 Editor::new(EditorMode::Full, buffer, None, true, cx)
6409 });
6410 let editor = window.root(cx).unwrap();
6411 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6412 let _state = window.update(cx, |editor, cx| {
6413 editor.cursor_shape = CursorShape::Block;
6414 editor.change_selections(None, cx, |s| {
6415 s.select_display_ranges([
6416 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
6417 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
6418 ]);
6419 });
6420 });
6421
6422 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6423 EditorElement::new(&editor, style)
6424 });
6425 assert_eq!(state.selections.len(), 1);
6426 let local_selections = &state.selections[0].1;
6427 assert_eq!(local_selections.len(), 2);
6428
6429 // moves cursor on excerpt boundary back a line
6430 // and doesn't allow selection to bleed through
6431 assert_eq!(
6432 local_selections[0].range,
6433 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
6434 );
6435 assert_eq!(
6436 local_selections[0].head,
6437 DisplayPoint::new(DisplayRow(6), 0)
6438 );
6439 // moves cursor on buffer boundary back two lines
6440 // and doesn't allow selection to bleed through
6441 assert_eq!(
6442 local_selections[1].range,
6443 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
6444 );
6445 assert_eq!(
6446 local_selections[1].head,
6447 DisplayPoint::new(DisplayRow(12), 0)
6448 );
6449 }
6450
6451 #[gpui::test]
6452 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
6453 init_test(cx, |_| {});
6454
6455 let window = cx.add_window(|cx| {
6456 let buffer = MultiBuffer::build_simple("", cx);
6457 Editor::new(EditorMode::Full, buffer, None, true, cx)
6458 });
6459 let cx = &mut VisualTestContext::from_window(*window, cx);
6460 let editor = window.root(cx).unwrap();
6461 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6462 window
6463 .update(cx, |editor, cx| {
6464 editor.set_placeholder_text("hello", cx);
6465 editor.insert_blocks(
6466 [BlockProperties {
6467 style: BlockStyle::Fixed,
6468 disposition: BlockDisposition::Above,
6469 height: 3,
6470 position: Anchor::min(),
6471 render: Box::new(|cx| div().h(3. * cx.line_height()).into_any()),
6472 }],
6473 None,
6474 cx,
6475 );
6476
6477 // Blur the editor so that it displays placeholder text.
6478 cx.blur();
6479 })
6480 .unwrap();
6481
6482 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6483 EditorElement::new(&editor, style)
6484 });
6485 assert_eq!(state.position_map.line_layouts.len(), 4);
6486 assert_eq!(
6487 state
6488 .line_numbers
6489 .iter()
6490 .map(Option::is_some)
6491 .collect::<Vec<_>>(),
6492 &[false, false, false, true]
6493 );
6494 }
6495
6496 #[gpui::test]
6497 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
6498 const TAB_SIZE: u32 = 4;
6499
6500 let input_text = "\t \t|\t| a b";
6501 let expected_invisibles = vec![
6502 Invisible::Tab {
6503 line_start_offset: 0,
6504 line_end_offset: TAB_SIZE as usize,
6505 },
6506 Invisible::Whitespace {
6507 line_offset: TAB_SIZE as usize,
6508 },
6509 Invisible::Tab {
6510 line_start_offset: TAB_SIZE as usize + 1,
6511 line_end_offset: TAB_SIZE as usize * 2,
6512 },
6513 Invisible::Tab {
6514 line_start_offset: TAB_SIZE as usize * 2 + 1,
6515 line_end_offset: TAB_SIZE as usize * 3,
6516 },
6517 Invisible::Whitespace {
6518 line_offset: TAB_SIZE as usize * 3 + 1,
6519 },
6520 Invisible::Whitespace {
6521 line_offset: TAB_SIZE as usize * 3 + 3,
6522 },
6523 ];
6524 assert_eq!(
6525 expected_invisibles.len(),
6526 input_text
6527 .chars()
6528 .filter(|initial_char| initial_char.is_whitespace())
6529 .count(),
6530 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6531 );
6532
6533 init_test(cx, |s| {
6534 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6535 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
6536 });
6537
6538 let actual_invisibles =
6539 collect_invisibles_from_new_editor(cx, EditorMode::Full, &input_text, px(500.0));
6540
6541 assert_eq!(expected_invisibles, actual_invisibles);
6542 }
6543
6544 #[gpui::test]
6545 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
6546 init_test(cx, |s| {
6547 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6548 s.defaults.tab_size = NonZeroU32::new(4);
6549 });
6550
6551 for editor_mode_without_invisibles in [
6552 EditorMode::SingleLine { auto_width: false },
6553 EditorMode::AutoHeight { max_lines: 100 },
6554 ] {
6555 let invisibles = collect_invisibles_from_new_editor(
6556 cx,
6557 editor_mode_without_invisibles,
6558 "\t\t\t| | a b",
6559 px(500.0),
6560 );
6561 assert!(invisibles.is_empty(),
6562 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
6563 }
6564 }
6565
6566 #[gpui::test]
6567 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
6568 let tab_size = 4;
6569 let input_text = "a\tbcd ".repeat(9);
6570 let repeated_invisibles = [
6571 Invisible::Tab {
6572 line_start_offset: 1,
6573 line_end_offset: tab_size as usize,
6574 },
6575 Invisible::Whitespace {
6576 line_offset: tab_size as usize + 3,
6577 },
6578 Invisible::Whitespace {
6579 line_offset: tab_size as usize + 4,
6580 },
6581 Invisible::Whitespace {
6582 line_offset: tab_size as usize + 5,
6583 },
6584 Invisible::Whitespace {
6585 line_offset: tab_size as usize + 6,
6586 },
6587 Invisible::Whitespace {
6588 line_offset: tab_size as usize + 7,
6589 },
6590 ];
6591 let expected_invisibles = std::iter::once(repeated_invisibles)
6592 .cycle()
6593 .take(9)
6594 .flatten()
6595 .collect::<Vec<_>>();
6596 assert_eq!(
6597 expected_invisibles.len(),
6598 input_text
6599 .chars()
6600 .filter(|initial_char| initial_char.is_whitespace())
6601 .count(),
6602 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
6603 );
6604 info!("Expected invisibles: {expected_invisibles:?}");
6605
6606 init_test(cx, |_| {});
6607
6608 // Put the same string with repeating whitespace pattern into editors of various size,
6609 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
6610 let resize_step = 10.0;
6611 let mut editor_width = 200.0;
6612 while editor_width <= 1000.0 {
6613 update_test_language_settings(cx, |s| {
6614 s.defaults.tab_size = NonZeroU32::new(tab_size);
6615 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
6616 s.defaults.preferred_line_length = Some(editor_width as u32);
6617 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
6618 });
6619
6620 let actual_invisibles = collect_invisibles_from_new_editor(
6621 cx,
6622 EditorMode::Full,
6623 &input_text,
6624 px(editor_width),
6625 );
6626
6627 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
6628 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
6629 let mut i = 0;
6630 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
6631 i = actual_index;
6632 match expected_invisibles.get(i) {
6633 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
6634 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
6635 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
6636 _ => {
6637 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
6638 }
6639 },
6640 None => panic!("Unexpected extra invisible {actual_invisible:?} at index {i}"),
6641 }
6642 }
6643 let missing_expected_invisibles = &expected_invisibles[i + 1..];
6644 assert!(
6645 missing_expected_invisibles.is_empty(),
6646 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
6647 );
6648
6649 editor_width += resize_step;
6650 }
6651 }
6652
6653 fn collect_invisibles_from_new_editor(
6654 cx: &mut TestAppContext,
6655 editor_mode: EditorMode,
6656 input_text: &str,
6657 editor_width: Pixels,
6658 ) -> Vec<Invisible> {
6659 info!(
6660 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
6661 editor_width.0
6662 );
6663 let window = cx.add_window(|cx| {
6664 let buffer = MultiBuffer::build_simple(&input_text, cx);
6665 Editor::new(editor_mode, buffer, None, true, cx)
6666 });
6667 let cx = &mut VisualTestContext::from_window(*window, cx);
6668 let editor = window.root(cx).unwrap();
6669 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
6670 window
6671 .update(cx, |editor, cx| {
6672 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
6673 editor.set_wrap_width(Some(editor_width), cx);
6674 })
6675 .unwrap();
6676 let (_, state) = cx.draw(point(px(500.), px(500.)), size(px(500.), px(500.)), |_| {
6677 EditorElement::new(&editor, style)
6678 });
6679 state
6680 .position_map
6681 .line_layouts
6682 .iter()
6683 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
6684 .cloned()
6685 .collect()
6686 }
6687}
6688
6689pub fn register_action<T: Action>(
6690 view: &View<Editor>,
6691 cx: &mut WindowContext,
6692 listener: impl Fn(&mut Editor, &T, &mut ViewContext<Editor>) + 'static,
6693) {
6694 let view = view.clone();
6695 cx.on_action(TypeId::of::<T>(), move |action, phase, cx| {
6696 let action = action.downcast_ref().unwrap();
6697 if phase == DispatchPhase::Bubble {
6698 view.update(cx, |editor, cx| {
6699 listener(editor, action, cx);
6700 })
6701 }
6702 })
6703}
6704
6705fn compute_auto_height_layout(
6706 editor: &mut Editor,
6707 max_lines: usize,
6708 max_line_number_width: Pixels,
6709 known_dimensions: Size<Option<Pixels>>,
6710 available_width: AvailableSpace,
6711 cx: &mut ViewContext<Editor>,
6712) -> Option<Size<Pixels>> {
6713 let width = known_dimensions.width.or_else(|| {
6714 if let AvailableSpace::Definite(available_width) = available_width {
6715 Some(available_width)
6716 } else {
6717 None
6718 }
6719 })?;
6720 if let Some(height) = known_dimensions.height {
6721 return Some(size(width, height));
6722 }
6723
6724 let style = editor.style.as_ref().unwrap();
6725 let font_id = cx.text_system().resolve_font(&style.text.font());
6726 let font_size = style.text.font_size.to_pixels(cx.rem_size());
6727 let line_height = style.text.line_height_in_pixels(cx.rem_size());
6728 let em_width = cx
6729 .text_system()
6730 .typographic_bounds(font_id, font_size, 'm')
6731 .unwrap()
6732 .size
6733 .width;
6734
6735 let mut snapshot = editor.snapshot(cx);
6736 let gutter_dimensions =
6737 snapshot.gutter_dimensions(font_id, font_size, em_width, max_line_number_width, cx);
6738
6739 editor.gutter_dimensions = gutter_dimensions;
6740 let text_width = width - gutter_dimensions.width;
6741 let overscroll = size(em_width, px(0.));
6742
6743 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
6744 if editor.set_wrap_width(Some(editor_width), cx) {
6745 snapshot = editor.snapshot(cx);
6746 }
6747
6748 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
6749 let height = scroll_height
6750 .max(line_height)
6751 .min(line_height * max_lines as f32);
6752
6753 Some(size(width, height))
6754}