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