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