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