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