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