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