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