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