1use crate::{
2 code_context_menus::{CodeActionsMenu, MENU_ASIDE_MAX_WIDTH, MENU_ASIDE_MIN_WIDTH, MENU_GAP},
3 commit_tooltip::{blame_entry_relative_timestamp, CommitTooltip, ParsedCommitMessage},
4 display_map::{
5 Block, BlockContext, BlockStyle, DisplaySnapshot, HighlightedChunk, ToDisplayPoint,
6 },
7 editor_settings::{
8 CurrentLineHighlight, DoubleClickInMultibuffer, MultiCursorModifier, ScrollBeyondLastLine,
9 ScrollbarDiagnostics, ShowScrollbar,
10 },
11 git::blame::GitBlame,
12 hover_popover::{
13 self, hover_at, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
14 },
15 items::BufferSearchHighlights,
16 mouse_context_menu::{self, MenuPosition, MouseContextMenu},
17 scroll::{axis_pair, scroll_amount::ScrollAmount, AxisPair},
18 BlockId, ChunkReplacement, CursorShape, CustomBlockId, DisplayPoint, DisplayRow,
19 DocumentHighlightRead, DocumentHighlightWrite, EditDisplayMode, Editor, EditorMode,
20 EditorSettings, EditorSnapshot, EditorStyle, ExpandExcerpts, FocusedBlock, GoToHunk,
21 GutterDimensions, HalfPageDown, HalfPageUp, HandleInput, HoveredCursor, InlineCompletion,
22 JumpData, LineDown, LineUp, OpenExcerpts, PageDown, PageUp, Point, RevertSelectedHunks, RowExt,
23 RowRangeExt, SelectPhase, SelectedTextHighlight, Selection, SoftWrap, StickyHeaderExcerpt,
24 ToPoint, ToggleFold, ToggleStagedSelectedDiffHunks, COLUMNAR_SELECTION_MODIFIERS,
25 CURSORS_VISIBLE_FOR, FILE_HEADER_HEIGHT, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED, MAX_LINE_LEN,
26 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
27};
28use buffer_diff::{DiffHunkSecondaryStatus, DiffHunkStatus};
29use client::ParticipantIndex;
30use collections::{BTreeMap, HashMap, HashSet};
31use file_icons::FileIcons;
32use git::{blame::BlameEntry, Oid};
33use gpui::{
34 anchored, deferred, div, fill, linear_color_stop, linear_gradient, outline, pattern_slash,
35 point, px, quad, relative, size, svg, transparent_black, Action, AnyElement, App,
36 AvailableSpace, Axis, Bounds, ClickEvent, ClipboardItem, ContentMask, Context, Corner, Corners,
37 CursorStyle, DispatchPhase, Edges, Element, ElementInputHandler, Entity, Focusable, FontId,
38 GlobalElementId, Hitbox, Hsla, InteractiveElement, IntoElement, Keystroke, Length,
39 ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
40 ParentElement, Pixels, ScrollDelta, ScrollWheelEvent, ShapedLine, SharedString, Size,
41 StatefulInteractiveElement, Style, Styled, Subscription, TextRun, TextStyleRefinement,
42 WeakEntity, Window,
43};
44use itertools::Itertools;
45use language::{
46 language_settings::{
47 IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings,
48 ShowWhitespaceSetting,
49 },
50 ChunkRendererContext,
51};
52use lsp::DiagnosticSeverity;
53use multi_buffer::{
54 Anchor, ExcerptId, ExcerptInfo, ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow,
55 RowInfo, ToOffset,
56};
57use project::project_settings::{GitGutterSetting, ProjectSettings};
58use settings::Settings;
59use smallvec::{smallvec, SmallVec};
60use std::{
61 any::TypeId,
62 borrow::Cow,
63 cmp::{self, Ordering},
64 fmt::{self, Write},
65 iter, mem,
66 ops::{Deref, Range},
67 rc::Rc,
68 sync::Arc,
69};
70use sum_tree::Bias;
71use text::BufferId;
72use theme::{ActiveTheme, Appearance, PlayerColor};
73use ui::{
74 h_flex, prelude::*, ButtonLike, ButtonStyle, ContextMenu, IconButtonShape, KeyBinding, Tooltip,
75 POPOVER_Y_PADDING,
76};
77use unicode_segmentation::UnicodeSegmentation;
78use util::{RangeExt, ResultExt};
79use workspace::{item::Item, notifications::NotifyTaskExt, Workspace};
80
81const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 7.;
82
83#[derive(Debug, Clone, PartialEq, Eq)]
84enum DisplayDiffHunk {
85 Folded {
86 display_row: DisplayRow,
87 },
88 Unfolded {
89 diff_base_byte_range: Range<usize>,
90 display_row_range: Range<DisplayRow>,
91 multi_buffer_range: Range<Anchor>,
92 status: DiffHunkStatus,
93 },
94}
95
96struct SelectionLayout {
97 head: DisplayPoint,
98 cursor_shape: CursorShape,
99 is_newest: bool,
100 is_local: bool,
101 range: Range<DisplayPoint>,
102 active_rows: Range<DisplayRow>,
103 user_name: Option<SharedString>,
104}
105
106impl SelectionLayout {
107 fn new<T: ToPoint + ToDisplayPoint + Clone>(
108 selection: Selection<T>,
109 line_mode: bool,
110 cursor_shape: CursorShape,
111 map: &DisplaySnapshot,
112 is_newest: bool,
113 is_local: bool,
114 user_name: Option<SharedString>,
115 ) -> Self {
116 let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
117 let display_selection = point_selection.map(|p| p.to_display_point(map));
118 let mut range = display_selection.range();
119 let mut head = display_selection.head();
120 let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
121 ..map.next_line_boundary(point_selection.end).1.row();
122
123 // vim visual line mode
124 if line_mode {
125 let point_range = map.expand_to_line(point_selection.range());
126 range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
127 }
128
129 // any vim visual mode (including line mode)
130 if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
131 && !range.is_empty()
132 && !selection.reversed
133 {
134 if head.column() > 0 {
135 head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
136 } else if head.row().0 > 0 && head != map.max_point() {
137 head = map.clip_point(
138 DisplayPoint::new(
139 head.row().previous_row(),
140 map.line_len(head.row().previous_row()),
141 ),
142 Bias::Left,
143 );
144 // updating range.end is a no-op unless you're cursor is
145 // on the newline containing a multi-buffer divider
146 // in which case the clip_point may have moved the head up
147 // an additional row.
148 range.end = DisplayPoint::new(head.row().next_row(), 0);
149 active_rows.end = head.row();
150 }
151 }
152
153 Self {
154 head,
155 cursor_shape,
156 is_newest,
157 is_local,
158 range,
159 active_rows,
160 user_name,
161 }
162 }
163}
164
165pub struct EditorElement {
166 editor: Entity<Editor>,
167 style: EditorStyle,
168}
169
170type DisplayRowDelta = u32;
171
172impl EditorElement {
173 pub(crate) const SCROLLBAR_WIDTH: Pixels = px(15.);
174
175 pub fn new(editor: &Entity<Editor>, style: EditorStyle) -> Self {
176 Self {
177 editor: editor.clone(),
178 style,
179 }
180 }
181
182 fn register_actions(&self, window: &mut Window, cx: &mut App) {
183 let editor = &self.editor;
184 editor.update(cx, |editor, cx| {
185 for action in editor.editor_actions.borrow().values() {
186 (action)(window, cx)
187 }
188 });
189
190 crate::rust_analyzer_ext::apply_related_actions(editor, window, cx);
191 crate::clangd_ext::apply_related_actions(editor, window, cx);
192 register_action(editor, window, Editor::open_context_menu);
193 register_action(editor, window, Editor::move_left);
194 register_action(editor, window, Editor::move_right);
195 register_action(editor, window, Editor::move_down);
196 register_action(editor, window, Editor::move_down_by_lines);
197 register_action(editor, window, Editor::select_down_by_lines);
198 register_action(editor, window, Editor::move_up);
199 register_action(editor, window, Editor::move_up_by_lines);
200 register_action(editor, window, Editor::select_up_by_lines);
201 register_action(editor, window, Editor::select_page_down);
202 register_action(editor, window, Editor::select_page_up);
203 register_action(editor, window, Editor::cancel);
204 register_action(editor, window, Editor::newline);
205 register_action(editor, window, Editor::newline_above);
206 register_action(editor, window, Editor::newline_below);
207 register_action(editor, window, Editor::backspace);
208 register_action(editor, window, Editor::delete);
209 register_action(editor, window, Editor::tab);
210 register_action(editor, window, Editor::tab_prev);
211 register_action(editor, window, Editor::indent);
212 register_action(editor, window, Editor::outdent);
213 register_action(editor, window, Editor::autoindent);
214 register_action(editor, window, Editor::delete_line);
215 register_action(editor, window, Editor::join_lines);
216 register_action(editor, window, Editor::sort_lines_case_sensitive);
217 register_action(editor, window, Editor::sort_lines_case_insensitive);
218 register_action(editor, window, Editor::reverse_lines);
219 register_action(editor, window, Editor::shuffle_lines);
220 register_action(editor, window, Editor::convert_to_upper_case);
221 register_action(editor, window, Editor::convert_to_lower_case);
222 register_action(editor, window, Editor::convert_to_title_case);
223 register_action(editor, window, Editor::convert_to_snake_case);
224 register_action(editor, window, Editor::convert_to_kebab_case);
225 register_action(editor, window, Editor::convert_to_upper_camel_case);
226 register_action(editor, window, Editor::convert_to_lower_camel_case);
227 register_action(editor, window, Editor::convert_to_opposite_case);
228 register_action(editor, window, Editor::delete_to_previous_word_start);
229 register_action(editor, window, Editor::delete_to_previous_subword_start);
230 register_action(editor, window, Editor::delete_to_next_word_end);
231 register_action(editor, window, Editor::delete_to_next_subword_end);
232 register_action(editor, window, Editor::delete_to_beginning_of_line);
233 register_action(editor, window, Editor::delete_to_end_of_line);
234 register_action(editor, window, Editor::cut_to_end_of_line);
235 register_action(editor, window, Editor::duplicate_line_up);
236 register_action(editor, window, Editor::duplicate_line_down);
237 register_action(editor, window, Editor::duplicate_selection);
238 register_action(editor, window, Editor::move_line_up);
239 register_action(editor, window, Editor::move_line_down);
240 register_action(editor, window, Editor::transpose);
241 register_action(editor, window, Editor::rewrap);
242 register_action(editor, window, Editor::cut);
243 register_action(editor, window, Editor::kill_ring_cut);
244 register_action(editor, window, Editor::kill_ring_yank);
245 register_action(editor, window, Editor::copy);
246 register_action(editor, window, Editor::paste);
247 register_action(editor, window, Editor::undo);
248 register_action(editor, window, Editor::redo);
249 register_action(editor, window, Editor::move_page_up);
250 register_action(editor, window, Editor::move_page_down);
251 register_action(editor, window, Editor::next_screen);
252 register_action(editor, window, Editor::scroll_cursor_top);
253 register_action(editor, window, Editor::scroll_cursor_center);
254 register_action(editor, window, Editor::scroll_cursor_bottom);
255 register_action(editor, window, Editor::scroll_cursor_center_top_bottom);
256 register_action(editor, window, |editor, _: &LineDown, window, cx| {
257 editor.scroll_screen(&ScrollAmount::Line(1.), window, cx)
258 });
259 register_action(editor, window, |editor, _: &LineUp, window, cx| {
260 editor.scroll_screen(&ScrollAmount::Line(-1.), window, cx)
261 });
262 register_action(editor, window, |editor, _: &HalfPageDown, window, cx| {
263 editor.scroll_screen(&ScrollAmount::Page(0.5), window, cx)
264 });
265 register_action(
266 editor,
267 window,
268 |editor, HandleInput(text): &HandleInput, window, cx| {
269 if text.is_empty() {
270 return;
271 }
272 editor.handle_input(text, window, cx);
273 },
274 );
275 register_action(editor, window, |editor, _: &HalfPageUp, window, cx| {
276 editor.scroll_screen(&ScrollAmount::Page(-0.5), window, cx)
277 });
278 register_action(editor, window, |editor, _: &PageDown, window, cx| {
279 editor.scroll_screen(&ScrollAmount::Page(1.), window, cx)
280 });
281 register_action(editor, window, |editor, _: &PageUp, window, cx| {
282 editor.scroll_screen(&ScrollAmount::Page(-1.), window, cx)
283 });
284 register_action(editor, window, Editor::move_to_previous_word_start);
285 register_action(editor, window, Editor::move_to_previous_subword_start);
286 register_action(editor, window, Editor::move_to_next_word_end);
287 register_action(editor, window, Editor::move_to_next_subword_end);
288 register_action(editor, window, Editor::move_to_beginning_of_line);
289 register_action(editor, window, Editor::move_to_end_of_line);
290 register_action(editor, window, Editor::move_to_start_of_paragraph);
291 register_action(editor, window, Editor::move_to_end_of_paragraph);
292 register_action(editor, window, Editor::move_to_beginning);
293 register_action(editor, window, Editor::move_to_end);
294 register_action(editor, window, Editor::select_up);
295 register_action(editor, window, Editor::select_down);
296 register_action(editor, window, Editor::select_left);
297 register_action(editor, window, Editor::select_right);
298 register_action(editor, window, Editor::select_to_previous_word_start);
299 register_action(editor, window, Editor::select_to_previous_subword_start);
300 register_action(editor, window, Editor::select_to_next_word_end);
301 register_action(editor, window, Editor::select_to_next_subword_end);
302 register_action(editor, window, Editor::select_to_beginning_of_line);
303 register_action(editor, window, Editor::select_to_end_of_line);
304 register_action(editor, window, Editor::select_to_start_of_paragraph);
305 register_action(editor, window, Editor::select_to_end_of_paragraph);
306 register_action(editor, window, Editor::select_to_beginning);
307 register_action(editor, window, Editor::select_to_end);
308 register_action(editor, window, Editor::select_all);
309 register_action(editor, window, |editor, action, window, cx| {
310 editor.select_all_matches(action, window, cx).log_err();
311 });
312 register_action(editor, window, Editor::select_line);
313 register_action(editor, window, Editor::split_selection_into_lines);
314 register_action(editor, window, Editor::add_selection_above);
315 register_action(editor, window, Editor::add_selection_below);
316 register_action(editor, window, |editor, action, window, cx| {
317 editor.select_next(action, window, cx).log_err();
318 });
319 register_action(editor, window, |editor, action, window, cx| {
320 editor.select_previous(action, window, cx).log_err();
321 });
322 register_action(editor, window, Editor::toggle_comments);
323 register_action(editor, window, Editor::select_larger_syntax_node);
324 register_action(editor, window, Editor::select_smaller_syntax_node);
325 register_action(editor, window, Editor::select_enclosing_symbol);
326 register_action(editor, window, Editor::move_to_enclosing_bracket);
327 register_action(editor, window, Editor::undo_selection);
328 register_action(editor, window, Editor::redo_selection);
329 if !editor.read(cx).is_singleton(cx) {
330 register_action(editor, window, Editor::expand_excerpts);
331 register_action(editor, window, Editor::expand_excerpts_up);
332 register_action(editor, window, Editor::expand_excerpts_down);
333 }
334 register_action(editor, window, Editor::go_to_diagnostic);
335 register_action(editor, window, Editor::go_to_prev_diagnostic);
336 register_action(editor, window, Editor::go_to_next_hunk);
337 register_action(editor, window, Editor::go_to_prev_hunk);
338 register_action(editor, window, |editor, action, window, cx| {
339 editor
340 .go_to_definition(action, window, cx)
341 .detach_and_log_err(cx);
342 });
343 register_action(editor, window, |editor, action, window, cx| {
344 editor
345 .go_to_definition_split(action, window, cx)
346 .detach_and_log_err(cx);
347 });
348 register_action(editor, window, |editor, action, window, cx| {
349 editor
350 .go_to_declaration(action, window, cx)
351 .detach_and_log_err(cx);
352 });
353 register_action(editor, window, |editor, action, window, cx| {
354 editor
355 .go_to_declaration_split(action, window, cx)
356 .detach_and_log_err(cx);
357 });
358 register_action(editor, window, |editor, action, window, cx| {
359 editor
360 .go_to_implementation(action, window, cx)
361 .detach_and_log_err(cx);
362 });
363 register_action(editor, window, |editor, action, window, cx| {
364 editor
365 .go_to_implementation_split(action, window, cx)
366 .detach_and_log_err(cx);
367 });
368 register_action(editor, window, |editor, action, window, cx| {
369 editor
370 .go_to_type_definition(action, window, cx)
371 .detach_and_log_err(cx);
372 });
373 register_action(editor, window, |editor, action, window, cx| {
374 editor
375 .go_to_type_definition_split(action, window, cx)
376 .detach_and_log_err(cx);
377 });
378 register_action(editor, window, Editor::open_url);
379 register_action(editor, window, Editor::open_selected_filename);
380 register_action(editor, window, Editor::fold);
381 register_action(editor, window, Editor::fold_at_level);
382 register_action(editor, window, Editor::fold_all);
383 register_action(editor, window, Editor::fold_function_bodies);
384 register_action(editor, window, Editor::fold_at);
385 register_action(editor, window, Editor::fold_recursive);
386 register_action(editor, window, Editor::toggle_fold);
387 register_action(editor, window, Editor::toggle_fold_recursive);
388 register_action(editor, window, Editor::unfold_lines);
389 register_action(editor, window, Editor::unfold_recursive);
390 register_action(editor, window, Editor::unfold_all);
391 register_action(editor, window, Editor::unfold_at);
392 register_action(editor, window, Editor::fold_selected_ranges);
393 register_action(editor, window, Editor::set_mark);
394 register_action(editor, window, Editor::swap_selection_ends);
395 register_action(editor, window, Editor::show_completions);
396 register_action(editor, window, Editor::toggle_code_actions);
397 register_action(editor, window, Editor::open_excerpts);
398 register_action(editor, window, Editor::open_excerpts_in_split);
399 register_action(editor, window, Editor::open_proposed_changes_editor);
400 register_action(editor, window, Editor::toggle_soft_wrap);
401 register_action(editor, window, Editor::toggle_tab_bar);
402 register_action(editor, window, Editor::toggle_line_numbers);
403 register_action(editor, window, Editor::toggle_relative_line_numbers);
404 register_action(editor, window, Editor::toggle_indent_guides);
405 register_action(editor, window, Editor::toggle_inlay_hints);
406 register_action(editor, window, Editor::toggle_inline_completions);
407 register_action(editor, window, hover_popover::hover);
408 register_action(editor, window, Editor::reveal_in_finder);
409 register_action(editor, window, Editor::copy_path);
410 register_action(editor, window, Editor::copy_relative_path);
411 register_action(editor, window, Editor::copy_file_name);
412 register_action(editor, window, Editor::copy_file_name_without_extension);
413 register_action(editor, window, Editor::copy_highlight_json);
414 register_action(editor, window, Editor::copy_permalink_to_line);
415 register_action(editor, window, Editor::open_permalink_to_line);
416 register_action(editor, window, Editor::copy_file_location);
417 register_action(editor, window, Editor::toggle_git_blame);
418 register_action(editor, window, Editor::toggle_git_blame_inline);
419 register_action(editor, window, Editor::toggle_selected_diff_hunks);
420 register_action(editor, window, Editor::toggle_staged_selected_diff_hunks);
421 register_action(editor, window, Editor::expand_all_diff_hunks);
422
423 register_action(editor, window, |editor, action, window, cx| {
424 if let Some(task) = editor.format(action, window, cx) {
425 task.detach_and_notify_err(window, cx);
426 } else {
427 cx.propagate();
428 }
429 });
430 register_action(editor, window, |editor, action, window, cx| {
431 if let Some(task) = editor.format_selections(action, window, cx) {
432 task.detach_and_notify_err(window, cx);
433 } else {
434 cx.propagate();
435 }
436 });
437 register_action(editor, window, Editor::restart_language_server);
438 register_action(editor, window, Editor::show_character_palette);
439 register_action(editor, window, |editor, action, window, cx| {
440 if let Some(task) = editor.confirm_completion(action, window, cx) {
441 task.detach_and_notify_err(window, cx);
442 } else {
443 cx.propagate();
444 }
445 });
446 register_action(editor, window, |editor, action, window, cx| {
447 if let Some(task) = editor.compose_completion(action, window, cx) {
448 task.detach_and_notify_err(window, cx);
449 } else {
450 cx.propagate();
451 }
452 });
453 register_action(editor, window, |editor, action, window, cx| {
454 if let Some(task) = editor.confirm_code_action(action, window, cx) {
455 task.detach_and_notify_err(window, cx);
456 } else {
457 cx.propagate();
458 }
459 });
460 register_action(editor, window, |editor, action, window, cx| {
461 if let Some(task) = editor.rename(action, window, cx) {
462 task.detach_and_notify_err(window, cx);
463 } else {
464 cx.propagate();
465 }
466 });
467 register_action(editor, window, |editor, action, window, cx| {
468 if let Some(task) = editor.confirm_rename(action, window, cx) {
469 task.detach_and_notify_err(window, cx);
470 } else {
471 cx.propagate();
472 }
473 });
474 register_action(editor, window, |editor, action, window, cx| {
475 if let Some(task) = editor.find_all_references(action, window, cx) {
476 task.detach_and_log_err(cx);
477 } else {
478 cx.propagate();
479 }
480 });
481 register_action(editor, window, Editor::show_signature_help);
482 register_action(editor, window, Editor::next_edit_prediction);
483 register_action(editor, window, Editor::previous_edit_prediction);
484 register_action(editor, window, Editor::show_inline_completion);
485 register_action(editor, window, Editor::context_menu_first);
486 register_action(editor, window, Editor::context_menu_prev);
487 register_action(editor, window, Editor::context_menu_next);
488 register_action(editor, window, Editor::context_menu_last);
489 register_action(editor, window, Editor::display_cursor_names);
490 register_action(editor, window, Editor::unique_lines_case_insensitive);
491 register_action(editor, window, Editor::unique_lines_case_sensitive);
492 register_action(editor, window, Editor::accept_partial_inline_completion);
493 register_action(editor, window, Editor::accept_edit_prediction);
494 register_action(editor, window, Editor::revert_file);
495 register_action(editor, window, Editor::revert_selected_hunks);
496 register_action(editor, window, Editor::apply_all_diff_hunks);
497 register_action(editor, window, Editor::apply_selected_diff_hunks);
498 register_action(editor, window, Editor::open_active_item_in_terminal);
499 register_action(editor, window, Editor::reload_file);
500 register_action(editor, window, Editor::spawn_nearest_task);
501 register_action(editor, window, Editor::insert_uuid_v4);
502 register_action(editor, window, Editor::insert_uuid_v7);
503 register_action(editor, window, Editor::open_selections_in_multibuffer);
504 }
505
506 fn register_key_listeners(&self, window: &mut Window, _: &mut App, layout: &EditorLayout) {
507 let position_map = layout.position_map.clone();
508 window.on_key_event({
509 let editor = self.editor.clone();
510 move |event: &ModifiersChangedEvent, phase, window, cx| {
511 if phase != DispatchPhase::Bubble {
512 return;
513 }
514 editor.update(cx, |editor, cx| {
515 if editor.hover_state.focused(window, cx) {
516 return;
517 }
518
519 editor.handle_modifiers_changed(event.modifiers, &position_map, window, cx);
520 })
521 }
522 });
523 }
524
525 fn mouse_left_down(
526 editor: &mut Editor,
527 event: &MouseDownEvent,
528 hovered_hunk: Option<Range<Anchor>>,
529 position_map: &PositionMap,
530 line_numbers: &HashMap<MultiBufferRow, LineNumberLayout>,
531 window: &mut Window,
532 cx: &mut Context<Editor>,
533 ) {
534 if window.default_prevented() {
535 return;
536 }
537
538 let text_hitbox = &position_map.text_hitbox;
539 let gutter_hitbox = &position_map.gutter_hitbox;
540 let mut click_count = event.click_count;
541 let mut modifiers = event.modifiers;
542
543 if let Some(hovered_hunk) = hovered_hunk {
544 editor.toggle_diff_hunks_in_ranges_narrow(vec![hovered_hunk], cx);
545 cx.notify();
546 return;
547 } else if gutter_hitbox.is_hovered(window) {
548 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
549 } else if !text_hitbox.is_hovered(window) {
550 return;
551 }
552
553 let is_singleton = editor.buffer().read(cx).is_singleton();
554
555 if click_count == 2 && !is_singleton {
556 match EditorSettings::get_global(cx).double_click_in_multibuffer {
557 DoubleClickInMultibuffer::Select => {
558 // do nothing special on double click, all selection logic is below
559 }
560 DoubleClickInMultibuffer::Open => {
561 if modifiers.alt {
562 // if double click is made with alt, pretend it's a regular double click without opening and alt,
563 // and run the selection logic.
564 modifiers.alt = false;
565 } else {
566 let scroll_position_row =
567 position_map.scroll_pixel_position.y / position_map.line_height;
568 let display_row = (((event.position - gutter_hitbox.bounds.origin).y
569 + position_map.scroll_pixel_position.y)
570 / position_map.line_height)
571 as u32;
572 let multi_buffer_row = position_map
573 .snapshot
574 .display_point_to_point(
575 DisplayPoint::new(DisplayRow(display_row), 0),
576 Bias::Right,
577 )
578 .row;
579 let line_offset_from_top = display_row - scroll_position_row as u32;
580 // if double click is made without alt, open the corresponding excerp
581 editor.open_excerpts_common(
582 Some(JumpData::MultiBufferRow {
583 row: MultiBufferRow(multi_buffer_row),
584 line_offset_from_top,
585 }),
586 false,
587 window,
588 cx,
589 );
590 return;
591 }
592 }
593 }
594 }
595
596 let point_for_position = position_map.point_for_position(event.position);
597 let position = point_for_position.previous_valid;
598 if modifiers == COLUMNAR_SELECTION_MODIFIERS {
599 editor.select(
600 SelectPhase::BeginColumnar {
601 position,
602 reset: false,
603 goal_column: point_for_position.exact_unclipped.column(),
604 },
605 window,
606 cx,
607 );
608 } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
609 {
610 editor.select(
611 SelectPhase::Extend {
612 position,
613 click_count,
614 },
615 window,
616 cx,
617 );
618 } else {
619 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
620 let multi_cursor_modifier = match multi_cursor_setting {
621 MultiCursorModifier::Alt => modifiers.alt,
622 MultiCursorModifier::CmdOrCtrl => modifiers.secondary(),
623 };
624 editor.select(
625 SelectPhase::Begin {
626 position,
627 add: multi_cursor_modifier,
628 click_count,
629 },
630 window,
631 cx,
632 );
633 }
634 cx.stop_propagation();
635
636 if !is_singleton {
637 let display_row = (((event.position - gutter_hitbox.bounds.origin).y
638 + position_map.scroll_pixel_position.y)
639 / position_map.line_height) as u32;
640 let multi_buffer_row = position_map
641 .snapshot
642 .display_point_to_point(DisplayPoint::new(DisplayRow(display_row), 0), Bias::Right)
643 .row;
644 if line_numbers
645 .get(&MultiBufferRow(multi_buffer_row))
646 .and_then(|line_number| line_number.hitbox.as_ref())
647 .is_some_and(|hitbox| hitbox.contains(&event.position))
648 {
649 let scroll_position_row =
650 position_map.scroll_pixel_position.y / position_map.line_height;
651 let line_offset_from_top = display_row - scroll_position_row as u32;
652
653 editor.open_excerpts_common(
654 Some(JumpData::MultiBufferRow {
655 row: MultiBufferRow(multi_buffer_row),
656 line_offset_from_top,
657 }),
658 modifiers.alt,
659 window,
660 cx,
661 );
662 cx.stop_propagation();
663 }
664 }
665 }
666
667 fn mouse_right_down(
668 editor: &mut Editor,
669 event: &MouseDownEvent,
670 position_map: &PositionMap,
671 window: &mut Window,
672 cx: &mut Context<Editor>,
673 ) {
674 if !position_map.text_hitbox.is_hovered(window) {
675 return;
676 }
677 let point_for_position = position_map.point_for_position(event.position);
678 mouse_context_menu::deploy_context_menu(
679 editor,
680 Some(event.position),
681 point_for_position.previous_valid,
682 window,
683 cx,
684 );
685 cx.stop_propagation();
686 }
687
688 fn mouse_middle_down(
689 editor: &mut Editor,
690 event: &MouseDownEvent,
691 position_map: &PositionMap,
692 window: &mut Window,
693 cx: &mut Context<Editor>,
694 ) {
695 if !position_map.text_hitbox.is_hovered(window) || window.default_prevented() {
696 return;
697 }
698
699 let point_for_position = position_map.point_for_position(event.position);
700 let position = point_for_position.previous_valid;
701
702 editor.select(
703 SelectPhase::BeginColumnar {
704 position,
705 reset: true,
706 goal_column: point_for_position.exact_unclipped.column(),
707 },
708 window,
709 cx,
710 );
711 }
712
713 fn mouse_up(
714 editor: &mut Editor,
715 event: &MouseUpEvent,
716 position_map: &PositionMap,
717 window: &mut Window,
718 cx: &mut Context<Editor>,
719 ) {
720 let text_hitbox = &position_map.text_hitbox;
721 let end_selection = editor.has_pending_selection();
722 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
723
724 if end_selection {
725 editor.select(SelectPhase::End, window, cx);
726 }
727
728 if end_selection && pending_nonempty_selections {
729 cx.stop_propagation();
730 } else if cfg!(any(target_os = "linux", target_os = "freebsd"))
731 && event.button == MouseButton::Middle
732 {
733 if !text_hitbox.is_hovered(window) || editor.read_only(cx) {
734 return;
735 }
736
737 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
738 if EditorSettings::get_global(cx).middle_click_paste {
739 if let Some(text) = cx.read_from_primary().and_then(|item| item.text()) {
740 let point_for_position = position_map.point_for_position(event.position);
741 let position = point_for_position.previous_valid;
742
743 editor.select(
744 SelectPhase::Begin {
745 position,
746 add: false,
747 click_count: 1,
748 },
749 window,
750 cx,
751 );
752 editor.insert(&text, window, cx);
753 }
754 cx.stop_propagation()
755 }
756 }
757 }
758
759 fn click(
760 editor: &mut Editor,
761 event: &ClickEvent,
762 position_map: &PositionMap,
763 window: &mut Window,
764 cx: &mut Context<Editor>,
765 ) {
766 let text_hitbox = &position_map.text_hitbox;
767 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
768
769 let multi_cursor_setting = EditorSettings::get_global(cx).multi_cursor_modifier;
770 let multi_cursor_modifier = match multi_cursor_setting {
771 MultiCursorModifier::Alt => event.modifiers().secondary(),
772 MultiCursorModifier::CmdOrCtrl => event.modifiers().alt,
773 };
774
775 if !pending_nonempty_selections && multi_cursor_modifier && text_hitbox.is_hovered(window) {
776 let point = position_map.point_for_position(event.up.position);
777 editor.handle_click_hovered_link(point, event.modifiers(), window, cx);
778
779 cx.stop_propagation();
780 }
781 }
782
783 fn mouse_dragged(
784 editor: &mut Editor,
785 event: &MouseMoveEvent,
786 position_map: &PositionMap,
787 window: &mut Window,
788 cx: &mut Context<Editor>,
789 ) {
790 if !editor.has_pending_selection() {
791 return;
792 }
793
794 let text_bounds = position_map.text_hitbox.bounds;
795 let point_for_position = position_map.point_for_position(event.position);
796 let mut scroll_delta = gpui::Point::<f32>::default();
797 let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
798 let top = text_bounds.origin.y + vertical_margin;
799 let bottom = text_bounds.bottom_left().y - vertical_margin;
800 if event.position.y < top {
801 scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
802 }
803 if event.position.y > bottom {
804 scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
805 }
806
807 // We need horizontal width of text
808 let style = editor.style.clone().unwrap_or_default();
809 let font_id = window.text_system().resolve_font(&style.text.font());
810 let font_size = style.text.font_size.to_pixels(window.rem_size());
811 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
812
813 let scroll_margin_x = EditorSettings::get_global(cx).horizontal_scroll_margin;
814
815 let scroll_space: Pixels = scroll_margin_x * em_width;
816
817 let left = text_bounds.origin.x + scroll_space;
818 let right = text_bounds.top_right().x - scroll_space;
819
820 if event.position.x < left {
821 scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
822 }
823 if event.position.x > right {
824 scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
825 }
826
827 editor.select(
828 SelectPhase::Update {
829 position: point_for_position.previous_valid,
830 goal_column: point_for_position.exact_unclipped.column(),
831 scroll_delta,
832 },
833 window,
834 cx,
835 );
836 }
837
838 fn mouse_moved(
839 editor: &mut Editor,
840 event: &MouseMoveEvent,
841 position_map: &PositionMap,
842 window: &mut Window,
843 cx: &mut Context<Editor>,
844 ) {
845 let text_hitbox = &position_map.text_hitbox;
846 let gutter_hitbox = &position_map.gutter_hitbox;
847 let modifiers = event.modifiers;
848 let gutter_hovered = gutter_hitbox.is_hovered(window);
849 editor.set_gutter_hovered(gutter_hovered, cx);
850
851 // Don't trigger hover popover if mouse is hovering over context menu
852 if text_hitbox.is_hovered(window) {
853 let point_for_position = position_map.point_for_position(event.position);
854
855 editor.update_hovered_link(
856 point_for_position,
857 &position_map.snapshot,
858 modifiers,
859 window,
860 cx,
861 );
862
863 if let Some(point) = point_for_position.as_valid() {
864 let anchor = position_map
865 .snapshot
866 .buffer_snapshot
867 .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
868 hover_at(editor, Some(anchor), window, cx);
869 Self::update_visible_cursor(editor, point, position_map, window, cx);
870 } else {
871 hover_at(editor, None, window, cx);
872 }
873 } else {
874 editor.hide_hovered_link(cx);
875 hover_at(editor, None, window, cx);
876 if gutter_hovered {
877 cx.stop_propagation();
878 }
879 }
880 }
881
882 fn update_visible_cursor(
883 editor: &mut Editor,
884 point: DisplayPoint,
885 position_map: &PositionMap,
886 window: &mut Window,
887 cx: &mut Context<Editor>,
888 ) {
889 let snapshot = &position_map.snapshot;
890 let Some(hub) = editor.collaboration_hub() else {
891 return;
892 };
893 let start = snapshot.display_snapshot.clip_point(
894 DisplayPoint::new(point.row(), point.column().saturating_sub(1)),
895 Bias::Left,
896 );
897 let end = snapshot.display_snapshot.clip_point(
898 DisplayPoint::new(
899 point.row(),
900 (point.column() + 1).min(snapshot.line_len(point.row())),
901 ),
902 Bias::Right,
903 );
904
905 let range = snapshot
906 .buffer_snapshot
907 .anchor_at(start.to_point(&snapshot.display_snapshot), Bias::Left)
908 ..snapshot
909 .buffer_snapshot
910 .anchor_at(end.to_point(&snapshot.display_snapshot), Bias::Right);
911
912 let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
913 return;
914 };
915 let key = crate::HoveredCursor {
916 replica_id: selection.replica_id,
917 selection_id: selection.selection.id,
918 };
919 editor.hovered_cursors.insert(
920 key.clone(),
921 cx.spawn_in(window, |editor, mut cx| async move {
922 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
923 editor
924 .update(&mut cx, |editor, cx| {
925 editor.hovered_cursors.remove(&key);
926 cx.notify();
927 })
928 .ok();
929 }),
930 );
931 cx.notify()
932 }
933
934 fn layout_selections(
935 &self,
936 start_anchor: Anchor,
937 end_anchor: Anchor,
938 local_selections: &[Selection<Point>],
939 snapshot: &EditorSnapshot,
940 start_row: DisplayRow,
941 end_row: DisplayRow,
942 window: &mut Window,
943 cx: &mut App,
944 ) -> (
945 Vec<(PlayerColor, Vec<SelectionLayout>)>,
946 BTreeMap<DisplayRow, bool>,
947 Option<DisplayPoint>,
948 ) {
949 let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
950 let mut active_rows = BTreeMap::new();
951 let mut newest_selection_head = None;
952 self.editor.update(cx, |editor, cx| {
953 if editor.show_local_selections {
954 let mut layouts = Vec::new();
955 let newest = editor.selections.newest(cx);
956 for selection in local_selections.iter().cloned() {
957 let is_empty = selection.start == selection.end;
958 let is_newest = selection == newest;
959
960 let layout = SelectionLayout::new(
961 selection,
962 editor.selections.line_mode,
963 editor.cursor_shape,
964 &snapshot.display_snapshot,
965 is_newest,
966 editor.leader_peer_id.is_none(),
967 None,
968 );
969 if is_newest {
970 newest_selection_head = Some(layout.head);
971 }
972
973 for row in cmp::max(layout.active_rows.start.0, start_row.0)
974 ..=cmp::min(layout.active_rows.end.0, end_row.0)
975 {
976 let contains_non_empty_selection =
977 active_rows.entry(DisplayRow(row)).or_insert(!is_empty);
978 *contains_non_empty_selection |= !is_empty;
979 }
980 layouts.push(layout);
981 }
982
983 let player = editor.current_user_player_color(cx);
984 selections.push((player, layouts));
985 }
986
987 if let Some(collaboration_hub) = &editor.collaboration_hub {
988 // When following someone, render the local selections in their color.
989 if let Some(leader_id) = editor.leader_peer_id {
990 if let Some(collaborator) = collaboration_hub.collaborators(cx).get(&leader_id)
991 {
992 if let Some(participant_index) = collaboration_hub
993 .user_participant_indices(cx)
994 .get(&collaborator.user_id)
995 {
996 if let Some((local_selection_style, _)) = selections.first_mut() {
997 *local_selection_style = cx
998 .theme()
999 .players()
1000 .color_for_participant(participant_index.0);
1001 }
1002 }
1003 }
1004 }
1005
1006 let mut remote_selections = HashMap::default();
1007 for selection in snapshot.remote_selections_in_range(
1008 &(start_anchor..end_anchor),
1009 collaboration_hub.as_ref(),
1010 cx,
1011 ) {
1012 let selection_style =
1013 Self::get_participant_color(selection.participant_index, cx);
1014
1015 // Don't re-render the leader's selections, since the local selections
1016 // match theirs.
1017 if Some(selection.peer_id) == editor.leader_peer_id {
1018 continue;
1019 }
1020 let key = HoveredCursor {
1021 replica_id: selection.replica_id,
1022 selection_id: selection.selection.id,
1023 };
1024
1025 let is_shown =
1026 editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
1027
1028 remote_selections
1029 .entry(selection.replica_id)
1030 .or_insert((selection_style, Vec::new()))
1031 .1
1032 .push(SelectionLayout::new(
1033 selection.selection,
1034 selection.line_mode,
1035 selection.cursor_shape,
1036 &snapshot.display_snapshot,
1037 false,
1038 false,
1039 if is_shown { selection.user_name } else { None },
1040 ));
1041 }
1042
1043 selections.extend(remote_selections.into_values());
1044 } else if !editor.is_focused(window) && editor.show_cursor_when_unfocused {
1045 let layouts = snapshot
1046 .buffer_snapshot
1047 .selections_in_range(&(start_anchor..end_anchor), true)
1048 .map(move |(_, line_mode, cursor_shape, selection)| {
1049 SelectionLayout::new(
1050 selection,
1051 line_mode,
1052 cursor_shape,
1053 &snapshot.display_snapshot,
1054 false,
1055 false,
1056 None,
1057 )
1058 })
1059 .collect::<Vec<_>>();
1060 let player = editor.current_user_player_color(cx);
1061 selections.push((player, layouts));
1062 }
1063 });
1064 (selections, active_rows, newest_selection_head)
1065 }
1066
1067 fn collect_cursors(
1068 &self,
1069 snapshot: &EditorSnapshot,
1070 cx: &mut App,
1071 ) -> Vec<(DisplayPoint, Hsla)> {
1072 let editor = self.editor.read(cx);
1073 let mut cursors = Vec::new();
1074 let mut skip_local = false;
1075 let mut add_cursor = |anchor: Anchor, color| {
1076 cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
1077 };
1078 // Remote cursors
1079 if let Some(collaboration_hub) = &editor.collaboration_hub {
1080 for remote_selection in snapshot.remote_selections_in_range(
1081 &(Anchor::min()..Anchor::max()),
1082 collaboration_hub.deref(),
1083 cx,
1084 ) {
1085 let color = Self::get_participant_color(remote_selection.participant_index, cx);
1086 add_cursor(remote_selection.selection.head(), color.cursor);
1087 if Some(remote_selection.peer_id) == editor.leader_peer_id {
1088 skip_local = true;
1089 }
1090 }
1091 }
1092 // Local cursors
1093 if !skip_local {
1094 let color = cx.theme().players().local().cursor;
1095 editor.selections.disjoint.iter().for_each(|selection| {
1096 add_cursor(selection.head(), color);
1097 });
1098 if let Some(ref selection) = editor.selections.pending_anchor() {
1099 add_cursor(selection.head(), color);
1100 }
1101 }
1102 cursors
1103 }
1104
1105 fn layout_visible_cursors(
1106 &self,
1107 snapshot: &EditorSnapshot,
1108 selections: &[(PlayerColor, Vec<SelectionLayout>)],
1109 block_start_rows: &HashSet<DisplayRow>,
1110 visible_display_row_range: Range<DisplayRow>,
1111 line_layouts: &[LineWithInvisibles],
1112 text_hitbox: &Hitbox,
1113 content_origin: gpui::Point<Pixels>,
1114 scroll_position: gpui::Point<f32>,
1115 scroll_pixel_position: gpui::Point<Pixels>,
1116 line_height: Pixels,
1117 em_width: Pixels,
1118 em_advance: Pixels,
1119 autoscroll_containing_element: bool,
1120 window: &mut Window,
1121 cx: &mut App,
1122 ) -> Vec<CursorLayout> {
1123 let mut autoscroll_bounds = None;
1124 let cursor_layouts = self.editor.update(cx, |editor, cx| {
1125 let mut cursors = Vec::new();
1126
1127 let show_local_cursors = editor.show_local_cursors(window, cx);
1128
1129 for (player_color, selections) in selections {
1130 for selection in selections {
1131 let cursor_position = selection.head;
1132
1133 let in_range = visible_display_row_range.contains(&cursor_position.row());
1134 if (selection.is_local && !show_local_cursors)
1135 || !in_range
1136 || block_start_rows.contains(&cursor_position.row())
1137 {
1138 continue;
1139 }
1140
1141 let cursor_row_layout = &line_layouts
1142 [cursor_position.row().minus(visible_display_row_range.start) as usize];
1143 let cursor_column = cursor_position.column() as usize;
1144
1145 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
1146 let mut block_width =
1147 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
1148 if block_width == Pixels::ZERO {
1149 block_width = em_advance;
1150 }
1151 let block_text = if let CursorShape::Block = selection.cursor_shape {
1152 snapshot
1153 .grapheme_at(cursor_position)
1154 .or_else(|| {
1155 if cursor_column == 0 {
1156 snapshot.placeholder_text().and_then(|s| {
1157 s.graphemes(true).next().map(|s| s.to_string().into())
1158 })
1159 } else {
1160 None
1161 }
1162 })
1163 .and_then(|text| {
1164 let len = text.len();
1165
1166 let font = cursor_row_layout
1167 .font_id_for_index(cursor_column)
1168 .and_then(|cursor_font_id| {
1169 window.text_system().get_font_for_id(cursor_font_id)
1170 })
1171 .unwrap_or(self.style.text.font());
1172
1173 // Invert the text color for the block cursor. Ensure that the text
1174 // color is opaque enough to be visible against the background color.
1175 //
1176 // 0.75 is an arbitrary threshold to determine if the background color is
1177 // opaque enough to use as a text color.
1178 //
1179 // TODO: In the future we should ensure themes have a `text_inverse` color.
1180 let color = if cx.theme().colors().editor_background.a < 0.75 {
1181 match cx.theme().appearance {
1182 Appearance::Dark => Hsla::black(),
1183 Appearance::Light => Hsla::white(),
1184 }
1185 } else {
1186 cx.theme().colors().editor_background
1187 };
1188
1189 window
1190 .text_system()
1191 .shape_line(
1192 text,
1193 cursor_row_layout.font_size,
1194 &[TextRun {
1195 len,
1196 font,
1197 color,
1198 background_color: None,
1199 strikethrough: None,
1200 underline: None,
1201 }],
1202 )
1203 .log_err()
1204 })
1205 } else {
1206 None
1207 };
1208
1209 let x = cursor_character_x - scroll_pixel_position.x;
1210 let y = (cursor_position.row().as_f32()
1211 - scroll_pixel_position.y / line_height)
1212 * line_height;
1213 if selection.is_newest {
1214 editor.pixel_position_of_newest_cursor = Some(point(
1215 text_hitbox.origin.x + x + block_width / 2.,
1216 text_hitbox.origin.y + y + line_height / 2.,
1217 ));
1218
1219 if autoscroll_containing_element {
1220 let top = text_hitbox.origin.y
1221 + (cursor_position.row().as_f32() - scroll_position.y - 3.).max(0.)
1222 * line_height;
1223 let left = text_hitbox.origin.x
1224 + (cursor_position.column() as f32 - scroll_position.x - 3.)
1225 .max(0.)
1226 * em_width;
1227
1228 let bottom = text_hitbox.origin.y
1229 + (cursor_position.row().as_f32() - scroll_position.y + 4.)
1230 * line_height;
1231 let right = text_hitbox.origin.x
1232 + (cursor_position.column() as f32 - scroll_position.x + 4.)
1233 * em_width;
1234
1235 autoscroll_bounds =
1236 Some(Bounds::from_corners(point(left, top), point(right, bottom)))
1237 }
1238 }
1239
1240 let mut cursor = CursorLayout {
1241 color: player_color.cursor,
1242 block_width,
1243 origin: point(x, y),
1244 line_height,
1245 shape: selection.cursor_shape,
1246 block_text,
1247 cursor_name: None,
1248 };
1249 let cursor_name = selection.user_name.clone().map(|name| CursorName {
1250 string: name,
1251 color: self.style.background,
1252 is_top_row: cursor_position.row().0 == 0,
1253 });
1254 cursor.layout(content_origin, cursor_name, window, cx);
1255 cursors.push(cursor);
1256 }
1257 }
1258
1259 cursors
1260 });
1261
1262 if let Some(bounds) = autoscroll_bounds {
1263 window.request_autoscroll(bounds);
1264 }
1265
1266 cursor_layouts
1267 }
1268
1269 fn layout_scrollbars(
1270 &self,
1271 snapshot: &EditorSnapshot,
1272 scrollbar_range_data: ScrollbarRangeData,
1273 scroll_position: gpui::Point<f32>,
1274 non_visible_cursors: bool,
1275 window: &mut Window,
1276 cx: &mut App,
1277 ) -> AxisPair<Option<ScrollbarLayout>> {
1278 let letter_size = scrollbar_range_data.letter_size;
1279 let text_units_per_page = axis_pair(
1280 scrollbar_range_data.scrollbar_bounds.size.width / letter_size.width,
1281 scrollbar_range_data.scrollbar_bounds.size.height / letter_size.height,
1282 );
1283
1284 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
1285 let show_scrollbars = self.editor.read(cx).show_scrollbars
1286 && match scrollbar_settings.show {
1287 ShowScrollbar::Auto => {
1288 let editor = self.editor.read(cx);
1289 let is_singleton = editor.is_singleton(cx);
1290 // Git
1291 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_diff_hunks())
1292 ||
1293 // Buffer Search Results
1294 (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
1295 ||
1296 // Selected Text Occurrences
1297 (is_singleton && scrollbar_settings.selected_text && editor.has_background_highlights::<SelectedTextHighlight>())
1298 ||
1299 // Selected Symbol Occurrences
1300 (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
1301 ||
1302 // Diagnostics
1303 (is_singleton && scrollbar_settings.diagnostics != ScrollbarDiagnostics::None && snapshot.buffer_snapshot.has_diagnostics())
1304 ||
1305 // Cursors out of sight
1306 non_visible_cursors
1307 ||
1308 // Scrollmanager
1309 editor.scroll_manager.scrollbars_visible()
1310 }
1311 ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
1312 ShowScrollbar::Always => true,
1313 ShowScrollbar::Never => false,
1314 };
1315
1316 let axes: AxisPair<bool> = scrollbar_settings.axes.into();
1317
1318 if snapshot.mode != EditorMode::Full {
1319 return axis_pair(None, None);
1320 }
1321
1322 let visible_range = axis_pair(
1323 axes.horizontal
1324 .then(|| scroll_position.x..scroll_position.x + text_units_per_page.horizontal),
1325 axes.vertical
1326 .then(|| scroll_position.y..scroll_position.y + text_units_per_page.vertical),
1327 );
1328
1329 // If a drag took place after we started dragging the scrollbar,
1330 // cancel the scrollbar drag.
1331 if cx.has_active_drag() {
1332 self.editor.update(cx, |editor, cx| {
1333 editor
1334 .scroll_manager
1335 .set_is_dragging_scrollbar(Axis::Horizontal, false, cx);
1336 editor
1337 .scroll_manager
1338 .set_is_dragging_scrollbar(Axis::Vertical, false, cx);
1339 });
1340 }
1341
1342 let text_bounds = scrollbar_range_data.scrollbar_bounds;
1343
1344 let track_bounds = axis_pair(
1345 axes.horizontal.then(|| {
1346 Bounds::from_corners(
1347 point(
1348 text_bounds.bottom_left().x,
1349 text_bounds.bottom_left().y - self.style.scrollbar_width,
1350 ),
1351 point(
1352 text_bounds.bottom_right().x
1353 - if axes.vertical {
1354 self.style.scrollbar_width
1355 } else {
1356 px(0.)
1357 },
1358 text_bounds.bottom_right().y,
1359 ),
1360 )
1361 }),
1362 axes.vertical.then(|| {
1363 Bounds::from_corners(
1364 point(self.scrollbar_left(&text_bounds), text_bounds.origin.y),
1365 text_bounds.bottom_right(),
1366 )
1367 }),
1368 );
1369
1370 let scroll_range_size = scrollbar_range_data.scroll_range.size;
1371 let total_text_units = axis_pair(
1372 Some(scroll_range_size.width / letter_size.width),
1373 Some(scroll_range_size.height / letter_size.height),
1374 );
1375
1376 let thumb_size = axis_pair(
1377 total_text_units
1378 .horizontal
1379 .zip(track_bounds.horizontal)
1380 .and_then(|(total_text_units_x, track_bounds_x)| {
1381 if text_units_per_page.horizontal >= total_text_units_x {
1382 return None;
1383 }
1384
1385 let thumb_percent =
1386 (text_units_per_page.horizontal / total_text_units_x).min(1.);
1387
1388 Some(track_bounds_x.size.width * thumb_percent)
1389 }),
1390 total_text_units.vertical.zip(track_bounds.vertical).map(
1391 |(total_text_units_y, track_bounds_y)| {
1392 let thumb_percent = (text_units_per_page.vertical / total_text_units_y).min(1.);
1393
1394 track_bounds_y.size.height * thumb_percent
1395 },
1396 ),
1397 );
1398
1399 // NOTE: Space not taken by track bounds divided by text units not on screen
1400 let text_unit_size = axis_pair(
1401 thumb_size
1402 .horizontal
1403 .zip(track_bounds.horizontal)
1404 .zip(total_text_units.horizontal)
1405 .map(|((thumb_size, track_bounds), total_text_units)| {
1406 (track_bounds.size.width - thumb_size)
1407 / (total_text_units - text_units_per_page.horizontal).max(0.)
1408 }),
1409 thumb_size
1410 .vertical
1411 .zip(track_bounds.vertical)
1412 .zip(total_text_units.vertical)
1413 .map(|((thumb_size, track_bounds), total_text_units)| {
1414 (track_bounds.size.height - thumb_size)
1415 / (total_text_units - text_units_per_page.vertical).max(0.)
1416 }),
1417 );
1418
1419 let horizontal_scrollbar = track_bounds
1420 .horizontal
1421 .zip(visible_range.horizontal)
1422 .zip(text_unit_size.horizontal)
1423 .zip(thumb_size.horizontal)
1424 .map(
1425 |(((track_bounds, visible_range), text_unit_size), thumb_size)| ScrollbarLayout {
1426 hitbox: window.insert_hitbox(track_bounds, false),
1427 visible_range,
1428 text_unit_size,
1429 visible: show_scrollbars,
1430 thumb_size,
1431 axis: Axis::Horizontal,
1432 },
1433 );
1434
1435 let vertical_scrollbar = track_bounds
1436 .vertical
1437 .zip(visible_range.vertical)
1438 .zip(text_unit_size.vertical)
1439 .zip(thumb_size.vertical)
1440 .map(
1441 |(((track_bounds, visible_range), text_unit_size), thumb_size)| ScrollbarLayout {
1442 hitbox: window.insert_hitbox(track_bounds, false),
1443 visible_range,
1444 text_unit_size,
1445 visible: show_scrollbars,
1446 thumb_size,
1447 axis: Axis::Vertical,
1448 },
1449 );
1450
1451 axis_pair(horizontal_scrollbar, vertical_scrollbar)
1452 }
1453
1454 fn prepaint_crease_toggles(
1455 &self,
1456 crease_toggles: &mut [Option<AnyElement>],
1457 line_height: Pixels,
1458 gutter_dimensions: &GutterDimensions,
1459 gutter_settings: crate::editor_settings::Gutter,
1460 scroll_pixel_position: gpui::Point<Pixels>,
1461 gutter_hitbox: &Hitbox,
1462 window: &mut Window,
1463 cx: &mut App,
1464 ) {
1465 for (ix, crease_toggle) in crease_toggles.iter_mut().enumerate() {
1466 if let Some(crease_toggle) = crease_toggle {
1467 debug_assert!(gutter_settings.folds);
1468 let available_space = size(
1469 AvailableSpace::MinContent,
1470 AvailableSpace::Definite(line_height * 0.55),
1471 );
1472 let crease_toggle_size = crease_toggle.layout_as_root(available_space, window, cx);
1473
1474 let position = point(
1475 gutter_dimensions.width - gutter_dimensions.right_padding,
1476 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1477 );
1478 let centering_offset = point(
1479 (gutter_dimensions.fold_area_width() - crease_toggle_size.width) / 2.,
1480 (line_height - crease_toggle_size.height) / 2.,
1481 );
1482 let origin = gutter_hitbox.origin + position + centering_offset;
1483 crease_toggle.prepaint_as_root(origin, available_space, window, cx);
1484 }
1485 }
1486 }
1487
1488 fn prepaint_crease_trailers(
1489 &self,
1490 trailers: Vec<Option<AnyElement>>,
1491 lines: &[LineWithInvisibles],
1492 line_height: Pixels,
1493 content_origin: gpui::Point<Pixels>,
1494 scroll_pixel_position: gpui::Point<Pixels>,
1495 em_width: Pixels,
1496 window: &mut Window,
1497 cx: &mut App,
1498 ) -> Vec<Option<CreaseTrailerLayout>> {
1499 trailers
1500 .into_iter()
1501 .enumerate()
1502 .map(|(ix, element)| {
1503 let mut element = element?;
1504 let available_space = size(
1505 AvailableSpace::MinContent,
1506 AvailableSpace::Definite(line_height),
1507 );
1508 let size = element.layout_as_root(available_space, window, cx);
1509
1510 let line = &lines[ix];
1511 let padding = if line.width == Pixels::ZERO {
1512 Pixels::ZERO
1513 } else {
1514 4. * em_width
1515 };
1516 let position = point(
1517 scroll_pixel_position.x + line.width + padding,
1518 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
1519 );
1520 let centering_offset = point(px(0.), (line_height - size.height) / 2.);
1521 let origin = content_origin + position + centering_offset;
1522 element.prepaint_as_root(origin, available_space, window, cx);
1523 Some(CreaseTrailerLayout {
1524 element,
1525 bounds: Bounds::new(origin, size),
1526 })
1527 })
1528 .collect()
1529 }
1530
1531 // Folds contained in a hunk are ignored apart from shrinking visual size
1532 // If a fold contains any hunks then that fold line is marked as modified
1533 fn layout_gutter_diff_hunks(
1534 &self,
1535 line_height: Pixels,
1536 gutter_hitbox: &Hitbox,
1537 display_rows: Range<DisplayRow>,
1538 snapshot: &EditorSnapshot,
1539 window: &mut Window,
1540 cx: &mut App,
1541 ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
1542 let buffer_start = DisplayPoint::new(display_rows.start, 0).to_point(snapshot);
1543 let buffer_end = DisplayPoint::new(display_rows.end, 0).to_point(snapshot);
1544
1545 let mut display_hunks = Vec::<(DisplayDiffHunk, Option<Hitbox>)>::new();
1546 let folded_buffers = self.editor.read(cx).folded_buffers(cx);
1547
1548 for hunk in snapshot
1549 .buffer_snapshot
1550 .diff_hunks_in_range(buffer_start..buffer_end)
1551 {
1552 if folded_buffers.contains(&hunk.buffer_id) {
1553 continue;
1554 }
1555
1556 let hunk_start_point = Point::new(hunk.row_range.start.0, 0);
1557 let hunk_end_point = Point::new(hunk.row_range.end.0, 0);
1558
1559 let hunk_display_start = snapshot.point_to_display_point(hunk_start_point, Bias::Left);
1560 let hunk_display_end = snapshot.point_to_display_point(hunk_end_point, Bias::Right);
1561
1562 let display_hunk = if hunk_display_start.column() != 0 {
1563 DisplayDiffHunk::Folded {
1564 display_row: hunk_display_start.row(),
1565 }
1566 } else {
1567 let mut end_row = hunk_display_end.row();
1568 if hunk_display_end.column() > 0 {
1569 end_row.0 += 1;
1570 }
1571 DisplayDiffHunk::Unfolded {
1572 status: hunk.status(),
1573 diff_base_byte_range: hunk.diff_base_byte_range,
1574 display_row_range: hunk_display_start.row()..end_row,
1575 multi_buffer_range: Anchor::range_in_buffer(
1576 hunk.excerpt_id,
1577 hunk.buffer_id,
1578 hunk.buffer_range,
1579 ),
1580 }
1581 };
1582
1583 display_hunks.push((display_hunk, None));
1584 }
1585
1586 let git_gutter_setting = ProjectSettings::get_global(cx)
1587 .git
1588 .git_gutter
1589 .unwrap_or_default();
1590 if let GitGutterSetting::TrackedFiles = git_gutter_setting {
1591 for (hunk, hitbox) in &mut display_hunks {
1592 if matches!(hunk, DisplayDiffHunk::Unfolded { .. }) {
1593 let hunk_bounds =
1594 Self::diff_hunk_bounds(snapshot, line_height, gutter_hitbox.bounds, hunk);
1595 *hitbox = Some(window.insert_hitbox(hunk_bounds, true));
1596 }
1597 }
1598 }
1599
1600 display_hunks
1601 }
1602
1603 fn layout_inline_blame(
1604 &self,
1605 display_row: DisplayRow,
1606 row_info: &RowInfo,
1607 line_layout: &LineWithInvisibles,
1608 crease_trailer: Option<&CreaseTrailerLayout>,
1609 em_width: Pixels,
1610 content_origin: gpui::Point<Pixels>,
1611 scroll_pixel_position: gpui::Point<Pixels>,
1612 line_height: Pixels,
1613 window: &mut Window,
1614 cx: &mut App,
1615 ) -> Option<AnyElement> {
1616 if !self
1617 .editor
1618 .update(cx, |editor, cx| editor.render_git_blame_inline(window, cx))
1619 {
1620 return None;
1621 }
1622
1623 let workspace = self
1624 .editor
1625 .read(cx)
1626 .workspace
1627 .as_ref()
1628 .map(|(w, _)| w.clone());
1629
1630 let editor = self.editor.read(cx);
1631 let blame = editor.blame.clone()?;
1632 let padding = {
1633 const INLINE_BLAME_PADDING_EM_WIDTHS: f32 = 6.;
1634 const INLINE_ACCEPT_SUGGESTION_EM_WIDTHS: f32 = 14.;
1635
1636 let mut padding = INLINE_BLAME_PADDING_EM_WIDTHS;
1637
1638 if let Some(inline_completion) = editor.active_inline_completion.as_ref() {
1639 match &inline_completion.completion {
1640 InlineCompletion::Edit {
1641 display_mode: EditDisplayMode::TabAccept,
1642 ..
1643 } => padding += INLINE_ACCEPT_SUGGESTION_EM_WIDTHS,
1644 _ => {}
1645 }
1646 }
1647
1648 padding * em_width
1649 };
1650
1651 let blame_entry = blame
1652 .update(cx, |blame, cx| {
1653 blame.blame_for_rows(&[*row_info], cx).next()
1654 })
1655 .flatten()?;
1656
1657 let mut element =
1658 render_inline_blame_entry(&blame, blame_entry, &self.style, workspace, cx);
1659
1660 let start_y = content_origin.y
1661 + line_height * (display_row.as_f32() - scroll_pixel_position.y / line_height);
1662
1663 let start_x = {
1664 let line_end = if let Some(crease_trailer) = crease_trailer {
1665 crease_trailer.bounds.right()
1666 } else {
1667 content_origin.x - scroll_pixel_position.x + line_layout.width
1668 };
1669
1670 let padded_line_end = line_end + padding;
1671
1672 let min_column_in_pixels = ProjectSettings::get_global(cx)
1673 .git
1674 .inline_blame
1675 .and_then(|settings| settings.min_column)
1676 .map(|col| self.column_pixels(col as usize, window, cx))
1677 .unwrap_or(px(0.));
1678 let min_start = content_origin.x - scroll_pixel_position.x + min_column_in_pixels;
1679
1680 cmp::max(padded_line_end, min_start)
1681 };
1682
1683 let absolute_offset = point(start_x, start_y);
1684 element.prepaint_as_root(absolute_offset, AvailableSpace::min_size(), window, cx);
1685
1686 Some(element)
1687 }
1688
1689 fn layout_blame_entries(
1690 &self,
1691 buffer_rows: &[RowInfo],
1692 em_width: Pixels,
1693 scroll_position: gpui::Point<f32>,
1694 line_height: Pixels,
1695 gutter_hitbox: &Hitbox,
1696 max_width: Option<Pixels>,
1697 window: &mut Window,
1698 cx: &mut App,
1699 ) -> Option<Vec<AnyElement>> {
1700 if !self
1701 .editor
1702 .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
1703 {
1704 return None;
1705 }
1706
1707 let blame = self.editor.read(cx).blame.clone()?;
1708 let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
1709 blame.blame_for_rows(buffer_rows, cx).collect()
1710 });
1711
1712 let width = if let Some(max_width) = max_width {
1713 AvailableSpace::Definite(max_width)
1714 } else {
1715 AvailableSpace::MaxContent
1716 };
1717 let scroll_top = scroll_position.y * line_height;
1718 let start_x = em_width;
1719
1720 let mut last_used_color: Option<(PlayerColor, Oid)> = None;
1721
1722 let shaped_lines = blamed_rows
1723 .into_iter()
1724 .enumerate()
1725 .flat_map(|(ix, blame_entry)| {
1726 if let Some(blame_entry) = blame_entry {
1727 let mut element = render_blame_entry(
1728 ix,
1729 &blame,
1730 blame_entry,
1731 &self.style,
1732 &mut last_used_color,
1733 self.editor.clone(),
1734 cx,
1735 );
1736
1737 let start_y = ix as f32 * line_height - (scroll_top % line_height);
1738 let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
1739
1740 element.prepaint_as_root(
1741 absolute_offset,
1742 size(width, AvailableSpace::MinContent),
1743 window,
1744 cx,
1745 );
1746
1747 Some(element)
1748 } else {
1749 None
1750 }
1751 })
1752 .collect();
1753
1754 Some(shaped_lines)
1755 }
1756
1757 fn layout_indent_guides(
1758 &self,
1759 content_origin: gpui::Point<Pixels>,
1760 text_origin: gpui::Point<Pixels>,
1761 visible_buffer_range: Range<MultiBufferRow>,
1762 scroll_pixel_position: gpui::Point<Pixels>,
1763 line_height: Pixels,
1764 snapshot: &DisplaySnapshot,
1765 window: &mut Window,
1766 cx: &mut App,
1767 ) -> Option<Vec<IndentGuideLayout>> {
1768 let indent_guides = self.editor.update(cx, |editor, cx| {
1769 editor.indent_guides(visible_buffer_range, snapshot, cx)
1770 })?;
1771
1772 let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
1773 editor
1774 .find_active_indent_guide_indices(&indent_guides, snapshot, window, cx)
1775 .unwrap_or_default()
1776 });
1777
1778 Some(
1779 indent_guides
1780 .into_iter()
1781 .enumerate()
1782 .filter_map(|(i, indent_guide)| {
1783 let single_indent_width =
1784 self.column_pixels(indent_guide.tab_size as usize, window, cx);
1785 let total_width = single_indent_width * indent_guide.depth as f32;
1786 let start_x = content_origin.x + total_width - scroll_pixel_position.x;
1787 if start_x >= text_origin.x {
1788 let (offset_y, length) = Self::calculate_indent_guide_bounds(
1789 indent_guide.start_row..indent_guide.end_row,
1790 line_height,
1791 snapshot,
1792 );
1793
1794 let start_y = content_origin.y + offset_y - scroll_pixel_position.y;
1795
1796 Some(IndentGuideLayout {
1797 origin: point(start_x, start_y),
1798 length,
1799 single_indent_width,
1800 depth: indent_guide.depth,
1801 active: active_indent_guide_indices.contains(&i),
1802 settings: indent_guide.settings,
1803 })
1804 } else {
1805 None
1806 }
1807 })
1808 .collect(),
1809 )
1810 }
1811
1812 fn calculate_indent_guide_bounds(
1813 row_range: Range<MultiBufferRow>,
1814 line_height: Pixels,
1815 snapshot: &DisplaySnapshot,
1816 ) -> (gpui::Pixels, gpui::Pixels) {
1817 let start_point = Point::new(row_range.start.0, 0);
1818 let end_point = Point::new(row_range.end.0, 0);
1819
1820 let row_range = start_point.to_display_point(snapshot).row()
1821 ..end_point.to_display_point(snapshot).row();
1822
1823 let mut prev_line = start_point;
1824 prev_line.row = prev_line.row.saturating_sub(1);
1825 let prev_line = prev_line.to_display_point(snapshot).row();
1826
1827 let mut cons_line = end_point;
1828 cons_line.row += 1;
1829 let cons_line = cons_line.to_display_point(snapshot).row();
1830
1831 let mut offset_y = row_range.start.0 as f32 * line_height;
1832 let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
1833
1834 // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
1835 if row_range.end == cons_line {
1836 length += line_height;
1837 }
1838
1839 // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
1840 // we want to extend the indent guide to the start of the block.
1841 let mut block_height = 0;
1842 let mut block_offset = 0;
1843 let mut found_excerpt_header = false;
1844 for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
1845 if matches!(block, Block::ExcerptBoundary { .. }) {
1846 found_excerpt_header = true;
1847 break;
1848 }
1849 block_offset += block.height();
1850 block_height += block.height();
1851 }
1852 if !found_excerpt_header {
1853 offset_y -= block_offset as f32 * line_height;
1854 length += block_height as f32 * line_height;
1855 }
1856
1857 // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
1858 // we want to ensure that the indent guide stops before the excerpt header.
1859 let mut block_height = 0;
1860 let mut found_excerpt_header = false;
1861 for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
1862 if matches!(block, Block::ExcerptBoundary { .. }) {
1863 found_excerpt_header = true;
1864 }
1865 block_height += block.height();
1866 }
1867 if found_excerpt_header {
1868 length -= block_height as f32 * line_height;
1869 }
1870
1871 (offset_y, length)
1872 }
1873
1874 fn layout_run_indicators(
1875 &self,
1876 line_height: Pixels,
1877 range: Range<DisplayRow>,
1878 scroll_pixel_position: gpui::Point<Pixels>,
1879 gutter_dimensions: &GutterDimensions,
1880 gutter_hitbox: &Hitbox,
1881 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
1882 snapshot: &EditorSnapshot,
1883 window: &mut Window,
1884 cx: &mut App,
1885 ) -> Vec<AnyElement> {
1886 self.editor.update(cx, |editor, cx| {
1887 let active_task_indicator_row =
1888 if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
1889 deployed_from_indicator,
1890 actions,
1891 ..
1892 })) = editor.context_menu.borrow().as_ref()
1893 {
1894 actions
1895 .tasks
1896 .as_ref()
1897 .map(|tasks| tasks.position.to_display_point(snapshot).row())
1898 .or(*deployed_from_indicator)
1899 } else {
1900 None
1901 };
1902
1903 let offset_range_start = snapshot
1904 .display_point_to_anchor(DisplayPoint::new(range.start, 0), Bias::Left)
1905 .to_offset(&snapshot.buffer_snapshot);
1906 let offset_range_end = snapshot
1907 .display_point_to_anchor(DisplayPoint::new(range.end, 0), Bias::Right)
1908 .to_offset(&snapshot.buffer_snapshot);
1909
1910 editor
1911 .tasks
1912 .iter()
1913 .filter_map(|(_, tasks)| {
1914 if tasks.offset.0 < offset_range_start || tasks.offset.0 >= offset_range_end {
1915 return None;
1916 }
1917 let multibuffer_point = tasks.offset.0.to_point(&snapshot.buffer_snapshot);
1918 let multibuffer_row = MultiBufferRow(multibuffer_point.row);
1919 let buffer_folded = snapshot
1920 .buffer_snapshot
1921 .buffer_line_for_row(multibuffer_row)
1922 .map(|(buffer_snapshot, _)| buffer_snapshot.remote_id())
1923 .map(|buffer_id| editor.is_buffer_folded(buffer_id, cx))
1924 .unwrap_or(false);
1925 if buffer_folded {
1926 return None;
1927 }
1928
1929 if snapshot.is_line_folded(multibuffer_row) {
1930 // Skip folded indicators, unless it's the starting line of a fold.
1931 if multibuffer_row
1932 .0
1933 .checked_sub(1)
1934 .map_or(false, |previous_row| {
1935 snapshot.is_line_folded(MultiBufferRow(previous_row))
1936 })
1937 {
1938 return None;
1939 }
1940 }
1941 let display_row = multibuffer_point.to_display_point(snapshot).row();
1942 let button = editor.render_run_indicator(
1943 &self.style,
1944 Some(display_row) == active_task_indicator_row,
1945 display_row,
1946 cx,
1947 );
1948
1949 let button = prepaint_gutter_button(
1950 button,
1951 display_row,
1952 line_height,
1953 gutter_dimensions,
1954 scroll_pixel_position,
1955 gutter_hitbox,
1956 rows_with_hunk_bounds,
1957 window,
1958 cx,
1959 );
1960 Some(button)
1961 })
1962 .collect_vec()
1963 })
1964 }
1965
1966 fn layout_code_actions_indicator(
1967 &self,
1968 line_height: Pixels,
1969 newest_selection_head: DisplayPoint,
1970 scroll_pixel_position: gpui::Point<Pixels>,
1971 gutter_dimensions: &GutterDimensions,
1972 gutter_hitbox: &Hitbox,
1973 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
1974 window: &mut Window,
1975 cx: &mut App,
1976 ) -> Option<AnyElement> {
1977 let mut active = false;
1978 let mut button = None;
1979 let row = newest_selection_head.row();
1980 self.editor.update(cx, |editor, cx| {
1981 if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
1982 deployed_from_indicator,
1983 ..
1984 })) = editor.context_menu.borrow().as_ref()
1985 {
1986 active = deployed_from_indicator.map_or(true, |indicator_row| indicator_row == row);
1987 };
1988 button = editor.render_code_actions_indicator(&self.style, row, active, cx);
1989 });
1990
1991 let button = prepaint_gutter_button(
1992 button?,
1993 row,
1994 line_height,
1995 gutter_dimensions,
1996 scroll_pixel_position,
1997 gutter_hitbox,
1998 rows_with_hunk_bounds,
1999 window,
2000 cx,
2001 );
2002
2003 Some(button)
2004 }
2005
2006 fn get_participant_color(participant_index: Option<ParticipantIndex>, cx: &App) -> PlayerColor {
2007 if let Some(index) = participant_index {
2008 cx.theme().players().color_for_participant(index.0)
2009 } else {
2010 cx.theme().players().absent()
2011 }
2012 }
2013
2014 fn calculate_relative_line_numbers(
2015 &self,
2016 snapshot: &EditorSnapshot,
2017 rows: &Range<DisplayRow>,
2018 relative_to: Option<DisplayRow>,
2019 ) -> HashMap<DisplayRow, DisplayRowDelta> {
2020 let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
2021 let Some(relative_to) = relative_to else {
2022 return relative_rows;
2023 };
2024
2025 let start = rows.start.min(relative_to);
2026 let end = rows.end.max(relative_to);
2027
2028 let buffer_rows = snapshot
2029 .row_infos(start)
2030 .take(1 + end.minus(start) as usize)
2031 .collect::<Vec<_>>();
2032
2033 let head_idx = relative_to.minus(start);
2034 let mut delta = 1;
2035 let mut i = head_idx + 1;
2036 while i < buffer_rows.len() as u32 {
2037 if buffer_rows[i as usize].buffer_row.is_some() {
2038 if rows.contains(&DisplayRow(i + start.0)) {
2039 relative_rows.insert(DisplayRow(i + start.0), delta);
2040 }
2041 delta += 1;
2042 }
2043 i += 1;
2044 }
2045 delta = 1;
2046 i = head_idx.min(buffer_rows.len() as u32 - 1);
2047 while i > 0 && buffer_rows[i as usize].buffer_row.is_none() {
2048 i -= 1;
2049 }
2050
2051 while i > 0 {
2052 i -= 1;
2053 if buffer_rows[i as usize].buffer_row.is_some() {
2054 if rows.contains(&DisplayRow(i + start.0)) {
2055 relative_rows.insert(DisplayRow(i + start.0), delta);
2056 }
2057 delta += 1;
2058 }
2059 }
2060
2061 relative_rows
2062 }
2063
2064 fn layout_line_numbers(
2065 &self,
2066 gutter_hitbox: Option<&Hitbox>,
2067 gutter_dimensions: GutterDimensions,
2068 line_height: Pixels,
2069 scroll_position: gpui::Point<f32>,
2070 rows: Range<DisplayRow>,
2071 buffer_rows: &[RowInfo],
2072 newest_selection_head: Option<DisplayPoint>,
2073 snapshot: &EditorSnapshot,
2074 window: &mut Window,
2075 cx: &mut App,
2076 ) -> Arc<HashMap<MultiBufferRow, LineNumberLayout>> {
2077 let include_line_numbers = snapshot.show_line_numbers.unwrap_or_else(|| {
2078 EditorSettings::get_global(cx).gutter.line_numbers && snapshot.mode == EditorMode::Full
2079 });
2080 if !include_line_numbers {
2081 return Arc::default();
2082 }
2083
2084 let (newest_selection_head, is_relative) = self.editor.update(cx, |editor, cx| {
2085 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
2086 let newest = editor.selections.newest::<Point>(cx);
2087 SelectionLayout::new(
2088 newest,
2089 editor.selections.line_mode,
2090 editor.cursor_shape,
2091 &snapshot.display_snapshot,
2092 true,
2093 true,
2094 None,
2095 )
2096 .head
2097 });
2098 let is_relative = editor.should_use_relative_line_numbers(cx);
2099 (newest_selection_head, is_relative)
2100 });
2101
2102 let relative_to = if is_relative {
2103 Some(newest_selection_head.row())
2104 } else {
2105 None
2106 };
2107 let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
2108 let mut line_number = String::new();
2109 let line_numbers = buffer_rows
2110 .into_iter()
2111 .enumerate()
2112 .flat_map(|(ix, row_info)| {
2113 let display_row = DisplayRow(rows.start.0 + ix as u32);
2114 line_number.clear();
2115 let non_relative_number = row_info.buffer_row? + 1;
2116 let number = relative_rows
2117 .get(&display_row)
2118 .unwrap_or(&non_relative_number);
2119 write!(&mut line_number, "{number}").unwrap();
2120 if matches!(row_info.diff_status, Some(DiffHunkStatus::Removed(_))) {
2121 return None;
2122 }
2123
2124 let color = cx.theme().colors().editor_line_number;
2125 let shaped_line = self
2126 .shape_line_number(SharedString::from(&line_number), color, window)
2127 .log_err()?;
2128 let scroll_top = scroll_position.y * line_height;
2129 let line_origin = gutter_hitbox.map(|hitbox| {
2130 hitbox.origin
2131 + point(
2132 hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
2133 ix as f32 * line_height - (scroll_top % line_height),
2134 )
2135 });
2136
2137 #[cfg(not(test))]
2138 let hitbox = line_origin.map(|line_origin| {
2139 window.insert_hitbox(
2140 Bounds::new(line_origin, size(shaped_line.width, line_height)),
2141 false,
2142 )
2143 });
2144 #[cfg(test)]
2145 let hitbox = {
2146 let _ = line_origin;
2147 None
2148 };
2149
2150 let multi_buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
2151 let multi_buffer_row = MultiBufferRow(multi_buffer_row);
2152 let line_number = LineNumberLayout {
2153 shaped_line,
2154 hitbox,
2155 display_row,
2156 };
2157 Some((multi_buffer_row, line_number))
2158 })
2159 .collect();
2160 Arc::new(line_numbers)
2161 }
2162
2163 fn layout_crease_toggles(
2164 &self,
2165 rows: Range<DisplayRow>,
2166 row_infos: &[RowInfo],
2167 active_rows: &BTreeMap<DisplayRow, bool>,
2168 snapshot: &EditorSnapshot,
2169 window: &mut Window,
2170 cx: &mut App,
2171 ) -> Vec<Option<AnyElement>> {
2172 let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
2173 && snapshot.mode == EditorMode::Full
2174 && self.editor.read(cx).is_singleton(cx);
2175 if include_fold_statuses {
2176 row_infos
2177 .into_iter()
2178 .enumerate()
2179 .map(|(ix, info)| {
2180 let row = info.multibuffer_row?;
2181 let display_row = DisplayRow(rows.start.0 + ix as u32);
2182 let active = active_rows.contains_key(&display_row);
2183
2184 snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
2185 })
2186 .collect()
2187 } else {
2188 Vec::new()
2189 }
2190 }
2191
2192 fn layout_crease_trailers(
2193 &self,
2194 buffer_rows: impl IntoIterator<Item = RowInfo>,
2195 snapshot: &EditorSnapshot,
2196 window: &mut Window,
2197 cx: &mut App,
2198 ) -> Vec<Option<AnyElement>> {
2199 buffer_rows
2200 .into_iter()
2201 .map(|row_info| {
2202 if let Some(row) = row_info.multibuffer_row {
2203 snapshot.render_crease_trailer(row, window, cx)
2204 } else {
2205 None
2206 }
2207 })
2208 .collect()
2209 }
2210
2211 fn layout_lines(
2212 rows: Range<DisplayRow>,
2213 snapshot: &EditorSnapshot,
2214 style: &EditorStyle,
2215 editor_width: Pixels,
2216 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2217 window: &mut Window,
2218 cx: &mut App,
2219 ) -> Vec<LineWithInvisibles> {
2220 if rows.start >= rows.end {
2221 return Vec::new();
2222 }
2223
2224 // Show the placeholder when the editor is empty
2225 if snapshot.is_empty() {
2226 let font_size = style.text.font_size.to_pixels(window.rem_size());
2227 let placeholder_color = cx.theme().colors().text_placeholder;
2228 let placeholder_text = snapshot.placeholder_text();
2229
2230 let placeholder_lines = placeholder_text
2231 .as_ref()
2232 .map_or("", AsRef::as_ref)
2233 .split('\n')
2234 .skip(rows.start.0 as usize)
2235 .chain(iter::repeat(""))
2236 .take(rows.len());
2237 placeholder_lines
2238 .filter_map(move |line| {
2239 let run = TextRun {
2240 len: line.len(),
2241 font: style.text.font(),
2242 color: placeholder_color,
2243 background_color: None,
2244 underline: Default::default(),
2245 strikethrough: None,
2246 };
2247 window
2248 .text_system()
2249 .shape_line(line.to_string().into(), font_size, &[run])
2250 .log_err()
2251 })
2252 .map(|line| LineWithInvisibles {
2253 width: line.width,
2254 len: line.len,
2255 fragments: smallvec![LineFragment::Text(line)],
2256 invisibles: Vec::new(),
2257 font_size,
2258 })
2259 .collect()
2260 } else {
2261 let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
2262 LineWithInvisibles::from_chunks(
2263 chunks,
2264 &style,
2265 MAX_LINE_LEN,
2266 rows.len(),
2267 snapshot.mode,
2268 editor_width,
2269 is_row_soft_wrapped,
2270 window,
2271 cx,
2272 )
2273 }
2274 }
2275
2276 fn prepaint_lines(
2277 &self,
2278 start_row: DisplayRow,
2279 line_layouts: &mut [LineWithInvisibles],
2280 line_height: Pixels,
2281 scroll_pixel_position: gpui::Point<Pixels>,
2282 content_origin: gpui::Point<Pixels>,
2283 window: &mut Window,
2284 cx: &mut App,
2285 ) -> SmallVec<[AnyElement; 1]> {
2286 let mut line_elements = SmallVec::new();
2287 for (ix, line) in line_layouts.iter_mut().enumerate() {
2288 let row = start_row + DisplayRow(ix as u32);
2289 line.prepaint(
2290 line_height,
2291 scroll_pixel_position,
2292 row,
2293 content_origin,
2294 &mut line_elements,
2295 window,
2296 cx,
2297 );
2298 }
2299 line_elements
2300 }
2301
2302 fn render_block(
2303 &self,
2304 block: &Block,
2305 available_width: AvailableSpace,
2306 block_id: BlockId,
2307 block_row_start: DisplayRow,
2308 snapshot: &EditorSnapshot,
2309 text_x: Pixels,
2310 rows: &Range<DisplayRow>,
2311 line_layouts: &[LineWithInvisibles],
2312 gutter_dimensions: &GutterDimensions,
2313 line_height: Pixels,
2314 em_width: Pixels,
2315 text_hitbox: &Hitbox,
2316 editor_width: Pixels,
2317 scroll_width: &mut Pixels,
2318 resized_blocks: &mut HashMap<CustomBlockId, u32>,
2319 selections: &[Selection<Point>],
2320 selected_buffer_ids: &Vec<BufferId>,
2321 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2322 sticky_header_excerpt_id: Option<ExcerptId>,
2323 window: &mut Window,
2324 cx: &mut App,
2325 ) -> (AnyElement, Size<Pixels>) {
2326 let mut element = match block {
2327 Block::Custom(block) => {
2328 let block_start = block.start().to_point(&snapshot.buffer_snapshot);
2329 let block_end = block.end().to_point(&snapshot.buffer_snapshot);
2330 let align_to = block_start.to_display_point(snapshot);
2331 let anchor_x = text_x
2332 + if rows.contains(&align_to.row()) {
2333 line_layouts[align_to.row().minus(rows.start) as usize]
2334 .x_for_index(align_to.column() as usize)
2335 } else {
2336 layout_line(
2337 align_to.row(),
2338 snapshot,
2339 &self.style,
2340 editor_width,
2341 is_row_soft_wrapped,
2342 window,
2343 cx,
2344 )
2345 .x_for_index(align_to.column() as usize)
2346 };
2347
2348 let selected = selections
2349 .binary_search_by(|selection| {
2350 if selection.end <= block_start {
2351 Ordering::Less
2352 } else if selection.start >= block_end {
2353 Ordering::Greater
2354 } else {
2355 Ordering::Equal
2356 }
2357 })
2358 .is_ok();
2359
2360 div()
2361 .size_full()
2362 .child(block.render(&mut BlockContext {
2363 window,
2364 app: cx,
2365 anchor_x,
2366 gutter_dimensions,
2367 line_height,
2368 em_width,
2369 block_id,
2370 selected,
2371 max_width: text_hitbox.size.width.max(*scroll_width),
2372 editor_style: &self.style,
2373 }))
2374 .into_any()
2375 }
2376
2377 Block::FoldedBuffer {
2378 first_excerpt,
2379 prev_excerpt,
2380 show_excerpt_controls,
2381 height,
2382 } => {
2383 let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
2384 let mut result = v_flex().id(block_id).w_full();
2385
2386 if let Some(prev_excerpt) = prev_excerpt {
2387 if *show_excerpt_controls {
2388 result = result.child(self.render_expand_excerpt_control(
2389 block_id,
2390 ExpandExcerptDirection::Down,
2391 prev_excerpt.id,
2392 gutter_dimensions,
2393 window,
2394 cx,
2395 ));
2396 }
2397 }
2398
2399 let jump_data = header_jump_data(snapshot, block_row_start, *height, first_excerpt);
2400 result
2401 .child(self.render_buffer_header(
2402 first_excerpt,
2403 true,
2404 selected,
2405 jump_data,
2406 window,
2407 cx,
2408 ))
2409 .into_any_element()
2410 }
2411
2412 Block::ExcerptBoundary {
2413 prev_excerpt,
2414 next_excerpt,
2415 show_excerpt_controls,
2416 height,
2417 starts_new_buffer,
2418 } => {
2419 let color = cx.theme().colors().clone();
2420 let mut result = v_flex().id(block_id).w_full();
2421
2422 if let Some(prev_excerpt) = prev_excerpt {
2423 if *show_excerpt_controls {
2424 result = result.child(self.render_expand_excerpt_control(
2425 block_id,
2426 ExpandExcerptDirection::Down,
2427 prev_excerpt.id,
2428 gutter_dimensions,
2429 window,
2430 cx,
2431 ));
2432 }
2433 }
2434
2435 if let Some(next_excerpt) = next_excerpt {
2436 let jump_data =
2437 header_jump_data(snapshot, block_row_start, *height, next_excerpt);
2438
2439 if *starts_new_buffer {
2440 if sticky_header_excerpt_id != Some(next_excerpt.id) {
2441 let selected = selected_buffer_ids.contains(&next_excerpt.buffer_id);
2442
2443 result = result.child(self.render_buffer_header(
2444 next_excerpt,
2445 false,
2446 selected,
2447 jump_data,
2448 window,
2449 cx,
2450 ));
2451 } else {
2452 result = result
2453 .child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
2454 }
2455
2456 if *show_excerpt_controls {
2457 result = result.child(self.render_expand_excerpt_control(
2458 block_id,
2459 ExpandExcerptDirection::Up,
2460 next_excerpt.id,
2461 gutter_dimensions,
2462 window,
2463 cx,
2464 ));
2465 }
2466 } else {
2467 if *show_excerpt_controls {
2468 result = result.child(
2469 h_flex()
2470 .relative()
2471 .child(
2472 div()
2473 .top(px(0.))
2474 .absolute()
2475 .w_full()
2476 .h_px()
2477 .bg(color.border_variant),
2478 )
2479 .child(self.render_expand_excerpt_control(
2480 block_id,
2481 ExpandExcerptDirection::Up,
2482 next_excerpt.id,
2483 gutter_dimensions,
2484 window,
2485 cx,
2486 )),
2487 );
2488 }
2489 };
2490 }
2491
2492 result.into_any()
2493 }
2494 };
2495
2496 // Discover the element's content height, then round up to the nearest multiple of line height.
2497 let preliminary_size = element.layout_as_root(
2498 size(available_width, AvailableSpace::MinContent),
2499 window,
2500 cx,
2501 );
2502 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
2503 let final_size = if preliminary_size.height == quantized_height {
2504 preliminary_size
2505 } else {
2506 element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
2507 };
2508
2509 if let BlockId::Custom(custom_block_id) = block_id {
2510 if block.height() > 0 {
2511 let element_height_in_lines =
2512 ((final_size.height / line_height).ceil() as u32).max(1);
2513 if element_height_in_lines != block.height() {
2514 resized_blocks.insert(custom_block_id, element_height_in_lines);
2515 }
2516 }
2517 }
2518
2519 (element, final_size)
2520 }
2521
2522 fn render_buffer_header(
2523 &self,
2524 for_excerpt: &ExcerptInfo,
2525 is_folded: bool,
2526 is_selected: bool,
2527 jump_data: JumpData,
2528 window: &mut Window,
2529 cx: &mut App,
2530 ) -> Div {
2531 let include_root = self
2532 .editor
2533 .read(cx)
2534 .project
2535 .as_ref()
2536 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
2537 .unwrap_or_default();
2538 let path = for_excerpt.buffer.resolve_file_path(cx, include_root);
2539 let filename = path
2540 .as_ref()
2541 .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
2542 let parent_path = path.as_ref().and_then(|path| {
2543 Some(path.parent()?.to_string_lossy().to_string() + std::path::MAIN_SEPARATOR_STR)
2544 });
2545 let focus_handle = self.editor.focus_handle(cx);
2546 let colors = cx.theme().colors();
2547
2548 div()
2549 .px_2()
2550 .pt_2()
2551 .w_full()
2552 .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
2553 .child(
2554 h_flex()
2555 .size_full()
2556 .gap_2()
2557 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
2558 .pl_0p5()
2559 .pr_5()
2560 .rounded_md()
2561 .shadow_md()
2562 .border_1()
2563 .map(|div| {
2564 let border_color = if is_selected && is_folded {
2565 colors.border_focused
2566 } else {
2567 colors.border
2568 };
2569 div.border_color(border_color)
2570 })
2571 .bg(colors.editor_subheader_background)
2572 .hover(|style| style.bg(colors.element_hover))
2573 .map(|header| {
2574 let editor = self.editor.clone();
2575 let buffer_id = for_excerpt.buffer_id;
2576 let toggle_chevron_icon =
2577 FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
2578 header.child(
2579 div()
2580 .hover(|style| style.bg(colors.element_selected))
2581 .rounded_sm()
2582 .child(
2583 ButtonLike::new("toggle-buffer-fold")
2584 .style(ui::ButtonStyle::Transparent)
2585 .size(ButtonSize::Large)
2586 .width(px(30.).into())
2587 .children(toggle_chevron_icon)
2588 .tooltip({
2589 let focus_handle = focus_handle.clone();
2590 move |window, cx| {
2591 Tooltip::for_action_in(
2592 "Toggle Excerpt Fold",
2593 &ToggleFold,
2594 &focus_handle,
2595 window,
2596 cx,
2597 )
2598 }
2599 })
2600 .on_click(move |_, _, cx| {
2601 if is_folded {
2602 editor.update(cx, |editor, cx| {
2603 editor.unfold_buffer(buffer_id, cx);
2604 });
2605 } else {
2606 editor.update(cx, |editor, cx| {
2607 editor.fold_buffer(buffer_id, cx);
2608 });
2609 }
2610 }),
2611 ),
2612 )
2613 })
2614 .children(
2615 self.editor
2616 .read(cx)
2617 .addons
2618 .values()
2619 .filter_map(|addon| {
2620 addon.render_buffer_header_controls(for_excerpt, window, cx)
2621 })
2622 .take(1),
2623 )
2624 .child(
2625 h_flex()
2626 .cursor_pointer()
2627 .id("path header block")
2628 .size_full()
2629 .justify_between()
2630 .child(
2631 h_flex()
2632 .gap_2()
2633 .child(
2634 filename
2635 .map(SharedString::from)
2636 .unwrap_or_else(|| "untitled".into()),
2637 )
2638 .when_some(parent_path, |then, path| {
2639 then.child(div().child(path).text_color(colors.text_muted))
2640 }),
2641 )
2642 .when(is_selected, |el| {
2643 el.child(
2644 h_flex()
2645 .id("jump-to-file-button")
2646 .gap_2p5()
2647 .child(Label::new("Jump To File"))
2648 .children(
2649 KeyBinding::for_action_in(
2650 &OpenExcerpts,
2651 &focus_handle,
2652 window,
2653 cx,
2654 )
2655 .map(|binding| binding.into_any_element()),
2656 ),
2657 )
2658 })
2659 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
2660 .on_click(window.listener_for(&self.editor, {
2661 move |editor, e: &ClickEvent, window, cx| {
2662 editor.open_excerpts_common(
2663 Some(jump_data.clone()),
2664 e.down.modifiers.secondary(),
2665 window,
2666 cx,
2667 );
2668 }
2669 })),
2670 ),
2671 )
2672 }
2673
2674 fn render_expand_excerpt_control(
2675 &self,
2676 block_id: BlockId,
2677 direction: ExpandExcerptDirection,
2678 excerpt_id: ExcerptId,
2679 gutter_dimensions: &GutterDimensions,
2680 window: &Window,
2681 cx: &mut App,
2682 ) -> impl IntoElement {
2683 let color = cx.theme().colors().clone();
2684 let hover_color = color.border_variant.opacity(0.5);
2685 let focus_handle = self.editor.focus_handle(cx).clone();
2686
2687 let icon_offset =
2688 gutter_dimensions.width - (gutter_dimensions.left_padding + gutter_dimensions.margin);
2689 let header_height = MULTI_BUFFER_EXCERPT_HEADER_HEIGHT as f32 * window.line_height();
2690 let group_name = if direction == ExpandExcerptDirection::Down {
2691 "expand-down"
2692 } else {
2693 "expand-up"
2694 };
2695
2696 let expand_area = |id: SharedString| {
2697 h_flex()
2698 .id(id)
2699 .w_full()
2700 .cursor_pointer()
2701 .block_mouse_down()
2702 .on_mouse_move(|_, _, cx| cx.stop_propagation())
2703 .hover(|style| style.bg(hover_color))
2704 .tooltip({
2705 let focus_handle = focus_handle.clone();
2706 move |window, cx| {
2707 Tooltip::for_action_in(
2708 "Expand Excerpt",
2709 &ExpandExcerpts { lines: 0 },
2710 &focus_handle,
2711 window,
2712 cx,
2713 )
2714 }
2715 })
2716 };
2717
2718 expand_area(
2719 format!(
2720 "block-{}-{}",
2721 block_id,
2722 if direction == ExpandExcerptDirection::Down {
2723 "down"
2724 } else {
2725 "up"
2726 }
2727 )
2728 .into(),
2729 )
2730 .group(group_name)
2731 .child(
2732 h_flex()
2733 .w(icon_offset)
2734 .h(header_height)
2735 .flex_none()
2736 .justify_end()
2737 .child(
2738 ButtonLike::new("expand-icon")
2739 .style(ButtonStyle::Transparent)
2740 .child(
2741 svg()
2742 .path(if direction == ExpandExcerptDirection::Down {
2743 IconName::ArrowDownFromLine.path()
2744 } else {
2745 IconName::ArrowUpFromLine.path()
2746 })
2747 .size(IconSize::XSmall.rems())
2748 .text_color(cx.theme().colors().editor_line_number)
2749 .group_hover(group_name, |style| {
2750 style.text_color(cx.theme().colors().editor_active_line_number)
2751 }),
2752 ),
2753 ),
2754 )
2755 .on_click(window.listener_for(&self.editor, {
2756 move |editor, _, _, cx| {
2757 editor.expand_excerpt(excerpt_id, direction, cx);
2758 cx.stop_propagation();
2759 }
2760 }))
2761 }
2762
2763 fn render_blocks(
2764 &self,
2765 rows: Range<DisplayRow>,
2766 snapshot: &EditorSnapshot,
2767 hitbox: &Hitbox,
2768 text_hitbox: &Hitbox,
2769 editor_width: Pixels,
2770 scroll_width: &mut Pixels,
2771 gutter_dimensions: &GutterDimensions,
2772 em_width: Pixels,
2773 text_x: Pixels,
2774 line_height: Pixels,
2775 line_layouts: &[LineWithInvisibles],
2776 selections: &[Selection<Point>],
2777 selected_buffer_ids: &Vec<BufferId>,
2778 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
2779 sticky_header_excerpt_id: Option<ExcerptId>,
2780 window: &mut Window,
2781 cx: &mut App,
2782 ) -> Result<Vec<BlockLayout>, HashMap<CustomBlockId, u32>> {
2783 let (fixed_blocks, non_fixed_blocks) = snapshot
2784 .blocks_in_range(rows.clone())
2785 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
2786
2787 let mut focused_block = self
2788 .editor
2789 .update(cx, |editor, _| editor.take_focused_block());
2790 let mut fixed_block_max_width = Pixels::ZERO;
2791 let mut blocks = Vec::new();
2792 let mut resized_blocks = HashMap::default();
2793
2794 for (row, block) in fixed_blocks {
2795 let block_id = block.id();
2796
2797 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2798 focused_block = None;
2799 }
2800
2801 let (element, element_size) = self.render_block(
2802 block,
2803 AvailableSpace::MinContent,
2804 block_id,
2805 row,
2806 snapshot,
2807 text_x,
2808 &rows,
2809 line_layouts,
2810 gutter_dimensions,
2811 line_height,
2812 em_width,
2813 text_hitbox,
2814 editor_width,
2815 scroll_width,
2816 &mut resized_blocks,
2817 selections,
2818 selected_buffer_ids,
2819 is_row_soft_wrapped,
2820 sticky_header_excerpt_id,
2821 window,
2822 cx,
2823 );
2824 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
2825 blocks.push(BlockLayout {
2826 id: block_id,
2827 row: Some(row),
2828 element,
2829 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
2830 style: BlockStyle::Fixed,
2831 });
2832 }
2833
2834 for (row, block) in non_fixed_blocks {
2835 let style = block.style();
2836 let width = match style {
2837 BlockStyle::Sticky => hitbox.size.width,
2838 BlockStyle::Flex => hitbox
2839 .size
2840 .width
2841 .max(fixed_block_max_width)
2842 .max(gutter_dimensions.width + *scroll_width),
2843 BlockStyle::Fixed => unreachable!(),
2844 };
2845 let block_id = block.id();
2846
2847 if focused_block.as_ref().map_or(false, |b| b.id == block_id) {
2848 focused_block = None;
2849 }
2850
2851 let (element, element_size) = self.render_block(
2852 block,
2853 width.into(),
2854 block_id,
2855 row,
2856 snapshot,
2857 text_x,
2858 &rows,
2859 line_layouts,
2860 gutter_dimensions,
2861 line_height,
2862 em_width,
2863 text_hitbox,
2864 editor_width,
2865 scroll_width,
2866 &mut resized_blocks,
2867 selections,
2868 selected_buffer_ids,
2869 is_row_soft_wrapped,
2870 sticky_header_excerpt_id,
2871 window,
2872 cx,
2873 );
2874
2875 blocks.push(BlockLayout {
2876 id: block_id,
2877 row: Some(row),
2878 element,
2879 available_space: size(width.into(), element_size.height.into()),
2880 style,
2881 });
2882 }
2883
2884 if let Some(focused_block) = focused_block {
2885 if let Some(focus_handle) = focused_block.focus_handle.upgrade() {
2886 if focus_handle.is_focused(window) {
2887 if let Some(block) = snapshot.block_for_id(focused_block.id) {
2888 let style = block.style();
2889 let width = match style {
2890 BlockStyle::Fixed => AvailableSpace::MinContent,
2891 BlockStyle::Flex => AvailableSpace::Definite(
2892 hitbox
2893 .size
2894 .width
2895 .max(fixed_block_max_width)
2896 .max(gutter_dimensions.width + *scroll_width),
2897 ),
2898 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
2899 };
2900
2901 let (element, element_size) = self.render_block(
2902 &block,
2903 width,
2904 focused_block.id,
2905 rows.end,
2906 snapshot,
2907 text_x,
2908 &rows,
2909 line_layouts,
2910 gutter_dimensions,
2911 line_height,
2912 em_width,
2913 text_hitbox,
2914 editor_width,
2915 scroll_width,
2916 &mut resized_blocks,
2917 selections,
2918 selected_buffer_ids,
2919 is_row_soft_wrapped,
2920 sticky_header_excerpt_id,
2921 window,
2922 cx,
2923 );
2924
2925 blocks.push(BlockLayout {
2926 id: block.id(),
2927 row: None,
2928 element,
2929 available_space: size(width, element_size.height.into()),
2930 style,
2931 });
2932 }
2933 }
2934 }
2935 }
2936
2937 if resized_blocks.is_empty() {
2938 *scroll_width = (*scroll_width).max(fixed_block_max_width - gutter_dimensions.width);
2939 Ok(blocks)
2940 } else {
2941 Err(resized_blocks)
2942 }
2943 }
2944
2945 /// Returns true if any of the blocks changed size since the previous frame. This will trigger
2946 /// a restart of rendering for the editor based on the new sizes.
2947 fn layout_blocks(
2948 &self,
2949 blocks: &mut Vec<BlockLayout>,
2950 block_starts: &mut HashSet<DisplayRow>,
2951 hitbox: &Hitbox,
2952 line_height: Pixels,
2953 scroll_pixel_position: gpui::Point<Pixels>,
2954 window: &mut Window,
2955 cx: &mut App,
2956 ) {
2957 for block in blocks {
2958 let mut origin = if let Some(row) = block.row {
2959 block_starts.insert(row);
2960 hitbox.origin
2961 + point(
2962 Pixels::ZERO,
2963 row.as_f32() * line_height - scroll_pixel_position.y,
2964 )
2965 } else {
2966 // Position the block outside the visible area
2967 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
2968 };
2969
2970 if !matches!(block.style, BlockStyle::Sticky) {
2971 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
2972 }
2973
2974 let focus_handle =
2975 block
2976 .element
2977 .prepaint_as_root(origin, block.available_space, window, cx);
2978
2979 if let Some(focus_handle) = focus_handle {
2980 self.editor.update(cx, |editor, _cx| {
2981 editor.set_focused_block(FocusedBlock {
2982 id: block.id,
2983 focus_handle: focus_handle.downgrade(),
2984 });
2985 });
2986 }
2987 }
2988 }
2989
2990 fn layout_sticky_buffer_header(
2991 &self,
2992 StickyHeaderExcerpt {
2993 excerpt,
2994 next_excerpt_controls_present,
2995 next_buffer_row,
2996 }: StickyHeaderExcerpt<'_>,
2997 scroll_position: f32,
2998 line_height: Pixels,
2999 snapshot: &EditorSnapshot,
3000 hitbox: &Hitbox,
3001 selected_buffer_ids: &Vec<BufferId>,
3002 window: &mut Window,
3003 cx: &mut App,
3004 ) -> AnyElement {
3005 let jump_data = header_jump_data(
3006 snapshot,
3007 DisplayRow(scroll_position as u32),
3008 FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
3009 excerpt,
3010 );
3011
3012 let editor_bg_color = cx.theme().colors().editor_background;
3013
3014 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3015
3016 let mut header = v_flex()
3017 .relative()
3018 .child(
3019 div()
3020 .w(hitbox.bounds.size.width)
3021 .h(FILE_HEADER_HEIGHT as f32 * line_height)
3022 .bg(linear_gradient(
3023 0.,
3024 linear_color_stop(editor_bg_color.opacity(0.), 0.),
3025 linear_color_stop(editor_bg_color, 0.6),
3026 ))
3027 .absolute()
3028 .top_0(),
3029 )
3030 .child(
3031 self.render_buffer_header(excerpt, false, selected, jump_data, window, cx)
3032 .into_any_element(),
3033 )
3034 .into_any_element();
3035
3036 let mut origin = hitbox.origin;
3037
3038 if let Some(next_buffer_row) = next_buffer_row {
3039 // Push up the sticky header when the excerpt is getting close to the top of the viewport
3040
3041 let mut max_row = next_buffer_row - FILE_HEADER_HEIGHT * 2;
3042
3043 if next_excerpt_controls_present {
3044 max_row -= MULTI_BUFFER_EXCERPT_HEADER_HEIGHT;
3045 }
3046
3047 let offset = scroll_position - max_row as f32;
3048
3049 if offset > 0.0 {
3050 origin.y -= Pixels(offset) * line_height;
3051 }
3052 }
3053
3054 let size = size(
3055 AvailableSpace::Definite(hitbox.size.width),
3056 AvailableSpace::MinContent,
3057 );
3058
3059 header.prepaint_as_root(origin, size, window, cx);
3060
3061 header
3062 }
3063
3064 fn layout_cursor_popovers(
3065 &self,
3066 line_height: Pixels,
3067 text_hitbox: &Hitbox,
3068 content_origin: gpui::Point<Pixels>,
3069 start_row: DisplayRow,
3070 scroll_pixel_position: gpui::Point<Pixels>,
3071 line_layouts: &[LineWithInvisibles],
3072 cursor: DisplayPoint,
3073 cursor_point: Point,
3074 style: &EditorStyle,
3075 window: &mut Window,
3076 cx: &mut App,
3077 ) {
3078 let mut min_menu_height = Pixels::ZERO;
3079 let mut max_menu_height = Pixels::ZERO;
3080 let mut height_above_menu = Pixels::ZERO;
3081 let height_below_menu = Pixels::ZERO;
3082 let mut edit_prediction_popover_visible = false;
3083 let mut context_menu_visible = false;
3084
3085 {
3086 let editor = self.editor.read(cx);
3087 if editor
3088 .edit_prediction_visible_in_cursor_popover(editor.has_active_inline_completion())
3089 {
3090 height_above_menu +=
3091 editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
3092 edit_prediction_popover_visible = true;
3093 }
3094
3095 if editor.context_menu_visible() {
3096 if let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin() {
3097 min_menu_height += line_height * 3. + POPOVER_Y_PADDING;
3098 max_menu_height += line_height * 12. + POPOVER_Y_PADDING;
3099 context_menu_visible = true;
3100 }
3101 }
3102 }
3103
3104 let visible = edit_prediction_popover_visible || context_menu_visible;
3105 if !visible {
3106 return;
3107 }
3108
3109 let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
3110 let target_position = content_origin
3111 + gpui::Point {
3112 x: cmp::max(
3113 px(0.),
3114 cursor_row_layout.x_for_index(cursor.column() as usize)
3115 - scroll_pixel_position.x,
3116 ),
3117 y: cmp::max(
3118 px(0.),
3119 cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
3120 ),
3121 };
3122
3123 let viewport_bounds =
3124 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3125 right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3126 ..Default::default()
3127 });
3128
3129 let min_height = height_above_menu + min_menu_height + height_below_menu;
3130 let max_height = height_above_menu + max_menu_height + height_below_menu;
3131 let Some((laid_out_popovers, y_flipped)) = self.layout_popovers_above_or_below_line(
3132 target_position,
3133 line_height,
3134 min_height,
3135 max_height,
3136 text_hitbox,
3137 viewport_bounds,
3138 window,
3139 cx,
3140 |height, max_width_for_stable_x, y_flipped, window, cx| {
3141 // First layout the menu to get its size - others can be at least this wide.
3142 let context_menu = if context_menu_visible {
3143 let menu_height = if y_flipped {
3144 height - height_below_menu
3145 } else {
3146 height - height_above_menu
3147 };
3148 let mut element = self
3149 .render_context_menu(line_height, menu_height, y_flipped, window, cx)
3150 .expect("Visible context menu should always render.");
3151 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3152 Some((CursorPopoverType::CodeContextMenu, element, size))
3153 } else {
3154 None
3155 };
3156 let min_width = context_menu
3157 .as_ref()
3158 .map_or(px(0.), |(_, _, size)| size.width);
3159 let max_width = max_width_for_stable_x.max(
3160 context_menu
3161 .as_ref()
3162 .map_or(px(0.), |(_, _, size)| size.width),
3163 );
3164
3165 let edit_prediction = if edit_prediction_popover_visible {
3166 self.editor.update(cx, move |editor, cx| {
3167 let accept_binding = editor.accept_edit_prediction_keybind(window, cx);
3168 let mut element = editor.render_edit_prediction_cursor_popover(
3169 min_width,
3170 max_width,
3171 cursor_point,
3172 style,
3173 accept_binding.keystroke(),
3174 window,
3175 cx,
3176 )?;
3177 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3178 Some((CursorPopoverType::EditPrediction, element, size))
3179 })
3180 } else {
3181 None
3182 };
3183 vec![edit_prediction, context_menu]
3184 .into_iter()
3185 .flatten()
3186 .collect::<Vec<_>>()
3187 },
3188 ) else {
3189 return;
3190 };
3191
3192 let Some((menu_ix, (_, menu_bounds))) = laid_out_popovers
3193 .iter()
3194 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))
3195 else {
3196 return;
3197 };
3198 let last_ix = laid_out_popovers.len() - 1;
3199 let menu_is_last = menu_ix == last_ix;
3200 let first_popover_bounds = laid_out_popovers[0].1;
3201 let last_popover_bounds = laid_out_popovers[last_ix].1;
3202
3203 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
3204 // right, and otherwise it goes below or to the right.
3205 let mut target_bounds = Bounds::from_corners(
3206 first_popover_bounds.origin,
3207 last_popover_bounds.bottom_right(),
3208 );
3209 target_bounds.size.width = menu_bounds.size.width;
3210
3211 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
3212 // based on this is preferred for layout stability.
3213 let mut max_target_bounds = target_bounds;
3214 max_target_bounds.size.height = max_height;
3215 if y_flipped {
3216 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
3217 }
3218
3219 // Add spacing around `target_bounds` and `max_target_bounds`.
3220 let mut extend_amount = Edges::all(MENU_GAP);
3221 if y_flipped {
3222 extend_amount.bottom = line_height;
3223 } else {
3224 extend_amount.top = line_height;
3225 }
3226 let target_bounds = target_bounds.extend(extend_amount);
3227 let max_target_bounds = max_target_bounds.extend(extend_amount);
3228
3229 let must_place_above_or_below =
3230 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
3231 laid_out_popovers[menu_ix + 1..]
3232 .iter()
3233 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
3234 } else {
3235 false
3236 };
3237
3238 self.layout_context_menu_aside(
3239 y_flipped,
3240 *menu_bounds,
3241 target_bounds,
3242 max_target_bounds,
3243 max_menu_height,
3244 must_place_above_or_below,
3245 text_hitbox,
3246 viewport_bounds,
3247 window,
3248 cx,
3249 );
3250 }
3251
3252 fn layout_gutter_menu(
3253 &self,
3254 line_height: Pixels,
3255 text_hitbox: &Hitbox,
3256 content_origin: gpui::Point<Pixels>,
3257 scroll_pixel_position: gpui::Point<Pixels>,
3258 gutter_overshoot: Pixels,
3259 window: &mut Window,
3260 cx: &mut App,
3261 ) {
3262 let editor = self.editor.read(cx);
3263 if !editor.context_menu_visible() {
3264 return;
3265 }
3266 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
3267 editor.context_menu_origin()
3268 else {
3269 return;
3270 };
3271 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
3272 // indicator than just a plain first column of the text field.
3273 let target_position = content_origin
3274 + gpui::Point {
3275 x: -gutter_overshoot,
3276 y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
3277 };
3278 let min_height = line_height * 3. + POPOVER_Y_PADDING;
3279 let max_height = line_height * 12. + POPOVER_Y_PADDING;
3280 let viewport_bounds =
3281 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3282 right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3283 ..Default::default()
3284 });
3285 self.layout_popovers_above_or_below_line(
3286 target_position,
3287 line_height,
3288 min_height,
3289 max_height,
3290 text_hitbox,
3291 viewport_bounds,
3292 window,
3293 cx,
3294 move |height, _max_width_for_stable_x, y_flipped, window, cx| {
3295 let mut element = self
3296 .render_context_menu(line_height, height, y_flipped, window, cx)
3297 .expect("Visible context menu should always render.");
3298 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3299 vec![(CursorPopoverType::CodeContextMenu, element, size)]
3300 },
3301 );
3302 }
3303
3304 fn layout_popovers_above_or_below_line(
3305 &self,
3306 target_position: gpui::Point<Pixels>,
3307 line_height: Pixels,
3308 min_height: Pixels,
3309 max_height: Pixels,
3310 text_hitbox: &Hitbox,
3311 viewport_bounds: Bounds<Pixels>,
3312 window: &mut Window,
3313 cx: &mut App,
3314 make_sized_popovers: impl FnOnce(
3315 Pixels,
3316 Pixels,
3317 bool,
3318 &mut Window,
3319 &mut App,
3320 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
3321 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
3322 // If the max height won't fit below and there is more space above, put it above the line.
3323 let bottom_y_when_flipped = target_position.y - line_height;
3324 let available_above = bottom_y_when_flipped - text_hitbox.top();
3325 let available_below = text_hitbox.bottom() - target_position.y;
3326 let y_overflows_below = max_height > available_below;
3327 let mut y_flipped = y_overflows_below && available_above > available_below;
3328 let mut height = cmp::min(
3329 max_height,
3330 if y_flipped {
3331 available_above
3332 } else {
3333 available_below
3334 },
3335 );
3336
3337 // If the min height doesn't fit within text bounds, instead fit within the window.
3338 if height < min_height {
3339 let available_above = bottom_y_when_flipped;
3340 let available_below = viewport_bounds.bottom() - target_position.y;
3341 if available_below > min_height {
3342 y_flipped = false;
3343 height = min_height;
3344 } else if available_above > min_height {
3345 y_flipped = true;
3346 height = min_height;
3347 } else if available_above > available_below {
3348 y_flipped = true;
3349 height = available_above;
3350 } else {
3351 y_flipped = false;
3352 height = available_below;
3353 }
3354 }
3355
3356 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
3357
3358 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
3359 // for very narrow windows.
3360 let popovers = make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
3361 if popovers.is_empty() {
3362 return None;
3363 }
3364
3365 let max_width = popovers
3366 .iter()
3367 .map(|(_, _, size)| size.width)
3368 .max()
3369 .unwrap_or_default();
3370
3371 let mut current_position = gpui::Point {
3372 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
3373 // overflow. Include space for the scrollbar.
3374 x: target_position
3375 .x
3376 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
3377 y: if y_flipped {
3378 bottom_y_when_flipped
3379 } else {
3380 target_position.y
3381 },
3382 };
3383
3384 let mut laid_out_popovers = popovers
3385 .into_iter()
3386 .map(|(popover_type, element, size)| {
3387 if y_flipped {
3388 current_position.y -= size.height;
3389 }
3390 let position = current_position;
3391 window.defer_draw(element, current_position, 1);
3392 if !y_flipped {
3393 current_position.y += size.height + MENU_GAP;
3394 } else {
3395 current_position.y -= MENU_GAP;
3396 }
3397 (popover_type, Bounds::new(position, size))
3398 })
3399 .collect::<Vec<_>>();
3400
3401 if y_flipped {
3402 laid_out_popovers.reverse();
3403 }
3404
3405 Some((laid_out_popovers, y_flipped))
3406 }
3407
3408 fn layout_context_menu_aside(
3409 &self,
3410 y_flipped: bool,
3411 menu_bounds: Bounds<Pixels>,
3412 target_bounds: Bounds<Pixels>,
3413 max_target_bounds: Bounds<Pixels>,
3414 max_height: Pixels,
3415 must_place_above_or_below: bool,
3416 text_hitbox: &Hitbox,
3417 viewport_bounds: Bounds<Pixels>,
3418 window: &mut Window,
3419 cx: &mut App,
3420 ) {
3421 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
3422 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
3423 && !must_place_above_or_below
3424 {
3425 let max_width = cmp::min(
3426 available_within_viewport.right - px(1.),
3427 MENU_ASIDE_MAX_WIDTH,
3428 );
3429 let Some(mut aside) =
3430 self.render_context_menu_aside(size(max_width, max_height - POPOVER_Y_PADDING), cx)
3431 else {
3432 return;
3433 };
3434 aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3435 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
3436 Some((aside, right_position))
3437 } else {
3438 let max_size = size(
3439 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
3440 // won't be needed here.
3441 cmp::min(
3442 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
3443 viewport_bounds.right(),
3444 ),
3445 cmp::min(
3446 max_height,
3447 cmp::max(
3448 available_within_viewport.top,
3449 available_within_viewport.bottom,
3450 ),
3451 ) - POPOVER_Y_PADDING,
3452 );
3453 let Some(mut aside) = self.render_context_menu_aside(max_size, cx) else {
3454 return;
3455 };
3456 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3457
3458 let top_position = point(
3459 menu_bounds.origin.x,
3460 target_bounds.top() - actual_size.height,
3461 );
3462 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
3463
3464 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
3465 // Prefer to fit on the same side of the line as the menu, then on the other side of
3466 // the line.
3467 if !y_flipped && wanted.height < available.bottom {
3468 Some(bottom_position)
3469 } else if !y_flipped && wanted.height < available.top {
3470 Some(top_position)
3471 } else if y_flipped && wanted.height < available.top {
3472 Some(top_position)
3473 } else if y_flipped && wanted.height < available.bottom {
3474 Some(bottom_position)
3475 } else {
3476 None
3477 }
3478 };
3479
3480 // Prefer choosing a direction using max sizes rather than actual size for stability.
3481 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
3482 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
3483 let aside_position = fit_within(available_within_text, wanted)
3484 // Fallback: fit max size in window.
3485 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
3486 // Fallback: fit actual size in window.
3487 .or_else(|| fit_within(available_within_viewport, actual_size));
3488
3489 aside_position.map(|position| (aside, position))
3490 };
3491
3492 // Skip drawing if it doesn't fit anywhere.
3493 if let Some((aside, position)) = positioned_aside {
3494 window.defer_draw(aside, position, 1);
3495 }
3496 }
3497
3498 fn render_context_menu(
3499 &self,
3500 line_height: Pixels,
3501 height: Pixels,
3502 y_flipped: bool,
3503 window: &mut Window,
3504 cx: &mut App,
3505 ) -> Option<AnyElement> {
3506 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
3507 self.editor.update(cx, |editor, cx| {
3508 editor.render_context_menu(&self.style, max_height_in_lines, y_flipped, window, cx)
3509 })
3510 }
3511
3512 fn render_context_menu_aside(
3513 &self,
3514 max_size: Size<Pixels>,
3515
3516 cx: &mut App,
3517 ) -> Option<AnyElement> {
3518 if max_size.width < px(100.) || max_size.height < px(12.) {
3519 None
3520 } else {
3521 self.editor.update(cx, |editor, cx| {
3522 editor.render_context_menu_aside(&self.style, max_size, cx)
3523 })
3524 }
3525 }
3526
3527 fn layout_edit_prediction_popover(
3528 &self,
3529 text_bounds: &Bounds<Pixels>,
3530 content_origin: gpui::Point<Pixels>,
3531 editor_snapshot: &EditorSnapshot,
3532 visible_row_range: Range<DisplayRow>,
3533 scroll_top: f32,
3534 scroll_bottom: f32,
3535 line_layouts: &[LineWithInvisibles],
3536 line_height: Pixels,
3537 scroll_pixel_position: gpui::Point<Pixels>,
3538 newest_selection_head: Option<DisplayPoint>,
3539 editor_width: Pixels,
3540 style: &EditorStyle,
3541 window: &mut Window,
3542 cx: &mut App,
3543 ) -> Option<AnyElement> {
3544 const PADDING_X: Pixels = Pixels(24.);
3545 const PADDING_Y: Pixels = Pixels(2.);
3546
3547 let editor = self.editor.read(cx);
3548 let active_inline_completion = editor.active_inline_completion.as_ref()?;
3549
3550 if editor.edit_prediction_visible_in_cursor_popover(true) {
3551 return None;
3552 }
3553
3554 // Adjust text origin for horizontal scrolling (in some cases here)
3555 let start_point = content_origin - gpui::Point::new(scroll_pixel_position.x, Pixels(0.0));
3556
3557 // Clamp left offset after extreme scrollings
3558 let clamp_start = |point: gpui::Point<Pixels>| gpui::Point {
3559 x: point.x.max(content_origin.x),
3560 y: point.y,
3561 };
3562
3563 match &active_inline_completion.completion {
3564 InlineCompletion::Move { target, .. } => {
3565 let target_display_point = target.to_display_point(editor_snapshot);
3566
3567 if editor.edit_prediction_requires_modifier() {
3568 if !editor.edit_prediction_preview_is_active() {
3569 return None;
3570 }
3571
3572 if target_display_point.row() < visible_row_range.start {
3573 let mut element = editor
3574 .render_edit_prediction_line_popover(
3575 "Scroll",
3576 Some(IconName::ArrowUp),
3577 window,
3578 cx,
3579 )?
3580 .into_any();
3581
3582 element.layout_as_root(AvailableSpace::min_size(), window, cx);
3583
3584 let cursor = newest_selection_head?;
3585 let cursor_row_layout = line_layouts
3586 .get(cursor.row().minus(visible_row_range.start) as usize)?;
3587 let cursor_column = cursor.column() as usize;
3588
3589 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
3590
3591 const PADDING_Y: Pixels = px(12.);
3592
3593 let origin = start_point + point(cursor_character_x, PADDING_Y);
3594
3595 element.prepaint_at(origin, window, cx);
3596 return Some(element);
3597 } else if target_display_point.row() >= visible_row_range.end {
3598 let mut element = editor
3599 .render_edit_prediction_line_popover(
3600 "Scroll",
3601 Some(IconName::ArrowDown),
3602 window,
3603 cx,
3604 )?
3605 .into_any();
3606
3607 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3608
3609 let cursor = newest_selection_head?;
3610 let cursor_row_layout = line_layouts
3611 .get(cursor.row().minus(visible_row_range.start) as usize)?;
3612 let cursor_column = cursor.column() as usize;
3613
3614 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
3615 const PADDING_Y: Pixels = px(12.);
3616
3617 let origin = start_point
3618 + point(
3619 cursor_character_x,
3620 text_bounds.size.height - size.height - PADDING_Y,
3621 );
3622
3623 element.prepaint_at(origin, window, cx);
3624 return Some(element);
3625 } else {
3626 const POLE_WIDTH: Pixels = px(2.);
3627
3628 let mut element = v_flex()
3629 .child(
3630 editor
3631 .render_edit_prediction_line_popover("Jump", None, window, cx)?
3632 .rounded_br(px(0.))
3633 .rounded_tr(px(0.))
3634 .border_r_2(),
3635 )
3636 .child(
3637 div()
3638 .w(POLE_WIDTH)
3639 .bg(cx.theme().colors().text_accent.opacity(0.8))
3640 .h(line_height),
3641 )
3642 .items_end()
3643 .into_any();
3644
3645 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3646
3647 let line_layout =
3648 line_layouts
3649 .get(target_display_point.row().minus(visible_row_range.start)
3650 as usize)?;
3651 let target_column = target_display_point.column() as usize;
3652
3653 let target_x = line_layout.x_for_index(target_column);
3654 let target_y = (target_display_point.row().as_f32() * line_height)
3655 - scroll_pixel_position.y;
3656
3657 let origin = clamp_start(
3658 start_point + point(target_x, target_y)
3659 - point(size.width - POLE_WIDTH, size.height - line_height),
3660 );
3661
3662 element.prepaint_at(origin, window, cx);
3663
3664 return Some(element);
3665 }
3666 }
3667
3668 if target_display_point.row().as_f32() < scroll_top {
3669 let mut element = editor
3670 .render_edit_prediction_line_popover(
3671 "Jump to Edit",
3672 Some(IconName::ArrowUp),
3673 window,
3674 cx,
3675 )?
3676 .into_any();
3677
3678 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3679 let offset = point((text_bounds.size.width - size.width) / 2., PADDING_Y);
3680
3681 element.prepaint_at(text_bounds.origin + offset, window, cx);
3682 Some(element)
3683 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
3684 let mut element = editor
3685 .render_edit_prediction_line_popover(
3686 "Jump to Edit",
3687 Some(IconName::ArrowDown),
3688 window,
3689 cx,
3690 )?
3691 .into_any();
3692
3693 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3694 let offset = point(
3695 (text_bounds.size.width - size.width) / 2.,
3696 text_bounds.size.height - size.height - PADDING_Y,
3697 );
3698
3699 element.prepaint_at(text_bounds.origin + offset, window, cx);
3700 Some(element)
3701 } else {
3702 let mut element = editor
3703 .render_edit_prediction_line_popover("Jump to Edit", None, window, cx)?
3704 .into_any();
3705 let target_line_end = DisplayPoint::new(
3706 target_display_point.row(),
3707 editor_snapshot.line_len(target_display_point.row()),
3708 );
3709 let origin = self.editor.update(cx, |editor, _cx| {
3710 editor.display_to_pixel_point(target_line_end, editor_snapshot, window)
3711 })?;
3712
3713 element.prepaint_as_root(
3714 clamp_start(start_point + origin + point(PADDING_X, px(0.))),
3715 AvailableSpace::min_size(),
3716 window,
3717 cx,
3718 );
3719 Some(element)
3720 }
3721 }
3722 InlineCompletion::Edit {
3723 edits,
3724 edit_preview,
3725 display_mode,
3726 snapshot,
3727 } => {
3728 if self.editor.read(cx).has_visible_completions_menu() {
3729 return None;
3730 }
3731
3732 let edit_start = edits
3733 .first()
3734 .unwrap()
3735 .0
3736 .start
3737 .to_display_point(editor_snapshot);
3738 let edit_end = edits
3739 .last()
3740 .unwrap()
3741 .0
3742 .end
3743 .to_display_point(editor_snapshot);
3744
3745 let is_visible = visible_row_range.contains(&edit_start.row())
3746 || visible_row_range.contains(&edit_end.row());
3747 if !is_visible {
3748 return None;
3749 }
3750
3751 match display_mode {
3752 EditDisplayMode::TabAccept => {
3753 let range = &edits.first()?.0;
3754 let target_display_point = range.end.to_display_point(editor_snapshot);
3755
3756 let target_line_end = DisplayPoint::new(
3757 target_display_point.row(),
3758 editor_snapshot.line_len(target_display_point.row()),
3759 );
3760 let (mut element, origin) = self.editor.update(cx, |editor, cx| {
3761 Some((
3762 editor
3763 .render_edit_prediction_line_popover(
3764 "Accept", None, window, cx,
3765 )?
3766 .into_any(),
3767 editor.display_to_pixel_point(
3768 target_line_end,
3769 editor_snapshot,
3770 window,
3771 )?,
3772 ))
3773 })?;
3774
3775 element.prepaint_as_root(
3776 clamp_start(start_point + origin + point(PADDING_X, px(0.))),
3777 AvailableSpace::min_size(),
3778 window,
3779 cx,
3780 );
3781 return Some(element);
3782 }
3783 EditDisplayMode::Inline => return None,
3784 EditDisplayMode::DiffPopover => {}
3785 }
3786
3787 let highlighted_edits = crate::inline_completion_edit_text(
3788 &snapshot,
3789 edits,
3790 edit_preview.as_ref()?,
3791 false,
3792 cx,
3793 );
3794
3795 let styled_text = highlighted_edits.to_styled_text(&style.text);
3796 let line_count = highlighted_edits.text.lines().count();
3797
3798 const BORDER_WIDTH: Pixels = px(1.);
3799
3800 let mut element = h_flex()
3801 .items_start()
3802 .child(
3803 h_flex()
3804 .bg(cx.theme().colors().editor_background)
3805 .border(BORDER_WIDTH)
3806 .shadow_sm()
3807 .border_color(cx.theme().colors().border)
3808 .rounded_l_lg()
3809 .when(line_count > 1, |el| el.rounded_br_lg())
3810 .pr_1()
3811 .child(styled_text),
3812 )
3813 .child(
3814 h_flex()
3815 .h(line_height + BORDER_WIDTH * px(2.))
3816 .px_1p5()
3817 .gap_1()
3818 // Workaround: For some reason, there's a gap if we don't do this
3819 .ml(-BORDER_WIDTH)
3820 .shadow(smallvec![gpui::BoxShadow {
3821 color: gpui::black().opacity(0.05),
3822 offset: point(px(1.), px(1.)),
3823 blur_radius: px(2.),
3824 spread_radius: px(0.),
3825 }])
3826 .bg(Editor::edit_prediction_line_popover_bg_color(cx))
3827 .border(BORDER_WIDTH)
3828 .border_color(cx.theme().colors().border)
3829 .rounded_r_lg()
3830 .children(editor.render_edit_prediction_accept_keybind(window, cx)),
3831 )
3832 .into_any();
3833
3834 let longest_row =
3835 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
3836 let longest_line_width = if visible_row_range.contains(&longest_row) {
3837 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
3838 } else {
3839 layout_line(
3840 longest_row,
3841 editor_snapshot,
3842 style,
3843 editor_width,
3844 |_| false,
3845 window,
3846 cx,
3847 )
3848 .width
3849 };
3850
3851 let viewport_bounds = Bounds::new(Default::default(), window.viewport_size())
3852 .extend(Edges {
3853 right: -Self::SCROLLBAR_WIDTH,
3854 ..Default::default()
3855 });
3856
3857 let x_after_longest =
3858 text_bounds.origin.x + longest_line_width + PADDING_X - scroll_pixel_position.x;
3859
3860 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3861
3862 // Fully visible if it can be displayed within the window (allow overlapping other
3863 // panes). However, this is only allowed if the popover starts within text_bounds.
3864 let can_position_to_the_right = x_after_longest < text_bounds.right()
3865 && x_after_longest + element_bounds.width < viewport_bounds.right();
3866
3867 let mut origin = if can_position_to_the_right {
3868 point(
3869 x_after_longest,
3870 text_bounds.origin.y + edit_start.row().as_f32() * line_height
3871 - scroll_pixel_position.y,
3872 )
3873 } else {
3874 let cursor_row = newest_selection_head.map(|head| head.row());
3875 let above_edit = edit_start
3876 .row()
3877 .0
3878 .checked_sub(line_count as u32)
3879 .map(DisplayRow);
3880 let below_edit = Some(edit_end.row() + 1);
3881 let above_cursor = cursor_row
3882 .and_then(|row| row.0.checked_sub(line_count as u32).map(DisplayRow));
3883 let below_cursor = cursor_row.map(|cursor_row| cursor_row + 1);
3884
3885 // Place the edit popover adjacent to the edit if there is a location
3886 // available that is onscreen and does not obscure the cursor. Otherwise,
3887 // place it adjacent to the cursor.
3888 let row_target = [above_edit, below_edit, above_cursor, below_cursor]
3889 .into_iter()
3890 .flatten()
3891 .find(|&start_row| {
3892 let end_row = start_row + line_count as u32;
3893 visible_row_range.contains(&start_row)
3894 && visible_row_range.contains(&end_row)
3895 && cursor_row.map_or(true, |cursor_row| {
3896 !((start_row..end_row).contains(&cursor_row))
3897 })
3898 })?;
3899
3900 content_origin
3901 + point(
3902 -scroll_pixel_position.x,
3903 row_target.as_f32() * line_height - scroll_pixel_position.y,
3904 )
3905 };
3906
3907 origin.x -= BORDER_WIDTH;
3908
3909 window.defer_draw(element, origin, 1);
3910
3911 // Do not return an element, since it will already be drawn due to defer_draw.
3912 None
3913 }
3914 }
3915 }
3916
3917 fn layout_mouse_context_menu(
3918 &self,
3919 editor_snapshot: &EditorSnapshot,
3920 visible_range: Range<DisplayRow>,
3921 content_origin: gpui::Point<Pixels>,
3922 window: &mut Window,
3923 cx: &mut App,
3924 ) -> Option<AnyElement> {
3925 let position = self.editor.update(cx, |editor, _cx| {
3926 let visible_start_point = editor.display_to_pixel_point(
3927 DisplayPoint::new(visible_range.start, 0),
3928 editor_snapshot,
3929 window,
3930 )?;
3931 let visible_end_point = editor.display_to_pixel_point(
3932 DisplayPoint::new(visible_range.end, 0),
3933 editor_snapshot,
3934 window,
3935 )?;
3936
3937 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3938 let (source_display_point, position) = match mouse_context_menu.position {
3939 MenuPosition::PinnedToScreen(point) => (None, point),
3940 MenuPosition::PinnedToEditor { source, offset } => {
3941 let source_display_point = source.to_display_point(editor_snapshot);
3942 let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
3943 let position = content_origin + source_point + offset;
3944 (Some(source_display_point), position)
3945 }
3946 };
3947
3948 let source_included = source_display_point.map_or(true, |source_display_point| {
3949 visible_range
3950 .to_inclusive()
3951 .contains(&source_display_point.row())
3952 });
3953 let position_included =
3954 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
3955 if !source_included && !position_included {
3956 None
3957 } else {
3958 Some(position)
3959 }
3960 })?;
3961
3962 let mut element = self.editor.update(cx, |editor, _| {
3963 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3964 let context_menu = mouse_context_menu.context_menu.clone();
3965
3966 Some(
3967 deferred(
3968 anchored()
3969 .position(position)
3970 .child(context_menu)
3971 .anchor(Corner::TopLeft)
3972 .snap_to_window_with_margin(px(8.)),
3973 )
3974 .with_priority(1)
3975 .into_any(),
3976 )
3977 })?;
3978
3979 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
3980 Some(element)
3981 }
3982
3983 fn layout_hover_popovers(
3984 &self,
3985 snapshot: &EditorSnapshot,
3986 hitbox: &Hitbox,
3987 text_hitbox: &Hitbox,
3988 visible_display_row_range: Range<DisplayRow>,
3989 content_origin: gpui::Point<Pixels>,
3990 scroll_pixel_position: gpui::Point<Pixels>,
3991 line_layouts: &[LineWithInvisibles],
3992 line_height: Pixels,
3993 em_width: Pixels,
3994 window: &mut Window,
3995 cx: &mut App,
3996 ) {
3997 struct MeasuredHoverPopover {
3998 element: AnyElement,
3999 size: Size<Pixels>,
4000 horizontal_offset: Pixels,
4001 }
4002
4003 let max_size = size(
4004 (120. * em_width) // Default size
4005 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4006 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4007 (16. * line_height) // Default size
4008 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4009 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4010 );
4011
4012 let hover_popovers = self.editor.update(cx, |editor, cx| {
4013 editor
4014 .hover_state
4015 .render(snapshot, visible_display_row_range.clone(), max_size, cx)
4016 });
4017 let Some((position, hover_popovers)) = hover_popovers else {
4018 return;
4019 };
4020
4021 // This is safe because we check on layout whether the required row is available
4022 let hovered_row_layout =
4023 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
4024
4025 // Compute Hovered Point
4026 let x =
4027 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
4028 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
4029 let hovered_point = content_origin + point(x, y);
4030
4031 let mut overall_height = Pixels::ZERO;
4032 let mut measured_hover_popovers = Vec::new();
4033 for mut hover_popover in hover_popovers {
4034 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
4035 let horizontal_offset =
4036 (text_hitbox.top_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
4037
4038 overall_height += HOVER_POPOVER_GAP + size.height;
4039
4040 measured_hover_popovers.push(MeasuredHoverPopover {
4041 element: hover_popover,
4042 size,
4043 horizontal_offset,
4044 });
4045 }
4046 overall_height += HOVER_POPOVER_GAP;
4047
4048 fn draw_occluder(
4049 width: Pixels,
4050 origin: gpui::Point<Pixels>,
4051 window: &mut Window,
4052 cx: &mut App,
4053 ) {
4054 let mut occlusion = div()
4055 .size_full()
4056 .occlude()
4057 .on_mouse_move(|_, _, cx| cx.stop_propagation())
4058 .into_any_element();
4059 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
4060 window.defer_draw(occlusion, origin, 2);
4061 }
4062
4063 if hovered_point.y > overall_height {
4064 // There is enough space above. Render popovers above the hovered point
4065 let mut current_y = hovered_point.y;
4066 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4067 let size = popover.size;
4068 let popover_origin = point(
4069 hovered_point.x + popover.horizontal_offset,
4070 current_y - size.height,
4071 );
4072
4073 window.defer_draw(popover.element, popover_origin, 2);
4074 if position != itertools::Position::Last {
4075 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
4076 draw_occluder(size.width, origin, window, cx);
4077 }
4078
4079 current_y = popover_origin.y - HOVER_POPOVER_GAP;
4080 }
4081 } else {
4082 // There is not enough space above. Render popovers below the hovered point
4083 let mut current_y = hovered_point.y + line_height;
4084 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
4085 let size = popover.size;
4086 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
4087
4088 window.defer_draw(popover.element, popover_origin, 2);
4089 if position != itertools::Position::Last {
4090 let origin = point(popover_origin.x, popover_origin.y + size.height);
4091 draw_occluder(size.width, origin, window, cx);
4092 }
4093
4094 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
4095 }
4096 }
4097 }
4098
4099 fn layout_diff_hunk_controls(
4100 &self,
4101 row_range: Range<DisplayRow>,
4102 row_infos: &[RowInfo],
4103 text_hitbox: &Hitbox,
4104 position_map: &PositionMap,
4105 newest_cursor_position: Option<DisplayPoint>,
4106 line_height: Pixels,
4107 scroll_pixel_position: gpui::Point<Pixels>,
4108 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
4109 editor: Entity<Editor>,
4110 window: &mut Window,
4111 cx: &mut App,
4112 ) -> Vec<AnyElement> {
4113 let point_for_position = position_map.point_for_position(window.mouse_position());
4114
4115 let mut controls = vec![];
4116
4117 let active_positions = [
4118 Some(point_for_position.previous_valid),
4119 newest_cursor_position,
4120 ];
4121
4122 for (hunk, _) in display_hunks {
4123 if let DisplayDiffHunk::Unfolded {
4124 display_row_range,
4125 multi_buffer_range,
4126 status,
4127 ..
4128 } = &hunk
4129 {
4130 if display_row_range.start < row_range.start
4131 || display_row_range.start >= row_range.end
4132 {
4133 continue;
4134 }
4135 let row_ix = (display_row_range.start - row_range.start).0 as usize;
4136 if row_infos[row_ix].diff_status.is_none() {
4137 continue;
4138 }
4139 if matches!(
4140 row_infos[row_ix].diff_status,
4141 Some(DiffHunkStatus::Added(_))
4142 ) && !matches!(*status, DiffHunkStatus::Added(_))
4143 {
4144 continue;
4145 }
4146 if active_positions
4147 .iter()
4148 .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
4149 {
4150 let y = display_row_range.start.as_f32() * line_height
4151 + text_hitbox.bounds.top()
4152 - scroll_pixel_position.y;
4153 let x = text_hitbox.bounds.right()
4154 - rems(6.).to_pixels(window.rem_size())
4155 - px(33.);
4156
4157 let mut element = diff_hunk_controls(
4158 display_row_range.start.0,
4159 multi_buffer_range.clone(),
4160 line_height,
4161 &editor,
4162 window,
4163 cx,
4164 );
4165 element.prepaint_as_root(
4166 gpui::Point::new(x, y),
4167 size(px(100.0), line_height).into(),
4168 window,
4169 cx,
4170 );
4171 controls.push(element);
4172 }
4173 }
4174 }
4175
4176 controls
4177 }
4178
4179 fn layout_signature_help(
4180 &self,
4181 hitbox: &Hitbox,
4182 content_origin: gpui::Point<Pixels>,
4183 scroll_pixel_position: gpui::Point<Pixels>,
4184 newest_selection_head: Option<DisplayPoint>,
4185 start_row: DisplayRow,
4186 line_layouts: &[LineWithInvisibles],
4187 line_height: Pixels,
4188 em_width: Pixels,
4189 window: &mut Window,
4190 cx: &mut App,
4191 ) {
4192 if !self.editor.focus_handle(cx).is_focused(window) {
4193 return;
4194 }
4195 let Some(newest_selection_head) = newest_selection_head else {
4196 return;
4197 };
4198 let selection_row = newest_selection_head.row();
4199 if selection_row < start_row {
4200 return;
4201 }
4202 let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
4203 else {
4204 return;
4205 };
4206
4207 let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
4208 - scroll_pixel_position.x
4209 + content_origin.x;
4210 let start_y =
4211 selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
4212
4213 let max_size = size(
4214 (120. * em_width) // Default size
4215 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4216 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4217 (16. * line_height) // Default size
4218 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4219 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4220 );
4221
4222 let maybe_element = self.editor.update(cx, |editor, cx| {
4223 if let Some(popover) = editor.signature_help_state.popover_mut() {
4224 let element = popover.render(
4225 &self.style,
4226 max_size,
4227 editor.workspace.as_ref().map(|(w, _)| w.clone()),
4228 cx,
4229 );
4230 Some(element)
4231 } else {
4232 None
4233 }
4234 });
4235 if let Some(mut element) = maybe_element {
4236 let window_size = window.viewport_size();
4237 let size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
4238 let mut point = point(start_x, start_y - size.height);
4239
4240 // Adjusting to ensure the popover does not overflow in the X-axis direction.
4241 if point.x + size.width >= window_size.width {
4242 point.x = window_size.width - size.width;
4243 }
4244
4245 window.defer_draw(element, point, 1)
4246 }
4247 }
4248
4249 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
4250 window.paint_layer(layout.hitbox.bounds, |window| {
4251 let scroll_top = layout.position_map.snapshot.scroll_position().y;
4252 let gutter_bg = cx.theme().colors().editor_gutter_background;
4253 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
4254 window.paint_quad(fill(
4255 layout.position_map.text_hitbox.bounds,
4256 self.style.background,
4257 ));
4258
4259 if let EditorMode::Full = layout.mode {
4260 let mut active_rows = layout.active_rows.iter().peekable();
4261 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
4262 let mut end_row = start_row.0;
4263 while active_rows
4264 .peek()
4265 .map_or(false, |(active_row, has_selection)| {
4266 active_row.0 == end_row + 1
4267 && *has_selection == contains_non_empty_selection
4268 })
4269 {
4270 active_rows.next().unwrap();
4271 end_row += 1;
4272 }
4273
4274 if !contains_non_empty_selection {
4275 let highlight_h_range =
4276 match layout.position_map.snapshot.current_line_highlight {
4277 CurrentLineHighlight::Gutter => Some(Range {
4278 start: layout.hitbox.left(),
4279 end: layout.gutter_hitbox.right(),
4280 }),
4281 CurrentLineHighlight::Line => Some(Range {
4282 start: layout.position_map.text_hitbox.bounds.left(),
4283 end: layout.position_map.text_hitbox.bounds.right(),
4284 }),
4285 CurrentLineHighlight::All => Some(Range {
4286 start: layout.hitbox.left(),
4287 end: layout.hitbox.right(),
4288 }),
4289 CurrentLineHighlight::None => None,
4290 };
4291 if let Some(range) = highlight_h_range {
4292 let active_line_bg = cx.theme().colors().editor_active_line_background;
4293 let bounds = Bounds {
4294 origin: point(
4295 range.start,
4296 layout.hitbox.origin.y
4297 + (start_row.as_f32() - scroll_top)
4298 * layout.position_map.line_height,
4299 ),
4300 size: size(
4301 range.end - range.start,
4302 layout.position_map.line_height
4303 * (end_row - start_row.0 + 1) as f32,
4304 ),
4305 };
4306 window.paint_quad(fill(bounds, active_line_bg));
4307 }
4308 }
4309 }
4310
4311 let mut paint_highlight =
4312 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
4313 let origin = point(
4314 layout.hitbox.origin.x,
4315 layout.hitbox.origin.y
4316 + (highlight_row_start.as_f32() - scroll_top)
4317 * layout.position_map.line_height,
4318 );
4319 let size = size(
4320 layout.hitbox.size.width,
4321 layout.position_map.line_height
4322 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
4323 );
4324 window.paint_quad(fill(Bounds { origin, size }, color));
4325 };
4326
4327 let mut current_paint: Option<(gpui::Background, Range<DisplayRow>)> = None;
4328 for (&new_row, &new_background) in &layout.highlighted_rows {
4329 match &mut current_paint {
4330 Some((current_background, current_range)) => {
4331 let current_background = *current_background;
4332 let new_range_started = current_background != new_background
4333 || current_range.end.next_row() != new_row;
4334 if new_range_started {
4335 paint_highlight(
4336 current_range.start,
4337 current_range.end,
4338 current_background,
4339 );
4340 current_paint = Some((new_background, new_row..new_row));
4341 continue;
4342 } else {
4343 current_range.end = current_range.end.next_row();
4344 }
4345 }
4346 None => current_paint = Some((new_background, new_row..new_row)),
4347 };
4348 }
4349 if let Some((color, range)) = current_paint {
4350 paint_highlight(range.start, range.end, color);
4351 }
4352
4353 let scroll_left =
4354 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
4355
4356 for (wrap_position, active) in layout.wrap_guides.iter() {
4357 let x = (layout.position_map.text_hitbox.origin.x
4358 + *wrap_position
4359 + layout.position_map.em_width / 2.)
4360 - scroll_left;
4361
4362 let show_scrollbars = {
4363 let (scrollbar_x, scrollbar_y) = &layout.scrollbars_layout.as_xy();
4364
4365 scrollbar_x.as_ref().map_or(false, |sx| sx.visible)
4366 || scrollbar_y.as_ref().map_or(false, |sy| sy.visible)
4367 };
4368
4369 if x < layout.position_map.text_hitbox.origin.x
4370 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
4371 {
4372 continue;
4373 }
4374
4375 let color = if *active {
4376 cx.theme().colors().editor_active_wrap_guide
4377 } else {
4378 cx.theme().colors().editor_wrap_guide
4379 };
4380 window.paint_quad(fill(
4381 Bounds {
4382 origin: point(x, layout.position_map.text_hitbox.origin.y),
4383 size: size(px(1.), layout.position_map.text_hitbox.size.height),
4384 },
4385 color,
4386 ));
4387 }
4388 }
4389 })
4390 }
4391
4392 fn paint_indent_guides(
4393 &mut self,
4394 layout: &mut EditorLayout,
4395 window: &mut Window,
4396 cx: &mut App,
4397 ) {
4398 let Some(indent_guides) = &layout.indent_guides else {
4399 return;
4400 };
4401
4402 let faded_color = |color: Hsla, alpha: f32| {
4403 let mut faded = color;
4404 faded.a = alpha;
4405 faded
4406 };
4407
4408 for indent_guide in indent_guides {
4409 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
4410 let settings = indent_guide.settings;
4411
4412 // TODO fixed for now, expose them through themes later
4413 const INDENT_AWARE_ALPHA: f32 = 0.2;
4414 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
4415 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
4416 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
4417
4418 let line_color = match (settings.coloring, indent_guide.active) {
4419 (IndentGuideColoring::Disabled, _) => None,
4420 (IndentGuideColoring::Fixed, false) => {
4421 Some(cx.theme().colors().editor_indent_guide)
4422 }
4423 (IndentGuideColoring::Fixed, true) => {
4424 Some(cx.theme().colors().editor_indent_guide_active)
4425 }
4426 (IndentGuideColoring::IndentAware, false) => {
4427 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
4428 }
4429 (IndentGuideColoring::IndentAware, true) => {
4430 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
4431 }
4432 };
4433
4434 let background_color = match (settings.background_coloring, indent_guide.active) {
4435 (IndentGuideBackgroundColoring::Disabled, _) => None,
4436 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
4437 indent_accent_colors,
4438 INDENT_AWARE_BACKGROUND_ALPHA,
4439 )),
4440 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
4441 indent_accent_colors,
4442 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
4443 )),
4444 };
4445
4446 let requested_line_width = if indent_guide.active {
4447 settings.active_line_width
4448 } else {
4449 settings.line_width
4450 }
4451 .clamp(1, 10);
4452 let mut line_indicator_width = 0.;
4453 if let Some(color) = line_color {
4454 window.paint_quad(fill(
4455 Bounds {
4456 origin: indent_guide.origin,
4457 size: size(px(requested_line_width as f32), indent_guide.length),
4458 },
4459 color,
4460 ));
4461 line_indicator_width = requested_line_width as f32;
4462 }
4463
4464 if let Some(color) = background_color {
4465 let width = indent_guide.single_indent_width - px(line_indicator_width);
4466 window.paint_quad(fill(
4467 Bounds {
4468 origin: point(
4469 indent_guide.origin.x + px(line_indicator_width),
4470 indent_guide.origin.y,
4471 ),
4472 size: size(width, indent_guide.length),
4473 },
4474 color,
4475 ));
4476 }
4477 }
4478 }
4479
4480 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4481 let is_singleton = self.editor.read(cx).is_singleton(cx);
4482
4483 let line_height = layout.position_map.line_height;
4484 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
4485
4486 for LineNumberLayout {
4487 shaped_line,
4488 hitbox,
4489 display_row,
4490 } in layout.line_numbers.values()
4491 {
4492 let Some(hitbox) = hitbox else {
4493 continue;
4494 };
4495
4496 let is_active = layout.active_rows.contains_key(&display_row);
4497
4498 let color = if is_active {
4499 cx.theme().colors().editor_active_line_number
4500 } else if !is_singleton && hitbox.is_hovered(window) {
4501 cx.theme().colors().editor_hover_line_number
4502 } else {
4503 cx.theme().colors().editor_line_number
4504 };
4505
4506 let Some(line) = self
4507 .shape_line_number(shaped_line.text.clone(), color, window)
4508 .log_err()
4509 else {
4510 continue;
4511 };
4512 let Some(()) = line.paint(hitbox.origin, line_height, window, cx).log_err() else {
4513 continue;
4514 };
4515 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
4516 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
4517 if is_singleton {
4518 window.set_cursor_style(CursorStyle::IBeam, &hitbox);
4519 } else {
4520 window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
4521 }
4522 }
4523 }
4524
4525 fn paint_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4526 if layout.display_hunks.is_empty() {
4527 return;
4528 }
4529
4530 let line_height = layout.position_map.line_height;
4531 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4532 for (hunk, hitbox) in &layout.display_hunks {
4533 let hunk_to_paint = match hunk {
4534 DisplayDiffHunk::Folded { .. } => {
4535 let hunk_bounds = Self::diff_hunk_bounds(
4536 &layout.position_map.snapshot,
4537 line_height,
4538 layout.gutter_hitbox.bounds,
4539 hunk,
4540 );
4541 Some((
4542 hunk_bounds,
4543 cx.theme().status().modified,
4544 Corners::all(px(0.)),
4545 &DiffHunkSecondaryStatus::None,
4546 ))
4547 }
4548 DisplayDiffHunk::Unfolded {
4549 status,
4550 display_row_range,
4551 ..
4552 } => hitbox.as_ref().map(|hunk_hitbox| match status {
4553 DiffHunkStatus::Added(secondary_status) => (
4554 hunk_hitbox.bounds,
4555 cx.theme().status().created,
4556 Corners::all(px(0.)),
4557 secondary_status,
4558 ),
4559 DiffHunkStatus::Modified(secondary_status) => (
4560 hunk_hitbox.bounds,
4561 cx.theme().status().modified,
4562 Corners::all(px(0.)),
4563 secondary_status,
4564 ),
4565 DiffHunkStatus::Removed(secondary_status)
4566 if !display_row_range.is_empty() =>
4567 {
4568 (
4569 hunk_hitbox.bounds,
4570 cx.theme().status().deleted,
4571 Corners::all(px(0.)),
4572 secondary_status,
4573 )
4574 }
4575 DiffHunkStatus::Removed(secondary_status) => (
4576 Bounds::new(
4577 point(
4578 hunk_hitbox.origin.x - hunk_hitbox.size.width,
4579 hunk_hitbox.origin.y,
4580 ),
4581 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
4582 ),
4583 cx.theme().status().deleted,
4584 Corners::all(1. * line_height),
4585 secondary_status,
4586 ),
4587 }),
4588 };
4589
4590 if let Some((hunk_bounds, mut background_color, corner_radii, secondary_status)) =
4591 hunk_to_paint
4592 {
4593 if *secondary_status != DiffHunkSecondaryStatus::None {
4594 background_color.a *= 0.6;
4595 }
4596 window.paint_quad(quad(
4597 hunk_bounds,
4598 corner_radii,
4599 background_color,
4600 Edges::default(),
4601 transparent_black(),
4602 ));
4603 }
4604 }
4605 });
4606 }
4607
4608 fn diff_hunk_bounds(
4609 snapshot: &EditorSnapshot,
4610 line_height: Pixels,
4611 gutter_bounds: Bounds<Pixels>,
4612 hunk: &DisplayDiffHunk,
4613 ) -> Bounds<Pixels> {
4614 let scroll_position = snapshot.scroll_position();
4615 let scroll_top = scroll_position.y * line_height;
4616 let gutter_strip_width = (0.275 * line_height).floor();
4617
4618 match hunk {
4619 DisplayDiffHunk::Folded { display_row, .. } => {
4620 let start_y = display_row.as_f32() * line_height - scroll_top;
4621 let end_y = start_y + line_height;
4622 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4623 let highlight_size = size(gutter_strip_width, end_y - start_y);
4624 Bounds::new(highlight_origin, highlight_size)
4625 }
4626 DisplayDiffHunk::Unfolded {
4627 display_row_range,
4628 status,
4629 ..
4630 } => {
4631 if status.is_removed() && display_row_range.is_empty() {
4632 let row = display_row_range.start;
4633
4634 let offset = line_height / 2.;
4635 let start_y = row.as_f32() * line_height - offset - scroll_top;
4636 let end_y = start_y + line_height;
4637
4638 let width = (0.35 * line_height).floor();
4639 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4640 let highlight_size = size(width, end_y - start_y);
4641 Bounds::new(highlight_origin, highlight_size)
4642 } else {
4643 let start_row = display_row_range.start;
4644 let end_row = display_row_range.end;
4645 // If we're in a multibuffer, row range span might include an
4646 // excerpt header, so if we were to draw the marker straight away,
4647 // the hunk might include the rows of that header.
4648 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
4649 // Instead, we simply check whether the range we're dealing with includes
4650 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
4651 let end_row_in_current_excerpt = snapshot
4652 .blocks_in_range(start_row..end_row)
4653 .find_map(|(start_row, block)| {
4654 if matches!(block, Block::ExcerptBoundary { .. }) {
4655 Some(start_row)
4656 } else {
4657 None
4658 }
4659 })
4660 .unwrap_or(end_row);
4661
4662 let start_y = start_row.as_f32() * line_height - scroll_top;
4663 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
4664
4665 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4666 let highlight_size = size(gutter_strip_width, end_y - start_y);
4667 Bounds::new(highlight_origin, highlight_size)
4668 }
4669 }
4670 }
4671 }
4672
4673 fn paint_gutter_indicators(
4674 &self,
4675 layout: &mut EditorLayout,
4676 window: &mut Window,
4677 cx: &mut App,
4678 ) {
4679 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4680 window.with_element_namespace("crease_toggles", |window| {
4681 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
4682 crease_toggle.paint(window, cx);
4683 }
4684 });
4685
4686 for test_indicator in layout.test_indicators.iter_mut() {
4687 test_indicator.paint(window, cx);
4688 }
4689
4690 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
4691 indicator.paint(window, cx);
4692 }
4693 });
4694 }
4695
4696 fn paint_gutter_highlights(
4697 &self,
4698 layout: &mut EditorLayout,
4699 window: &mut Window,
4700 cx: &mut App,
4701 ) {
4702 for (_, hunk_hitbox) in &layout.display_hunks {
4703 if let Some(hunk_hitbox) = hunk_hitbox {
4704 if !self
4705 .editor
4706 .read(cx)
4707 .buffer()
4708 .read(cx)
4709 .all_diff_hunks_expanded()
4710 {
4711 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
4712 }
4713 }
4714 }
4715
4716 let show_git_gutter = layout
4717 .position_map
4718 .snapshot
4719 .show_git_diff_gutter
4720 .unwrap_or_else(|| {
4721 matches!(
4722 ProjectSettings::get_global(cx).git.git_gutter,
4723 Some(GitGutterSetting::TrackedFiles)
4724 )
4725 });
4726 if show_git_gutter {
4727 Self::paint_diff_hunks(layout, window, cx)
4728 }
4729
4730 let highlight_width = 0.275 * layout.position_map.line_height;
4731 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
4732 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4733 for (range, color) in &layout.highlighted_gutter_ranges {
4734 let start_row = if range.start.row() < layout.visible_display_row_range.start {
4735 layout.visible_display_row_range.start - DisplayRow(1)
4736 } else {
4737 range.start.row()
4738 };
4739 let end_row = if range.end.row() > layout.visible_display_row_range.end {
4740 layout.visible_display_row_range.end + DisplayRow(1)
4741 } else {
4742 range.end.row()
4743 };
4744
4745 let start_y = layout.gutter_hitbox.top()
4746 + start_row.0 as f32 * layout.position_map.line_height
4747 - layout.position_map.scroll_pixel_position.y;
4748 let end_y = layout.gutter_hitbox.top()
4749 + (end_row.0 + 1) as f32 * layout.position_map.line_height
4750 - layout.position_map.scroll_pixel_position.y;
4751 let bounds = Bounds::from_corners(
4752 point(layout.gutter_hitbox.left(), start_y),
4753 point(layout.gutter_hitbox.left() + highlight_width, end_y),
4754 );
4755 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
4756 }
4757 });
4758 }
4759
4760 fn paint_blamed_display_rows(
4761 &self,
4762 layout: &mut EditorLayout,
4763 window: &mut Window,
4764 cx: &mut App,
4765 ) {
4766 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
4767 return;
4768 };
4769
4770 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4771 for mut blame_element in blamed_display_rows.into_iter() {
4772 blame_element.paint(window, cx);
4773 }
4774 })
4775 }
4776
4777 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4778 window.with_content_mask(
4779 Some(ContentMask {
4780 bounds: layout.position_map.text_hitbox.bounds,
4781 }),
4782 |window| {
4783 let cursor_style = if self
4784 .editor
4785 .read(cx)
4786 .hovered_link_state
4787 .as_ref()
4788 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
4789 {
4790 CursorStyle::PointingHand
4791 } else {
4792 CursorStyle::IBeam
4793 };
4794 window.set_cursor_style(cursor_style, &layout.position_map.text_hitbox);
4795
4796 let invisible_display_ranges = self.paint_highlights(layout, window);
4797 self.paint_lines(&invisible_display_ranges, layout, window, cx);
4798 self.paint_redactions(layout, window);
4799 self.paint_cursors(layout, window, cx);
4800 self.paint_inline_blame(layout, window, cx);
4801 self.paint_diff_hunk_controls(layout, window, cx);
4802 window.with_element_namespace("crease_trailers", |window| {
4803 for trailer in layout.crease_trailers.iter_mut().flatten() {
4804 trailer.element.paint(window, cx);
4805 }
4806 });
4807 },
4808 )
4809 }
4810
4811 fn paint_highlights(
4812 &mut self,
4813 layout: &mut EditorLayout,
4814 window: &mut Window,
4815 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
4816 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4817 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
4818 let line_end_overshoot = 0.15 * layout.position_map.line_height;
4819 for (range, color) in &layout.highlighted_ranges {
4820 self.paint_highlighted_range(
4821 range.clone(),
4822 *color,
4823 Pixels::ZERO,
4824 line_end_overshoot,
4825 layout,
4826 window,
4827 );
4828 }
4829
4830 let corner_radius = 0.15 * layout.position_map.line_height;
4831
4832 for (player_color, selections) in &layout.selections {
4833 for selection in selections.iter() {
4834 self.paint_highlighted_range(
4835 selection.range.clone(),
4836 player_color.selection,
4837 corner_radius,
4838 corner_radius * 2.,
4839 layout,
4840 window,
4841 );
4842
4843 if selection.is_local && !selection.range.is_empty() {
4844 invisible_display_ranges.push(selection.range.clone());
4845 }
4846 }
4847 }
4848 invisible_display_ranges
4849 })
4850 }
4851
4852 fn paint_lines(
4853 &mut self,
4854 invisible_display_ranges: &[Range<DisplayPoint>],
4855 layout: &mut EditorLayout,
4856 window: &mut Window,
4857 cx: &mut App,
4858 ) {
4859 let whitespace_setting = self
4860 .editor
4861 .read(cx)
4862 .buffer
4863 .read(cx)
4864 .settings_at(0, cx)
4865 .show_whitespaces;
4866
4867 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4868 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4869 line_with_invisibles.draw(
4870 layout,
4871 row,
4872 layout.content_origin,
4873 whitespace_setting,
4874 invisible_display_ranges,
4875 window,
4876 cx,
4877 )
4878 }
4879
4880 for line_element in &mut layout.line_elements {
4881 line_element.paint(window, cx);
4882 }
4883 }
4884
4885 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
4886 if layout.redacted_ranges.is_empty() {
4887 return;
4888 }
4889
4890 let line_end_overshoot = layout.line_end_overshoot();
4891
4892 // A softer than perfect black
4893 let redaction_color = gpui::rgb(0x0e1111);
4894
4895 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4896 for range in layout.redacted_ranges.iter() {
4897 self.paint_highlighted_range(
4898 range.clone(),
4899 redaction_color.into(),
4900 Pixels::ZERO,
4901 line_end_overshoot,
4902 layout,
4903 window,
4904 );
4905 }
4906 });
4907 }
4908
4909 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4910 for cursor in &mut layout.visible_cursors {
4911 cursor.paint(layout.content_origin, window, cx);
4912 }
4913 }
4914
4915 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4916 let (scrollbar_x, scrollbar_y) = layout.scrollbars_layout.as_xy();
4917
4918 if let Some(scrollbar_layout) = scrollbar_x {
4919 let hitbox = scrollbar_layout.hitbox.clone();
4920 let text_unit_size = scrollbar_layout.text_unit_size;
4921 let visible_range = scrollbar_layout.visible_range.clone();
4922 let thumb_bounds = scrollbar_layout.thumb_bounds();
4923
4924 if scrollbar_layout.visible {
4925 window.paint_layer(hitbox.bounds, |window| {
4926 window.paint_quad(quad(
4927 hitbox.bounds,
4928 Corners::default(),
4929 cx.theme().colors().scrollbar_track_background,
4930 Edges {
4931 top: Pixels::ZERO,
4932 right: Pixels::ZERO,
4933 bottom: Pixels::ZERO,
4934 left: Pixels::ZERO,
4935 },
4936 cx.theme().colors().scrollbar_track_border,
4937 ));
4938
4939 window.paint_quad(quad(
4940 thumb_bounds,
4941 Corners::default(),
4942 cx.theme().colors().scrollbar_thumb_background,
4943 Edges {
4944 top: Pixels::ZERO,
4945 right: Pixels::ZERO,
4946 bottom: Pixels::ZERO,
4947 left: ScrollbarLayout::BORDER_WIDTH,
4948 },
4949 cx.theme().colors().scrollbar_thumb_border,
4950 ));
4951 })
4952 }
4953
4954 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
4955
4956 window.on_mouse_event({
4957 let editor = self.editor.clone();
4958
4959 // there may be a way to avoid this clone
4960 let hitbox = hitbox.clone();
4961
4962 let mut mouse_position = window.mouse_position();
4963 move |event: &MouseMoveEvent, phase, window, cx| {
4964 if phase == DispatchPhase::Capture {
4965 return;
4966 }
4967
4968 editor.update(cx, |editor, cx| {
4969 if event.pressed_button == Some(MouseButton::Left)
4970 && editor
4971 .scroll_manager
4972 .is_dragging_scrollbar(Axis::Horizontal)
4973 {
4974 let x = mouse_position.x;
4975 let new_x = event.position.x;
4976 if (hitbox.left()..hitbox.right()).contains(&x) {
4977 let mut position = editor.scroll_position(cx);
4978
4979 position.x += (new_x - x) / text_unit_size;
4980 if position.x < 0.0 {
4981 position.x = 0.0;
4982 }
4983 editor.set_scroll_position(position, window, cx);
4984 }
4985
4986 cx.stop_propagation();
4987 } else {
4988 editor.scroll_manager.set_is_dragging_scrollbar(
4989 Axis::Horizontal,
4990 false,
4991 cx,
4992 );
4993
4994 if hitbox.is_hovered(window) {
4995 editor.scroll_manager.show_scrollbar(window, cx);
4996 }
4997 }
4998 mouse_position = event.position;
4999 })
5000 }
5001 });
5002
5003 if self
5004 .editor
5005 .read(cx)
5006 .scroll_manager
5007 .is_dragging_scrollbar(Axis::Horizontal)
5008 {
5009 window.on_mouse_event({
5010 let editor = self.editor.clone();
5011 move |_: &MouseUpEvent, phase, _, cx| {
5012 if phase == DispatchPhase::Capture {
5013 return;
5014 }
5015
5016 editor.update(cx, |editor, cx| {
5017 editor.scroll_manager.set_is_dragging_scrollbar(
5018 Axis::Horizontal,
5019 false,
5020 cx,
5021 );
5022 cx.stop_propagation();
5023 });
5024 }
5025 });
5026 } else {
5027 window.on_mouse_event({
5028 let editor = self.editor.clone();
5029
5030 move |event: &MouseDownEvent, phase, window, cx| {
5031 if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5032 return;
5033 }
5034
5035 editor.update(cx, |editor, cx| {
5036 editor.scroll_manager.set_is_dragging_scrollbar(
5037 Axis::Horizontal,
5038 true,
5039 cx,
5040 );
5041
5042 let x = event.position.x;
5043
5044 if x < thumb_bounds.left() || thumb_bounds.right() < x {
5045 let center_row =
5046 ((x - hitbox.left()) / text_unit_size).round() as u32;
5047 let top_row = center_row.saturating_sub(
5048 (visible_range.end - visible_range.start) as u32 / 2,
5049 );
5050
5051 let mut position = editor.scroll_position(cx);
5052 position.x = top_row as f32;
5053
5054 editor.set_scroll_position(position, window, cx);
5055 } else {
5056 editor.scroll_manager.show_scrollbar(window, cx);
5057 }
5058
5059 cx.stop_propagation();
5060 });
5061 }
5062 });
5063 }
5064 }
5065
5066 if let Some(scrollbar_layout) = scrollbar_y {
5067 let hitbox = scrollbar_layout.hitbox.clone();
5068 let text_unit_size = scrollbar_layout.text_unit_size;
5069 let visible_range = scrollbar_layout.visible_range.clone();
5070 let thumb_bounds = scrollbar_layout.thumb_bounds();
5071
5072 if scrollbar_layout.visible {
5073 window.paint_layer(hitbox.bounds, |window| {
5074 window.paint_quad(quad(
5075 hitbox.bounds,
5076 Corners::default(),
5077 cx.theme().colors().scrollbar_track_background,
5078 Edges {
5079 top: Pixels::ZERO,
5080 right: Pixels::ZERO,
5081 bottom: Pixels::ZERO,
5082 left: ScrollbarLayout::BORDER_WIDTH,
5083 },
5084 cx.theme().colors().scrollbar_track_border,
5085 ));
5086
5087 let fast_markers =
5088 self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
5089 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
5090 self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
5091
5092 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
5093 for marker in markers.iter().chain(&fast_markers) {
5094 let mut marker = marker.clone();
5095 marker.bounds.origin += hitbox.origin;
5096 window.paint_quad(marker);
5097 }
5098
5099 window.paint_quad(quad(
5100 thumb_bounds,
5101 Corners::default(),
5102 cx.theme().colors().scrollbar_thumb_background,
5103 Edges {
5104 top: Pixels::ZERO,
5105 right: Pixels::ZERO,
5106 bottom: Pixels::ZERO,
5107 left: ScrollbarLayout::BORDER_WIDTH,
5108 },
5109 cx.theme().colors().scrollbar_thumb_border,
5110 ));
5111 });
5112 }
5113
5114 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
5115
5116 window.on_mouse_event({
5117 let editor = self.editor.clone();
5118
5119 let hitbox = hitbox.clone();
5120
5121 let mut mouse_position = window.mouse_position();
5122 move |event: &MouseMoveEvent, phase, window, cx| {
5123 if phase == DispatchPhase::Capture {
5124 return;
5125 }
5126
5127 editor.update(cx, |editor, cx| {
5128 if event.pressed_button == Some(MouseButton::Left)
5129 && editor.scroll_manager.is_dragging_scrollbar(Axis::Vertical)
5130 {
5131 let y = mouse_position.y;
5132 let new_y = event.position.y;
5133 if (hitbox.top()..hitbox.bottom()).contains(&y) {
5134 let mut position = editor.scroll_position(cx);
5135 position.y += (new_y - y) / text_unit_size;
5136 if position.y < 0.0 {
5137 position.y = 0.0;
5138 }
5139 editor.set_scroll_position(position, window, cx);
5140 }
5141 } else {
5142 editor.scroll_manager.set_is_dragging_scrollbar(
5143 Axis::Vertical,
5144 false,
5145 cx,
5146 );
5147
5148 if hitbox.is_hovered(window) {
5149 editor.scroll_manager.show_scrollbar(window, cx);
5150 }
5151 }
5152 mouse_position = event.position;
5153 })
5154 }
5155 });
5156
5157 if self
5158 .editor
5159 .read(cx)
5160 .scroll_manager
5161 .is_dragging_scrollbar(Axis::Vertical)
5162 {
5163 window.on_mouse_event({
5164 let editor = self.editor.clone();
5165 move |_: &MouseUpEvent, phase, _, cx| {
5166 if phase == DispatchPhase::Capture {
5167 return;
5168 }
5169
5170 editor.update(cx, |editor, cx| {
5171 editor.scroll_manager.set_is_dragging_scrollbar(
5172 Axis::Vertical,
5173 false,
5174 cx,
5175 );
5176 cx.stop_propagation();
5177 });
5178 }
5179 });
5180 } else {
5181 window.on_mouse_event({
5182 let editor = self.editor.clone();
5183
5184 move |event: &MouseDownEvent, phase, window, cx| {
5185 if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5186 return;
5187 }
5188
5189 editor.update(cx, |editor, cx| {
5190 editor.scroll_manager.set_is_dragging_scrollbar(
5191 Axis::Vertical,
5192 true,
5193 cx,
5194 );
5195
5196 let y = event.position.y;
5197 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
5198 let center_row =
5199 ((y - hitbox.top()) / text_unit_size).round() as u32;
5200 let top_row = center_row.saturating_sub(
5201 (visible_range.end - visible_range.start) as u32 / 2,
5202 );
5203 let mut position = editor.scroll_position(cx);
5204 position.y = top_row as f32;
5205 editor.set_scroll_position(position, window, cx);
5206 } else {
5207 editor.scroll_manager.show_scrollbar(window, cx);
5208 }
5209
5210 cx.stop_propagation();
5211 });
5212 }
5213 });
5214 }
5215 }
5216 }
5217
5218 fn collect_fast_scrollbar_markers(
5219 &self,
5220 layout: &EditorLayout,
5221 scrollbar_layout: &ScrollbarLayout,
5222 cx: &mut App,
5223 ) -> Vec<PaintQuad> {
5224 const LIMIT: usize = 100;
5225 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5226 return vec![];
5227 }
5228 let cursor_ranges = layout
5229 .cursors
5230 .iter()
5231 .map(|(point, color)| ColoredRange {
5232 start: point.row(),
5233 end: point.row(),
5234 color: *color,
5235 })
5236 .collect_vec();
5237 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5238 }
5239
5240 fn refresh_slow_scrollbar_markers(
5241 &self,
5242 layout: &EditorLayout,
5243 scrollbar_layout: &ScrollbarLayout,
5244 window: &mut Window,
5245 cx: &mut App,
5246 ) {
5247 self.editor.update(cx, |editor, cx| {
5248 if !editor.is_singleton(cx)
5249 || !editor
5250 .scrollbar_marker_state
5251 .should_refresh(scrollbar_layout.hitbox.size)
5252 {
5253 return;
5254 }
5255
5256 let scrollbar_layout = scrollbar_layout.clone();
5257 let background_highlights = editor.background_highlights.clone();
5258 let snapshot = layout.position_map.snapshot.clone();
5259 let theme = cx.theme().clone();
5260 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5261
5262 editor.scrollbar_marker_state.dirty = false;
5263 editor.scrollbar_marker_state.pending_refresh =
5264 Some(cx.spawn_in(window, |editor, mut cx| async move {
5265 let scrollbar_size = scrollbar_layout.hitbox.size;
5266 let scrollbar_markers = cx
5267 .background_spawn(async move {
5268 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5269 let mut marker_quads = Vec::new();
5270 if scrollbar_settings.git_diff {
5271 let marker_row_ranges =
5272 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5273 let start_display_row =
5274 MultiBufferPoint::new(hunk.row_range.start.0, 0)
5275 .to_display_point(&snapshot.display_snapshot)
5276 .row();
5277 let mut end_display_row =
5278 MultiBufferPoint::new(hunk.row_range.end.0, 0)
5279 .to_display_point(&snapshot.display_snapshot)
5280 .row();
5281 if end_display_row != start_display_row {
5282 end_display_row.0 -= 1;
5283 }
5284 let color = match &hunk.status() {
5285 DiffHunkStatus::Added(_) => theme.status().created,
5286 DiffHunkStatus::Modified(_) => theme.status().modified,
5287 DiffHunkStatus::Removed(_) => theme.status().deleted,
5288 };
5289 ColoredRange {
5290 start: start_display_row,
5291 end: end_display_row,
5292 color,
5293 }
5294 });
5295
5296 marker_quads.extend(
5297 scrollbar_layout
5298 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5299 );
5300 }
5301
5302 for (background_highlight_id, (_, background_ranges)) in
5303 background_highlights.iter()
5304 {
5305 let is_search_highlights = *background_highlight_id
5306 == TypeId::of::<BufferSearchHighlights>();
5307 let is_text_highlights = *background_highlight_id
5308 == TypeId::of::<SelectedTextHighlight>();
5309 let is_symbol_occurrences = *background_highlight_id
5310 == TypeId::of::<DocumentHighlightRead>()
5311 || *background_highlight_id
5312 == TypeId::of::<DocumentHighlightWrite>();
5313 if (is_search_highlights && scrollbar_settings.search_results)
5314 || (is_text_highlights && scrollbar_settings.selected_text)
5315 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5316 {
5317 let mut color = theme.status().info;
5318 if is_symbol_occurrences {
5319 color.fade_out(0.5);
5320 }
5321 let marker_row_ranges = background_ranges.iter().map(|range| {
5322 let display_start = range
5323 .start
5324 .to_display_point(&snapshot.display_snapshot);
5325 let display_end =
5326 range.end.to_display_point(&snapshot.display_snapshot);
5327 ColoredRange {
5328 start: display_start.row(),
5329 end: display_end.row(),
5330 color,
5331 }
5332 });
5333 marker_quads.extend(
5334 scrollbar_layout
5335 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5336 );
5337 }
5338 }
5339
5340 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5341 let diagnostics = snapshot
5342 .buffer_snapshot
5343 .diagnostics_in_range::<Point>(Point::zero()..max_point)
5344 // Don't show diagnostics the user doesn't care about
5345 .filter(|diagnostic| {
5346 match (
5347 scrollbar_settings.diagnostics,
5348 diagnostic.diagnostic.severity,
5349 ) {
5350 (ScrollbarDiagnostics::All, _) => true,
5351 (
5352 ScrollbarDiagnostics::Error,
5353 DiagnosticSeverity::ERROR,
5354 ) => true,
5355 (
5356 ScrollbarDiagnostics::Warning,
5357 DiagnosticSeverity::ERROR
5358 | DiagnosticSeverity::WARNING,
5359 ) => true,
5360 (
5361 ScrollbarDiagnostics::Information,
5362 DiagnosticSeverity::ERROR
5363 | DiagnosticSeverity::WARNING
5364 | DiagnosticSeverity::INFORMATION,
5365 ) => true,
5366 (_, _) => false,
5367 }
5368 })
5369 // We want to sort by severity, in order to paint the most severe diagnostics last.
5370 .sorted_by_key(|diagnostic| {
5371 std::cmp::Reverse(diagnostic.diagnostic.severity)
5372 });
5373
5374 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5375 let start_display = diagnostic
5376 .range
5377 .start
5378 .to_display_point(&snapshot.display_snapshot);
5379 let end_display = diagnostic
5380 .range
5381 .end
5382 .to_display_point(&snapshot.display_snapshot);
5383 let color = match diagnostic.diagnostic.severity {
5384 DiagnosticSeverity::ERROR => theme.status().error,
5385 DiagnosticSeverity::WARNING => theme.status().warning,
5386 DiagnosticSeverity::INFORMATION => theme.status().info,
5387 _ => theme.status().hint,
5388 };
5389 ColoredRange {
5390 start: start_display.row(),
5391 end: end_display.row(),
5392 color,
5393 }
5394 });
5395 marker_quads.extend(
5396 scrollbar_layout
5397 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5398 );
5399 }
5400
5401 Arc::from(marker_quads)
5402 })
5403 .await;
5404
5405 editor.update(&mut cx, |editor, cx| {
5406 editor.scrollbar_marker_state.markers = scrollbar_markers;
5407 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5408 editor.scrollbar_marker_state.pending_refresh = None;
5409 cx.notify();
5410 })?;
5411
5412 Ok(())
5413 }));
5414 });
5415 }
5416
5417 fn paint_highlighted_range(
5418 &self,
5419 range: Range<DisplayPoint>,
5420 color: Hsla,
5421 corner_radius: Pixels,
5422 line_end_overshoot: Pixels,
5423 layout: &EditorLayout,
5424 window: &mut Window,
5425 ) {
5426 let start_row = layout.visible_display_row_range.start;
5427 let end_row = layout.visible_display_row_range.end;
5428 if range.start != range.end {
5429 let row_range = if range.end.column() == 0 {
5430 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5431 } else {
5432 cmp::max(range.start.row(), start_row)
5433 ..cmp::min(range.end.row().next_row(), end_row)
5434 };
5435
5436 let highlighted_range = HighlightedRange {
5437 color,
5438 line_height: layout.position_map.line_height,
5439 corner_radius,
5440 start_y: layout.content_origin.y
5441 + row_range.start.as_f32() * layout.position_map.line_height
5442 - layout.position_map.scroll_pixel_position.y,
5443 lines: row_range
5444 .iter_rows()
5445 .map(|row| {
5446 let line_layout =
5447 &layout.position_map.line_layouts[row.minus(start_row) as usize];
5448 HighlightedRangeLine {
5449 start_x: if row == range.start.row() {
5450 layout.content_origin.x
5451 + line_layout.x_for_index(range.start.column() as usize)
5452 - layout.position_map.scroll_pixel_position.x
5453 } else {
5454 layout.content_origin.x
5455 - layout.position_map.scroll_pixel_position.x
5456 },
5457 end_x: if row == range.end.row() {
5458 layout.content_origin.x
5459 + line_layout.x_for_index(range.end.column() as usize)
5460 - layout.position_map.scroll_pixel_position.x
5461 } else {
5462 layout.content_origin.x + line_layout.width + line_end_overshoot
5463 - layout.position_map.scroll_pixel_position.x
5464 },
5465 }
5466 })
5467 .collect(),
5468 };
5469
5470 highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5471 }
5472 }
5473
5474 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5475 if let Some(mut inline_blame) = layout.inline_blame.take() {
5476 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5477 inline_blame.paint(window, cx);
5478 })
5479 }
5480 }
5481
5482 fn paint_diff_hunk_controls(
5483 &mut self,
5484 layout: &mut EditorLayout,
5485 window: &mut Window,
5486 cx: &mut App,
5487 ) {
5488 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5489 diff_hunk_control.paint(window, cx);
5490 }
5491 }
5492
5493 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5494 for mut block in layout.blocks.drain(..) {
5495 block.element.paint(window, cx);
5496 }
5497 }
5498
5499 fn paint_inline_completion_popover(
5500 &mut self,
5501 layout: &mut EditorLayout,
5502 window: &mut Window,
5503 cx: &mut App,
5504 ) {
5505 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5506 inline_completion_popover.paint(window, cx);
5507 }
5508 }
5509
5510 fn paint_mouse_context_menu(
5511 &mut self,
5512 layout: &mut EditorLayout,
5513 window: &mut Window,
5514 cx: &mut App,
5515 ) {
5516 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5517 mouse_context_menu.paint(window, cx);
5518 }
5519 }
5520
5521 fn paint_scroll_wheel_listener(
5522 &mut self,
5523 layout: &EditorLayout,
5524 window: &mut Window,
5525 cx: &mut App,
5526 ) {
5527 window.on_mouse_event({
5528 let position_map = layout.position_map.clone();
5529 let editor = self.editor.clone();
5530 let hitbox = layout.hitbox.clone();
5531 let mut delta = ScrollDelta::default();
5532
5533 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5534 // accidentally turn off their scrolling.
5535 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5536
5537 move |event: &ScrollWheelEvent, phase, window, cx| {
5538 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5539 delta = delta.coalesce(event.delta);
5540 editor.update(cx, |editor, cx| {
5541 let position_map: &PositionMap = &position_map;
5542
5543 let line_height = position_map.line_height;
5544 let max_glyph_width = position_map.em_width;
5545 let (delta, axis) = match delta {
5546 gpui::ScrollDelta::Pixels(mut pixels) => {
5547 //Trackpad
5548 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5549 (pixels, axis)
5550 }
5551
5552 gpui::ScrollDelta::Lines(lines) => {
5553 //Not trackpad
5554 let pixels =
5555 point(lines.x * max_glyph_width, lines.y * line_height);
5556 (pixels, None)
5557 }
5558 };
5559
5560 let current_scroll_position = position_map.snapshot.scroll_position();
5561 let x = (current_scroll_position.x * max_glyph_width
5562 - (delta.x * scroll_sensitivity))
5563 / max_glyph_width;
5564 let y = (current_scroll_position.y * line_height
5565 - (delta.y * scroll_sensitivity))
5566 / line_height;
5567 let mut scroll_position =
5568 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5569 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5570 if forbid_vertical_scroll {
5571 scroll_position.y = current_scroll_position.y;
5572 }
5573
5574 if scroll_position != current_scroll_position {
5575 editor.scroll(scroll_position, axis, window, cx);
5576 cx.stop_propagation();
5577 } else if y < 0. {
5578 // Due to clamping, we may fail to detect cases of overscroll to the top;
5579 // We want the scroll manager to get an update in such cases and detect the change of direction
5580 // on the next frame.
5581 cx.notify();
5582 }
5583 });
5584 }
5585 }
5586 });
5587 }
5588
5589 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5590 self.paint_scroll_wheel_listener(layout, window, cx);
5591
5592 window.on_mouse_event({
5593 let position_map = layout.position_map.clone();
5594 let editor = self.editor.clone();
5595 let diff_hunk_range =
5596 layout
5597 .display_hunks
5598 .iter()
5599 .find_map(|(hunk, hunk_hitbox)| match hunk {
5600 DisplayDiffHunk::Folded { .. } => None,
5601 DisplayDiffHunk::Unfolded {
5602 multi_buffer_range, ..
5603 } => {
5604 if hunk_hitbox
5605 .as_ref()
5606 .map(|hitbox| hitbox.is_hovered(window))
5607 .unwrap_or(false)
5608 {
5609 Some(multi_buffer_range.clone())
5610 } else {
5611 None
5612 }
5613 }
5614 });
5615 let line_numbers = layout.line_numbers.clone();
5616
5617 move |event: &MouseDownEvent, phase, window, cx| {
5618 if phase == DispatchPhase::Bubble {
5619 match event.button {
5620 MouseButton::Left => editor.update(cx, |editor, cx| {
5621 let pending_mouse_down = editor
5622 .pending_mouse_down
5623 .get_or_insert_with(Default::default)
5624 .clone();
5625
5626 *pending_mouse_down.borrow_mut() = Some(event.clone());
5627
5628 Self::mouse_left_down(
5629 editor,
5630 event,
5631 diff_hunk_range.clone(),
5632 &position_map,
5633 line_numbers.as_ref(),
5634 window,
5635 cx,
5636 );
5637 }),
5638 MouseButton::Right => editor.update(cx, |editor, cx| {
5639 Self::mouse_right_down(editor, event, &position_map, window, cx);
5640 }),
5641 MouseButton::Middle => editor.update(cx, |editor, cx| {
5642 Self::mouse_middle_down(editor, event, &position_map, window, cx);
5643 }),
5644 _ => {}
5645 };
5646 }
5647 }
5648 });
5649
5650 window.on_mouse_event({
5651 let editor = self.editor.clone();
5652 let position_map = layout.position_map.clone();
5653
5654 move |event: &MouseUpEvent, phase, window, cx| {
5655 if phase == DispatchPhase::Bubble {
5656 editor.update(cx, |editor, cx| {
5657 Self::mouse_up(editor, event, &position_map, window, cx)
5658 });
5659 }
5660 }
5661 });
5662
5663 window.on_mouse_event({
5664 let editor = self.editor.clone();
5665 let position_map = layout.position_map.clone();
5666 let mut captured_mouse_down = None;
5667
5668 move |event: &MouseUpEvent, phase, window, cx| match phase {
5669 // Clear the pending mouse down during the capture phase,
5670 // so that it happens even if another event handler stops
5671 // propagation.
5672 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
5673 let pending_mouse_down = editor
5674 .pending_mouse_down
5675 .get_or_insert_with(Default::default)
5676 .clone();
5677
5678 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
5679 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
5680 captured_mouse_down = pending_mouse_down.take();
5681 window.refresh();
5682 }
5683 }),
5684 // Fire click handlers during the bubble phase.
5685 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
5686 if let Some(mouse_down) = captured_mouse_down.take() {
5687 let event = ClickEvent {
5688 down: mouse_down,
5689 up: event.clone(),
5690 };
5691 Self::click(editor, &event, &position_map, window, cx);
5692 }
5693 }),
5694 }
5695 });
5696
5697 window.on_mouse_event({
5698 let position_map = layout.position_map.clone();
5699 let editor = self.editor.clone();
5700
5701 move |event: &MouseMoveEvent, phase, window, cx| {
5702 if phase == DispatchPhase::Bubble {
5703 editor.update(cx, |editor, cx| {
5704 if editor.hover_state.focused(window, cx) {
5705 return;
5706 }
5707 if event.pressed_button == Some(MouseButton::Left)
5708 || event.pressed_button == Some(MouseButton::Middle)
5709 {
5710 Self::mouse_dragged(editor, event, &position_map, window, cx)
5711 }
5712
5713 Self::mouse_moved(editor, event, &position_map, window, cx)
5714 });
5715 }
5716 }
5717 });
5718 }
5719
5720 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
5721 bounds.top_right().x - self.style.scrollbar_width
5722 }
5723
5724 fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
5725 let style = &self.style;
5726 let font_size = style.text.font_size.to_pixels(window.rem_size());
5727 let layout = window
5728 .text_system()
5729 .shape_line(
5730 SharedString::from(" ".repeat(column)),
5731 font_size,
5732 &[TextRun {
5733 len: column,
5734 font: style.text.font(),
5735 color: Hsla::default(),
5736 background_color: None,
5737 underline: None,
5738 strikethrough: None,
5739 }],
5740 )
5741 .unwrap();
5742
5743 layout.width
5744 }
5745
5746 fn max_line_number_width(
5747 &self,
5748 snapshot: &EditorSnapshot,
5749 window: &mut Window,
5750 cx: &mut App,
5751 ) -> Pixels {
5752 let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
5753 self.column_pixels(digit_count, window, cx)
5754 }
5755
5756 fn shape_line_number(
5757 &self,
5758 text: SharedString,
5759 color: Hsla,
5760 window: &mut Window,
5761 ) -> anyhow::Result<ShapedLine> {
5762 let run = TextRun {
5763 len: text.len(),
5764 font: self.style.text.font(),
5765 color,
5766 background_color: None,
5767 underline: None,
5768 strikethrough: None,
5769 };
5770 window.text_system().shape_line(
5771 text,
5772 self.style.text.font_size.to_pixels(window.rem_size()),
5773 &[run],
5774 )
5775 }
5776}
5777
5778fn header_jump_data(
5779 snapshot: &EditorSnapshot,
5780 block_row_start: DisplayRow,
5781 height: u32,
5782 for_excerpt: &ExcerptInfo,
5783) -> JumpData {
5784 let range = &for_excerpt.range;
5785 let buffer = &for_excerpt.buffer;
5786 let jump_anchor = range
5787 .primary
5788 .as_ref()
5789 .map_or(range.context.start, |primary| primary.start);
5790
5791 let excerpt_start = range.context.start;
5792 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
5793 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
5794 0
5795 } else {
5796 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
5797 jump_position.row.saturating_sub(excerpt_start_point.row)
5798 };
5799
5800 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
5801 .saturating_sub(
5802 snapshot
5803 .scroll_anchor
5804 .scroll_position(&snapshot.display_snapshot)
5805 .y as u32,
5806 );
5807
5808 JumpData::MultiBufferPoint {
5809 excerpt_id: for_excerpt.id,
5810 anchor: jump_anchor,
5811 position: jump_position,
5812 line_offset_from_top,
5813 }
5814}
5815
5816pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
5817
5818impl AcceptEditPredictionBinding {
5819 pub fn keystroke(&self) -> Option<&Keystroke> {
5820 if let Some(binding) = self.0.as_ref() {
5821 match &binding.keystrokes() {
5822 [keystroke] => Some(keystroke),
5823 _ => None,
5824 }
5825 } else {
5826 None
5827 }
5828 }
5829}
5830
5831fn prepaint_gutter_button(
5832 button: IconButton,
5833 row: DisplayRow,
5834 line_height: Pixels,
5835 gutter_dimensions: &GutterDimensions,
5836 scroll_pixel_position: gpui::Point<Pixels>,
5837 gutter_hitbox: &Hitbox,
5838 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
5839 window: &mut Window,
5840 cx: &mut App,
5841) -> AnyElement {
5842 let mut button = button.into_any_element();
5843 let available_space = size(
5844 AvailableSpace::MinContent,
5845 AvailableSpace::Definite(line_height),
5846 );
5847 let indicator_size = button.layout_as_root(available_space, window, cx);
5848
5849 let blame_width = gutter_dimensions.git_blame_entries_width;
5850 let gutter_width = rows_with_hunk_bounds
5851 .get(&row)
5852 .map(|bounds| bounds.size.width);
5853 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
5854
5855 let mut x = left_offset;
5856 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
5857 - indicator_size.width
5858 - left_offset;
5859 x += available_width / 2.;
5860
5861 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
5862 y += (line_height - indicator_size.height) / 2.;
5863
5864 button.prepaint_as_root(
5865 gutter_hitbox.origin + point(x, y),
5866 available_space,
5867 window,
5868 cx,
5869 );
5870 button
5871}
5872
5873fn render_inline_blame_entry(
5874 blame: &gpui::Entity<GitBlame>,
5875 blame_entry: BlameEntry,
5876 style: &EditorStyle,
5877 workspace: Option<WeakEntity<Workspace>>,
5878 cx: &mut App,
5879) -> AnyElement {
5880 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5881
5882 let author = blame_entry.author.as_deref().unwrap_or_default();
5883 let summary_enabled = ProjectSettings::get_global(cx)
5884 .git
5885 .show_inline_commit_summary();
5886
5887 let text = match blame_entry.summary.as_ref() {
5888 Some(summary) if summary_enabled => {
5889 format!("{}, {} - {}", author, relative_timestamp, summary)
5890 }
5891 _ => format!("{}, {}", author, relative_timestamp),
5892 };
5893
5894 let details = blame.read(cx).details_for_entry(&blame_entry);
5895
5896 let tooltip =
5897 cx.new(|_| CommitTooltip::blame_entry(blame_entry, details, style.clone(), workspace));
5898
5899 h_flex()
5900 .id("inline-blame")
5901 .w_full()
5902 .font_family(style.text.font().family)
5903 .text_color(cx.theme().status().hint)
5904 .line_height(style.text.line_height)
5905 .child(Icon::new(IconName::FileGit).color(Color::Hint))
5906 .child(text)
5907 .gap_2()
5908 .hoverable_tooltip(move |_, _| tooltip.clone().into())
5909 .into_any()
5910}
5911
5912fn render_blame_entry(
5913 ix: usize,
5914 blame: &gpui::Entity<GitBlame>,
5915 blame_entry: BlameEntry,
5916 style: &EditorStyle,
5917 last_used_color: &mut Option<(PlayerColor, Oid)>,
5918 editor: Entity<Editor>,
5919 cx: &mut App,
5920) -> AnyElement {
5921 let mut sha_color = cx
5922 .theme()
5923 .players()
5924 .color_for_participant(blame_entry.sha.into());
5925 // If the last color we used is the same as the one we get for this line, but
5926 // the commit SHAs are different, then we try again to get a different color.
5927 match *last_used_color {
5928 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
5929 let index: u32 = blame_entry.sha.into();
5930 sha_color = cx.theme().players().color_for_participant(index + 1);
5931 }
5932 _ => {}
5933 };
5934 last_used_color.replace((sha_color, blame_entry.sha));
5935
5936 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5937
5938 let short_commit_id = blame_entry.sha.display_short();
5939
5940 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
5941 let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
5942
5943 let details = blame.read(cx).details_for_entry(&blame_entry);
5944
5945 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
5946
5947 let tooltip = cx.new(|_| {
5948 CommitTooltip::blame_entry(
5949 blame_entry.clone(),
5950 details.clone(),
5951 style.clone(),
5952 workspace,
5953 )
5954 });
5955
5956 h_flex()
5957 .w_full()
5958 .justify_between()
5959 .font_family(style.text.font().family)
5960 .line_height(style.text.line_height)
5961 .id(("blame", ix))
5962 .text_color(cx.theme().status().hint)
5963 .pr_2()
5964 .gap_2()
5965 .child(
5966 h_flex()
5967 .items_center()
5968 .gap_2()
5969 .child(div().text_color(sha_color.cursor).child(short_commit_id))
5970 .child(name),
5971 )
5972 .child(relative_timestamp)
5973 .on_mouse_down(MouseButton::Right, {
5974 let blame_entry = blame_entry.clone();
5975 let details = details.clone();
5976 move |event, window, cx| {
5977 deploy_blame_entry_context_menu(
5978 &blame_entry,
5979 details.as_ref(),
5980 editor.clone(),
5981 event.position,
5982 window,
5983 cx,
5984 );
5985 }
5986 })
5987 .hover(|style| style.bg(cx.theme().colors().element_hover))
5988 .when_some(
5989 details.and_then(|details| details.permalink),
5990 |this, url| {
5991 let url = url.clone();
5992 this.cursor_pointer().on_click(move |_, _, cx| {
5993 cx.stop_propagation();
5994 cx.open_url(url.as_str())
5995 })
5996 },
5997 )
5998 .hoverable_tooltip(move |_, _| tooltip.clone().into())
5999 .into_any()
6000}
6001
6002fn deploy_blame_entry_context_menu(
6003 blame_entry: &BlameEntry,
6004 details: Option<&ParsedCommitMessage>,
6005 editor: Entity<Editor>,
6006 position: gpui::Point<Pixels>,
6007 window: &mut Window,
6008 cx: &mut App,
6009) {
6010 let context_menu = ContextMenu::build(window, cx, move |menu, _, _| {
6011 let sha = format!("{}", blame_entry.sha);
6012 menu.on_blur_subscription(Subscription::new(|| {}))
6013 .entry("Copy commit SHA", None, move |_, cx| {
6014 cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
6015 })
6016 .when_some(
6017 details.and_then(|details| details.permalink.clone()),
6018 |this, url| {
6019 this.entry("Open permalink", None, move |_, cx| {
6020 cx.open_url(url.as_str())
6021 })
6022 },
6023 )
6024 });
6025
6026 editor.update(cx, move |editor, cx| {
6027 editor.mouse_context_menu = Some(MouseContextMenu::new(
6028 MenuPosition::PinnedToScreen(position),
6029 context_menu,
6030 window,
6031 cx,
6032 ));
6033 cx.notify();
6034 });
6035}
6036
6037#[derive(Debug)]
6038pub(crate) struct LineWithInvisibles {
6039 fragments: SmallVec<[LineFragment; 1]>,
6040 invisibles: Vec<Invisible>,
6041 len: usize,
6042 width: Pixels,
6043 font_size: Pixels,
6044}
6045
6046#[allow(clippy::large_enum_variant)]
6047enum LineFragment {
6048 Text(ShapedLine),
6049 Element {
6050 element: Option<AnyElement>,
6051 size: Size<Pixels>,
6052 len: usize,
6053 },
6054}
6055
6056impl fmt::Debug for LineFragment {
6057 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6058 match self {
6059 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6060 LineFragment::Element { size, len, .. } => f
6061 .debug_struct("Element")
6062 .field("size", size)
6063 .field("len", len)
6064 .finish(),
6065 }
6066 }
6067}
6068
6069impl LineWithInvisibles {
6070 fn from_chunks<'a>(
6071 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6072 editor_style: &EditorStyle,
6073 max_line_len: usize,
6074 max_line_count: usize,
6075 editor_mode: EditorMode,
6076 text_width: Pixels,
6077 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6078 window: &mut Window,
6079 cx: &mut App,
6080 ) -> Vec<Self> {
6081 let text_style = &editor_style.text;
6082 let mut layouts = Vec::with_capacity(max_line_count);
6083 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6084 let mut line = String::new();
6085 let mut invisibles = Vec::new();
6086 let mut width = Pixels::ZERO;
6087 let mut len = 0;
6088 let mut styles = Vec::new();
6089 let mut non_whitespace_added = false;
6090 let mut row = 0;
6091 let mut line_exceeded_max_len = false;
6092 let font_size = text_style.font_size.to_pixels(window.rem_size());
6093
6094 let ellipsis = SharedString::from("⋯");
6095
6096 for highlighted_chunk in chunks.chain([HighlightedChunk {
6097 text: "\n",
6098 style: None,
6099 is_tab: false,
6100 replacement: None,
6101 }]) {
6102 if let Some(replacement) = highlighted_chunk.replacement {
6103 if !line.is_empty() {
6104 let shaped_line = window
6105 .text_system()
6106 .shape_line(line.clone().into(), font_size, &styles)
6107 .unwrap();
6108 width += shaped_line.width;
6109 len += shaped_line.len;
6110 fragments.push(LineFragment::Text(shaped_line));
6111 line.clear();
6112 styles.clear();
6113 }
6114
6115 match replacement {
6116 ChunkReplacement::Renderer(renderer) => {
6117 let available_width = if renderer.constrain_width {
6118 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6119 ellipsis.clone()
6120 } else {
6121 SharedString::from(Arc::from(highlighted_chunk.text))
6122 };
6123 let shaped_line = window
6124 .text_system()
6125 .shape_line(
6126 chunk,
6127 font_size,
6128 &[text_style.to_run(highlighted_chunk.text.len())],
6129 )
6130 .unwrap();
6131 AvailableSpace::Definite(shaped_line.width)
6132 } else {
6133 AvailableSpace::MinContent
6134 };
6135
6136 let mut element = (renderer.render)(&mut ChunkRendererContext {
6137 context: cx,
6138 window,
6139 max_width: text_width,
6140 });
6141 let line_height = text_style.line_height_in_pixels(window.rem_size());
6142 let size = element.layout_as_root(
6143 size(available_width, AvailableSpace::Definite(line_height)),
6144 window,
6145 cx,
6146 );
6147
6148 width += size.width;
6149 len += highlighted_chunk.text.len();
6150 fragments.push(LineFragment::Element {
6151 element: Some(element),
6152 size,
6153 len: highlighted_chunk.text.len(),
6154 });
6155 }
6156 ChunkReplacement::Str(x) => {
6157 let text_style = if let Some(style) = highlighted_chunk.style {
6158 Cow::Owned(text_style.clone().highlight(style))
6159 } else {
6160 Cow::Borrowed(text_style)
6161 };
6162
6163 let run = TextRun {
6164 len: x.len(),
6165 font: text_style.font(),
6166 color: text_style.color,
6167 background_color: text_style.background_color,
6168 underline: text_style.underline,
6169 strikethrough: text_style.strikethrough,
6170 };
6171 let line_layout = window
6172 .text_system()
6173 .shape_line(x, font_size, &[run])
6174 .unwrap()
6175 .with_len(highlighted_chunk.text.len());
6176
6177 width += line_layout.width;
6178 len += highlighted_chunk.text.len();
6179 fragments.push(LineFragment::Text(line_layout))
6180 }
6181 }
6182 } else {
6183 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6184 if ix > 0 {
6185 let shaped_line = window
6186 .text_system()
6187 .shape_line(line.clone().into(), font_size, &styles)
6188 .unwrap();
6189 width += shaped_line.width;
6190 len += shaped_line.len;
6191 fragments.push(LineFragment::Text(shaped_line));
6192 layouts.push(Self {
6193 width: mem::take(&mut width),
6194 len: mem::take(&mut len),
6195 fragments: mem::take(&mut fragments),
6196 invisibles: std::mem::take(&mut invisibles),
6197 font_size,
6198 });
6199
6200 line.clear();
6201 styles.clear();
6202 row += 1;
6203 line_exceeded_max_len = false;
6204 non_whitespace_added = false;
6205 if row == max_line_count {
6206 return layouts;
6207 }
6208 }
6209
6210 if !line_chunk.is_empty() && !line_exceeded_max_len {
6211 let text_style = if let Some(style) = highlighted_chunk.style {
6212 Cow::Owned(text_style.clone().highlight(style))
6213 } else {
6214 Cow::Borrowed(text_style)
6215 };
6216
6217 if line.len() + line_chunk.len() > max_line_len {
6218 let mut chunk_len = max_line_len - line.len();
6219 while !line_chunk.is_char_boundary(chunk_len) {
6220 chunk_len -= 1;
6221 }
6222 line_chunk = &line_chunk[..chunk_len];
6223 line_exceeded_max_len = true;
6224 }
6225
6226 styles.push(TextRun {
6227 len: line_chunk.len(),
6228 font: text_style.font(),
6229 color: text_style.color,
6230 background_color: text_style.background_color,
6231 underline: text_style.underline,
6232 strikethrough: text_style.strikethrough,
6233 });
6234
6235 if editor_mode == EditorMode::Full {
6236 // Line wrap pads its contents with fake whitespaces,
6237 // avoid printing them
6238 let is_soft_wrapped = is_row_soft_wrapped(row);
6239 if highlighted_chunk.is_tab {
6240 if non_whitespace_added || !is_soft_wrapped {
6241 invisibles.push(Invisible::Tab {
6242 line_start_offset: line.len(),
6243 line_end_offset: line.len() + line_chunk.len(),
6244 });
6245 }
6246 } else {
6247 invisibles.extend(line_chunk.char_indices().filter_map(
6248 |(index, c)| {
6249 let is_whitespace = c.is_whitespace();
6250 non_whitespace_added |= !is_whitespace;
6251 if is_whitespace
6252 && (non_whitespace_added || !is_soft_wrapped)
6253 {
6254 Some(Invisible::Whitespace {
6255 line_offset: line.len() + index,
6256 })
6257 } else {
6258 None
6259 }
6260 },
6261 ))
6262 }
6263 }
6264
6265 line.push_str(line_chunk);
6266 }
6267 }
6268 }
6269 }
6270
6271 layouts
6272 }
6273
6274 fn prepaint(
6275 &mut self,
6276 line_height: Pixels,
6277 scroll_pixel_position: gpui::Point<Pixels>,
6278 row: DisplayRow,
6279 content_origin: gpui::Point<Pixels>,
6280 line_elements: &mut SmallVec<[AnyElement; 1]>,
6281 window: &mut Window,
6282 cx: &mut App,
6283 ) {
6284 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6285 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6286 for fragment in &mut self.fragments {
6287 match fragment {
6288 LineFragment::Text(line) => {
6289 fragment_origin.x += line.width;
6290 }
6291 LineFragment::Element { element, size, .. } => {
6292 let mut element = element
6293 .take()
6294 .expect("you can't prepaint LineWithInvisibles twice");
6295
6296 // Center the element vertically within the line.
6297 let mut element_origin = fragment_origin;
6298 element_origin.y += (line_height - size.height) / 2.;
6299 element.prepaint_at(element_origin, window, cx);
6300 line_elements.push(element);
6301
6302 fragment_origin.x += size.width;
6303 }
6304 }
6305 }
6306 }
6307
6308 fn draw(
6309 &self,
6310 layout: &EditorLayout,
6311 row: DisplayRow,
6312 content_origin: gpui::Point<Pixels>,
6313 whitespace_setting: ShowWhitespaceSetting,
6314 selection_ranges: &[Range<DisplayPoint>],
6315 window: &mut Window,
6316 cx: &mut App,
6317 ) {
6318 let line_height = layout.position_map.line_height;
6319 let line_y = line_height
6320 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6321
6322 let mut fragment_origin =
6323 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6324
6325 for fragment in &self.fragments {
6326 match fragment {
6327 LineFragment::Text(line) => {
6328 line.paint(fragment_origin, line_height, window, cx)
6329 .log_err();
6330 fragment_origin.x += line.width;
6331 }
6332 LineFragment::Element { size, .. } => {
6333 fragment_origin.x += size.width;
6334 }
6335 }
6336 }
6337
6338 self.draw_invisibles(
6339 selection_ranges,
6340 layout,
6341 content_origin,
6342 line_y,
6343 row,
6344 line_height,
6345 whitespace_setting,
6346 window,
6347 cx,
6348 );
6349 }
6350
6351 fn draw_invisibles(
6352 &self,
6353 selection_ranges: &[Range<DisplayPoint>],
6354 layout: &EditorLayout,
6355 content_origin: gpui::Point<Pixels>,
6356 line_y: Pixels,
6357 row: DisplayRow,
6358 line_height: Pixels,
6359 whitespace_setting: ShowWhitespaceSetting,
6360 window: &mut Window,
6361 cx: &mut App,
6362 ) {
6363 let extract_whitespace_info = |invisible: &Invisible| {
6364 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6365 Invisible::Tab {
6366 line_start_offset,
6367 line_end_offset,
6368 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6369 Invisible::Whitespace { line_offset } => {
6370 (*line_offset, line_offset + 1, &layout.space_invisible)
6371 }
6372 };
6373
6374 let x_offset = self.x_for_index(token_offset);
6375 let invisible_offset =
6376 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6377 let origin = content_origin
6378 + gpui::point(
6379 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6380 line_y,
6381 );
6382
6383 (
6384 [token_offset, token_end_offset],
6385 Box::new(move |window: &mut Window, cx: &mut App| {
6386 invisible_symbol
6387 .paint(origin, line_height, window, cx)
6388 .log_err();
6389 }),
6390 )
6391 };
6392
6393 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6394 match whitespace_setting {
6395 ShowWhitespaceSetting::None => (),
6396 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6397 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6398 let invisible_point = DisplayPoint::new(row, start as u32);
6399 if !selection_ranges
6400 .iter()
6401 .any(|region| region.start <= invisible_point && invisible_point < region.end)
6402 {
6403 return;
6404 }
6405
6406 paint(window, cx);
6407 }),
6408
6409 // For a whitespace to be on a boundary, any of the following conditions need to be met:
6410 // - It is a tab
6411 // - It is adjacent to an edge (start or end)
6412 // - It is adjacent to a whitespace (left or right)
6413 ShowWhitespaceSetting::Boundary => {
6414 // 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
6415 // the above cases.
6416 // Note: We zip in the original `invisibles` to check for tab equality
6417 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6418 for (([start, end], paint), invisible) in
6419 invisible_iter.zip_eq(self.invisibles.iter())
6420 {
6421 let should_render = match (&last_seen, invisible) {
6422 (_, Invisible::Tab { .. }) => true,
6423 (Some((_, last_end, _)), _) => *last_end == start,
6424 _ => false,
6425 };
6426
6427 if should_render || start == 0 || end == self.len {
6428 paint(window, cx);
6429
6430 // Since we are scanning from the left, we will skip over the first available whitespace that is part
6431 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6432 if let Some((should_render_last, last_end, paint_last)) = last_seen {
6433 // Note that we need to make sure that the last one is actually adjacent
6434 if !should_render_last && last_end == start {
6435 paint_last(window, cx);
6436 }
6437 }
6438 }
6439
6440 // Manually render anything within a selection
6441 let invisible_point = DisplayPoint::new(row, start as u32);
6442 if selection_ranges.iter().any(|region| {
6443 region.start <= invisible_point && invisible_point < region.end
6444 }) {
6445 paint(window, cx);
6446 }
6447
6448 last_seen = Some((should_render, end, paint));
6449 }
6450 }
6451 }
6452 }
6453
6454 pub fn x_for_index(&self, index: usize) -> Pixels {
6455 let mut fragment_start_x = Pixels::ZERO;
6456 let mut fragment_start_index = 0;
6457
6458 for fragment in &self.fragments {
6459 match fragment {
6460 LineFragment::Text(shaped_line) => {
6461 let fragment_end_index = fragment_start_index + shaped_line.len;
6462 if index < fragment_end_index {
6463 return fragment_start_x
6464 + shaped_line.x_for_index(index - fragment_start_index);
6465 }
6466 fragment_start_x += shaped_line.width;
6467 fragment_start_index = fragment_end_index;
6468 }
6469 LineFragment::Element { len, size, .. } => {
6470 let fragment_end_index = fragment_start_index + len;
6471 if index < fragment_end_index {
6472 return fragment_start_x;
6473 }
6474 fragment_start_x += size.width;
6475 fragment_start_index = fragment_end_index;
6476 }
6477 }
6478 }
6479
6480 fragment_start_x
6481 }
6482
6483 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6484 let mut fragment_start_x = Pixels::ZERO;
6485 let mut fragment_start_index = 0;
6486
6487 for fragment in &self.fragments {
6488 match fragment {
6489 LineFragment::Text(shaped_line) => {
6490 let fragment_end_x = fragment_start_x + shaped_line.width;
6491 if x < fragment_end_x {
6492 return Some(
6493 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6494 );
6495 }
6496 fragment_start_x = fragment_end_x;
6497 fragment_start_index += shaped_line.len;
6498 }
6499 LineFragment::Element { len, size, .. } => {
6500 let fragment_end_x = fragment_start_x + size.width;
6501 if x < fragment_end_x {
6502 return Some(fragment_start_index);
6503 }
6504 fragment_start_index += len;
6505 fragment_start_x = fragment_end_x;
6506 }
6507 }
6508 }
6509
6510 None
6511 }
6512
6513 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6514 let mut fragment_start_index = 0;
6515
6516 for fragment in &self.fragments {
6517 match fragment {
6518 LineFragment::Text(shaped_line) => {
6519 let fragment_end_index = fragment_start_index + shaped_line.len;
6520 if index < fragment_end_index {
6521 return shaped_line.font_id_for_index(index - fragment_start_index);
6522 }
6523 fragment_start_index = fragment_end_index;
6524 }
6525 LineFragment::Element { len, .. } => {
6526 let fragment_end_index = fragment_start_index + len;
6527 if index < fragment_end_index {
6528 return None;
6529 }
6530 fragment_start_index = fragment_end_index;
6531 }
6532 }
6533 }
6534
6535 None
6536 }
6537}
6538
6539#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6540enum Invisible {
6541 /// A tab character
6542 ///
6543 /// A tab character is internally represented by spaces (configured by the user's tab width)
6544 /// aligned to the nearest column, so it's necessary to store the start and end offset for
6545 /// adjacency checks.
6546 Tab {
6547 line_start_offset: usize,
6548 line_end_offset: usize,
6549 },
6550 Whitespace {
6551 line_offset: usize,
6552 },
6553}
6554
6555impl EditorElement {
6556 /// Returns the rem size to use when rendering the [`EditorElement`].
6557 ///
6558 /// This allows UI elements to scale based on the `buffer_font_size`.
6559 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6560 match self.editor.read(cx).mode {
6561 EditorMode::Full => {
6562 let buffer_font_size = self.style.text.font_size;
6563 match buffer_font_size {
6564 AbsoluteLength::Pixels(pixels) => {
6565 let rem_size_scale = {
6566 // Our default UI font size is 14px on a 16px base scale.
6567 // This means the default UI font size is 0.875rems.
6568 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6569
6570 // We then determine the delta between a single rem and the default font
6571 // size scale.
6572 let default_font_size_delta = 1. - default_font_size_scale;
6573
6574 // Finally, we add this delta to 1rem to get the scale factor that
6575 // should be used to scale up the UI.
6576 1. + default_font_size_delta
6577 };
6578
6579 Some(pixels * rem_size_scale)
6580 }
6581 AbsoluteLength::Rems(rems) => {
6582 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6583 }
6584 }
6585 }
6586 // We currently use single-line and auto-height editors in UI contexts,
6587 // so we don't want to scale everything with the buffer font size, as it
6588 // ends up looking off.
6589 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
6590 }
6591 }
6592}
6593
6594impl Element for EditorElement {
6595 type RequestLayoutState = ();
6596 type PrepaintState = EditorLayout;
6597
6598 fn id(&self) -> Option<ElementId> {
6599 None
6600 }
6601
6602 fn request_layout(
6603 &mut self,
6604 _: Option<&GlobalElementId>,
6605 window: &mut Window,
6606 cx: &mut App,
6607 ) -> (gpui::LayoutId, ()) {
6608 let rem_size = self.rem_size(cx);
6609 window.with_rem_size(rem_size, |window| {
6610 self.editor.update(cx, |editor, cx| {
6611 editor.set_style(self.style.clone(), window, cx);
6612
6613 let layout_id = match editor.mode {
6614 EditorMode::SingleLine { auto_width } => {
6615 let rem_size = window.rem_size();
6616
6617 let height = self.style.text.line_height_in_pixels(rem_size);
6618 if auto_width {
6619 let editor_handle = cx.entity().clone();
6620 let style = self.style.clone();
6621 window.request_measured_layout(
6622 Style::default(),
6623 move |_, _, window, cx| {
6624 let editor_snapshot = editor_handle
6625 .update(cx, |editor, cx| editor.snapshot(window, cx));
6626 let line = Self::layout_lines(
6627 DisplayRow(0)..DisplayRow(1),
6628 &editor_snapshot,
6629 &style,
6630 px(f32::MAX),
6631 |_| false, // Single lines never soft wrap
6632 window,
6633 cx,
6634 )
6635 .pop()
6636 .unwrap();
6637
6638 let font_id =
6639 window.text_system().resolve_font(&style.text.font());
6640 let font_size =
6641 style.text.font_size.to_pixels(window.rem_size());
6642 let em_width =
6643 window.text_system().em_width(font_id, font_size).unwrap();
6644
6645 size(line.width + em_width, height)
6646 },
6647 )
6648 } else {
6649 let mut style = Style::default();
6650 style.size.height = height.into();
6651 style.size.width = relative(1.).into();
6652 window.request_layout(style, None, cx)
6653 }
6654 }
6655 EditorMode::AutoHeight { max_lines } => {
6656 let editor_handle = cx.entity().clone();
6657 let max_line_number_width =
6658 self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
6659 window.request_measured_layout(
6660 Style::default(),
6661 move |known_dimensions, available_space, window, cx| {
6662 editor_handle
6663 .update(cx, |editor, cx| {
6664 compute_auto_height_layout(
6665 editor,
6666 max_lines,
6667 max_line_number_width,
6668 known_dimensions,
6669 available_space.width,
6670 window,
6671 cx,
6672 )
6673 })
6674 .unwrap_or_default()
6675 },
6676 )
6677 }
6678 EditorMode::Full => {
6679 let mut style = Style::default();
6680 style.size.width = relative(1.).into();
6681 style.size.height = relative(1.).into();
6682 window.request_layout(style, None, cx)
6683 }
6684 };
6685
6686 (layout_id, ())
6687 })
6688 })
6689 }
6690
6691 fn prepaint(
6692 &mut self,
6693 _: Option<&GlobalElementId>,
6694 bounds: Bounds<Pixels>,
6695 _: &mut Self::RequestLayoutState,
6696 window: &mut Window,
6697 cx: &mut App,
6698 ) -> Self::PrepaintState {
6699 let text_style = TextStyleRefinement {
6700 font_size: Some(self.style.text.font_size),
6701 line_height: Some(self.style.text.line_height),
6702 ..Default::default()
6703 };
6704 let focus_handle = self.editor.focus_handle(cx);
6705 window.set_view_id(self.editor.entity_id());
6706 window.set_focus_handle(&focus_handle, cx);
6707
6708 let rem_size = self.rem_size(cx);
6709 window.with_rem_size(rem_size, |window| {
6710 window.with_text_style(Some(text_style), |window| {
6711 window.with_content_mask(Some(ContentMask { bounds }), |window| {
6712 let mut snapshot = self
6713 .editor
6714 .update(cx, |editor, cx| editor.snapshot(window, cx));
6715 let style = self.style.clone();
6716
6717 let font_id = window.text_system().resolve_font(&style.text.font());
6718 let font_size = style.text.font_size.to_pixels(window.rem_size());
6719 let line_height = style.text.line_height_in_pixels(window.rem_size());
6720 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
6721 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
6722
6723 let letter_size = size(em_width, line_height);
6724
6725 let gutter_dimensions = snapshot
6726 .gutter_dimensions(
6727 font_id,
6728 font_size,
6729 self.max_line_number_width(&snapshot, window, cx),
6730 cx,
6731 )
6732 .unwrap_or_default();
6733 let text_width = bounds.size.width - gutter_dimensions.width;
6734
6735 let editor_width =
6736 text_width - gutter_dimensions.margin - em_width - style.scrollbar_width;
6737
6738 snapshot = self.editor.update(cx, |editor, cx| {
6739 editor.last_bounds = Some(bounds);
6740 editor.gutter_dimensions = gutter_dimensions;
6741 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
6742
6743 if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
6744 snapshot
6745 } else {
6746 let wrap_width = match editor.soft_wrap_mode(cx) {
6747 SoftWrap::GitDiff => None,
6748 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
6749 SoftWrap::EditorWidth => Some(editor_width),
6750 SoftWrap::Column(column) => Some(column as f32 * em_advance),
6751 SoftWrap::Bounded(column) => {
6752 Some(editor_width.min(column as f32 * em_advance))
6753 }
6754 };
6755
6756 if editor.set_wrap_width(wrap_width, cx) {
6757 editor.snapshot(window, cx)
6758 } else {
6759 snapshot
6760 }
6761 }
6762 });
6763
6764 let wrap_guides = self
6765 .editor
6766 .read(cx)
6767 .wrap_guides(cx)
6768 .iter()
6769 .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
6770 .collect::<SmallVec<[_; 2]>>();
6771
6772 let hitbox = window.insert_hitbox(bounds, false);
6773 let gutter_hitbox =
6774 window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
6775 let text_hitbox = window.insert_hitbox(
6776 Bounds {
6777 origin: gutter_hitbox.top_right(),
6778 size: size(text_width, bounds.size.height),
6779 },
6780 false,
6781 );
6782 // Offset the content_bounds from the text_bounds by the gutter margin (which
6783 // is roughly half a character wide) to make hit testing work more like how we want.
6784 let content_origin =
6785 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
6786
6787 let scrollbar_bounds =
6788 Bounds::from_corners(content_origin, bounds.bottom_right());
6789
6790 let height_in_lines = scrollbar_bounds.size.height / line_height;
6791
6792 // NOTE: The max row number in the current file, minus one
6793 let max_row = snapshot.max_point().row().as_f32();
6794
6795 // NOTE: The max scroll position for the top of the window
6796 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
6797 (max_row - height_in_lines + 1.).max(0.)
6798 } else {
6799 let settings = EditorSettings::get_global(cx);
6800 match settings.scroll_beyond_last_line {
6801 ScrollBeyondLastLine::OnePage => max_row,
6802 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
6803 ScrollBeyondLastLine::VerticalScrollMargin => {
6804 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
6805 .max(0.)
6806 }
6807 }
6808 };
6809
6810 // TODO: Autoscrolling for both axes
6811 let mut autoscroll_request = None;
6812 let mut autoscroll_containing_element = false;
6813 let mut autoscroll_horizontally = false;
6814 self.editor.update(cx, |editor, cx| {
6815 autoscroll_request = editor.autoscroll_request();
6816 autoscroll_containing_element =
6817 autoscroll_request.is_some() || editor.has_pending_selection();
6818 // TODO: Is this horizontal or vertical?!
6819 autoscroll_horizontally = editor.autoscroll_vertically(
6820 bounds,
6821 line_height,
6822 max_scroll_top,
6823 window,
6824 cx,
6825 );
6826 snapshot = editor.snapshot(window, cx);
6827 });
6828
6829 let mut scroll_position = snapshot.scroll_position();
6830 // The scroll position is a fractional point, the whole number of which represents
6831 // the top of the window in terms of display rows.
6832 let start_row = DisplayRow(scroll_position.y as u32);
6833 let max_row = snapshot.max_point().row();
6834 let end_row = cmp::min(
6835 (scroll_position.y + height_in_lines).ceil() as u32,
6836 max_row.next_row().0,
6837 );
6838 let end_row = DisplayRow(end_row);
6839
6840 let row_infos = snapshot
6841 .row_infos(start_row)
6842 .take((start_row..end_row).len())
6843 .collect::<Vec<RowInfo>>();
6844 let is_row_soft_wrapped = |row: usize| {
6845 row_infos
6846 .get(row)
6847 .map_or(true, |info| info.buffer_row.is_none())
6848 };
6849
6850 let start_anchor = if start_row == Default::default() {
6851 Anchor::min()
6852 } else {
6853 snapshot.buffer_snapshot.anchor_before(
6854 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
6855 )
6856 };
6857 let end_anchor = if end_row > max_row {
6858 Anchor::max()
6859 } else {
6860 snapshot.buffer_snapshot.anchor_before(
6861 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
6862 )
6863 };
6864
6865 let (mut highlighted_rows, distinguish_unstaged_hunks) =
6866 self.editor.update(cx, |editor, cx| {
6867 (
6868 editor.highlighted_display_rows(window, cx),
6869 editor.distinguish_unstaged_diff_hunks,
6870 )
6871 });
6872
6873 for (ix, row_info) in row_infos.iter().enumerate() {
6874 let background = match row_info.diff_status {
6875 Some(DiffHunkStatus::Added(secondary_status)) => {
6876 let color = style.status.created_background;
6877 match secondary_status {
6878 DiffHunkSecondaryStatus::HasSecondaryHunk
6879 | DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk
6880 if distinguish_unstaged_hunks =>
6881 {
6882 pattern_slash(color, line_height.0 / 4.0)
6883 }
6884 _ => color.into(),
6885 }
6886 }
6887 Some(DiffHunkStatus::Removed(secondary_status)) => {
6888 let color = style.status.deleted_background;
6889 match secondary_status {
6890 DiffHunkSecondaryStatus::HasSecondaryHunk
6891 | DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk
6892 if distinguish_unstaged_hunks =>
6893 {
6894 pattern_slash(color, line_height.0 / 4.0)
6895 }
6896 _ => color.into(),
6897 }
6898 }
6899 _ => continue,
6900 };
6901
6902 highlighted_rows
6903 .entry(start_row + DisplayRow(ix as u32))
6904 .or_insert(background);
6905 }
6906
6907 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
6908 start_anchor..end_anchor,
6909 &snapshot.display_snapshot,
6910 cx.theme().colors(),
6911 );
6912 let highlighted_gutter_ranges =
6913 self.editor.read(cx).gutter_highlights_in_range(
6914 start_anchor..end_anchor,
6915 &snapshot.display_snapshot,
6916 cx,
6917 );
6918
6919 let redacted_ranges = self.editor.read(cx).redacted_ranges(
6920 start_anchor..end_anchor,
6921 &snapshot.display_snapshot,
6922 cx,
6923 );
6924
6925 let (local_selections, selected_buffer_ids): (
6926 Vec<Selection<Point>>,
6927 Vec<BufferId>,
6928 ) = self.editor.update(cx, |editor, cx| {
6929 let all_selections = editor.selections.all::<Point>(cx);
6930 let selected_buffer_ids = if editor.is_singleton(cx) {
6931 Vec::new()
6932 } else {
6933 let mut selected_buffer_ids = Vec::with_capacity(all_selections.len());
6934
6935 for selection in all_selections {
6936 for buffer_id in snapshot
6937 .buffer_snapshot
6938 .buffer_ids_for_range(selection.range())
6939 {
6940 if selected_buffer_ids.last() != Some(&buffer_id) {
6941 selected_buffer_ids.push(buffer_id);
6942 }
6943 }
6944 }
6945
6946 selected_buffer_ids
6947 };
6948
6949 let mut selections = editor
6950 .selections
6951 .disjoint_in_range(start_anchor..end_anchor, cx);
6952 selections.extend(editor.selections.pending(cx));
6953
6954 (selections, selected_buffer_ids)
6955 });
6956
6957 let (selections, active_rows, newest_selection_head) = self.layout_selections(
6958 start_anchor,
6959 end_anchor,
6960 &local_selections,
6961 &snapshot,
6962 start_row,
6963 end_row,
6964 window,
6965 cx,
6966 );
6967
6968 let line_numbers = self.layout_line_numbers(
6969 Some(&gutter_hitbox),
6970 gutter_dimensions,
6971 line_height,
6972 scroll_position,
6973 start_row..end_row,
6974 &row_infos,
6975 newest_selection_head,
6976 &snapshot,
6977 window,
6978 cx,
6979 );
6980
6981 let mut crease_toggles =
6982 window.with_element_namespace("crease_toggles", |window| {
6983 self.layout_crease_toggles(
6984 start_row..end_row,
6985 &row_infos,
6986 &active_rows,
6987 &snapshot,
6988 window,
6989 cx,
6990 )
6991 });
6992 let crease_trailers =
6993 window.with_element_namespace("crease_trailers", |window| {
6994 self.layout_crease_trailers(
6995 row_infos.iter().copied(),
6996 &snapshot,
6997 window,
6998 cx,
6999 )
7000 });
7001
7002 let display_hunks = self.layout_gutter_diff_hunks(
7003 line_height,
7004 &gutter_hitbox,
7005 start_row..end_row,
7006 &snapshot,
7007 window,
7008 cx,
7009 );
7010
7011 let mut line_layouts = Self::layout_lines(
7012 start_row..end_row,
7013 &snapshot,
7014 &self.style,
7015 editor_width,
7016 is_row_soft_wrapped,
7017 window,
7018 cx,
7019 );
7020
7021 let longest_line_blame_width = self
7022 .editor
7023 .update(cx, |editor, cx| {
7024 if !editor.show_git_blame_inline {
7025 return None;
7026 }
7027 let blame = editor.blame.as_ref()?;
7028 let blame_entry = blame
7029 .update(cx, |blame, cx| {
7030 let row_infos =
7031 snapshot.row_infos(snapshot.longest_row()).next()?;
7032 blame.blame_for_rows(&[row_infos], cx).next()
7033 })
7034 .flatten()?;
7035 let workspace = editor.workspace.as_ref().map(|(w, _)| w.to_owned());
7036 let mut element = render_inline_blame_entry(
7037 blame,
7038 blame_entry,
7039 &style,
7040 workspace,
7041 cx,
7042 );
7043 let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
7044 Some(
7045 element
7046 .layout_as_root(AvailableSpace::min_size(), window, cx)
7047 .width
7048 + inline_blame_padding,
7049 )
7050 })
7051 .unwrap_or(Pixels::ZERO);
7052
7053 let longest_line_width = layout_line(
7054 snapshot.longest_row(),
7055 &snapshot,
7056 &style,
7057 editor_width,
7058 is_row_soft_wrapped,
7059 window,
7060 cx,
7061 )
7062 .width;
7063
7064 let scrollbar_range_data = ScrollbarRangeData::new(
7065 scrollbar_bounds,
7066 letter_size,
7067 &snapshot,
7068 longest_line_width,
7069 longest_line_blame_width,
7070 &style,
7071 editor_width,
7072 cx,
7073 );
7074
7075 let scroll_range_bounds = scrollbar_range_data.scroll_range;
7076 let mut scroll_width = scroll_range_bounds.size.width;
7077
7078 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
7079 snapshot.sticky_header_excerpt(start_row)
7080 } else {
7081 None
7082 };
7083 let sticky_header_excerpt_id =
7084 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7085
7086 let blocks = window.with_element_namespace("blocks", |window| {
7087 self.render_blocks(
7088 start_row..end_row,
7089 &snapshot,
7090 &hitbox,
7091 &text_hitbox,
7092 editor_width,
7093 &mut scroll_width,
7094 &gutter_dimensions,
7095 em_width,
7096 gutter_dimensions.full_width(),
7097 line_height,
7098 &line_layouts,
7099 &local_selections,
7100 &selected_buffer_ids,
7101 is_row_soft_wrapped,
7102 sticky_header_excerpt_id,
7103 window,
7104 cx,
7105 )
7106 });
7107 let mut blocks = match blocks {
7108 Ok(blocks) => blocks,
7109 Err(resized_blocks) => {
7110 self.editor.update(cx, |editor, cx| {
7111 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7112 });
7113 return self.prepaint(None, bounds, &mut (), window, cx);
7114 }
7115 };
7116
7117 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7118 window.with_element_namespace("blocks", |window| {
7119 self.layout_sticky_buffer_header(
7120 sticky_header_excerpt,
7121 scroll_position.y,
7122 line_height,
7123 &snapshot,
7124 &hitbox,
7125 &selected_buffer_ids,
7126 window,
7127 cx,
7128 )
7129 })
7130 });
7131
7132 let start_buffer_row =
7133 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7134 let end_buffer_row =
7135 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7136
7137 let scroll_max = point(
7138 ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7139 max_row.as_f32(),
7140 );
7141
7142 self.editor.update(cx, |editor, cx| {
7143 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7144
7145 let autoscrolled = if autoscroll_horizontally {
7146 editor.autoscroll_horizontally(
7147 start_row,
7148 editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
7149 scroll_width,
7150 em_width,
7151 &line_layouts,
7152 cx,
7153 )
7154 } else {
7155 false
7156 };
7157
7158 if clamped || autoscrolled {
7159 snapshot = editor.snapshot(window, cx);
7160 scroll_position = snapshot.scroll_position();
7161 }
7162 });
7163
7164 let scroll_pixel_position = point(
7165 scroll_position.x * em_width,
7166 scroll_position.y * line_height,
7167 );
7168
7169 let indent_guides = self.layout_indent_guides(
7170 content_origin,
7171 text_hitbox.origin,
7172 start_buffer_row..end_buffer_row,
7173 scroll_pixel_position,
7174 line_height,
7175 &snapshot,
7176 window,
7177 cx,
7178 );
7179
7180 let crease_trailers =
7181 window.with_element_namespace("crease_trailers", |window| {
7182 self.prepaint_crease_trailers(
7183 crease_trailers,
7184 &line_layouts,
7185 line_height,
7186 content_origin,
7187 scroll_pixel_position,
7188 em_width,
7189 window,
7190 cx,
7191 )
7192 });
7193
7194 let mut inline_blame = None;
7195 if let Some(newest_selection_head) = newest_selection_head {
7196 let display_row = newest_selection_head.row();
7197 if (start_row..end_row).contains(&display_row) {
7198 let line_ix = display_row.minus(start_row) as usize;
7199 let row_info = &row_infos[line_ix];
7200 let line_layout = &line_layouts[line_ix];
7201 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7202 inline_blame = self.layout_inline_blame(
7203 display_row,
7204 row_info,
7205 line_layout,
7206 crease_trailer_layout,
7207 em_width,
7208 content_origin,
7209 scroll_pixel_position,
7210 line_height,
7211 window,
7212 cx,
7213 );
7214 }
7215 }
7216
7217 let blamed_display_rows = self.layout_blame_entries(
7218 &row_infos,
7219 em_width,
7220 scroll_position,
7221 line_height,
7222 &gutter_hitbox,
7223 gutter_dimensions.git_blame_entries_width,
7224 window,
7225 cx,
7226 );
7227
7228 let scroll_max = point(
7229 ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7230 max_scroll_top,
7231 );
7232
7233 self.editor.update(cx, |editor, cx| {
7234 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7235
7236 let autoscrolled = if autoscroll_horizontally {
7237 editor.autoscroll_horizontally(
7238 start_row,
7239 editor_width - (letter_size.width / 2.0) + style.scrollbar_width,
7240 scroll_width,
7241 em_width,
7242 &line_layouts,
7243 cx,
7244 )
7245 } else {
7246 false
7247 };
7248
7249 if clamped || autoscrolled {
7250 snapshot = editor.snapshot(window, cx);
7251 scroll_position = snapshot.scroll_position();
7252 }
7253 });
7254
7255 let line_elements = self.prepaint_lines(
7256 start_row,
7257 &mut line_layouts,
7258 line_height,
7259 scroll_pixel_position,
7260 content_origin,
7261 window,
7262 cx,
7263 );
7264
7265 let mut block_start_rows = HashSet::default();
7266
7267 window.with_element_namespace("blocks", |window| {
7268 self.layout_blocks(
7269 &mut blocks,
7270 &mut block_start_rows,
7271 &hitbox,
7272 line_height,
7273 scroll_pixel_position,
7274 window,
7275 cx,
7276 );
7277 });
7278
7279 let cursors = self.collect_cursors(&snapshot, cx);
7280 let visible_row_range = start_row..end_row;
7281 let non_visible_cursors = cursors
7282 .iter()
7283 .any(|c| !visible_row_range.contains(&c.0.row()));
7284
7285 let visible_cursors = self.layout_visible_cursors(
7286 &snapshot,
7287 &selections,
7288 &block_start_rows,
7289 start_row..end_row,
7290 &line_layouts,
7291 &text_hitbox,
7292 content_origin,
7293 scroll_position,
7294 scroll_pixel_position,
7295 line_height,
7296 em_width,
7297 em_advance,
7298 autoscroll_containing_element,
7299 window,
7300 cx,
7301 );
7302
7303 let scrollbars_layout = self.layout_scrollbars(
7304 &snapshot,
7305 scrollbar_range_data,
7306 scroll_position,
7307 non_visible_cursors,
7308 window,
7309 cx,
7310 );
7311
7312 let gutter_settings = EditorSettings::get_global(cx).gutter;
7313
7314 let rows_with_hunk_bounds = display_hunks
7315 .iter()
7316 .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
7317 .fold(
7318 HashMap::default(),
7319 |mut rows_with_hunk_bounds, (hunk, bounds)| {
7320 match hunk {
7321 DisplayDiffHunk::Folded { display_row } => {
7322 rows_with_hunk_bounds.insert(*display_row, bounds);
7323 }
7324 DisplayDiffHunk::Unfolded {
7325 display_row_range, ..
7326 } => {
7327 for display_row in display_row_range.iter_rows() {
7328 rows_with_hunk_bounds.insert(display_row, bounds);
7329 }
7330 }
7331 }
7332 rows_with_hunk_bounds
7333 },
7334 );
7335 let mut code_actions_indicator = None;
7336 if let Some(newest_selection_head) = newest_selection_head {
7337 let newest_selection_point =
7338 newest_selection_head.to_point(&snapshot.display_snapshot);
7339
7340 if (start_row..end_row).contains(&newest_selection_head.row()) {
7341 self.layout_cursor_popovers(
7342 line_height,
7343 &text_hitbox,
7344 content_origin,
7345 start_row,
7346 scroll_pixel_position,
7347 &line_layouts,
7348 newest_selection_head,
7349 newest_selection_point,
7350 &style,
7351 window,
7352 cx,
7353 );
7354
7355 let show_code_actions = snapshot
7356 .show_code_actions
7357 .unwrap_or(gutter_settings.code_actions);
7358 if show_code_actions {
7359 let newest_selection_point =
7360 newest_selection_head.to_point(&snapshot.display_snapshot);
7361 if !snapshot
7362 .is_line_folded(MultiBufferRow(newest_selection_point.row))
7363 {
7364 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
7365 MultiBufferRow(newest_selection_point.row),
7366 );
7367 if let Some((buffer, range)) = buffer {
7368 let buffer_id = buffer.remote_id();
7369 let row = range.start.row;
7370 let has_test_indicator = self
7371 .editor
7372 .read(cx)
7373 .tasks
7374 .contains_key(&(buffer_id, row));
7375
7376 if !has_test_indicator {
7377 code_actions_indicator = self
7378 .layout_code_actions_indicator(
7379 line_height,
7380 newest_selection_head,
7381 scroll_pixel_position,
7382 &gutter_dimensions,
7383 &gutter_hitbox,
7384 &rows_with_hunk_bounds,
7385 window,
7386 cx,
7387 );
7388 }
7389 }
7390 }
7391 }
7392 }
7393 }
7394
7395 self.layout_gutter_menu(
7396 line_height,
7397 &text_hitbox,
7398 content_origin,
7399 scroll_pixel_position,
7400 gutter_dimensions.width - gutter_dimensions.left_padding,
7401 window,
7402 cx,
7403 );
7404
7405 let test_indicators = if gutter_settings.runnables {
7406 self.layout_run_indicators(
7407 line_height,
7408 start_row..end_row,
7409 scroll_pixel_position,
7410 &gutter_dimensions,
7411 &gutter_hitbox,
7412 &rows_with_hunk_bounds,
7413 &snapshot,
7414 window,
7415 cx,
7416 )
7417 } else {
7418 Vec::new()
7419 };
7420
7421 self.layout_signature_help(
7422 &hitbox,
7423 content_origin,
7424 scroll_pixel_position,
7425 newest_selection_head,
7426 start_row,
7427 &line_layouts,
7428 line_height,
7429 em_width,
7430 window,
7431 cx,
7432 );
7433
7434 if !cx.has_active_drag() {
7435 self.layout_hover_popovers(
7436 &snapshot,
7437 &hitbox,
7438 &text_hitbox,
7439 start_row..end_row,
7440 content_origin,
7441 scroll_pixel_position,
7442 &line_layouts,
7443 line_height,
7444 em_width,
7445 window,
7446 cx,
7447 );
7448 }
7449
7450 let inline_completion_popover = self.layout_edit_prediction_popover(
7451 &text_hitbox.bounds,
7452 content_origin,
7453 &snapshot,
7454 start_row..end_row,
7455 scroll_position.y,
7456 scroll_position.y + height_in_lines,
7457 &line_layouts,
7458 line_height,
7459 scroll_pixel_position,
7460 newest_selection_head,
7461 editor_width,
7462 &style,
7463 window,
7464 cx,
7465 );
7466
7467 let mouse_context_menu = self.layout_mouse_context_menu(
7468 &snapshot,
7469 start_row..end_row,
7470 content_origin,
7471 window,
7472 cx,
7473 );
7474
7475 window.with_element_namespace("crease_toggles", |window| {
7476 self.prepaint_crease_toggles(
7477 &mut crease_toggles,
7478 line_height,
7479 &gutter_dimensions,
7480 gutter_settings,
7481 scroll_pixel_position,
7482 &gutter_hitbox,
7483 window,
7484 cx,
7485 )
7486 });
7487
7488 let invisible_symbol_font_size = font_size / 2.;
7489 let tab_invisible = window
7490 .text_system()
7491 .shape_line(
7492 "→".into(),
7493 invisible_symbol_font_size,
7494 &[TextRun {
7495 len: "→".len(),
7496 font: self.style.text.font(),
7497 color: cx.theme().colors().editor_invisible,
7498 background_color: None,
7499 underline: None,
7500 strikethrough: None,
7501 }],
7502 )
7503 .unwrap();
7504 let space_invisible = window
7505 .text_system()
7506 .shape_line(
7507 "•".into(),
7508 invisible_symbol_font_size,
7509 &[TextRun {
7510 len: "•".len(),
7511 font: self.style.text.font(),
7512 color: cx.theme().colors().editor_invisible,
7513 background_color: None,
7514 underline: None,
7515 strikethrough: None,
7516 }],
7517 )
7518 .unwrap();
7519
7520 let mode = snapshot.mode;
7521
7522 let position_map = Rc::new(PositionMap {
7523 size: bounds.size,
7524 visible_row_range,
7525 scroll_pixel_position,
7526 scroll_max,
7527 line_layouts,
7528 line_height,
7529 em_width,
7530 em_advance,
7531 snapshot,
7532 gutter_hitbox: gutter_hitbox.clone(),
7533 text_hitbox: text_hitbox.clone(),
7534 });
7535
7536 self.editor.update(cx, |editor, _| {
7537 editor.last_position_map = Some(position_map.clone())
7538 });
7539
7540 let hunk_controls = self.layout_diff_hunk_controls(
7541 start_row..end_row,
7542 &row_infos,
7543 &text_hitbox,
7544 &position_map,
7545 newest_selection_head,
7546 line_height,
7547 scroll_pixel_position,
7548 &display_hunks,
7549 self.editor.clone(),
7550 window,
7551 cx,
7552 );
7553
7554 EditorLayout {
7555 mode,
7556 position_map,
7557 visible_display_row_range: start_row..end_row,
7558 wrap_guides,
7559 indent_guides,
7560 hitbox,
7561 gutter_hitbox,
7562 display_hunks,
7563 content_origin,
7564 scrollbars_layout,
7565 active_rows,
7566 highlighted_rows,
7567 highlighted_ranges,
7568 highlighted_gutter_ranges,
7569 redacted_ranges,
7570 line_elements,
7571 line_numbers,
7572 blamed_display_rows,
7573 inline_blame,
7574 blocks,
7575 cursors,
7576 visible_cursors,
7577 selections,
7578 inline_completion_popover,
7579 diff_hunk_controls: hunk_controls,
7580 mouse_context_menu,
7581 test_indicators,
7582 code_actions_indicator,
7583 crease_toggles,
7584 crease_trailers,
7585 tab_invisible,
7586 space_invisible,
7587 sticky_buffer_header,
7588 }
7589 })
7590 })
7591 })
7592 }
7593
7594 fn paint(
7595 &mut self,
7596 _: Option<&GlobalElementId>,
7597 bounds: Bounds<gpui::Pixels>,
7598 _: &mut Self::RequestLayoutState,
7599 layout: &mut Self::PrepaintState,
7600 window: &mut Window,
7601 cx: &mut App,
7602 ) {
7603 let focus_handle = self.editor.focus_handle(cx);
7604 let key_context = self
7605 .editor
7606 .update(cx, |editor, cx| editor.key_context(window, cx));
7607
7608 window.set_key_context(key_context);
7609 window.handle_input(
7610 &focus_handle,
7611 ElementInputHandler::new(bounds, self.editor.clone()),
7612 cx,
7613 );
7614 self.register_actions(window, cx);
7615 self.register_key_listeners(window, cx, layout);
7616
7617 let text_style = TextStyleRefinement {
7618 font_size: Some(self.style.text.font_size),
7619 line_height: Some(self.style.text.line_height),
7620 ..Default::default()
7621 };
7622 let rem_size = self.rem_size(cx);
7623 window.with_rem_size(rem_size, |window| {
7624 window.with_text_style(Some(text_style), |window| {
7625 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7626 self.paint_mouse_listeners(layout, window, cx);
7627 self.paint_background(layout, window, cx);
7628 self.paint_indent_guides(layout, window, cx);
7629
7630 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7631 self.paint_blamed_display_rows(layout, window, cx);
7632 self.paint_line_numbers(layout, window, cx);
7633 }
7634
7635 self.paint_text(layout, window, cx);
7636
7637 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7638 self.paint_gutter_highlights(layout, window, cx);
7639 self.paint_gutter_indicators(layout, window, cx);
7640 }
7641
7642 if !layout.blocks.is_empty() {
7643 window.with_element_namespace("blocks", |window| {
7644 self.paint_blocks(layout, window, cx);
7645 });
7646 }
7647
7648 window.with_element_namespace("blocks", |window| {
7649 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
7650 sticky_header.paint(window, cx)
7651 }
7652 });
7653
7654 self.paint_scrollbars(layout, window, cx);
7655 self.paint_inline_completion_popover(layout, window, cx);
7656 self.paint_mouse_context_menu(layout, window, cx);
7657 });
7658 })
7659 })
7660 }
7661}
7662
7663pub(super) fn gutter_bounds(
7664 editor_bounds: Bounds<Pixels>,
7665 gutter_dimensions: GutterDimensions,
7666) -> Bounds<Pixels> {
7667 Bounds {
7668 origin: editor_bounds.origin,
7669 size: size(gutter_dimensions.width, editor_bounds.size.height),
7670 }
7671}
7672
7673struct ScrollbarRangeData {
7674 scrollbar_bounds: Bounds<Pixels>,
7675 scroll_range: Bounds<Pixels>,
7676 letter_size: Size<Pixels>,
7677}
7678
7679impl ScrollbarRangeData {
7680 pub fn new(
7681 scrollbar_bounds: Bounds<Pixels>,
7682 letter_size: Size<Pixels>,
7683 snapshot: &EditorSnapshot,
7684 longest_line_width: Pixels,
7685 longest_line_blame_width: Pixels,
7686 style: &EditorStyle,
7687 editor_width: Pixels,
7688 cx: &mut App,
7689 ) -> ScrollbarRangeData {
7690 // TODO: Simplify this function down, it requires a lot of parameters
7691 let max_row = snapshot.max_point().row();
7692 let text_bounds_size = size(longest_line_width, max_row.0 as f32 * letter_size.height);
7693
7694 let settings = EditorSettings::get_global(cx);
7695 let scroll_beyond_last_line: Pixels = match settings.scroll_beyond_last_line {
7696 ScrollBeyondLastLine::OnePage => px(scrollbar_bounds.size.height / letter_size.height),
7697 ScrollBeyondLastLine::Off => px(1.),
7698 ScrollBeyondLastLine::VerticalScrollMargin => px(1.0 + settings.vertical_scroll_margin),
7699 };
7700
7701 let right_margin = if longest_line_width + longest_line_blame_width >= editor_width {
7702 letter_size.width + style.scrollbar_width
7703 } else {
7704 px(0.0)
7705 };
7706
7707 let overscroll = size(
7708 right_margin + longest_line_blame_width,
7709 letter_size.height * scroll_beyond_last_line,
7710 );
7711
7712 let scroll_range = Bounds {
7713 origin: scrollbar_bounds.origin,
7714 size: text_bounds_size + overscroll,
7715 };
7716
7717 ScrollbarRangeData {
7718 scrollbar_bounds,
7719 scroll_range,
7720 letter_size,
7721 }
7722 }
7723}
7724
7725impl IntoElement for EditorElement {
7726 type Element = Self;
7727
7728 fn into_element(self) -> Self::Element {
7729 self
7730 }
7731}
7732
7733pub struct EditorLayout {
7734 position_map: Rc<PositionMap>,
7735 hitbox: Hitbox,
7736 gutter_hitbox: Hitbox,
7737 content_origin: gpui::Point<Pixels>,
7738 scrollbars_layout: AxisPair<Option<ScrollbarLayout>>,
7739 mode: EditorMode,
7740 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
7741 indent_guides: Option<Vec<IndentGuideLayout>>,
7742 visible_display_row_range: Range<DisplayRow>,
7743 active_rows: BTreeMap<DisplayRow, bool>,
7744 highlighted_rows: BTreeMap<DisplayRow, gpui::Background>,
7745 line_elements: SmallVec<[AnyElement; 1]>,
7746 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
7747 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
7748 blamed_display_rows: Option<Vec<AnyElement>>,
7749 inline_blame: Option<AnyElement>,
7750 blocks: Vec<BlockLayout>,
7751 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7752 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7753 redacted_ranges: Vec<Range<DisplayPoint>>,
7754 cursors: Vec<(DisplayPoint, Hsla)>,
7755 visible_cursors: Vec<CursorLayout>,
7756 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
7757 code_actions_indicator: Option<AnyElement>,
7758 test_indicators: Vec<AnyElement>,
7759 crease_toggles: Vec<Option<AnyElement>>,
7760 diff_hunk_controls: Vec<AnyElement>,
7761 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
7762 inline_completion_popover: Option<AnyElement>,
7763 mouse_context_menu: Option<AnyElement>,
7764 tab_invisible: ShapedLine,
7765 space_invisible: ShapedLine,
7766 sticky_buffer_header: Option<AnyElement>,
7767}
7768
7769impl EditorLayout {
7770 fn line_end_overshoot(&self) -> Pixels {
7771 0.15 * self.position_map.line_height
7772 }
7773}
7774
7775struct LineNumberLayout {
7776 shaped_line: ShapedLine,
7777 hitbox: Option<Hitbox>,
7778 display_row: DisplayRow,
7779}
7780
7781struct ColoredRange<T> {
7782 start: T,
7783 end: T,
7784 color: Hsla,
7785}
7786
7787#[derive(Clone)]
7788struct ScrollbarLayout {
7789 hitbox: Hitbox,
7790 visible_range: Range<f32>,
7791 visible: bool,
7792 text_unit_size: Pixels,
7793 thumb_size: Pixels,
7794 axis: Axis,
7795}
7796
7797impl ScrollbarLayout {
7798 const BORDER_WIDTH: Pixels = px(1.0);
7799 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
7800 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
7801 // const MIN_THUMB_HEIGHT: Pixels = px(20.0);
7802
7803 fn thumb_bounds(&self) -> Bounds<Pixels> {
7804 match self.axis {
7805 Axis::Vertical => {
7806 let thumb_top = self.y_for_row(self.visible_range.start);
7807 let thumb_bottom = thumb_top + self.thumb_size;
7808 Bounds::from_corners(
7809 point(self.hitbox.left(), thumb_top),
7810 point(self.hitbox.right(), thumb_bottom),
7811 )
7812 }
7813 Axis::Horizontal => {
7814 let thumb_left =
7815 self.hitbox.left() + self.visible_range.start * self.text_unit_size;
7816 let thumb_right = thumb_left + self.thumb_size;
7817 Bounds::from_corners(
7818 point(thumb_left, self.hitbox.top()),
7819 point(thumb_right, self.hitbox.bottom()),
7820 )
7821 }
7822 }
7823 }
7824
7825 fn y_for_row(&self, row: f32) -> Pixels {
7826 self.hitbox.top() + row * self.text_unit_size
7827 }
7828
7829 fn marker_quads_for_ranges(
7830 &self,
7831 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
7832 column: Option<usize>,
7833 ) -> Vec<PaintQuad> {
7834 struct MinMax {
7835 min: Pixels,
7836 max: Pixels,
7837 }
7838 let (x_range, height_limit) = if let Some(column) = column {
7839 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
7840 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
7841 let end = start + column_width;
7842 (
7843 Range { start, end },
7844 MinMax {
7845 min: Self::MIN_MARKER_HEIGHT,
7846 max: px(f32::MAX),
7847 },
7848 )
7849 } else {
7850 (
7851 Range {
7852 start: Self::BORDER_WIDTH,
7853 end: self.hitbox.size.width,
7854 },
7855 MinMax {
7856 min: Self::LINE_MARKER_HEIGHT,
7857 max: Self::LINE_MARKER_HEIGHT,
7858 },
7859 )
7860 };
7861
7862 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
7863 let mut pixel_ranges = row_ranges
7864 .into_iter()
7865 .map(|range| {
7866 let start_y = row_to_y(range.start);
7867 let end_y = row_to_y(range.end)
7868 + self
7869 .text_unit_size
7870 .max(height_limit.min)
7871 .min(height_limit.max);
7872 ColoredRange {
7873 start: start_y,
7874 end: end_y,
7875 color: range.color,
7876 }
7877 })
7878 .peekable();
7879
7880 let mut quads = Vec::new();
7881 while let Some(mut pixel_range) = pixel_ranges.next() {
7882 while let Some(next_pixel_range) = pixel_ranges.peek() {
7883 if pixel_range.end >= next_pixel_range.start - px(1.0)
7884 && pixel_range.color == next_pixel_range.color
7885 {
7886 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
7887 pixel_ranges.next();
7888 } else {
7889 break;
7890 }
7891 }
7892
7893 let bounds = Bounds::from_corners(
7894 point(x_range.start, pixel_range.start),
7895 point(x_range.end, pixel_range.end),
7896 );
7897 quads.push(quad(
7898 bounds,
7899 Corners::default(),
7900 pixel_range.color,
7901 Edges::default(),
7902 Hsla::transparent_black(),
7903 ));
7904 }
7905
7906 quads
7907 }
7908}
7909
7910struct CreaseTrailerLayout {
7911 element: AnyElement,
7912 bounds: Bounds<Pixels>,
7913}
7914
7915pub(crate) struct PositionMap {
7916 pub size: Size<Pixels>,
7917 pub line_height: Pixels,
7918 pub scroll_pixel_position: gpui::Point<Pixels>,
7919 pub scroll_max: gpui::Point<f32>,
7920 pub em_width: Pixels,
7921 pub em_advance: Pixels,
7922 pub visible_row_range: Range<DisplayRow>,
7923 pub line_layouts: Vec<LineWithInvisibles>,
7924 pub snapshot: EditorSnapshot,
7925 pub text_hitbox: Hitbox,
7926 pub gutter_hitbox: Hitbox,
7927}
7928
7929#[derive(Debug, Copy, Clone)]
7930pub struct PointForPosition {
7931 pub previous_valid: DisplayPoint,
7932 pub next_valid: DisplayPoint,
7933 pub exact_unclipped: DisplayPoint,
7934 pub column_overshoot_after_line_end: u32,
7935}
7936
7937impl PointForPosition {
7938 pub fn as_valid(&self) -> Option<DisplayPoint> {
7939 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
7940 Some(self.previous_valid)
7941 } else {
7942 None
7943 }
7944 }
7945}
7946
7947impl PositionMap {
7948 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
7949 let text_bounds = self.text_hitbox.bounds;
7950 let scroll_position = self.snapshot.scroll_position();
7951 let position = position - text_bounds.origin;
7952 let y = position.y.max(px(0.)).min(self.size.height);
7953 let x = position.x + (scroll_position.x * self.em_width);
7954 let row = ((y / self.line_height) + scroll_position.y) as u32;
7955
7956 let (column, x_overshoot_after_line_end) = if let Some(line) = self
7957 .line_layouts
7958 .get(row as usize - scroll_position.y as usize)
7959 {
7960 if let Some(ix) = line.index_for_x(x) {
7961 (ix as u32, px(0.))
7962 } else {
7963 (line.len as u32, px(0.).max(x - line.width))
7964 }
7965 } else {
7966 (0, x)
7967 };
7968
7969 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
7970 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
7971 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
7972
7973 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
7974 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
7975 PointForPosition {
7976 previous_valid,
7977 next_valid,
7978 exact_unclipped,
7979 column_overshoot_after_line_end,
7980 }
7981 }
7982}
7983
7984struct BlockLayout {
7985 id: BlockId,
7986 row: Option<DisplayRow>,
7987 element: AnyElement,
7988 available_space: Size<AvailableSpace>,
7989 style: BlockStyle,
7990}
7991
7992fn layout_line(
7993 row: DisplayRow,
7994 snapshot: &EditorSnapshot,
7995 style: &EditorStyle,
7996 text_width: Pixels,
7997 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
7998 window: &mut Window,
7999 cx: &mut App,
8000) -> LineWithInvisibles {
8001 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
8002 LineWithInvisibles::from_chunks(
8003 chunks,
8004 &style,
8005 MAX_LINE_LEN,
8006 1,
8007 snapshot.mode,
8008 text_width,
8009 is_row_soft_wrapped,
8010 window,
8011 cx,
8012 )
8013 .pop()
8014 .unwrap()
8015}
8016
8017#[derive(Debug)]
8018pub struct IndentGuideLayout {
8019 origin: gpui::Point<Pixels>,
8020 length: Pixels,
8021 single_indent_width: Pixels,
8022 depth: u32,
8023 active: bool,
8024 settings: IndentGuideSettings,
8025}
8026
8027pub struct CursorLayout {
8028 origin: gpui::Point<Pixels>,
8029 block_width: Pixels,
8030 line_height: Pixels,
8031 color: Hsla,
8032 shape: CursorShape,
8033 block_text: Option<ShapedLine>,
8034 cursor_name: Option<AnyElement>,
8035}
8036
8037#[derive(Debug)]
8038pub struct CursorName {
8039 string: SharedString,
8040 color: Hsla,
8041 is_top_row: bool,
8042}
8043
8044impl CursorLayout {
8045 pub fn new(
8046 origin: gpui::Point<Pixels>,
8047 block_width: Pixels,
8048 line_height: Pixels,
8049 color: Hsla,
8050 shape: CursorShape,
8051 block_text: Option<ShapedLine>,
8052 ) -> CursorLayout {
8053 CursorLayout {
8054 origin,
8055 block_width,
8056 line_height,
8057 color,
8058 shape,
8059 block_text,
8060 cursor_name: None,
8061 }
8062 }
8063
8064 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8065 Bounds {
8066 origin: self.origin + origin,
8067 size: size(self.block_width, self.line_height),
8068 }
8069 }
8070
8071 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
8072 match self.shape {
8073 CursorShape::Bar => Bounds {
8074 origin: self.origin + origin,
8075 size: size(px(2.0), self.line_height),
8076 },
8077 CursorShape::Block | CursorShape::Hollow => Bounds {
8078 origin: self.origin + origin,
8079 size: size(self.block_width, self.line_height),
8080 },
8081 CursorShape::Underline => Bounds {
8082 origin: self.origin
8083 + origin
8084 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
8085 size: size(self.block_width, px(2.0)),
8086 },
8087 }
8088 }
8089
8090 pub fn layout(
8091 &mut self,
8092 origin: gpui::Point<Pixels>,
8093 cursor_name: Option<CursorName>,
8094 window: &mut Window,
8095 cx: &mut App,
8096 ) {
8097 if let Some(cursor_name) = cursor_name {
8098 let bounds = self.bounds(origin);
8099 let text_size = self.line_height / 1.5;
8100
8101 let name_origin = if cursor_name.is_top_row {
8102 point(bounds.right() - px(1.), bounds.top())
8103 } else {
8104 match self.shape {
8105 CursorShape::Bar => point(
8106 bounds.right() - px(2.),
8107 bounds.top() - text_size / 2. - px(1.),
8108 ),
8109 _ => point(
8110 bounds.right() - px(1.),
8111 bounds.top() - text_size / 2. - px(1.),
8112 ),
8113 }
8114 };
8115 let mut name_element = div()
8116 .bg(self.color)
8117 .text_size(text_size)
8118 .px_0p5()
8119 .line_height(text_size + px(2.))
8120 .text_color(cursor_name.color)
8121 .child(cursor_name.string.clone())
8122 .into_any_element();
8123
8124 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8125
8126 self.cursor_name = Some(name_element);
8127 }
8128 }
8129
8130 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8131 let bounds = self.bounds(origin);
8132
8133 //Draw background or border quad
8134 let cursor = if matches!(self.shape, CursorShape::Hollow) {
8135 outline(bounds, self.color)
8136 } else {
8137 fill(bounds, self.color)
8138 };
8139
8140 if let Some(name) = &mut self.cursor_name {
8141 name.paint(window, cx);
8142 }
8143
8144 window.paint_quad(cursor);
8145
8146 if let Some(block_text) = &self.block_text {
8147 block_text
8148 .paint(self.origin + origin, self.line_height, window, cx)
8149 .log_err();
8150 }
8151 }
8152
8153 pub fn shape(&self) -> CursorShape {
8154 self.shape
8155 }
8156}
8157
8158#[derive(Debug)]
8159pub struct HighlightedRange {
8160 pub start_y: Pixels,
8161 pub line_height: Pixels,
8162 pub lines: Vec<HighlightedRangeLine>,
8163 pub color: Hsla,
8164 pub corner_radius: Pixels,
8165}
8166
8167#[derive(Debug)]
8168pub struct HighlightedRangeLine {
8169 pub start_x: Pixels,
8170 pub end_x: Pixels,
8171}
8172
8173impl HighlightedRange {
8174 pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8175 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8176 self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8177 self.paint_lines(
8178 self.start_y + self.line_height,
8179 &self.lines[1..],
8180 bounds,
8181 window,
8182 );
8183 } else {
8184 self.paint_lines(self.start_y, &self.lines, bounds, window);
8185 }
8186 }
8187
8188 fn paint_lines(
8189 &self,
8190 start_y: Pixels,
8191 lines: &[HighlightedRangeLine],
8192 _bounds: Bounds<Pixels>,
8193 window: &mut Window,
8194 ) {
8195 if lines.is_empty() {
8196 return;
8197 }
8198
8199 let first_line = lines.first().unwrap();
8200 let last_line = lines.last().unwrap();
8201
8202 let first_top_left = point(first_line.start_x, start_y);
8203 let first_top_right = point(first_line.end_x, start_y);
8204
8205 let curve_height = point(Pixels::ZERO, self.corner_radius);
8206 let curve_width = |start_x: Pixels, end_x: Pixels| {
8207 let max = (end_x - start_x) / 2.;
8208 let width = if max < self.corner_radius {
8209 max
8210 } else {
8211 self.corner_radius
8212 };
8213
8214 point(width, Pixels::ZERO)
8215 };
8216
8217 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
8218 let mut builder = gpui::PathBuilder::fill();
8219 builder.move_to(first_top_right - top_curve_width);
8220 builder.curve_to(first_top_right + curve_height, first_top_right);
8221
8222 let mut iter = lines.iter().enumerate().peekable();
8223 while let Some((ix, line)) = iter.next() {
8224 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
8225
8226 if let Some((_, next_line)) = iter.peek() {
8227 let next_top_right = point(next_line.end_x, bottom_right.y);
8228
8229 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
8230 Ordering::Equal => {
8231 builder.line_to(bottom_right);
8232 }
8233 Ordering::Less => {
8234 let curve_width = curve_width(next_top_right.x, bottom_right.x);
8235 builder.line_to(bottom_right - curve_height);
8236 if self.corner_radius > Pixels::ZERO {
8237 builder.curve_to(bottom_right - curve_width, bottom_right);
8238 }
8239 builder.line_to(next_top_right + curve_width);
8240 if self.corner_radius > Pixels::ZERO {
8241 builder.curve_to(next_top_right + curve_height, next_top_right);
8242 }
8243 }
8244 Ordering::Greater => {
8245 let curve_width = curve_width(bottom_right.x, next_top_right.x);
8246 builder.line_to(bottom_right - curve_height);
8247 if self.corner_radius > Pixels::ZERO {
8248 builder.curve_to(bottom_right + curve_width, bottom_right);
8249 }
8250 builder.line_to(next_top_right - curve_width);
8251 if self.corner_radius > Pixels::ZERO {
8252 builder.curve_to(next_top_right + curve_height, next_top_right);
8253 }
8254 }
8255 }
8256 } else {
8257 let curve_width = curve_width(line.start_x, line.end_x);
8258 builder.line_to(bottom_right - curve_height);
8259 if self.corner_radius > Pixels::ZERO {
8260 builder.curve_to(bottom_right - curve_width, bottom_right);
8261 }
8262
8263 let bottom_left = point(line.start_x, bottom_right.y);
8264 builder.line_to(bottom_left + curve_width);
8265 if self.corner_radius > Pixels::ZERO {
8266 builder.curve_to(bottom_left - curve_height, bottom_left);
8267 }
8268 }
8269 }
8270
8271 if first_line.start_x > last_line.start_x {
8272 let curve_width = curve_width(last_line.start_x, first_line.start_x);
8273 let second_top_left = point(last_line.start_x, start_y + self.line_height);
8274 builder.line_to(second_top_left + curve_height);
8275 if self.corner_radius > Pixels::ZERO {
8276 builder.curve_to(second_top_left + curve_width, second_top_left);
8277 }
8278 let first_bottom_left = point(first_line.start_x, second_top_left.y);
8279 builder.line_to(first_bottom_left - curve_width);
8280 if self.corner_radius > Pixels::ZERO {
8281 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
8282 }
8283 }
8284
8285 builder.line_to(first_top_left + curve_height);
8286 if self.corner_radius > Pixels::ZERO {
8287 builder.curve_to(first_top_left + top_curve_width, first_top_left);
8288 }
8289 builder.line_to(first_top_right - top_curve_width);
8290
8291 if let Ok(path) = builder.build() {
8292 window.paint_path(path, self.color);
8293 }
8294 }
8295}
8296
8297enum CursorPopoverType {
8298 CodeContextMenu,
8299 EditPrediction,
8300}
8301
8302pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8303 (delta.pow(1.5) / 100.0).into()
8304}
8305
8306fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8307 (delta.pow(1.2) / 300.0).into()
8308}
8309
8310pub fn register_action<T: Action>(
8311 editor: &Entity<Editor>,
8312 window: &mut Window,
8313 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
8314) {
8315 let editor = editor.clone();
8316 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
8317 let action = action.downcast_ref().unwrap();
8318 if phase == DispatchPhase::Bubble {
8319 editor.update(cx, |editor, cx| {
8320 listener(editor, action, window, cx);
8321 })
8322 }
8323 })
8324}
8325
8326fn compute_auto_height_layout(
8327 editor: &mut Editor,
8328 max_lines: usize,
8329 max_line_number_width: Pixels,
8330 known_dimensions: Size<Option<Pixels>>,
8331 available_width: AvailableSpace,
8332 window: &mut Window,
8333 cx: &mut Context<Editor>,
8334) -> Option<Size<Pixels>> {
8335 let width = known_dimensions.width.or({
8336 if let AvailableSpace::Definite(available_width) = available_width {
8337 Some(available_width)
8338 } else {
8339 None
8340 }
8341 })?;
8342 if let Some(height) = known_dimensions.height {
8343 return Some(size(width, height));
8344 }
8345
8346 let style = editor.style.as_ref().unwrap();
8347 let font_id = window.text_system().resolve_font(&style.text.font());
8348 let font_size = style.text.font_size.to_pixels(window.rem_size());
8349 let line_height = style.text.line_height_in_pixels(window.rem_size());
8350 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8351
8352 let mut snapshot = editor.snapshot(window, cx);
8353 let gutter_dimensions = snapshot
8354 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
8355 .unwrap_or_default();
8356
8357 editor.gutter_dimensions = gutter_dimensions;
8358 let text_width = width - gutter_dimensions.width;
8359 let overscroll = size(em_width, px(0.));
8360
8361 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
8362 if editor.set_wrap_width(Some(editor_width), cx) {
8363 snapshot = editor.snapshot(window, cx);
8364 }
8365
8366 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
8367 let height = scroll_height
8368 .max(line_height)
8369 .min(line_height * max_lines as f32);
8370
8371 Some(size(width, height))
8372}
8373
8374#[cfg(test)]
8375mod tests {
8376 use super::*;
8377 use crate::{
8378 display_map::{BlockPlacement, BlockProperties},
8379 editor_tests::{init_test, update_test_language_settings},
8380 Editor, MultiBuffer,
8381 };
8382 use gpui::{TestAppContext, VisualTestContext};
8383 use language::language_settings;
8384 use log::info;
8385 use similar::DiffableStr;
8386 use std::num::NonZeroU32;
8387 use util::test::sample_text;
8388
8389 #[gpui::test]
8390 fn test_shape_line_numbers(cx: &mut TestAppContext) {
8391 init_test(cx, |_| {});
8392 let window = cx.add_window(|window, cx| {
8393 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
8394 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8395 });
8396
8397 let editor = window.root(cx).unwrap();
8398 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
8399 let line_height = window
8400 .update(cx, |_, window, _| {
8401 style.text.line_height_in_pixels(window.rem_size())
8402 })
8403 .unwrap();
8404 let element = EditorElement::new(&editor, style);
8405 let snapshot = window
8406 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
8407 .unwrap();
8408
8409 let layouts = cx
8410 .update_window(*window, |_, window, cx| {
8411 element.layout_line_numbers(
8412 None,
8413 GutterDimensions {
8414 left_padding: Pixels::ZERO,
8415 right_padding: Pixels::ZERO,
8416 width: px(30.0),
8417 margin: Pixels::ZERO,
8418 git_blame_entries_width: None,
8419 },
8420 line_height,
8421 gpui::Point::default(),
8422 DisplayRow(0)..DisplayRow(6),
8423 &(0..6)
8424 .map(|row| RowInfo {
8425 buffer_row: Some(row),
8426 ..Default::default()
8427 })
8428 .collect::<Vec<_>>(),
8429 Some(DisplayPoint::new(DisplayRow(0), 0)),
8430 &snapshot,
8431 window,
8432 cx,
8433 )
8434 })
8435 .unwrap();
8436 assert_eq!(layouts.len(), 6);
8437
8438 let relative_rows = window
8439 .update(cx, |editor, window, cx| {
8440 let snapshot = editor.snapshot(window, cx);
8441 element.calculate_relative_line_numbers(
8442 &snapshot,
8443 &(DisplayRow(0)..DisplayRow(6)),
8444 Some(DisplayRow(3)),
8445 )
8446 })
8447 .unwrap();
8448 assert_eq!(relative_rows[&DisplayRow(0)], 3);
8449 assert_eq!(relative_rows[&DisplayRow(1)], 2);
8450 assert_eq!(relative_rows[&DisplayRow(2)], 1);
8451 // current line has no relative number
8452 assert_eq!(relative_rows[&DisplayRow(4)], 1);
8453 assert_eq!(relative_rows[&DisplayRow(5)], 2);
8454
8455 // works if cursor is before screen
8456 let relative_rows = window
8457 .update(cx, |editor, window, cx| {
8458 let snapshot = editor.snapshot(window, cx);
8459 element.calculate_relative_line_numbers(
8460 &snapshot,
8461 &(DisplayRow(3)..DisplayRow(6)),
8462 Some(DisplayRow(1)),
8463 )
8464 })
8465 .unwrap();
8466 assert_eq!(relative_rows.len(), 3);
8467 assert_eq!(relative_rows[&DisplayRow(3)], 2);
8468 assert_eq!(relative_rows[&DisplayRow(4)], 3);
8469 assert_eq!(relative_rows[&DisplayRow(5)], 4);
8470
8471 // works if cursor is after screen
8472 let relative_rows = window
8473 .update(cx, |editor, window, cx| {
8474 let snapshot = editor.snapshot(window, cx);
8475 element.calculate_relative_line_numbers(
8476 &snapshot,
8477 &(DisplayRow(0)..DisplayRow(3)),
8478 Some(DisplayRow(6)),
8479 )
8480 })
8481 .unwrap();
8482 assert_eq!(relative_rows.len(), 3);
8483 assert_eq!(relative_rows[&DisplayRow(0)], 5);
8484 assert_eq!(relative_rows[&DisplayRow(1)], 4);
8485 assert_eq!(relative_rows[&DisplayRow(2)], 3);
8486 }
8487
8488 #[gpui::test]
8489 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
8490 init_test(cx, |_| {});
8491
8492 let window = cx.add_window(|window, cx| {
8493 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
8494 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8495 });
8496 let cx = &mut VisualTestContext::from_window(*window, cx);
8497 let editor = window.root(cx).unwrap();
8498 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8499
8500 window
8501 .update(cx, |editor, window, cx| {
8502 editor.cursor_shape = CursorShape::Block;
8503 editor.change_selections(None, window, cx, |s| {
8504 s.select_ranges([
8505 Point::new(0, 0)..Point::new(1, 0),
8506 Point::new(3, 2)..Point::new(3, 3),
8507 Point::new(5, 6)..Point::new(6, 0),
8508 ]);
8509 });
8510 })
8511 .unwrap();
8512
8513 let (_, state) = cx.draw(
8514 point(px(500.), px(500.)),
8515 size(px(500.), px(500.)),
8516 |_, _| EditorElement::new(&editor, style),
8517 );
8518
8519 assert_eq!(state.selections.len(), 1);
8520 let local_selections = &state.selections[0].1;
8521 assert_eq!(local_selections.len(), 3);
8522 // moves cursor back one line
8523 assert_eq!(
8524 local_selections[0].head,
8525 DisplayPoint::new(DisplayRow(0), 6)
8526 );
8527 assert_eq!(
8528 local_selections[0].range,
8529 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
8530 );
8531
8532 // moves cursor back one column
8533 assert_eq!(
8534 local_selections[1].range,
8535 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
8536 );
8537 assert_eq!(
8538 local_selections[1].head,
8539 DisplayPoint::new(DisplayRow(3), 2)
8540 );
8541
8542 // leaves cursor on the max point
8543 assert_eq!(
8544 local_selections[2].range,
8545 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
8546 );
8547 assert_eq!(
8548 local_selections[2].head,
8549 DisplayPoint::new(DisplayRow(6), 0)
8550 );
8551
8552 // active lines does not include 1 (even though the range of the selection does)
8553 assert_eq!(
8554 state.active_rows.keys().cloned().collect::<Vec<_>>(),
8555 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
8556 );
8557
8558 // multi-buffer support
8559 // in DisplayPoint coordinates, this is what we're dealing with:
8560 // 0: [[file
8561 // 1: header
8562 // 2: section]]
8563 // 3: aaaaaa
8564 // 4: bbbbbb
8565 // 5: cccccc
8566 // 6:
8567 // 7: [[footer]]
8568 // 8: [[header]]
8569 // 9: ffffff
8570 // 10: gggggg
8571 // 11: hhhhhh
8572 // 12:
8573 // 13: [[footer]]
8574 // 14: [[file
8575 // 15: header
8576 // 16: section]]
8577 // 17: bbbbbb
8578 // 18: cccccc
8579 // 19: dddddd
8580 // 20: [[footer]]
8581 let window = cx.add_window(|window, cx| {
8582 let buffer = MultiBuffer::build_multi(
8583 [
8584 (
8585 &(sample_text(8, 6, 'a') + "\n"),
8586 vec![
8587 Point::new(0, 0)..Point::new(3, 0),
8588 Point::new(4, 0)..Point::new(7, 0),
8589 ],
8590 ),
8591 (
8592 &(sample_text(8, 6, 'a') + "\n"),
8593 vec![Point::new(1, 0)..Point::new(3, 0)],
8594 ),
8595 ],
8596 cx,
8597 );
8598 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8599 });
8600 let editor = window.root(cx).unwrap();
8601 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8602 let _state = window.update(cx, |editor, window, cx| {
8603 editor.cursor_shape = CursorShape::Block;
8604 editor.change_selections(None, window, cx, |s| {
8605 s.select_display_ranges([
8606 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
8607 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
8608 ]);
8609 });
8610 });
8611
8612 let (_, state) = cx.draw(
8613 point(px(500.), px(500.)),
8614 size(px(500.), px(500.)),
8615 |_, _| EditorElement::new(&editor, style),
8616 );
8617 assert_eq!(state.selections.len(), 1);
8618 let local_selections = &state.selections[0].1;
8619 assert_eq!(local_selections.len(), 2);
8620
8621 // moves cursor on excerpt boundary back a line
8622 // and doesn't allow selection to bleed through
8623 assert_eq!(
8624 local_selections[0].range,
8625 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
8626 );
8627 assert_eq!(
8628 local_selections[0].head,
8629 DisplayPoint::new(DisplayRow(6), 0)
8630 );
8631 // moves cursor on buffer boundary back two lines
8632 // and doesn't allow selection to bleed through
8633 assert_eq!(
8634 local_selections[1].range,
8635 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
8636 );
8637 assert_eq!(
8638 local_selections[1].head,
8639 DisplayPoint::new(DisplayRow(12), 0)
8640 );
8641 }
8642
8643 #[gpui::test]
8644 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
8645 init_test(cx, |_| {});
8646
8647 let window = cx.add_window(|window, cx| {
8648 let buffer = MultiBuffer::build_simple("", cx);
8649 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8650 });
8651 let cx = &mut VisualTestContext::from_window(*window, cx);
8652 let editor = window.root(cx).unwrap();
8653 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8654 window
8655 .update(cx, |editor, window, cx| {
8656 editor.set_placeholder_text("hello", cx);
8657 editor.insert_blocks(
8658 [BlockProperties {
8659 style: BlockStyle::Fixed,
8660 placement: BlockPlacement::Above(Anchor::min()),
8661 height: 3,
8662 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
8663 priority: 0,
8664 }],
8665 None,
8666 cx,
8667 );
8668
8669 // Blur the editor so that it displays placeholder text.
8670 window.blur();
8671 })
8672 .unwrap();
8673
8674 let (_, state) = cx.draw(
8675 point(px(500.), px(500.)),
8676 size(px(500.), px(500.)),
8677 |_, _| EditorElement::new(&editor, style),
8678 );
8679 assert_eq!(state.position_map.line_layouts.len(), 4);
8680 assert_eq!(state.line_numbers.len(), 1);
8681 assert_eq!(
8682 state
8683 .line_numbers
8684 .get(&MultiBufferRow(0))
8685 .and_then(|line_number| line_number.shaped_line.text.as_str()),
8686 Some("1")
8687 );
8688 }
8689
8690 #[gpui::test]
8691 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
8692 const TAB_SIZE: u32 = 4;
8693
8694 let input_text = "\t \t|\t| a b";
8695 let expected_invisibles = vec![
8696 Invisible::Tab {
8697 line_start_offset: 0,
8698 line_end_offset: TAB_SIZE as usize,
8699 },
8700 Invisible::Whitespace {
8701 line_offset: TAB_SIZE as usize,
8702 },
8703 Invisible::Tab {
8704 line_start_offset: TAB_SIZE as usize + 1,
8705 line_end_offset: TAB_SIZE as usize * 2,
8706 },
8707 Invisible::Tab {
8708 line_start_offset: TAB_SIZE as usize * 2 + 1,
8709 line_end_offset: TAB_SIZE as usize * 3,
8710 },
8711 Invisible::Whitespace {
8712 line_offset: TAB_SIZE as usize * 3 + 1,
8713 },
8714 Invisible::Whitespace {
8715 line_offset: TAB_SIZE as usize * 3 + 3,
8716 },
8717 ];
8718 assert_eq!(
8719 expected_invisibles.len(),
8720 input_text
8721 .chars()
8722 .filter(|initial_char| initial_char.is_whitespace())
8723 .count(),
8724 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8725 );
8726
8727 for show_line_numbers in [true, false] {
8728 init_test(cx, |s| {
8729 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8730 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
8731 });
8732
8733 let actual_invisibles = collect_invisibles_from_new_editor(
8734 cx,
8735 EditorMode::Full,
8736 input_text,
8737 px(500.0),
8738 show_line_numbers,
8739 );
8740
8741 assert_eq!(expected_invisibles, actual_invisibles);
8742 }
8743 }
8744
8745 #[gpui::test]
8746 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
8747 init_test(cx, |s| {
8748 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8749 s.defaults.tab_size = NonZeroU32::new(4);
8750 });
8751
8752 for editor_mode_without_invisibles in [
8753 EditorMode::SingleLine { auto_width: false },
8754 EditorMode::AutoHeight { max_lines: 100 },
8755 ] {
8756 for show_line_numbers in [true, false] {
8757 let invisibles = collect_invisibles_from_new_editor(
8758 cx,
8759 editor_mode_without_invisibles,
8760 "\t\t\t| | a b",
8761 px(500.0),
8762 show_line_numbers,
8763 );
8764 assert!(invisibles.is_empty(),
8765 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
8766 }
8767 }
8768 }
8769
8770 #[gpui::test]
8771 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
8772 let tab_size = 4;
8773 let input_text = "a\tbcd ".repeat(9);
8774 let repeated_invisibles = [
8775 Invisible::Tab {
8776 line_start_offset: 1,
8777 line_end_offset: tab_size as usize,
8778 },
8779 Invisible::Whitespace {
8780 line_offset: tab_size as usize + 3,
8781 },
8782 Invisible::Whitespace {
8783 line_offset: tab_size as usize + 4,
8784 },
8785 Invisible::Whitespace {
8786 line_offset: tab_size as usize + 5,
8787 },
8788 Invisible::Whitespace {
8789 line_offset: tab_size as usize + 6,
8790 },
8791 Invisible::Whitespace {
8792 line_offset: tab_size as usize + 7,
8793 },
8794 ];
8795 let expected_invisibles = std::iter::once(repeated_invisibles)
8796 .cycle()
8797 .take(9)
8798 .flatten()
8799 .collect::<Vec<_>>();
8800 assert_eq!(
8801 expected_invisibles.len(),
8802 input_text
8803 .chars()
8804 .filter(|initial_char| initial_char.is_whitespace())
8805 .count(),
8806 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8807 );
8808 info!("Expected invisibles: {expected_invisibles:?}");
8809
8810 init_test(cx, |_| {});
8811
8812 // Put the same string with repeating whitespace pattern into editors of various size,
8813 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
8814 let resize_step = 10.0;
8815 let mut editor_width = 200.0;
8816 while editor_width <= 1000.0 {
8817 for show_line_numbers in [true, false] {
8818 update_test_language_settings(cx, |s| {
8819 s.defaults.tab_size = NonZeroU32::new(tab_size);
8820 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8821 s.defaults.preferred_line_length = Some(editor_width as u32);
8822 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
8823 });
8824
8825 let actual_invisibles = collect_invisibles_from_new_editor(
8826 cx,
8827 EditorMode::Full,
8828 &input_text,
8829 px(editor_width),
8830 show_line_numbers,
8831 );
8832
8833 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
8834 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
8835 let mut i = 0;
8836 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
8837 i = actual_index;
8838 match expected_invisibles.get(i) {
8839 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
8840 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
8841 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
8842 _ => {
8843 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
8844 }
8845 },
8846 None => {
8847 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
8848 }
8849 }
8850 }
8851 let missing_expected_invisibles = &expected_invisibles[i + 1..];
8852 assert!(
8853 missing_expected_invisibles.is_empty(),
8854 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
8855 );
8856
8857 editor_width += resize_step;
8858 }
8859 }
8860 }
8861
8862 fn collect_invisibles_from_new_editor(
8863 cx: &mut TestAppContext,
8864 editor_mode: EditorMode,
8865 input_text: &str,
8866 editor_width: Pixels,
8867 show_line_numbers: bool,
8868 ) -> Vec<Invisible> {
8869 info!(
8870 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
8871 editor_width.0
8872 );
8873 let window = cx.add_window(|window, cx| {
8874 let buffer = MultiBuffer::build_simple(input_text, cx);
8875 Editor::new(editor_mode, buffer, None, true, window, cx)
8876 });
8877 let cx = &mut VisualTestContext::from_window(*window, cx);
8878 let editor = window.root(cx).unwrap();
8879
8880 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8881 window
8882 .update(cx, |editor, _, cx| {
8883 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
8884 editor.set_wrap_width(Some(editor_width), cx);
8885 editor.set_show_line_numbers(show_line_numbers, cx);
8886 })
8887 .unwrap();
8888 let (_, state) = cx.draw(
8889 point(px(500.), px(500.)),
8890 size(px(500.), px(500.)),
8891 |_, _| EditorElement::new(&editor, style),
8892 );
8893 state
8894 .position_map
8895 .line_layouts
8896 .iter()
8897 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
8898 .cloned()
8899 .collect()
8900 }
8901}
8902
8903fn diff_hunk_controls(
8904 row: u32,
8905 hunk_range: Range<Anchor>,
8906 line_height: Pixels,
8907 editor: &Entity<Editor>,
8908 _window: &mut Window,
8909 cx: &mut App,
8910) -> AnyElement {
8911 let stage = editor.update(cx, |editor, cx| {
8912 let snapshot = editor.buffer.read(cx).snapshot(cx);
8913 editor.has_stageable_diff_hunks_in_ranges(&[hunk_range.start..hunk_range.start], &snapshot)
8914 });
8915 h_flex()
8916 .h(line_height)
8917 .mr_1()
8918 .gap_1()
8919 .px_1()
8920 .pb_1()
8921 .border_b_1()
8922 .border_color(cx.theme().colors().border_variant)
8923 .rounded_b_lg()
8924 .bg(cx.theme().colors().editor_background)
8925 .gap_1()
8926 .child(
8927 IconButton::new(("discard-hunk", row as u64), IconName::Undo)
8928 .shape(IconButtonShape::Square)
8929 .icon_size(IconSize::Small)
8930 .tooltip({
8931 let focus_handle = editor.focus_handle(cx);
8932 move |window, cx| {
8933 Tooltip::for_action_in(
8934 "Discard Hunk",
8935 &RevertSelectedHunks,
8936 &focus_handle,
8937 window,
8938 cx,
8939 )
8940 }
8941 })
8942 .on_click({
8943 let editor = editor.clone();
8944 move |_event, window, cx| {
8945 editor.update(cx, |editor, cx| {
8946 let snapshot = editor.snapshot(window, cx);
8947 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
8948 editor.discard_hunks_in_ranges([point..point].into_iter(), window, cx);
8949 });
8950 }
8951 }),
8952 )
8953 .child(
8954 Button::new(("skip-hunk", row as u64), "Skip")
8955 .label_size(LabelSize::Small)
8956 .tooltip({
8957 let focus_handle = editor.focus_handle(cx);
8958 move |window, cx| {
8959 Tooltip::for_action_in("Skip Hunk", &GoToHunk, &focus_handle, window, cx)
8960 }
8961 })
8962 .on_click({
8963 let editor = editor.clone();
8964 move |_event, window, cx| {
8965 editor.update(cx, |editor, cx| {
8966 let snapshot = editor.snapshot(window, cx);
8967 let position = hunk_range.end.to_point(&snapshot.buffer_snapshot);
8968 editor.go_to_hunk_after_position(&snapshot, position, window, cx);
8969 editor.expand_selected_diff_hunks(cx);
8970 });
8971 }
8972 }),
8973 )
8974 .child(
8975 Button::new(
8976 ("stage-unstage-hunk", row as u64),
8977 if stage { "Stage" } else { "Unstage" },
8978 )
8979 .label_size(LabelSize::Small)
8980 .tooltip({
8981 let focus_handle = editor.focus_handle(cx);
8982 move |window, cx| {
8983 Tooltip::for_action_in(
8984 if stage { "Stage Hunk" } else { "Unstage Hunk" },
8985 &ToggleStagedSelectedDiffHunks,
8986 &focus_handle,
8987 window,
8988 cx,
8989 )
8990 }
8991 })
8992 .on_click({
8993 let editor = editor.clone();
8994 move |_event, _window, cx| {
8995 editor.update(cx, |editor, cx| {
8996 editor
8997 .stage_or_unstage_diff_hunks(&[hunk_range.start..hunk_range.start], cx);
8998 });
8999 }
9000 }),
9001 )
9002 .into_any_element()
9003}