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