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