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