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