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, Focusable as _, FontId, GlobalElementId, Hitbox,
38 Hsla, InteractiveElement, IntoElement, KeyBindingContextPredicate, Keystroke, Length,
39 ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad,
40 ParentElement, Pixels, ScrollDelta, ScrollWheelEvent, ShapedLine, SharedString, Size,
41 StatefulInteractiveElement, Style, Styled, Subscription, TextRun, TextStyleRefinement,
42 WeakEntity, Window,
43};
44use itertools::Itertools;
45use language::{
46 language_settings::{
47 IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings,
48 ShowWhitespaceSetting,
49 },
50 ChunkRendererContext,
51};
52use lsp::DiagnosticSeverity;
53use multi_buffer::{
54 Anchor, ExcerptId, ExcerptInfo, ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow,
55 RowInfo, ToOffset,
56};
57use project::project_settings::{GitGutterSetting, ProjectSettings};
58use settings::{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 self.editor.update(cx, move |editor, cx| {
3171 let accept_binding = editor.accept_edit_prediction_keybind(window, cx);
3172 let mut element = editor.render_edit_prediction_cursor_popover(
3173 min_width,
3174 max_width,
3175 cursor_point,
3176 style,
3177 accept_binding.keystroke()?,
3178 window,
3179 cx,
3180 )?;
3181 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3182 Some((CursorPopoverType::EditPrediction, element, size))
3183 })
3184 } else {
3185 None
3186 };
3187 vec![edit_prediction, context_menu]
3188 .into_iter()
3189 .flatten()
3190 .collect::<Vec<_>>()
3191 },
3192 ) else {
3193 return;
3194 };
3195
3196 let Some((menu_ix, (_, menu_bounds))) = laid_out_popovers
3197 .iter()
3198 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))
3199 else {
3200 return;
3201 };
3202 let last_ix = laid_out_popovers.len() - 1;
3203 let menu_is_last = menu_ix == last_ix;
3204 let first_popover_bounds = laid_out_popovers[0].1;
3205 let last_popover_bounds = laid_out_popovers[last_ix].1;
3206
3207 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
3208 // right, and otherwise it goes below or to the right.
3209 let mut target_bounds = Bounds::from_corners(
3210 first_popover_bounds.origin,
3211 last_popover_bounds.bottom_right(),
3212 );
3213 target_bounds.size.width = menu_bounds.size.width;
3214
3215 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
3216 // based on this is preferred for layout stability.
3217 let mut max_target_bounds = target_bounds;
3218 max_target_bounds.size.height = max_height;
3219 if y_flipped {
3220 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
3221 }
3222
3223 // Add spacing around `target_bounds` and `max_target_bounds`.
3224 let mut extend_amount = Edges::all(MENU_GAP);
3225 if y_flipped {
3226 extend_amount.bottom = line_height;
3227 } else {
3228 extend_amount.top = line_height;
3229 }
3230 let target_bounds = target_bounds.extend(extend_amount);
3231 let max_target_bounds = max_target_bounds.extend(extend_amount);
3232
3233 let must_place_above_or_below =
3234 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
3235 laid_out_popovers[menu_ix + 1..]
3236 .iter()
3237 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
3238 } else {
3239 false
3240 };
3241
3242 self.layout_context_menu_aside(
3243 y_flipped,
3244 *menu_bounds,
3245 target_bounds,
3246 max_target_bounds,
3247 max_menu_height,
3248 must_place_above_or_below,
3249 text_hitbox,
3250 viewport_bounds,
3251 window,
3252 cx,
3253 );
3254 }
3255
3256 #[allow(clippy::too_many_arguments)]
3257 fn layout_gutter_menu(
3258 &self,
3259 line_height: Pixels,
3260 text_hitbox: &Hitbox,
3261 content_origin: gpui::Point<Pixels>,
3262 scroll_pixel_position: gpui::Point<Pixels>,
3263 gutter_overshoot: Pixels,
3264 window: &mut Window,
3265 cx: &mut App,
3266 ) {
3267 let editor = self.editor.read(cx);
3268 if !editor.context_menu_visible() {
3269 return;
3270 }
3271 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
3272 editor.context_menu_origin()
3273 else {
3274 return;
3275 };
3276 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
3277 // indicator than just a plain first column of the text field.
3278 let target_position = content_origin
3279 + gpui::Point {
3280 x: -gutter_overshoot,
3281 y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
3282 };
3283 let min_height = line_height * 3. + POPOVER_Y_PADDING;
3284 let max_height = line_height * 12. + POPOVER_Y_PADDING;
3285 let viewport_bounds =
3286 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
3287 right: -Self::SCROLLBAR_WIDTH - MENU_GAP,
3288 ..Default::default()
3289 });
3290 self.layout_popovers_above_or_below_line(
3291 target_position,
3292 line_height,
3293 min_height,
3294 max_height,
3295 text_hitbox,
3296 viewport_bounds,
3297 window,
3298 cx,
3299 move |height, _max_width_for_stable_x, y_flipped, window, cx| {
3300 let mut element = self
3301 .render_context_menu(line_height, height, y_flipped, window, cx)
3302 .expect("Visible context menu should always render.");
3303 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3304 vec![(CursorPopoverType::CodeContextMenu, element, size)]
3305 },
3306 );
3307 }
3308
3309 #[allow(clippy::too_many_arguments)]
3310 fn layout_popovers_above_or_below_line(
3311 &self,
3312 target_position: gpui::Point<Pixels>,
3313 line_height: Pixels,
3314 min_height: Pixels,
3315 max_height: Pixels,
3316 text_hitbox: &Hitbox,
3317 viewport_bounds: Bounds<Pixels>,
3318 window: &mut Window,
3319 cx: &mut App,
3320 make_sized_popovers: impl FnOnce(
3321 Pixels,
3322 Pixels,
3323 bool,
3324 &mut Window,
3325 &mut App,
3326 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
3327 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
3328 // If the max height won't fit below and there is more space above, put it above the line.
3329 let bottom_y_when_flipped = target_position.y - line_height;
3330 let available_above = bottom_y_when_flipped - text_hitbox.top();
3331 let available_below = text_hitbox.bottom() - target_position.y;
3332 let y_overflows_below = max_height > available_below;
3333 let mut y_flipped = y_overflows_below && available_above > available_below;
3334 let mut height = cmp::min(
3335 max_height,
3336 if y_flipped {
3337 available_above
3338 } else {
3339 available_below
3340 },
3341 );
3342
3343 // If the min height doesn't fit within text bounds, instead fit within the window.
3344 if height < min_height {
3345 let available_above = bottom_y_when_flipped;
3346 let available_below = viewport_bounds.bottom() - target_position.y;
3347 if available_below > min_height {
3348 y_flipped = false;
3349 height = min_height;
3350 } else if available_above > min_height {
3351 y_flipped = true;
3352 height = min_height;
3353 } else if available_above > available_below {
3354 y_flipped = true;
3355 height = available_above;
3356 } else {
3357 y_flipped = false;
3358 height = available_below;
3359 }
3360 }
3361
3362 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
3363
3364 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
3365 // for very narrow windows.
3366 let popovers = make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
3367 if popovers.is_empty() {
3368 return None;
3369 }
3370
3371 let max_width = popovers
3372 .iter()
3373 .map(|(_, _, size)| size.width)
3374 .max()
3375 .unwrap_or_default();
3376
3377 let mut current_position = gpui::Point {
3378 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
3379 // overflow. Include space for the scrollbar.
3380 x: target_position
3381 .x
3382 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
3383 y: if y_flipped {
3384 bottom_y_when_flipped
3385 } else {
3386 target_position.y
3387 },
3388 };
3389
3390 let mut laid_out_popovers = popovers
3391 .into_iter()
3392 .map(|(popover_type, element, size)| {
3393 if y_flipped {
3394 current_position.y -= size.height;
3395 }
3396 let position = current_position;
3397 window.defer_draw(element, current_position, 1);
3398 if !y_flipped {
3399 current_position.y += size.height + MENU_GAP;
3400 } else {
3401 current_position.y -= MENU_GAP;
3402 }
3403 (popover_type, Bounds::new(position, size))
3404 })
3405 .collect::<Vec<_>>();
3406
3407 if y_flipped {
3408 laid_out_popovers.reverse();
3409 }
3410
3411 Some((laid_out_popovers, y_flipped))
3412 }
3413
3414 #[allow(clippy::too_many_arguments)]
3415 fn layout_context_menu_aside(
3416 &self,
3417 y_flipped: bool,
3418 menu_bounds: Bounds<Pixels>,
3419 target_bounds: Bounds<Pixels>,
3420 max_target_bounds: Bounds<Pixels>,
3421 max_height: Pixels,
3422 must_place_above_or_below: bool,
3423 text_hitbox: &Hitbox,
3424 viewport_bounds: Bounds<Pixels>,
3425 window: &mut Window,
3426 cx: &mut App,
3427 ) {
3428 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
3429 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
3430 && !must_place_above_or_below
3431 {
3432 let max_width = cmp::min(
3433 available_within_viewport.right - px(1.),
3434 MENU_ASIDE_MAX_WIDTH,
3435 );
3436 let Some(mut aside) =
3437 self.render_context_menu_aside(size(max_width, max_height - POPOVER_Y_PADDING), cx)
3438 else {
3439 return;
3440 };
3441 aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3442 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
3443 Some((aside, right_position))
3444 } else {
3445 let max_size = size(
3446 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
3447 // won't be needed here.
3448 cmp::min(
3449 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
3450 viewport_bounds.right(),
3451 ),
3452 cmp::min(
3453 max_height,
3454 cmp::max(
3455 available_within_viewport.top,
3456 available_within_viewport.bottom,
3457 ),
3458 ) - POPOVER_Y_PADDING,
3459 );
3460 let Some(mut aside) = self.render_context_menu_aside(max_size, cx) else {
3461 return;
3462 };
3463 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
3464
3465 let top_position = point(
3466 menu_bounds.origin.x,
3467 target_bounds.top() - actual_size.height,
3468 );
3469 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
3470
3471 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
3472 // Prefer to fit on the same side of the line as the menu, then on the other side of
3473 // the line.
3474 if !y_flipped && wanted.height < available.bottom {
3475 Some(bottom_position)
3476 } else if !y_flipped && wanted.height < available.top {
3477 Some(top_position)
3478 } else if y_flipped && wanted.height < available.top {
3479 Some(top_position)
3480 } else if y_flipped && wanted.height < available.bottom {
3481 Some(bottom_position)
3482 } else {
3483 None
3484 }
3485 };
3486
3487 // Prefer choosing a direction using max sizes rather than actual size for stability.
3488 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
3489 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
3490 let aside_position = fit_within(available_within_text, wanted)
3491 // Fallback: fit max size in window.
3492 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
3493 // Fallback: fit actual size in window.
3494 .or_else(|| fit_within(available_within_viewport, actual_size));
3495
3496 aside_position.map(|position| (aside, position))
3497 };
3498
3499 // Skip drawing if it doesn't fit anywhere.
3500 if let Some((aside, position)) = positioned_aside {
3501 window.defer_draw(aside, position, 1);
3502 }
3503 }
3504
3505 fn render_context_menu(
3506 &self,
3507 line_height: Pixels,
3508 height: Pixels,
3509 y_flipped: bool,
3510 window: &mut Window,
3511 cx: &mut App,
3512 ) -> Option<AnyElement> {
3513 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
3514 self.editor.update(cx, |editor, cx| {
3515 editor.render_context_menu(&self.style, max_height_in_lines, y_flipped, window, cx)
3516 })
3517 }
3518
3519 fn render_context_menu_aside(
3520 &self,
3521 max_size: Size<Pixels>,
3522
3523 cx: &mut App,
3524 ) -> Option<AnyElement> {
3525 if max_size.width < px(100.) || max_size.height < px(12.) {
3526 None
3527 } else {
3528 self.editor.update(cx, |editor, cx| {
3529 editor.render_context_menu_aside(&self.style, max_size, cx)
3530 })
3531 }
3532 }
3533
3534 #[allow(clippy::too_many_arguments)]
3535 fn layout_inline_completion_popover(
3536 &self,
3537 text_bounds: &Bounds<Pixels>,
3538 editor_snapshot: &EditorSnapshot,
3539 visible_row_range: Range<DisplayRow>,
3540 scroll_top: f32,
3541 scroll_bottom: f32,
3542 line_layouts: &[LineWithInvisibles],
3543 line_height: Pixels,
3544 scroll_pixel_position: gpui::Point<Pixels>,
3545 newest_selection_head: Option<DisplayPoint>,
3546 editor_width: Pixels,
3547 style: &EditorStyle,
3548 window: &mut Window,
3549 cx: &mut App,
3550 ) -> Option<AnyElement> {
3551 const PADDING_X: Pixels = Pixels(24.);
3552 const PADDING_Y: Pixels = Pixels(2.);
3553
3554 let editor = self.editor.read(cx);
3555 let active_inline_completion = editor.active_inline_completion.as_ref()?;
3556
3557 if editor.edit_prediction_visible_in_cursor_popover(true) {
3558 return None;
3559 }
3560
3561 match &active_inline_completion.completion {
3562 InlineCompletion::Move { target, .. } => {
3563 let previewing = false;
3564 let target_display_point = target.to_display_point(editor_snapshot);
3565 if target_display_point.row().as_f32() < scroll_top {
3566 let mut element = inline_completion_accept_indicator(
3567 "Jump to Edit",
3568 Some(IconName::ArrowUp),
3569 previewing,
3570 editor,
3571 window,
3572 cx,
3573 )?;
3574 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3575 let offset = point((text_bounds.size.width - size.width) / 2., PADDING_Y);
3576 element.prepaint_at(text_bounds.origin + offset, window, cx);
3577 Some(element)
3578 } else if (target_display_point.row().as_f32() + 1.) > scroll_bottom {
3579 let mut element = inline_completion_accept_indicator(
3580 "Jump to Edit",
3581 Some(IconName::ArrowDown),
3582 previewing,
3583 editor,
3584 window,
3585 cx,
3586 )?;
3587 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3588 let offset = point(
3589 (text_bounds.size.width - size.width) / 2.,
3590 text_bounds.size.height - size.height - PADDING_Y,
3591 );
3592 element.prepaint_at(text_bounds.origin + offset, window, cx);
3593 Some(element)
3594 } else {
3595 let mut element = inline_completion_accept_indicator(
3596 "Jump to Edit",
3597 None,
3598 previewing,
3599 editor,
3600 window,
3601 cx,
3602 )?;
3603
3604 let target_line_end = DisplayPoint::new(
3605 target_display_point.row(),
3606 editor_snapshot.line_len(target_display_point.row()),
3607 );
3608 let origin = self.editor.update(cx, |editor, _cx| {
3609 editor.display_to_pixel_point(target_line_end, editor_snapshot, window)
3610 })?;
3611 element.prepaint_as_root(
3612 text_bounds.origin + origin + point(PADDING_X, px(0.)),
3613 AvailableSpace::min_size(),
3614 window,
3615 cx,
3616 );
3617 Some(element)
3618 }
3619 }
3620 InlineCompletion::Edit {
3621 edits,
3622 edit_preview,
3623 display_mode,
3624 snapshot,
3625 } => {
3626 if self.editor.read(cx).has_visible_completions_menu() {
3627 return None;
3628 }
3629
3630 let edit_start = edits
3631 .first()
3632 .unwrap()
3633 .0
3634 .start
3635 .to_display_point(editor_snapshot);
3636 let edit_end = edits
3637 .last()
3638 .unwrap()
3639 .0
3640 .end
3641 .to_display_point(editor_snapshot);
3642
3643 let is_visible = visible_row_range.contains(&edit_start.row())
3644 || visible_row_range.contains(&edit_end.row());
3645 if !is_visible {
3646 return None;
3647 }
3648
3649 match display_mode {
3650 EditDisplayMode::TabAccept => {
3651 let range = &edits.first()?.0;
3652 let target_display_point = range.end.to_display_point(editor_snapshot);
3653
3654 let target_line_end = DisplayPoint::new(
3655 target_display_point.row(),
3656 editor_snapshot.line_len(target_display_point.row()),
3657 );
3658 let (mut element, origin) = self.editor.update(cx, |editor, cx| {
3659 Some((
3660 inline_completion_accept_indicator(
3661 "Accept",
3662 None,
3663 editor.previewing_inline_completion,
3664 editor,
3665 window,
3666 cx,
3667 )?,
3668 editor.display_to_pixel_point(
3669 target_line_end,
3670 editor_snapshot,
3671 window,
3672 )?,
3673 ))
3674 })?;
3675
3676 element.prepaint_as_root(
3677 text_bounds.origin + origin + point(PADDING_X, px(0.)),
3678 AvailableSpace::min_size(),
3679 window,
3680 cx,
3681 );
3682
3683 return Some(element);
3684 }
3685 EditDisplayMode::Inline => return None,
3686 EditDisplayMode::DiffPopover => {}
3687 }
3688
3689 let highlighted_edits = crate::inline_completion_edit_text(
3690 &snapshot,
3691 edits,
3692 edit_preview.as_ref()?,
3693 false,
3694 cx,
3695 );
3696
3697 let line_count = highlighted_edits.text.lines().count();
3698
3699 let longest_row =
3700 editor_snapshot.longest_row_in_range(edit_start.row()..edit_end.row() + 1);
3701 let longest_line_width = if visible_row_range.contains(&longest_row) {
3702 line_layouts[(longest_row.0 - visible_row_range.start.0) as usize].width
3703 } else {
3704 layout_line(
3705 longest_row,
3706 editor_snapshot,
3707 style,
3708 editor_width,
3709 |_| false,
3710 window,
3711 cx,
3712 )
3713 .width
3714 };
3715
3716 let styled_text = highlighted_edits.to_styled_text(&style.text);
3717
3718 let mut element = div()
3719 .bg(cx.theme().colors().editor_background)
3720 .border_1()
3721 .border_color(cx.theme().colors().border)
3722 .rounded_md()
3723 .child(styled_text)
3724 .into_any();
3725
3726 let viewport_bounds = Bounds::new(Default::default(), window.viewport_size())
3727 .extend(Edges {
3728 right: -Self::SCROLLBAR_WIDTH,
3729 ..Default::default()
3730 });
3731
3732 let x_after_longest =
3733 text_bounds.origin.x + longest_line_width + PADDING_X - scroll_pixel_position.x;
3734
3735 let element_bounds = element.layout_as_root(AvailableSpace::min_size(), window, cx);
3736
3737 // Fully visible if it can be displayed within the window (allow overlapping other
3738 // panes). However, this is only allowed if the popover starts within text_bounds.
3739 let is_fully_visible = x_after_longest < text_bounds.right()
3740 && x_after_longest + element_bounds.width < viewport_bounds.right();
3741
3742 let origin = if is_fully_visible {
3743 point(
3744 x_after_longest,
3745 text_bounds.origin.y + edit_start.row().as_f32() * line_height
3746 - scroll_pixel_position.y,
3747 )
3748 } else {
3749 // Avoid overlapping both the edited rows and the user's cursor.
3750 let target_above = DisplayRow(
3751 edit_start
3752 .row()
3753 .0
3754 .min(
3755 newest_selection_head
3756 .map_or(u32::MAX, |cursor_row| cursor_row.row().0),
3757 )
3758 .saturating_sub(line_count as u32),
3759 );
3760 let mut row_target;
3761 if visible_row_range.contains(&DisplayRow(target_above.0.saturating_sub(1))) {
3762 row_target = target_above;
3763 } else {
3764 row_target = DisplayRow(
3765 edit_end.row().0.max(
3766 newest_selection_head.map_or(0, |cursor_row| cursor_row.row().0),
3767 ) + 1,
3768 );
3769 if !visible_row_range.contains(&row_target) {
3770 // Not visible, so fallback on displaying immediately below the cursor.
3771 if let Some(cursor) = newest_selection_head {
3772 row_target = DisplayRow(cursor.row().0 + 1);
3773 } else {
3774 // Not visible and no cursor visible, so fallback on displaying at the top of the editor.
3775 row_target = DisplayRow(0);
3776 }
3777 }
3778 };
3779
3780 text_bounds.origin
3781 + point(
3782 -scroll_pixel_position.x,
3783 row_target.as_f32() * line_height - scroll_pixel_position.y,
3784 )
3785 };
3786
3787 window.defer_draw(element, origin, 1);
3788
3789 // Do not return an element, since it will already be drawn due to defer_draw.
3790 None
3791 }
3792 }
3793 }
3794
3795 fn layout_mouse_context_menu(
3796 &self,
3797 editor_snapshot: &EditorSnapshot,
3798 visible_range: Range<DisplayRow>,
3799 content_origin: gpui::Point<Pixels>,
3800 window: &mut Window,
3801 cx: &mut App,
3802 ) -> Option<AnyElement> {
3803 let position = self.editor.update(cx, |editor, _cx| {
3804 let visible_start_point = editor.display_to_pixel_point(
3805 DisplayPoint::new(visible_range.start, 0),
3806 editor_snapshot,
3807 window,
3808 )?;
3809 let visible_end_point = editor.display_to_pixel_point(
3810 DisplayPoint::new(visible_range.end, 0),
3811 editor_snapshot,
3812 window,
3813 )?;
3814
3815 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3816 let (source_display_point, position) = match mouse_context_menu.position {
3817 MenuPosition::PinnedToScreen(point) => (None, point),
3818 MenuPosition::PinnedToEditor { source, offset } => {
3819 let source_display_point = source.to_display_point(editor_snapshot);
3820 let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
3821 let position = content_origin + source_point + offset;
3822 (Some(source_display_point), position)
3823 }
3824 };
3825
3826 let source_included = source_display_point.map_or(true, |source_display_point| {
3827 visible_range
3828 .to_inclusive()
3829 .contains(&source_display_point.row())
3830 });
3831 let position_included =
3832 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
3833 if !source_included && !position_included {
3834 None
3835 } else {
3836 Some(position)
3837 }
3838 })?;
3839
3840 let mut element = self.editor.update(cx, |editor, _| {
3841 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
3842 let context_menu = mouse_context_menu.context_menu.clone();
3843
3844 Some(
3845 deferred(
3846 anchored()
3847 .position(position)
3848 .child(context_menu)
3849 .anchor(Corner::TopLeft)
3850 .snap_to_window_with_margin(px(8.)),
3851 )
3852 .with_priority(1)
3853 .into_any(),
3854 )
3855 })?;
3856
3857 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
3858 Some(element)
3859 }
3860
3861 #[allow(clippy::too_many_arguments)]
3862 fn layout_hover_popovers(
3863 &self,
3864 snapshot: &EditorSnapshot,
3865 hitbox: &Hitbox,
3866 text_hitbox: &Hitbox,
3867 visible_display_row_range: Range<DisplayRow>,
3868 content_origin: gpui::Point<Pixels>,
3869 scroll_pixel_position: gpui::Point<Pixels>,
3870 line_layouts: &[LineWithInvisibles],
3871 line_height: Pixels,
3872 em_width: Pixels,
3873 window: &mut Window,
3874 cx: &mut App,
3875 ) {
3876 struct MeasuredHoverPopover {
3877 element: AnyElement,
3878 size: Size<Pixels>,
3879 horizontal_offset: Pixels,
3880 }
3881
3882 let max_size = size(
3883 (120. * em_width) // Default size
3884 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
3885 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
3886 (16. * line_height) // Default size
3887 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
3888 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
3889 );
3890
3891 let hover_popovers = self.editor.update(cx, |editor, cx| {
3892 editor
3893 .hover_state
3894 .render(snapshot, visible_display_row_range.clone(), max_size, cx)
3895 });
3896 let Some((position, hover_popovers)) = hover_popovers else {
3897 return;
3898 };
3899
3900 // This is safe because we check on layout whether the required row is available
3901 let hovered_row_layout =
3902 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
3903
3904 // Compute Hovered Point
3905 let x =
3906 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
3907 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
3908 let hovered_point = content_origin + point(x, y);
3909
3910 let mut overall_height = Pixels::ZERO;
3911 let mut measured_hover_popovers = Vec::new();
3912 for mut hover_popover in hover_popovers {
3913 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
3914 let horizontal_offset =
3915 (text_hitbox.top_right().x - (hovered_point.x + size.width)).min(Pixels::ZERO);
3916
3917 overall_height += HOVER_POPOVER_GAP + size.height;
3918
3919 measured_hover_popovers.push(MeasuredHoverPopover {
3920 element: hover_popover,
3921 size,
3922 horizontal_offset,
3923 });
3924 }
3925 overall_height += HOVER_POPOVER_GAP;
3926
3927 fn draw_occluder(
3928 width: Pixels,
3929 origin: gpui::Point<Pixels>,
3930 window: &mut Window,
3931 cx: &mut App,
3932 ) {
3933 let mut occlusion = div()
3934 .size_full()
3935 .occlude()
3936 .on_mouse_move(|_, _, cx| cx.stop_propagation())
3937 .into_any_element();
3938 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
3939 window.defer_draw(occlusion, origin, 2);
3940 }
3941
3942 if hovered_point.y > overall_height {
3943 // There is enough space above. Render popovers above the hovered point
3944 let mut current_y = hovered_point.y;
3945 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3946 let size = popover.size;
3947 let popover_origin = point(
3948 hovered_point.x + popover.horizontal_offset,
3949 current_y - size.height,
3950 );
3951
3952 window.defer_draw(popover.element, popover_origin, 2);
3953 if position != itertools::Position::Last {
3954 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
3955 draw_occluder(size.width, origin, window, cx);
3956 }
3957
3958 current_y = popover_origin.y - HOVER_POPOVER_GAP;
3959 }
3960 } else {
3961 // There is not enough space above. Render popovers below the hovered point
3962 let mut current_y = hovered_point.y + line_height;
3963 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
3964 let size = popover.size;
3965 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
3966
3967 window.defer_draw(popover.element, popover_origin, 2);
3968 if position != itertools::Position::Last {
3969 let origin = point(popover_origin.x, popover_origin.y + size.height);
3970 draw_occluder(size.width, origin, window, cx);
3971 }
3972
3973 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
3974 }
3975 }
3976 }
3977
3978 #[allow(clippy::too_many_arguments)]
3979 fn layout_diff_hunk_controls(
3980 &self,
3981 row_range: Range<DisplayRow>,
3982 row_infos: &[RowInfo],
3983 text_hitbox: &Hitbox,
3984 position_map: &PositionMap,
3985 newest_cursor_position: Option<DisplayPoint>,
3986 line_height: Pixels,
3987 scroll_pixel_position: gpui::Point<Pixels>,
3988 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
3989 editor: Entity<Editor>,
3990 window: &mut Window,
3991 cx: &mut App,
3992 ) -> Vec<AnyElement> {
3993 let point_for_position = position_map.point_for_position(window.mouse_position());
3994
3995 let mut controls = vec![];
3996
3997 let active_positions = [
3998 Some(point_for_position.previous_valid),
3999 newest_cursor_position,
4000 ];
4001
4002 for (hunk, _) in display_hunks {
4003 if let DisplayDiffHunk::Unfolded {
4004 display_row_range,
4005 multi_buffer_range,
4006 status,
4007 ..
4008 } = &hunk
4009 {
4010 if display_row_range.start < row_range.start
4011 || display_row_range.start >= row_range.end
4012 {
4013 continue;
4014 }
4015 let row_ix = (display_row_range.start - row_range.start).0 as usize;
4016 if row_infos[row_ix].diff_status.is_none() {
4017 continue;
4018 }
4019 if row_infos[row_ix].diff_status == Some(DiffHunkStatus::Added)
4020 && *status != DiffHunkStatus::Added
4021 {
4022 continue;
4023 }
4024 if active_positions
4025 .iter()
4026 .any(|p| p.map_or(false, |p| display_row_range.contains(&p.row())))
4027 {
4028 let y = display_row_range.start.as_f32() * line_height
4029 + text_hitbox.bounds.top()
4030 - scroll_pixel_position.y;
4031 let x = text_hitbox.bounds.right() - px(100.);
4032
4033 let mut element = diff_hunk_controls(
4034 display_row_range.start.0,
4035 multi_buffer_range.clone(),
4036 line_height,
4037 &editor,
4038 cx,
4039 );
4040 element.prepaint_as_root(
4041 gpui::Point::new(x, y),
4042 size(px(100.0), line_height).into(),
4043 window,
4044 cx,
4045 );
4046 controls.push(element);
4047 }
4048 }
4049 }
4050
4051 controls
4052 }
4053
4054 #[allow(clippy::too_many_arguments)]
4055 fn layout_signature_help(
4056 &self,
4057 hitbox: &Hitbox,
4058 content_origin: gpui::Point<Pixels>,
4059 scroll_pixel_position: gpui::Point<Pixels>,
4060 newest_selection_head: Option<DisplayPoint>,
4061 start_row: DisplayRow,
4062 line_layouts: &[LineWithInvisibles],
4063 line_height: Pixels,
4064 em_width: Pixels,
4065 window: &mut Window,
4066 cx: &mut App,
4067 ) {
4068 if !self.editor.focus_handle(cx).is_focused(window) {
4069 return;
4070 }
4071 let Some(newest_selection_head) = newest_selection_head else {
4072 return;
4073 };
4074 let selection_row = newest_selection_head.row();
4075 if selection_row < start_row {
4076 return;
4077 }
4078 let Some(cursor_row_layout) = line_layouts.get(selection_row.minus(start_row) as usize)
4079 else {
4080 return;
4081 };
4082
4083 let start_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
4084 - scroll_pixel_position.x
4085 + content_origin.x;
4086 let start_y =
4087 selection_row.as_f32() * line_height + content_origin.y - scroll_pixel_position.y;
4088
4089 let max_size = size(
4090 (120. * em_width) // Default size
4091 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4092 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4093 (16. * line_height) // Default size
4094 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4095 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4096 );
4097
4098 let maybe_element = self.editor.update(cx, |editor, cx| {
4099 if let Some(popover) = editor.signature_help_state.popover_mut() {
4100 let element = popover.render(
4101 &self.style,
4102 max_size,
4103 editor.workspace.as_ref().map(|(w, _)| w.clone()),
4104 cx,
4105 );
4106 Some(element)
4107 } else {
4108 None
4109 }
4110 });
4111 if let Some(mut element) = maybe_element {
4112 let window_size = window.viewport_size();
4113 let size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
4114 let mut point = point(start_x, start_y - size.height);
4115
4116 // Adjusting to ensure the popover does not overflow in the X-axis direction.
4117 if point.x + size.width >= window_size.width {
4118 point.x = window_size.width - size.width;
4119 }
4120
4121 window.defer_draw(element, point, 1)
4122 }
4123 }
4124
4125 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
4126 window.paint_layer(layout.hitbox.bounds, |window| {
4127 let scroll_top = layout.position_map.snapshot.scroll_position().y;
4128 let gutter_bg = cx.theme().colors().editor_gutter_background;
4129 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
4130 window.paint_quad(fill(
4131 layout.position_map.text_hitbox.bounds,
4132 self.style.background,
4133 ));
4134
4135 if let EditorMode::Full = layout.mode {
4136 let mut active_rows = layout.active_rows.iter().peekable();
4137 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
4138 let mut end_row = start_row.0;
4139 while active_rows
4140 .peek()
4141 .map_or(false, |(active_row, has_selection)| {
4142 active_row.0 == end_row + 1
4143 && *has_selection == contains_non_empty_selection
4144 })
4145 {
4146 active_rows.next().unwrap();
4147 end_row += 1;
4148 }
4149
4150 if !contains_non_empty_selection {
4151 let highlight_h_range =
4152 match layout.position_map.snapshot.current_line_highlight {
4153 CurrentLineHighlight::Gutter => Some(Range {
4154 start: layout.hitbox.left(),
4155 end: layout.gutter_hitbox.right(),
4156 }),
4157 CurrentLineHighlight::Line => Some(Range {
4158 start: layout.position_map.text_hitbox.bounds.left(),
4159 end: layout.position_map.text_hitbox.bounds.right(),
4160 }),
4161 CurrentLineHighlight::All => Some(Range {
4162 start: layout.hitbox.left(),
4163 end: layout.hitbox.right(),
4164 }),
4165 CurrentLineHighlight::None => None,
4166 };
4167 if let Some(range) = highlight_h_range {
4168 let active_line_bg = cx.theme().colors().editor_active_line_background;
4169 let bounds = Bounds {
4170 origin: point(
4171 range.start,
4172 layout.hitbox.origin.y
4173 + (start_row.as_f32() - scroll_top)
4174 * layout.position_map.line_height,
4175 ),
4176 size: size(
4177 range.end - range.start,
4178 layout.position_map.line_height
4179 * (end_row - start_row.0 + 1) as f32,
4180 ),
4181 };
4182 window.paint_quad(fill(bounds, active_line_bg));
4183 }
4184 }
4185 }
4186
4187 let mut paint_highlight =
4188 |highlight_row_start: DisplayRow, highlight_row_end: DisplayRow, color| {
4189 let origin = point(
4190 layout.hitbox.origin.x,
4191 layout.hitbox.origin.y
4192 + (highlight_row_start.as_f32() - scroll_top)
4193 * layout.position_map.line_height,
4194 );
4195 let size = size(
4196 layout.hitbox.size.width,
4197 layout.position_map.line_height
4198 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
4199 );
4200 window.paint_quad(fill(Bounds { origin, size }, color));
4201 };
4202
4203 let mut current_paint: Option<(Hsla, Range<DisplayRow>)> = None;
4204 for (&new_row, &new_color) in &layout.highlighted_rows {
4205 match &mut current_paint {
4206 Some((current_color, current_range)) => {
4207 let current_color = *current_color;
4208 let new_range_started = current_color != new_color
4209 || current_range.end.next_row() != new_row;
4210 if new_range_started {
4211 paint_highlight(
4212 current_range.start,
4213 current_range.end,
4214 current_color,
4215 );
4216 current_paint = Some((new_color, new_row..new_row));
4217 continue;
4218 } else {
4219 current_range.end = current_range.end.next_row();
4220 }
4221 }
4222 None => current_paint = Some((new_color, new_row..new_row)),
4223 };
4224 }
4225 if let Some((color, range)) = current_paint {
4226 paint_highlight(range.start, range.end, color);
4227 }
4228
4229 let scroll_left =
4230 layout.position_map.snapshot.scroll_position().x * layout.position_map.em_width;
4231
4232 for (wrap_position, active) in layout.wrap_guides.iter() {
4233 let x = (layout.position_map.text_hitbox.origin.x
4234 + *wrap_position
4235 + layout.position_map.em_width / 2.)
4236 - scroll_left;
4237
4238 let show_scrollbars = {
4239 let (scrollbar_x, scrollbar_y) = &layout.scrollbars_layout.as_xy();
4240
4241 scrollbar_x.as_ref().map_or(false, |sx| sx.visible)
4242 || scrollbar_y.as_ref().map_or(false, |sy| sy.visible)
4243 };
4244
4245 if x < layout.position_map.text_hitbox.origin.x
4246 || (show_scrollbars && x > self.scrollbar_left(&layout.hitbox.bounds))
4247 {
4248 continue;
4249 }
4250
4251 let color = if *active {
4252 cx.theme().colors().editor_active_wrap_guide
4253 } else {
4254 cx.theme().colors().editor_wrap_guide
4255 };
4256 window.paint_quad(fill(
4257 Bounds {
4258 origin: point(x, layout.position_map.text_hitbox.origin.y),
4259 size: size(px(1.), layout.position_map.text_hitbox.size.height),
4260 },
4261 color,
4262 ));
4263 }
4264 }
4265 })
4266 }
4267
4268 fn paint_indent_guides(
4269 &mut self,
4270 layout: &mut EditorLayout,
4271 window: &mut Window,
4272 cx: &mut App,
4273 ) {
4274 let Some(indent_guides) = &layout.indent_guides else {
4275 return;
4276 };
4277
4278 let faded_color = |color: Hsla, alpha: f32| {
4279 let mut faded = color;
4280 faded.a = alpha;
4281 faded
4282 };
4283
4284 for indent_guide in indent_guides {
4285 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
4286 let settings = indent_guide.settings;
4287
4288 // TODO fixed for now, expose them through themes later
4289 const INDENT_AWARE_ALPHA: f32 = 0.2;
4290 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
4291 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
4292 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
4293
4294 let line_color = match (settings.coloring, indent_guide.active) {
4295 (IndentGuideColoring::Disabled, _) => None,
4296 (IndentGuideColoring::Fixed, false) => {
4297 Some(cx.theme().colors().editor_indent_guide)
4298 }
4299 (IndentGuideColoring::Fixed, true) => {
4300 Some(cx.theme().colors().editor_indent_guide_active)
4301 }
4302 (IndentGuideColoring::IndentAware, false) => {
4303 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
4304 }
4305 (IndentGuideColoring::IndentAware, true) => {
4306 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
4307 }
4308 };
4309
4310 let background_color = match (settings.background_coloring, indent_guide.active) {
4311 (IndentGuideBackgroundColoring::Disabled, _) => None,
4312 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
4313 indent_accent_colors,
4314 INDENT_AWARE_BACKGROUND_ALPHA,
4315 )),
4316 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
4317 indent_accent_colors,
4318 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
4319 )),
4320 };
4321
4322 let requested_line_width = if indent_guide.active {
4323 settings.active_line_width
4324 } else {
4325 settings.line_width
4326 }
4327 .clamp(1, 10);
4328 let mut line_indicator_width = 0.;
4329 if let Some(color) = line_color {
4330 window.paint_quad(fill(
4331 Bounds {
4332 origin: indent_guide.origin,
4333 size: size(px(requested_line_width as f32), indent_guide.length),
4334 },
4335 color,
4336 ));
4337 line_indicator_width = requested_line_width as f32;
4338 }
4339
4340 if let Some(color) = background_color {
4341 let width = indent_guide.single_indent_width - px(line_indicator_width);
4342 window.paint_quad(fill(
4343 Bounds {
4344 origin: point(
4345 indent_guide.origin.x + px(line_indicator_width),
4346 indent_guide.origin.y,
4347 ),
4348 size: size(width, indent_guide.length),
4349 },
4350 color,
4351 ));
4352 }
4353 }
4354 }
4355
4356 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4357 let is_singleton = self.editor.read(cx).is_singleton(cx);
4358
4359 let line_height = layout.position_map.line_height;
4360 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
4361
4362 for LineNumberLayout {
4363 shaped_line,
4364 hitbox,
4365 display_row,
4366 } in layout.line_numbers.values()
4367 {
4368 let Some(hitbox) = hitbox else {
4369 continue;
4370 };
4371
4372 let is_active = layout.active_rows.contains_key(&display_row);
4373
4374 let color = if is_active {
4375 cx.theme().colors().editor_active_line_number
4376 } else if !is_singleton && hitbox.is_hovered(window) {
4377 cx.theme().colors().editor_hover_line_number
4378 } else {
4379 cx.theme().colors().editor_line_number
4380 };
4381
4382 let Some(line) = self
4383 .shape_line_number(shaped_line.text.clone(), color, window)
4384 .log_err()
4385 else {
4386 continue;
4387 };
4388 let Some(()) = line.paint(hitbox.origin, line_height, window, cx).log_err() else {
4389 continue;
4390 };
4391 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
4392 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
4393 if is_singleton {
4394 window.set_cursor_style(CursorStyle::IBeam, &hitbox);
4395 } else {
4396 window.set_cursor_style(CursorStyle::PointingHand, &hitbox);
4397 }
4398 }
4399 }
4400
4401 fn paint_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4402 if layout.display_hunks.is_empty() {
4403 return;
4404 }
4405
4406 let line_height = layout.position_map.line_height;
4407 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4408 for (hunk, hitbox) in &layout.display_hunks {
4409 let hunk_to_paint = match hunk {
4410 DisplayDiffHunk::Folded { .. } => {
4411 let hunk_bounds = Self::diff_hunk_bounds(
4412 &layout.position_map.snapshot,
4413 line_height,
4414 layout.gutter_hitbox.bounds,
4415 hunk,
4416 );
4417 Some((
4418 hunk_bounds,
4419 cx.theme().status().modified,
4420 Corners::all(px(0.)),
4421 ))
4422 }
4423 DisplayDiffHunk::Unfolded {
4424 status,
4425 display_row_range,
4426 ..
4427 } => hitbox.as_ref().map(|hunk_hitbox| match status {
4428 DiffHunkStatus::Added => (
4429 hunk_hitbox.bounds,
4430 cx.theme().status().created,
4431 Corners::all(px(0.)),
4432 ),
4433 DiffHunkStatus::Modified => (
4434 hunk_hitbox.bounds,
4435 cx.theme().status().modified,
4436 Corners::all(px(0.)),
4437 ),
4438 DiffHunkStatus::Removed if !display_row_range.is_empty() => (
4439 hunk_hitbox.bounds,
4440 cx.theme().status().deleted,
4441 Corners::all(px(0.)),
4442 ),
4443 DiffHunkStatus::Removed => (
4444 Bounds::new(
4445 point(
4446 hunk_hitbox.origin.x - hunk_hitbox.size.width,
4447 hunk_hitbox.origin.y,
4448 ),
4449 size(hunk_hitbox.size.width * px(2.), hunk_hitbox.size.height),
4450 ),
4451 cx.theme().status().deleted,
4452 Corners::all(1. * line_height),
4453 ),
4454 }),
4455 };
4456
4457 if let Some((hunk_bounds, background_color, corner_radii)) = hunk_to_paint {
4458 window.paint_quad(quad(
4459 hunk_bounds,
4460 corner_radii,
4461 background_color,
4462 Edges::default(),
4463 transparent_black(),
4464 ));
4465 }
4466 }
4467 });
4468 }
4469
4470 fn diff_hunk_bounds(
4471 snapshot: &EditorSnapshot,
4472 line_height: Pixels,
4473 gutter_bounds: Bounds<Pixels>,
4474 hunk: &DisplayDiffHunk,
4475 ) -> Bounds<Pixels> {
4476 let scroll_position = snapshot.scroll_position();
4477 let scroll_top = scroll_position.y * line_height;
4478 let gutter_strip_width = (0.275 * line_height).floor();
4479
4480 match hunk {
4481 DisplayDiffHunk::Folded { display_row, .. } => {
4482 let start_y = display_row.as_f32() * line_height - scroll_top;
4483 let end_y = start_y + line_height;
4484 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4485 let highlight_size = size(gutter_strip_width, end_y - start_y);
4486 Bounds::new(highlight_origin, highlight_size)
4487 }
4488 DisplayDiffHunk::Unfolded {
4489 display_row_range,
4490 status,
4491 ..
4492 } => {
4493 if *status == DiffHunkStatus::Removed && display_row_range.is_empty() {
4494 let row = display_row_range.start;
4495
4496 let offset = line_height / 2.;
4497 let start_y = row.as_f32() * line_height - offset - scroll_top;
4498 let end_y = start_y + line_height;
4499
4500 let width = (0.35 * line_height).floor();
4501 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4502 let highlight_size = size(width, end_y - start_y);
4503 Bounds::new(highlight_origin, highlight_size)
4504 } else {
4505 let start_row = display_row_range.start;
4506 let end_row = display_row_range.end;
4507 // If we're in a multibuffer, row range span might include an
4508 // excerpt header, so if we were to draw the marker straight away,
4509 // the hunk might include the rows of that header.
4510 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
4511 // Instead, we simply check whether the range we're dealing with includes
4512 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
4513 let end_row_in_current_excerpt = snapshot
4514 .blocks_in_range(start_row..end_row)
4515 .find_map(|(start_row, block)| {
4516 if matches!(block, Block::ExcerptBoundary { .. }) {
4517 Some(start_row)
4518 } else {
4519 None
4520 }
4521 })
4522 .unwrap_or(end_row);
4523
4524 let start_y = start_row.as_f32() * line_height - scroll_top;
4525 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
4526
4527 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
4528 let highlight_size = size(gutter_strip_width, end_y - start_y);
4529 Bounds::new(highlight_origin, highlight_size)
4530 }
4531 }
4532 }
4533 }
4534
4535 fn paint_gutter_indicators(
4536 &self,
4537 layout: &mut EditorLayout,
4538 window: &mut Window,
4539 cx: &mut App,
4540 ) {
4541 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4542 window.with_element_namespace("crease_toggles", |window| {
4543 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
4544 crease_toggle.paint(window, cx);
4545 }
4546 });
4547
4548 for test_indicator in layout.test_indicators.iter_mut() {
4549 test_indicator.paint(window, cx);
4550 }
4551
4552 if let Some(indicator) = layout.code_actions_indicator.as_mut() {
4553 indicator.paint(window, cx);
4554 }
4555 });
4556 }
4557
4558 fn paint_gutter_highlights(
4559 &self,
4560 layout: &mut EditorLayout,
4561 window: &mut Window,
4562 cx: &mut App,
4563 ) {
4564 for (_, hunk_hitbox) in &layout.display_hunks {
4565 if let Some(hunk_hitbox) = hunk_hitbox {
4566 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
4567 }
4568 }
4569
4570 let show_git_gutter = layout
4571 .position_map
4572 .snapshot
4573 .show_git_diff_gutter
4574 .unwrap_or_else(|| {
4575 matches!(
4576 ProjectSettings::get_global(cx).git.git_gutter,
4577 Some(GitGutterSetting::TrackedFiles)
4578 )
4579 });
4580 if show_git_gutter {
4581 Self::paint_diff_hunks(layout, window, cx)
4582 }
4583
4584 let highlight_width = 0.275 * layout.position_map.line_height;
4585 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
4586 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4587 for (range, color) in &layout.highlighted_gutter_ranges {
4588 let start_row = if range.start.row() < layout.visible_display_row_range.start {
4589 layout.visible_display_row_range.start - DisplayRow(1)
4590 } else {
4591 range.start.row()
4592 };
4593 let end_row = if range.end.row() > layout.visible_display_row_range.end {
4594 layout.visible_display_row_range.end + DisplayRow(1)
4595 } else {
4596 range.end.row()
4597 };
4598
4599 let start_y = layout.gutter_hitbox.top()
4600 + start_row.0 as f32 * layout.position_map.line_height
4601 - layout.position_map.scroll_pixel_position.y;
4602 let end_y = layout.gutter_hitbox.top()
4603 + (end_row.0 + 1) as f32 * layout.position_map.line_height
4604 - layout.position_map.scroll_pixel_position.y;
4605 let bounds = Bounds::from_corners(
4606 point(layout.gutter_hitbox.left(), start_y),
4607 point(layout.gutter_hitbox.left() + highlight_width, end_y),
4608 );
4609 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
4610 }
4611 });
4612 }
4613
4614 fn paint_blamed_display_rows(
4615 &self,
4616 layout: &mut EditorLayout,
4617 window: &mut Window,
4618 cx: &mut App,
4619 ) {
4620 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
4621 return;
4622 };
4623
4624 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
4625 for mut blame_element in blamed_display_rows.into_iter() {
4626 blame_element.paint(window, cx);
4627 }
4628 })
4629 }
4630
4631 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4632 window.with_content_mask(
4633 Some(ContentMask {
4634 bounds: layout.position_map.text_hitbox.bounds,
4635 }),
4636 |window| {
4637 let cursor_style = if self
4638 .editor
4639 .read(cx)
4640 .hovered_link_state
4641 .as_ref()
4642 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
4643 {
4644 CursorStyle::PointingHand
4645 } else {
4646 CursorStyle::IBeam
4647 };
4648 window.set_cursor_style(cursor_style, &layout.position_map.text_hitbox);
4649
4650 let invisible_display_ranges = self.paint_highlights(layout, window);
4651 self.paint_lines(&invisible_display_ranges, layout, window, cx);
4652 self.paint_redactions(layout, window);
4653 self.paint_cursors(layout, window, cx);
4654 self.paint_inline_blame(layout, window, cx);
4655 self.paint_diff_hunk_controls(layout, window, cx);
4656 window.with_element_namespace("crease_trailers", |window| {
4657 for trailer in layout.crease_trailers.iter_mut().flatten() {
4658 trailer.element.paint(window, cx);
4659 }
4660 });
4661 },
4662 )
4663 }
4664
4665 fn paint_highlights(
4666 &mut self,
4667 layout: &mut EditorLayout,
4668 window: &mut Window,
4669 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
4670 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4671 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
4672 let line_end_overshoot = 0.15 * layout.position_map.line_height;
4673 for (range, color) in &layout.highlighted_ranges {
4674 self.paint_highlighted_range(
4675 range.clone(),
4676 *color,
4677 Pixels::ZERO,
4678 line_end_overshoot,
4679 layout,
4680 window,
4681 );
4682 }
4683
4684 let corner_radius = 0.15 * layout.position_map.line_height;
4685
4686 for (player_color, selections) in &layout.selections {
4687 for selection in selections.iter() {
4688 self.paint_highlighted_range(
4689 selection.range.clone(),
4690 player_color.selection,
4691 corner_radius,
4692 corner_radius * 2.,
4693 layout,
4694 window,
4695 );
4696
4697 if selection.is_local && !selection.range.is_empty() {
4698 invisible_display_ranges.push(selection.range.clone());
4699 }
4700 }
4701 }
4702 invisible_display_ranges
4703 })
4704 }
4705
4706 fn paint_lines(
4707 &mut self,
4708 invisible_display_ranges: &[Range<DisplayPoint>],
4709 layout: &mut EditorLayout,
4710 window: &mut Window,
4711 cx: &mut App,
4712 ) {
4713 let whitespace_setting = self
4714 .editor
4715 .read(cx)
4716 .buffer
4717 .read(cx)
4718 .settings_at(0, cx)
4719 .show_whitespaces;
4720
4721 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
4722 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
4723 line_with_invisibles.draw(
4724 layout,
4725 row,
4726 layout.content_origin,
4727 whitespace_setting,
4728 invisible_display_ranges,
4729 window,
4730 cx,
4731 )
4732 }
4733
4734 for line_element in &mut layout.line_elements {
4735 line_element.paint(window, cx);
4736 }
4737 }
4738
4739 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
4740 if layout.redacted_ranges.is_empty() {
4741 return;
4742 }
4743
4744 let line_end_overshoot = layout.line_end_overshoot();
4745
4746 // A softer than perfect black
4747 let redaction_color = gpui::rgb(0x0e1111);
4748
4749 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
4750 for range in layout.redacted_ranges.iter() {
4751 self.paint_highlighted_range(
4752 range.clone(),
4753 redaction_color.into(),
4754 Pixels::ZERO,
4755 line_end_overshoot,
4756 layout,
4757 window,
4758 );
4759 }
4760 });
4761 }
4762
4763 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4764 for cursor in &mut layout.visible_cursors {
4765 cursor.paint(layout.content_origin, window, cx);
4766 }
4767 }
4768
4769 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
4770 let (scrollbar_x, scrollbar_y) = layout.scrollbars_layout.as_xy();
4771
4772 if let Some(scrollbar_layout) = scrollbar_x {
4773 let hitbox = scrollbar_layout.hitbox.clone();
4774 let text_unit_size = scrollbar_layout.text_unit_size;
4775 let visible_range = scrollbar_layout.visible_range.clone();
4776 let thumb_bounds = scrollbar_layout.thumb_bounds();
4777
4778 if scrollbar_layout.visible {
4779 window.paint_layer(hitbox.bounds, |window| {
4780 window.paint_quad(quad(
4781 hitbox.bounds,
4782 Corners::default(),
4783 cx.theme().colors().scrollbar_track_background,
4784 Edges {
4785 top: Pixels::ZERO,
4786 right: Pixels::ZERO,
4787 bottom: Pixels::ZERO,
4788 left: Pixels::ZERO,
4789 },
4790 cx.theme().colors().scrollbar_track_border,
4791 ));
4792
4793 window.paint_quad(quad(
4794 thumb_bounds,
4795 Corners::default(),
4796 cx.theme().colors().scrollbar_thumb_background,
4797 Edges {
4798 top: Pixels::ZERO,
4799 right: Pixels::ZERO,
4800 bottom: Pixels::ZERO,
4801 left: ScrollbarLayout::BORDER_WIDTH,
4802 },
4803 cx.theme().colors().scrollbar_thumb_border,
4804 ));
4805 })
4806 }
4807
4808 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
4809
4810 window.on_mouse_event({
4811 let editor = self.editor.clone();
4812
4813 // there may be a way to avoid this clone
4814 let hitbox = hitbox.clone();
4815
4816 let mut mouse_position = window.mouse_position();
4817 move |event: &MouseMoveEvent, phase, window, cx| {
4818 if phase == DispatchPhase::Capture {
4819 return;
4820 }
4821
4822 editor.update(cx, |editor, cx| {
4823 if event.pressed_button == Some(MouseButton::Left)
4824 && editor
4825 .scroll_manager
4826 .is_dragging_scrollbar(Axis::Horizontal)
4827 {
4828 let x = mouse_position.x;
4829 let new_x = event.position.x;
4830 if (hitbox.left()..hitbox.right()).contains(&x) {
4831 let mut position = editor.scroll_position(cx);
4832
4833 position.x += (new_x - x) / text_unit_size;
4834 if position.x < 0.0 {
4835 position.x = 0.0;
4836 }
4837 editor.set_scroll_position(position, window, cx);
4838 }
4839
4840 cx.stop_propagation();
4841 } else {
4842 editor.scroll_manager.set_is_dragging_scrollbar(
4843 Axis::Horizontal,
4844 false,
4845 cx,
4846 );
4847
4848 if hitbox.is_hovered(window) {
4849 editor.scroll_manager.show_scrollbar(window, cx);
4850 }
4851 }
4852 mouse_position = event.position;
4853 })
4854 }
4855 });
4856
4857 if self
4858 .editor
4859 .read(cx)
4860 .scroll_manager
4861 .is_dragging_scrollbar(Axis::Horizontal)
4862 {
4863 window.on_mouse_event({
4864 let editor = self.editor.clone();
4865 move |_: &MouseUpEvent, phase, _, cx| {
4866 if phase == DispatchPhase::Capture {
4867 return;
4868 }
4869
4870 editor.update(cx, |editor, cx| {
4871 editor.scroll_manager.set_is_dragging_scrollbar(
4872 Axis::Horizontal,
4873 false,
4874 cx,
4875 );
4876 cx.stop_propagation();
4877 });
4878 }
4879 });
4880 } else {
4881 window.on_mouse_event({
4882 let editor = self.editor.clone();
4883
4884 move |event: &MouseDownEvent, phase, window, cx| {
4885 if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
4886 return;
4887 }
4888
4889 editor.update(cx, |editor, cx| {
4890 editor.scroll_manager.set_is_dragging_scrollbar(
4891 Axis::Horizontal,
4892 true,
4893 cx,
4894 );
4895
4896 let x = event.position.x;
4897
4898 if x < thumb_bounds.left() || thumb_bounds.right() < x {
4899 let center_row =
4900 ((x - hitbox.left()) / text_unit_size).round() as u32;
4901 let top_row = center_row.saturating_sub(
4902 (visible_range.end - visible_range.start) as u32 / 2,
4903 );
4904
4905 let mut position = editor.scroll_position(cx);
4906 position.x = top_row as f32;
4907
4908 editor.set_scroll_position(position, window, cx);
4909 } else {
4910 editor.scroll_manager.show_scrollbar(window, cx);
4911 }
4912
4913 cx.stop_propagation();
4914 });
4915 }
4916 });
4917 }
4918 }
4919
4920 if let Some(scrollbar_layout) = scrollbar_y {
4921 let hitbox = scrollbar_layout.hitbox.clone();
4922 let text_unit_size = scrollbar_layout.text_unit_size;
4923 let visible_range = scrollbar_layout.visible_range.clone();
4924 let thumb_bounds = scrollbar_layout.thumb_bounds();
4925
4926 if scrollbar_layout.visible {
4927 window.paint_layer(hitbox.bounds, |window| {
4928 window.paint_quad(quad(
4929 hitbox.bounds,
4930 Corners::default(),
4931 cx.theme().colors().scrollbar_track_background,
4932 Edges {
4933 top: Pixels::ZERO,
4934 right: Pixels::ZERO,
4935 bottom: Pixels::ZERO,
4936 left: ScrollbarLayout::BORDER_WIDTH,
4937 },
4938 cx.theme().colors().scrollbar_track_border,
4939 ));
4940
4941 let fast_markers =
4942 self.collect_fast_scrollbar_markers(layout, &scrollbar_layout, cx);
4943 // Refresh slow scrollbar markers in the background. Below, we paint whatever markers have already been computed.
4944 self.refresh_slow_scrollbar_markers(layout, &scrollbar_layout, window, cx);
4945
4946 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
4947 for marker in markers.iter().chain(&fast_markers) {
4948 let mut marker = marker.clone();
4949 marker.bounds.origin += hitbox.origin;
4950 window.paint_quad(marker);
4951 }
4952
4953 window.paint_quad(quad(
4954 thumb_bounds,
4955 Corners::default(),
4956 cx.theme().colors().scrollbar_thumb_background,
4957 Edges {
4958 top: Pixels::ZERO,
4959 right: Pixels::ZERO,
4960 bottom: Pixels::ZERO,
4961 left: ScrollbarLayout::BORDER_WIDTH,
4962 },
4963 cx.theme().colors().scrollbar_thumb_border,
4964 ));
4965 });
4966 }
4967
4968 window.set_cursor_style(CursorStyle::Arrow, &hitbox);
4969
4970 window.on_mouse_event({
4971 let editor = self.editor.clone();
4972
4973 let hitbox = hitbox.clone();
4974
4975 let mut mouse_position = window.mouse_position();
4976 move |event: &MouseMoveEvent, phase, window, cx| {
4977 if phase == DispatchPhase::Capture {
4978 return;
4979 }
4980
4981 editor.update(cx, |editor, cx| {
4982 if event.pressed_button == Some(MouseButton::Left)
4983 && editor.scroll_manager.is_dragging_scrollbar(Axis::Vertical)
4984 {
4985 let y = mouse_position.y;
4986 let new_y = event.position.y;
4987 if (hitbox.top()..hitbox.bottom()).contains(&y) {
4988 let mut position = editor.scroll_position(cx);
4989 position.y += (new_y - y) / text_unit_size;
4990 if position.y < 0.0 {
4991 position.y = 0.0;
4992 }
4993 editor.set_scroll_position(position, window, cx);
4994 }
4995 } else {
4996 editor.scroll_manager.set_is_dragging_scrollbar(
4997 Axis::Vertical,
4998 false,
4999 cx,
5000 );
5001
5002 if hitbox.is_hovered(window) {
5003 editor.scroll_manager.show_scrollbar(window, cx);
5004 }
5005 }
5006 mouse_position = event.position;
5007 })
5008 }
5009 });
5010
5011 if self
5012 .editor
5013 .read(cx)
5014 .scroll_manager
5015 .is_dragging_scrollbar(Axis::Vertical)
5016 {
5017 window.on_mouse_event({
5018 let editor = self.editor.clone();
5019 move |_: &MouseUpEvent, phase, _, cx| {
5020 if phase == DispatchPhase::Capture {
5021 return;
5022 }
5023
5024 editor.update(cx, |editor, cx| {
5025 editor.scroll_manager.set_is_dragging_scrollbar(
5026 Axis::Vertical,
5027 false,
5028 cx,
5029 );
5030 cx.stop_propagation();
5031 });
5032 }
5033 });
5034 } else {
5035 window.on_mouse_event({
5036 let editor = self.editor.clone();
5037
5038 move |event: &MouseDownEvent, phase, window, cx| {
5039 if phase == DispatchPhase::Capture || !hitbox.is_hovered(window) {
5040 return;
5041 }
5042
5043 editor.update(cx, |editor, cx| {
5044 editor.scroll_manager.set_is_dragging_scrollbar(
5045 Axis::Vertical,
5046 true,
5047 cx,
5048 );
5049
5050 let y = event.position.y;
5051 if y < thumb_bounds.top() || thumb_bounds.bottom() < y {
5052 let center_row =
5053 ((y - hitbox.top()) / text_unit_size).round() as u32;
5054 let top_row = center_row.saturating_sub(
5055 (visible_range.end - visible_range.start) as u32 / 2,
5056 );
5057 let mut position = editor.scroll_position(cx);
5058 position.y = top_row as f32;
5059 editor.set_scroll_position(position, window, cx);
5060 } else {
5061 editor.scroll_manager.show_scrollbar(window, cx);
5062 }
5063
5064 cx.stop_propagation();
5065 });
5066 }
5067 });
5068 }
5069 }
5070 }
5071
5072 fn collect_fast_scrollbar_markers(
5073 &self,
5074 layout: &EditorLayout,
5075 scrollbar_layout: &ScrollbarLayout,
5076 cx: &mut App,
5077 ) -> Vec<PaintQuad> {
5078 const LIMIT: usize = 100;
5079 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
5080 return vec![];
5081 }
5082 let cursor_ranges = layout
5083 .cursors
5084 .iter()
5085 .map(|(point, color)| ColoredRange {
5086 start: point.row(),
5087 end: point.row(),
5088 color: *color,
5089 })
5090 .collect_vec();
5091 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
5092 }
5093
5094 fn refresh_slow_scrollbar_markers(
5095 &self,
5096 layout: &EditorLayout,
5097 scrollbar_layout: &ScrollbarLayout,
5098 window: &mut Window,
5099 cx: &mut App,
5100 ) {
5101 self.editor.update(cx, |editor, cx| {
5102 if !editor.is_singleton(cx)
5103 || !editor
5104 .scrollbar_marker_state
5105 .should_refresh(scrollbar_layout.hitbox.size)
5106 {
5107 return;
5108 }
5109
5110 let scrollbar_layout = scrollbar_layout.clone();
5111 let background_highlights = editor.background_highlights.clone();
5112 let snapshot = layout.position_map.snapshot.clone();
5113 let theme = cx.theme().clone();
5114 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
5115
5116 editor.scrollbar_marker_state.dirty = false;
5117 editor.scrollbar_marker_state.pending_refresh =
5118 Some(cx.spawn_in(window, |editor, mut cx| async move {
5119 let scrollbar_size = scrollbar_layout.hitbox.size;
5120 let scrollbar_markers = cx
5121 .background_executor()
5122 .spawn(async move {
5123 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
5124 let mut marker_quads = Vec::new();
5125 if scrollbar_settings.git_diff {
5126 let marker_row_ranges =
5127 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
5128 let start_display_row =
5129 MultiBufferPoint::new(hunk.row_range.start.0, 0)
5130 .to_display_point(&snapshot.display_snapshot)
5131 .row();
5132 let mut end_display_row =
5133 MultiBufferPoint::new(hunk.row_range.end.0, 0)
5134 .to_display_point(&snapshot.display_snapshot)
5135 .row();
5136 if end_display_row != start_display_row {
5137 end_display_row.0 -= 1;
5138 }
5139 let color = match &hunk.status() {
5140 DiffHunkStatus::Added => theme.status().created,
5141 DiffHunkStatus::Modified => theme.status().modified,
5142 DiffHunkStatus::Removed => theme.status().deleted,
5143 };
5144 ColoredRange {
5145 start: start_display_row,
5146 end: end_display_row,
5147 color,
5148 }
5149 });
5150
5151 marker_quads.extend(
5152 scrollbar_layout
5153 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
5154 );
5155 }
5156
5157 for (background_highlight_id, (_, background_ranges)) in
5158 background_highlights.iter()
5159 {
5160 let is_search_highlights = *background_highlight_id
5161 == TypeId::of::<BufferSearchHighlights>();
5162 let is_symbol_occurrences = *background_highlight_id
5163 == TypeId::of::<DocumentHighlightRead>()
5164 || *background_highlight_id
5165 == TypeId::of::<DocumentHighlightWrite>();
5166 if (is_search_highlights && scrollbar_settings.search_results)
5167 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
5168 {
5169 let mut color = theme.status().info;
5170 if is_symbol_occurrences {
5171 color.fade_out(0.5);
5172 }
5173 let marker_row_ranges = background_ranges.iter().map(|range| {
5174 let display_start = range
5175 .start
5176 .to_display_point(&snapshot.display_snapshot);
5177 let display_end =
5178 range.end.to_display_point(&snapshot.display_snapshot);
5179 ColoredRange {
5180 start: display_start.row(),
5181 end: display_end.row(),
5182 color,
5183 }
5184 });
5185 marker_quads.extend(
5186 scrollbar_layout
5187 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
5188 );
5189 }
5190 }
5191
5192 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
5193 let diagnostics = snapshot
5194 .buffer_snapshot
5195 .diagnostics_in_range::<Point>(Point::zero()..max_point)
5196 // Don't show diagnostics the user doesn't care about
5197 .filter(|diagnostic| {
5198 match (
5199 scrollbar_settings.diagnostics,
5200 diagnostic.diagnostic.severity,
5201 ) {
5202 (ScrollbarDiagnostics::All, _) => true,
5203 (
5204 ScrollbarDiagnostics::Error,
5205 DiagnosticSeverity::ERROR,
5206 ) => true,
5207 (
5208 ScrollbarDiagnostics::Warning,
5209 DiagnosticSeverity::ERROR
5210 | DiagnosticSeverity::WARNING,
5211 ) => true,
5212 (
5213 ScrollbarDiagnostics::Information,
5214 DiagnosticSeverity::ERROR
5215 | DiagnosticSeverity::WARNING
5216 | DiagnosticSeverity::INFORMATION,
5217 ) => true,
5218 (_, _) => false,
5219 }
5220 })
5221 // We want to sort by severity, in order to paint the most severe diagnostics last.
5222 .sorted_by_key(|diagnostic| {
5223 std::cmp::Reverse(diagnostic.diagnostic.severity)
5224 });
5225
5226 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
5227 let start_display = diagnostic
5228 .range
5229 .start
5230 .to_display_point(&snapshot.display_snapshot);
5231 let end_display = diagnostic
5232 .range
5233 .end
5234 .to_display_point(&snapshot.display_snapshot);
5235 let color = match diagnostic.diagnostic.severity {
5236 DiagnosticSeverity::ERROR => theme.status().error,
5237 DiagnosticSeverity::WARNING => theme.status().warning,
5238 DiagnosticSeverity::INFORMATION => theme.status().info,
5239 _ => theme.status().hint,
5240 };
5241 ColoredRange {
5242 start: start_display.row(),
5243 end: end_display.row(),
5244 color,
5245 }
5246 });
5247 marker_quads.extend(
5248 scrollbar_layout
5249 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
5250 );
5251 }
5252
5253 Arc::from(marker_quads)
5254 })
5255 .await;
5256
5257 editor.update(&mut cx, |editor, cx| {
5258 editor.scrollbar_marker_state.markers = scrollbar_markers;
5259 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
5260 editor.scrollbar_marker_state.pending_refresh = None;
5261 cx.notify();
5262 })?;
5263
5264 Ok(())
5265 }));
5266 });
5267 }
5268
5269 #[allow(clippy::too_many_arguments)]
5270 fn paint_highlighted_range(
5271 &self,
5272 range: Range<DisplayPoint>,
5273 color: Hsla,
5274 corner_radius: Pixels,
5275 line_end_overshoot: Pixels,
5276 layout: &EditorLayout,
5277 window: &mut Window,
5278 ) {
5279 let start_row = layout.visible_display_row_range.start;
5280 let end_row = layout.visible_display_row_range.end;
5281 if range.start != range.end {
5282 let row_range = if range.end.column() == 0 {
5283 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
5284 } else {
5285 cmp::max(range.start.row(), start_row)
5286 ..cmp::min(range.end.row().next_row(), end_row)
5287 };
5288
5289 let highlighted_range = HighlightedRange {
5290 color,
5291 line_height: layout.position_map.line_height,
5292 corner_radius,
5293 start_y: layout.content_origin.y
5294 + row_range.start.as_f32() * layout.position_map.line_height
5295 - layout.position_map.scroll_pixel_position.y,
5296 lines: row_range
5297 .iter_rows()
5298 .map(|row| {
5299 let line_layout =
5300 &layout.position_map.line_layouts[row.minus(start_row) as usize];
5301 HighlightedRangeLine {
5302 start_x: if row == range.start.row() {
5303 layout.content_origin.x
5304 + line_layout.x_for_index(range.start.column() as usize)
5305 - layout.position_map.scroll_pixel_position.x
5306 } else {
5307 layout.content_origin.x
5308 - layout.position_map.scroll_pixel_position.x
5309 },
5310 end_x: if row == range.end.row() {
5311 layout.content_origin.x
5312 + line_layout.x_for_index(range.end.column() as usize)
5313 - layout.position_map.scroll_pixel_position.x
5314 } else {
5315 layout.content_origin.x + line_layout.width + line_end_overshoot
5316 - layout.position_map.scroll_pixel_position.x
5317 },
5318 }
5319 })
5320 .collect(),
5321 };
5322
5323 highlighted_range.paint(layout.position_map.text_hitbox.bounds, window);
5324 }
5325 }
5326
5327 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5328 if let Some(mut inline_blame) = layout.inline_blame.take() {
5329 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
5330 inline_blame.paint(window, cx);
5331 })
5332 }
5333 }
5334
5335 fn paint_diff_hunk_controls(
5336 &mut self,
5337 layout: &mut EditorLayout,
5338 window: &mut Window,
5339 cx: &mut App,
5340 ) {
5341 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
5342 diff_hunk_control.paint(window, cx);
5343 }
5344 }
5345
5346 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5347 for mut block in layout.blocks.drain(..) {
5348 block.element.paint(window, cx);
5349 }
5350 }
5351
5352 fn paint_inline_completion_popover(
5353 &mut self,
5354 layout: &mut EditorLayout,
5355 window: &mut Window,
5356 cx: &mut App,
5357 ) {
5358 if let Some(inline_completion_popover) = layout.inline_completion_popover.as_mut() {
5359 inline_completion_popover.paint(window, cx);
5360 }
5361 }
5362
5363 fn paint_mouse_context_menu(
5364 &mut self,
5365 layout: &mut EditorLayout,
5366 window: &mut Window,
5367 cx: &mut App,
5368 ) {
5369 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
5370 mouse_context_menu.paint(window, cx);
5371 }
5372 }
5373
5374 fn paint_scroll_wheel_listener(
5375 &mut self,
5376 layout: &EditorLayout,
5377 window: &mut Window,
5378 cx: &mut App,
5379 ) {
5380 window.on_mouse_event({
5381 let position_map = layout.position_map.clone();
5382 let editor = self.editor.clone();
5383 let hitbox = layout.hitbox.clone();
5384 let mut delta = ScrollDelta::default();
5385
5386 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
5387 // accidentally turn off their scrolling.
5388 let scroll_sensitivity = EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
5389
5390 move |event: &ScrollWheelEvent, phase, window, cx| {
5391 if phase == DispatchPhase::Bubble && hitbox.is_hovered(window) {
5392 delta = delta.coalesce(event.delta);
5393 editor.update(cx, |editor, cx| {
5394 let position_map: &PositionMap = &position_map;
5395
5396 let line_height = position_map.line_height;
5397 let max_glyph_width = position_map.em_width;
5398 let (delta, axis) = match delta {
5399 gpui::ScrollDelta::Pixels(mut pixels) => {
5400 //Trackpad
5401 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
5402 (pixels, axis)
5403 }
5404
5405 gpui::ScrollDelta::Lines(lines) => {
5406 //Not trackpad
5407 let pixels =
5408 point(lines.x * max_glyph_width, lines.y * line_height);
5409 (pixels, None)
5410 }
5411 };
5412
5413 let current_scroll_position = position_map.snapshot.scroll_position();
5414 let x = (current_scroll_position.x * max_glyph_width
5415 - (delta.x * scroll_sensitivity))
5416 / max_glyph_width;
5417 let y = (current_scroll_position.y * line_height
5418 - (delta.y * scroll_sensitivity))
5419 / line_height;
5420 let mut scroll_position =
5421 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
5422 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
5423 if forbid_vertical_scroll {
5424 scroll_position.y = current_scroll_position.y;
5425 }
5426
5427 if scroll_position != current_scroll_position {
5428 editor.scroll(scroll_position, axis, window, cx);
5429 cx.stop_propagation();
5430 } else if y < 0. {
5431 // Due to clamping, we may fail to detect cases of overscroll to the top;
5432 // We want the scroll manager to get an update in such cases and detect the change of direction
5433 // on the next frame.
5434 cx.notify();
5435 }
5436 });
5437 }
5438 }
5439 });
5440 }
5441
5442 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5443 self.paint_scroll_wheel_listener(layout, window, cx);
5444
5445 window.on_mouse_event({
5446 let position_map = layout.position_map.clone();
5447 let editor = self.editor.clone();
5448 let multi_buffer_range =
5449 layout
5450 .display_hunks
5451 .iter()
5452 .find_map(|(hunk, hunk_hitbox)| match hunk {
5453 DisplayDiffHunk::Folded { .. } => None,
5454 DisplayDiffHunk::Unfolded {
5455 multi_buffer_range, ..
5456 } => {
5457 if hunk_hitbox
5458 .as_ref()
5459 .map(|hitbox| hitbox.is_hovered(window))
5460 .unwrap_or(false)
5461 {
5462 Some(multi_buffer_range.clone())
5463 } else {
5464 None
5465 }
5466 }
5467 });
5468 let line_numbers = layout.line_numbers.clone();
5469
5470 move |event: &MouseDownEvent, phase, window, cx| {
5471 if phase == DispatchPhase::Bubble {
5472 match event.button {
5473 MouseButton::Left => editor.update(cx, |editor, cx| {
5474 let pending_mouse_down = editor
5475 .pending_mouse_down
5476 .get_or_insert_with(Default::default)
5477 .clone();
5478
5479 *pending_mouse_down.borrow_mut() = Some(event.clone());
5480
5481 Self::mouse_left_down(
5482 editor,
5483 event,
5484 multi_buffer_range.clone(),
5485 &position_map,
5486 line_numbers.as_ref(),
5487 window,
5488 cx,
5489 );
5490 }),
5491 MouseButton::Right => editor.update(cx, |editor, cx| {
5492 Self::mouse_right_down(editor, event, &position_map, window, cx);
5493 }),
5494 MouseButton::Middle => editor.update(cx, |editor, cx| {
5495 Self::mouse_middle_down(editor, event, &position_map, window, cx);
5496 }),
5497 _ => {}
5498 };
5499 }
5500 }
5501 });
5502
5503 window.on_mouse_event({
5504 let editor = self.editor.clone();
5505 let position_map = layout.position_map.clone();
5506
5507 move |event: &MouseUpEvent, phase, window, cx| {
5508 if phase == DispatchPhase::Bubble {
5509 editor.update(cx, |editor, cx| {
5510 Self::mouse_up(editor, event, &position_map, window, cx)
5511 });
5512 }
5513 }
5514 });
5515
5516 window.on_mouse_event({
5517 let editor = self.editor.clone();
5518 let position_map = layout.position_map.clone();
5519 let mut captured_mouse_down = None;
5520
5521 move |event: &MouseUpEvent, phase, window, cx| match phase {
5522 // Clear the pending mouse down during the capture phase,
5523 // so that it happens even if another event handler stops
5524 // propagation.
5525 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
5526 let pending_mouse_down = editor
5527 .pending_mouse_down
5528 .get_or_insert_with(Default::default)
5529 .clone();
5530
5531 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
5532 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
5533 captured_mouse_down = pending_mouse_down.take();
5534 window.refresh();
5535 }
5536 }),
5537 // Fire click handlers during the bubble phase.
5538 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
5539 if let Some(mouse_down) = captured_mouse_down.take() {
5540 let event = ClickEvent {
5541 down: mouse_down,
5542 up: event.clone(),
5543 };
5544 Self::click(editor, &event, &position_map, window, cx);
5545 }
5546 }),
5547 }
5548 });
5549
5550 window.on_mouse_event({
5551 let position_map = layout.position_map.clone();
5552 let editor = self.editor.clone();
5553
5554 move |event: &MouseMoveEvent, phase, window, cx| {
5555 if phase == DispatchPhase::Bubble {
5556 editor.update(cx, |editor, cx| {
5557 if editor.hover_state.focused(window, cx) {
5558 return;
5559 }
5560 if event.pressed_button == Some(MouseButton::Left)
5561 || event.pressed_button == Some(MouseButton::Middle)
5562 {
5563 Self::mouse_dragged(editor, event, &position_map, window, cx)
5564 }
5565
5566 Self::mouse_moved(editor, event, &position_map, window, cx)
5567 });
5568 }
5569 }
5570 });
5571 }
5572
5573 fn scrollbar_left(&self, bounds: &Bounds<Pixels>) -> Pixels {
5574 bounds.top_right().x - self.style.scrollbar_width
5575 }
5576
5577 fn column_pixels(&self, column: usize, window: &mut Window, _: &mut App) -> Pixels {
5578 let style = &self.style;
5579 let font_size = style.text.font_size.to_pixels(window.rem_size());
5580 let layout = window
5581 .text_system()
5582 .shape_line(
5583 SharedString::from(" ".repeat(column)),
5584 font_size,
5585 &[TextRun {
5586 len: column,
5587 font: style.text.font(),
5588 color: Hsla::default(),
5589 background_color: None,
5590 underline: None,
5591 strikethrough: None,
5592 }],
5593 )
5594 .unwrap();
5595
5596 layout.width
5597 }
5598
5599 fn max_line_number_width(
5600 &self,
5601 snapshot: &EditorSnapshot,
5602 window: &mut Window,
5603 cx: &mut App,
5604 ) -> Pixels {
5605 let digit_count = (snapshot.widest_line_number() as f32).log10().floor() as usize + 1;
5606 self.column_pixels(digit_count, window, cx)
5607 }
5608
5609 fn shape_line_number(
5610 &self,
5611 text: SharedString,
5612 color: Hsla,
5613 window: &mut Window,
5614 ) -> anyhow::Result<ShapedLine> {
5615 let run = TextRun {
5616 len: text.len(),
5617 font: self.style.text.font(),
5618 color,
5619 background_color: None,
5620 underline: None,
5621 strikethrough: None,
5622 };
5623 window.text_system().shape_line(
5624 text,
5625 self.style.text.font_size.to_pixels(window.rem_size()),
5626 &[run],
5627 )
5628 }
5629}
5630
5631fn header_jump_data(
5632 snapshot: &EditorSnapshot,
5633 block_row_start: DisplayRow,
5634 height: u32,
5635 for_excerpt: &ExcerptInfo,
5636) -> JumpData {
5637 let range = &for_excerpt.range;
5638 let buffer = &for_excerpt.buffer;
5639 let jump_anchor = range
5640 .primary
5641 .as_ref()
5642 .map_or(range.context.start, |primary| primary.start);
5643
5644 let excerpt_start = range.context.start;
5645 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
5646 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
5647 0
5648 } else {
5649 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
5650 jump_position.row.saturating_sub(excerpt_start_point.row)
5651 };
5652
5653 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
5654 .saturating_sub(
5655 snapshot
5656 .scroll_anchor
5657 .scroll_position(&snapshot.display_snapshot)
5658 .y as u32,
5659 );
5660
5661 JumpData::MultiBufferPoint {
5662 excerpt_id: for_excerpt.id,
5663 anchor: jump_anchor,
5664 position: jump_position,
5665 line_offset_from_top,
5666 }
5667}
5668
5669fn inline_completion_accept_indicator(
5670 label: impl Into<SharedString>,
5671 icon: Option<IconName>,
5672 previewing: bool,
5673 editor: &Editor,
5674 window: &mut Window,
5675 cx: &App,
5676) -> Option<AnyElement> {
5677 let accept_binding = editor.accept_edit_prediction_keybind(window, cx);
5678 let accept_keystroke = accept_binding.keystroke()?;
5679
5680 let accept_key = h_flex()
5681 .px_0p5()
5682 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
5683 .text_size(TextSize::XSmall.rems(cx))
5684 .text_color(cx.theme().colors().text)
5685 .gap_1()
5686 .when(!previewing, |parent| {
5687 parent.children(ui::render_modifiers(
5688 &accept_keystroke.modifiers,
5689 PlatformStyle::platform(),
5690 Some(Color::Default),
5691 None,
5692 false,
5693 ))
5694 })
5695 .child(accept_keystroke.key.clone());
5696
5697 let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
5698 let accent_color = cx.theme().colors().text_accent;
5699 let editor_bg_color = cx.theme().colors().editor_background;
5700 let bg_color = editor_bg_color.blend(accent_color.opacity(0.2));
5701
5702 Some(
5703 h_flex()
5704 .py_0p5()
5705 .pl_1()
5706 .pr(padding_right)
5707 .gap_1()
5708 .bg(bg_color)
5709 .border_1()
5710 .border_color(cx.theme().colors().text_accent.opacity(0.8))
5711 .rounded_md()
5712 .shadow_sm()
5713 .child(accept_key)
5714 .child(Label::new(label).size(LabelSize::Small))
5715 .when_some(icon, |element, icon| {
5716 element.child(
5717 div()
5718 .mt(px(1.5))
5719 .child(Icon::new(icon).size(IconSize::Small)),
5720 )
5721 })
5722 .into_any(),
5723 )
5724}
5725
5726pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
5727
5728impl AcceptEditPredictionBinding {
5729 pub fn keystroke(&self) -> Option<&Keystroke> {
5730 if let Some(binding) = self.0.as_ref() {
5731 match &binding.keystrokes() {
5732 [keystroke] => Some(keystroke),
5733 _ => None,
5734 }
5735 } else {
5736 None
5737 }
5738 }
5739}
5740
5741struct AcceptEditPredictionsBindingValidator;
5742
5743inventory::submit! { KeyBindingValidatorRegistration(|| Box::new(AcceptEditPredictionsBindingValidator)) }
5744
5745impl KeyBindingValidator for AcceptEditPredictionsBindingValidator {
5746 fn action_type_id(&self) -> TypeId {
5747 TypeId::of::<AcceptEditPrediction>()
5748 }
5749
5750 fn validate(&self, binding: &gpui::KeyBinding) -> Result<(), MarkdownString> {
5751 use KeyBindingContextPredicate::*;
5752
5753 if binding.keystrokes().len() == 1 && binding.keystrokes()[0].modifiers.modified() {
5754 return Ok(());
5755 }
5756 let required_predicate =
5757 Not(Identifier(EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT.into()).into());
5758 match binding.predicate() {
5759 Some(predicate) if required_predicate.is_superset(&predicate) => {
5760 return Ok(());
5761 }
5762 _ => {}
5763 }
5764 Err(MarkdownString(format!(
5765 "{} can only be bound to a single keystroke with modifiers, so \
5766 that holding down these modifiers can be used to preview \
5767 completions inline when the completions menu is open.\n\n\
5768 This restriction does not apply when the context requires {}, \
5769 since these bindings will not be used when the completions menu \
5770 is open.",
5771 MarkdownString::inline_code(AcceptEditPrediction.name()),
5772 MarkdownString::inline_code(&format!(
5773 "!{}",
5774 EDIT_PREDICTION_REQUIRES_MODIFIER_KEY_CONTEXT
5775 )),
5776 )))
5777 }
5778}
5779
5780#[allow(clippy::too_many_arguments)]
5781fn prepaint_gutter_button(
5782 button: IconButton,
5783 row: DisplayRow,
5784 line_height: Pixels,
5785 gutter_dimensions: &GutterDimensions,
5786 scroll_pixel_position: gpui::Point<Pixels>,
5787 gutter_hitbox: &Hitbox,
5788 rows_with_hunk_bounds: &HashMap<DisplayRow, Bounds<Pixels>>,
5789 window: &mut Window,
5790 cx: &mut App,
5791) -> AnyElement {
5792 let mut button = button.into_any_element();
5793 let available_space = size(
5794 AvailableSpace::MinContent,
5795 AvailableSpace::Definite(line_height),
5796 );
5797 let indicator_size = button.layout_as_root(available_space, window, cx);
5798
5799 let blame_width = gutter_dimensions.git_blame_entries_width;
5800 let gutter_width = rows_with_hunk_bounds
5801 .get(&row)
5802 .map(|bounds| bounds.size.width);
5803 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
5804
5805 let mut x = left_offset;
5806 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
5807 - indicator_size.width
5808 - left_offset;
5809 x += available_width / 2.;
5810
5811 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
5812 y += (line_height - indicator_size.height) / 2.;
5813
5814 button.prepaint_as_root(
5815 gutter_hitbox.origin + point(x, y),
5816 available_space,
5817 window,
5818 cx,
5819 );
5820 button
5821}
5822
5823fn render_inline_blame_entry(
5824 blame: &gpui::Entity<GitBlame>,
5825 blame_entry: BlameEntry,
5826 style: &EditorStyle,
5827 workspace: Option<WeakEntity<Workspace>>,
5828 cx: &mut App,
5829) -> AnyElement {
5830 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5831
5832 let author = blame_entry.author.as_deref().unwrap_or_default();
5833 let summary_enabled = ProjectSettings::get_global(cx)
5834 .git
5835 .show_inline_commit_summary();
5836
5837 let text = match blame_entry.summary.as_ref() {
5838 Some(summary) if summary_enabled => {
5839 format!("{}, {} - {}", author, relative_timestamp, summary)
5840 }
5841 _ => format!("{}, {}", author, relative_timestamp),
5842 };
5843
5844 let details = blame.read(cx).details_for_entry(&blame_entry);
5845
5846 let tooltip = cx.new(|_| BlameEntryTooltip::new(blame_entry, details, style, workspace));
5847
5848 h_flex()
5849 .id("inline-blame")
5850 .w_full()
5851 .font_family(style.text.font().family)
5852 .text_color(cx.theme().status().hint)
5853 .line_height(style.text.line_height)
5854 .child(Icon::new(IconName::FileGit).color(Color::Hint))
5855 .child(text)
5856 .gap_2()
5857 .hoverable_tooltip(move |_, _| tooltip.clone().into())
5858 .into_any()
5859}
5860
5861fn render_blame_entry(
5862 ix: usize,
5863 blame: &gpui::Entity<GitBlame>,
5864 blame_entry: BlameEntry,
5865 style: &EditorStyle,
5866 last_used_color: &mut Option<(PlayerColor, Oid)>,
5867 editor: Entity<Editor>,
5868 cx: &mut App,
5869) -> AnyElement {
5870 let mut sha_color = cx
5871 .theme()
5872 .players()
5873 .color_for_participant(blame_entry.sha.into());
5874 // If the last color we used is the same as the one we get for this line, but
5875 // the commit SHAs are different, then we try again to get a different color.
5876 match *last_used_color {
5877 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
5878 let index: u32 = blame_entry.sha.into();
5879 sha_color = cx.theme().players().color_for_participant(index + 1);
5880 }
5881 _ => {}
5882 };
5883 last_used_color.replace((sha_color, blame_entry.sha));
5884
5885 let relative_timestamp = blame_entry_relative_timestamp(&blame_entry);
5886
5887 let short_commit_id = blame_entry.sha.display_short();
5888
5889 let author_name = blame_entry.author.as_deref().unwrap_or("<no name>");
5890 let name = util::truncate_and_trailoff(author_name, GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED);
5891
5892 let details = blame.read(cx).details_for_entry(&blame_entry);
5893
5894 let workspace = editor.read(cx).workspace.as_ref().map(|(w, _)| w.clone());
5895
5896 let tooltip =
5897 cx.new(|_| BlameEntryTooltip::new(blame_entry.clone(), details.clone(), style, workspace));
5898
5899 h_flex()
5900 .w_full()
5901 .justify_between()
5902 .font_family(style.text.font().family)
5903 .line_height(style.text.line_height)
5904 .id(("blame", ix))
5905 .text_color(cx.theme().status().hint)
5906 .pr_2()
5907 .gap_2()
5908 .child(
5909 h_flex()
5910 .items_center()
5911 .gap_2()
5912 .child(div().text_color(sha_color.cursor).child(short_commit_id))
5913 .child(name),
5914 )
5915 .child(relative_timestamp)
5916 .on_mouse_down(MouseButton::Right, {
5917 let blame_entry = blame_entry.clone();
5918 let details = details.clone();
5919 move |event, window, cx| {
5920 deploy_blame_entry_context_menu(
5921 &blame_entry,
5922 details.as_ref(),
5923 editor.clone(),
5924 event.position,
5925 window,
5926 cx,
5927 );
5928 }
5929 })
5930 .hover(|style| style.bg(cx.theme().colors().element_hover))
5931 .when_some(
5932 details.and_then(|details| details.permalink),
5933 |this, url| {
5934 let url = url.clone();
5935 this.cursor_pointer().on_click(move |_, _, cx| {
5936 cx.stop_propagation();
5937 cx.open_url(url.as_str())
5938 })
5939 },
5940 )
5941 .hoverable_tooltip(move |_, _| tooltip.clone().into())
5942 .into_any()
5943}
5944
5945fn deploy_blame_entry_context_menu(
5946 blame_entry: &BlameEntry,
5947 details: Option<&CommitDetails>,
5948 editor: Entity<Editor>,
5949 position: gpui::Point<Pixels>,
5950 window: &mut Window,
5951 cx: &mut App,
5952) {
5953 let context_menu = ContextMenu::build(window, cx, move |menu, _, _| {
5954 let sha = format!("{}", blame_entry.sha);
5955 menu.on_blur_subscription(Subscription::new(|| {}))
5956 .entry("Copy commit SHA", None, move |_, cx| {
5957 cx.write_to_clipboard(ClipboardItem::new_string(sha.clone()));
5958 })
5959 .when_some(
5960 details.and_then(|details| details.permalink.clone()),
5961 |this, url| {
5962 this.entry("Open permalink", None, move |_, cx| {
5963 cx.open_url(url.as_str())
5964 })
5965 },
5966 )
5967 });
5968
5969 editor.update(cx, move |editor, cx| {
5970 editor.mouse_context_menu = Some(MouseContextMenu::new(
5971 MenuPosition::PinnedToScreen(position),
5972 context_menu,
5973 window,
5974 cx,
5975 ));
5976 cx.notify();
5977 });
5978}
5979
5980#[derive(Debug)]
5981pub(crate) struct LineWithInvisibles {
5982 fragments: SmallVec<[LineFragment; 1]>,
5983 invisibles: Vec<Invisible>,
5984 len: usize,
5985 width: Pixels,
5986 font_size: Pixels,
5987}
5988
5989#[allow(clippy::large_enum_variant)]
5990enum LineFragment {
5991 Text(ShapedLine),
5992 Element {
5993 element: Option<AnyElement>,
5994 size: Size<Pixels>,
5995 len: usize,
5996 },
5997}
5998
5999impl fmt::Debug for LineFragment {
6000 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6001 match self {
6002 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
6003 LineFragment::Element { size, len, .. } => f
6004 .debug_struct("Element")
6005 .field("size", size)
6006 .field("len", len)
6007 .finish(),
6008 }
6009 }
6010}
6011
6012impl LineWithInvisibles {
6013 #[allow(clippy::too_many_arguments)]
6014 fn from_chunks<'a>(
6015 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
6016 editor_style: &EditorStyle,
6017 max_line_len: usize,
6018 max_line_count: usize,
6019 editor_mode: EditorMode,
6020 text_width: Pixels,
6021 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
6022 window: &mut Window,
6023 cx: &mut App,
6024 ) -> Vec<Self> {
6025 let text_style = &editor_style.text;
6026 let mut layouts = Vec::with_capacity(max_line_count);
6027 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
6028 let mut line = String::new();
6029 let mut invisibles = Vec::new();
6030 let mut width = Pixels::ZERO;
6031 let mut len = 0;
6032 let mut styles = Vec::new();
6033 let mut non_whitespace_added = false;
6034 let mut row = 0;
6035 let mut line_exceeded_max_len = false;
6036 let font_size = text_style.font_size.to_pixels(window.rem_size());
6037
6038 let ellipsis = SharedString::from("⋯");
6039
6040 for highlighted_chunk in chunks.chain([HighlightedChunk {
6041 text: "\n",
6042 style: None,
6043 is_tab: false,
6044 replacement: None,
6045 }]) {
6046 if let Some(replacement) = highlighted_chunk.replacement {
6047 if !line.is_empty() {
6048 let shaped_line = window
6049 .text_system()
6050 .shape_line(line.clone().into(), font_size, &styles)
6051 .unwrap();
6052 width += shaped_line.width;
6053 len += shaped_line.len;
6054 fragments.push(LineFragment::Text(shaped_line));
6055 line.clear();
6056 styles.clear();
6057 }
6058
6059 match replacement {
6060 ChunkReplacement::Renderer(renderer) => {
6061 let available_width = if renderer.constrain_width {
6062 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
6063 ellipsis.clone()
6064 } else {
6065 SharedString::from(Arc::from(highlighted_chunk.text))
6066 };
6067 let shaped_line = window
6068 .text_system()
6069 .shape_line(
6070 chunk,
6071 font_size,
6072 &[text_style.to_run(highlighted_chunk.text.len())],
6073 )
6074 .unwrap();
6075 AvailableSpace::Definite(shaped_line.width)
6076 } else {
6077 AvailableSpace::MinContent
6078 };
6079
6080 let mut element = (renderer.render)(&mut ChunkRendererContext {
6081 context: cx,
6082 window,
6083 max_width: text_width,
6084 });
6085 let line_height = text_style.line_height_in_pixels(window.rem_size());
6086 let size = element.layout_as_root(
6087 size(available_width, AvailableSpace::Definite(line_height)),
6088 window,
6089 cx,
6090 );
6091
6092 width += size.width;
6093 len += highlighted_chunk.text.len();
6094 fragments.push(LineFragment::Element {
6095 element: Some(element),
6096 size,
6097 len: highlighted_chunk.text.len(),
6098 });
6099 }
6100 ChunkReplacement::Str(x) => {
6101 let text_style = if let Some(style) = highlighted_chunk.style {
6102 Cow::Owned(text_style.clone().highlight(style))
6103 } else {
6104 Cow::Borrowed(text_style)
6105 };
6106
6107 let run = TextRun {
6108 len: x.len(),
6109 font: text_style.font(),
6110 color: text_style.color,
6111 background_color: text_style.background_color,
6112 underline: text_style.underline,
6113 strikethrough: text_style.strikethrough,
6114 };
6115 let line_layout = window
6116 .text_system()
6117 .shape_line(x, font_size, &[run])
6118 .unwrap()
6119 .with_len(highlighted_chunk.text.len());
6120
6121 width += line_layout.width;
6122 len += highlighted_chunk.text.len();
6123 fragments.push(LineFragment::Text(line_layout))
6124 }
6125 }
6126 } else {
6127 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
6128 if ix > 0 {
6129 let shaped_line = window
6130 .text_system()
6131 .shape_line(line.clone().into(), font_size, &styles)
6132 .unwrap();
6133 width += shaped_line.width;
6134 len += shaped_line.len;
6135 fragments.push(LineFragment::Text(shaped_line));
6136 layouts.push(Self {
6137 width: mem::take(&mut width),
6138 len: mem::take(&mut len),
6139 fragments: mem::take(&mut fragments),
6140 invisibles: std::mem::take(&mut invisibles),
6141 font_size,
6142 });
6143
6144 line.clear();
6145 styles.clear();
6146 row += 1;
6147 line_exceeded_max_len = false;
6148 non_whitespace_added = false;
6149 if row == max_line_count {
6150 return layouts;
6151 }
6152 }
6153
6154 if !line_chunk.is_empty() && !line_exceeded_max_len {
6155 let text_style = if let Some(style) = highlighted_chunk.style {
6156 Cow::Owned(text_style.clone().highlight(style))
6157 } else {
6158 Cow::Borrowed(text_style)
6159 };
6160
6161 if line.len() + line_chunk.len() > max_line_len {
6162 let mut chunk_len = max_line_len - line.len();
6163 while !line_chunk.is_char_boundary(chunk_len) {
6164 chunk_len -= 1;
6165 }
6166 line_chunk = &line_chunk[..chunk_len];
6167 line_exceeded_max_len = true;
6168 }
6169
6170 styles.push(TextRun {
6171 len: line_chunk.len(),
6172 font: text_style.font(),
6173 color: text_style.color,
6174 background_color: text_style.background_color,
6175 underline: text_style.underline,
6176 strikethrough: text_style.strikethrough,
6177 });
6178
6179 if editor_mode == EditorMode::Full {
6180 // Line wrap pads its contents with fake whitespaces,
6181 // avoid printing them
6182 let is_soft_wrapped = is_row_soft_wrapped(row);
6183 if highlighted_chunk.is_tab {
6184 if non_whitespace_added || !is_soft_wrapped {
6185 invisibles.push(Invisible::Tab {
6186 line_start_offset: line.len(),
6187 line_end_offset: line.len() + line_chunk.len(),
6188 });
6189 }
6190 } else {
6191 invisibles.extend(line_chunk.char_indices().filter_map(
6192 |(index, c)| {
6193 let is_whitespace = c.is_whitespace();
6194 non_whitespace_added |= !is_whitespace;
6195 if is_whitespace
6196 && (non_whitespace_added || !is_soft_wrapped)
6197 {
6198 Some(Invisible::Whitespace {
6199 line_offset: line.len() + index,
6200 })
6201 } else {
6202 None
6203 }
6204 },
6205 ))
6206 }
6207 }
6208
6209 line.push_str(line_chunk);
6210 }
6211 }
6212 }
6213 }
6214
6215 layouts
6216 }
6217
6218 #[allow(clippy::too_many_arguments)]
6219 fn prepaint(
6220 &mut self,
6221 line_height: Pixels,
6222 scroll_pixel_position: gpui::Point<Pixels>,
6223 row: DisplayRow,
6224 content_origin: gpui::Point<Pixels>,
6225 line_elements: &mut SmallVec<[AnyElement; 1]>,
6226 window: &mut Window,
6227 cx: &mut App,
6228 ) {
6229 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
6230 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
6231 for fragment in &mut self.fragments {
6232 match fragment {
6233 LineFragment::Text(line) => {
6234 fragment_origin.x += line.width;
6235 }
6236 LineFragment::Element { element, size, .. } => {
6237 let mut element = element
6238 .take()
6239 .expect("you can't prepaint LineWithInvisibles twice");
6240
6241 // Center the element vertically within the line.
6242 let mut element_origin = fragment_origin;
6243 element_origin.y += (line_height - size.height) / 2.;
6244 element.prepaint_at(element_origin, window, cx);
6245 line_elements.push(element);
6246
6247 fragment_origin.x += size.width;
6248 }
6249 }
6250 }
6251 }
6252
6253 #[allow(clippy::too_many_arguments)]
6254 fn draw(
6255 &self,
6256 layout: &EditorLayout,
6257 row: DisplayRow,
6258 content_origin: gpui::Point<Pixels>,
6259 whitespace_setting: ShowWhitespaceSetting,
6260 selection_ranges: &[Range<DisplayPoint>],
6261 window: &mut Window,
6262 cx: &mut App,
6263 ) {
6264 let line_height = layout.position_map.line_height;
6265 let line_y = line_height
6266 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
6267
6268 let mut fragment_origin =
6269 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
6270
6271 for fragment in &self.fragments {
6272 match fragment {
6273 LineFragment::Text(line) => {
6274 line.paint(fragment_origin, line_height, window, cx)
6275 .log_err();
6276 fragment_origin.x += line.width;
6277 }
6278 LineFragment::Element { size, .. } => {
6279 fragment_origin.x += size.width;
6280 }
6281 }
6282 }
6283
6284 self.draw_invisibles(
6285 selection_ranges,
6286 layout,
6287 content_origin,
6288 line_y,
6289 row,
6290 line_height,
6291 whitespace_setting,
6292 window,
6293 cx,
6294 );
6295 }
6296
6297 #[allow(clippy::too_many_arguments)]
6298 fn draw_invisibles(
6299 &self,
6300 selection_ranges: &[Range<DisplayPoint>],
6301 layout: &EditorLayout,
6302 content_origin: gpui::Point<Pixels>,
6303 line_y: Pixels,
6304 row: DisplayRow,
6305 line_height: Pixels,
6306 whitespace_setting: ShowWhitespaceSetting,
6307 window: &mut Window,
6308 cx: &mut App,
6309 ) {
6310 let extract_whitespace_info = |invisible: &Invisible| {
6311 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
6312 Invisible::Tab {
6313 line_start_offset,
6314 line_end_offset,
6315 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
6316 Invisible::Whitespace { line_offset } => {
6317 (*line_offset, line_offset + 1, &layout.space_invisible)
6318 }
6319 };
6320
6321 let x_offset = self.x_for_index(token_offset);
6322 let invisible_offset =
6323 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
6324 let origin = content_origin
6325 + gpui::point(
6326 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
6327 line_y,
6328 );
6329
6330 (
6331 [token_offset, token_end_offset],
6332 Box::new(move |window: &mut Window, cx: &mut App| {
6333 invisible_symbol
6334 .paint(origin, line_height, window, cx)
6335 .log_err();
6336 }),
6337 )
6338 };
6339
6340 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
6341 match whitespace_setting {
6342 ShowWhitespaceSetting::None => (),
6343 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
6344 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
6345 let invisible_point = DisplayPoint::new(row, start as u32);
6346 if !selection_ranges
6347 .iter()
6348 .any(|region| region.start <= invisible_point && invisible_point < region.end)
6349 {
6350 return;
6351 }
6352
6353 paint(window, cx);
6354 }),
6355
6356 // For a whitespace to be on a boundary, any of the following conditions need to be met:
6357 // - It is a tab
6358 // - It is adjacent to an edge (start or end)
6359 // - It is adjacent to a whitespace (left or right)
6360 ShowWhitespaceSetting::Boundary => {
6361 // 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
6362 // the above cases.
6363 // Note: We zip in the original `invisibles` to check for tab equality
6364 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
6365 for (([start, end], paint), invisible) in
6366 invisible_iter.zip_eq(self.invisibles.iter())
6367 {
6368 let should_render = match (&last_seen, invisible) {
6369 (_, Invisible::Tab { .. }) => true,
6370 (Some((_, last_end, _)), _) => *last_end == start,
6371 _ => false,
6372 };
6373
6374 if should_render || start == 0 || end == self.len {
6375 paint(window, cx);
6376
6377 // Since we are scanning from the left, we will skip over the first available whitespace that is part
6378 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
6379 if let Some((should_render_last, last_end, paint_last)) = last_seen {
6380 // Note that we need to make sure that the last one is actually adjacent
6381 if !should_render_last && last_end == start {
6382 paint_last(window, cx);
6383 }
6384 }
6385 }
6386
6387 // Manually render anything within a selection
6388 let invisible_point = DisplayPoint::new(row, start as u32);
6389 if selection_ranges.iter().any(|region| {
6390 region.start <= invisible_point && invisible_point < region.end
6391 }) {
6392 paint(window, cx);
6393 }
6394
6395 last_seen = Some((should_render, end, paint));
6396 }
6397 }
6398 }
6399 }
6400
6401 pub fn x_for_index(&self, index: usize) -> Pixels {
6402 let mut fragment_start_x = Pixels::ZERO;
6403 let mut fragment_start_index = 0;
6404
6405 for fragment in &self.fragments {
6406 match fragment {
6407 LineFragment::Text(shaped_line) => {
6408 let fragment_end_index = fragment_start_index + shaped_line.len;
6409 if index < fragment_end_index {
6410 return fragment_start_x
6411 + shaped_line.x_for_index(index - fragment_start_index);
6412 }
6413 fragment_start_x += shaped_line.width;
6414 fragment_start_index = fragment_end_index;
6415 }
6416 LineFragment::Element { len, size, .. } => {
6417 let fragment_end_index = fragment_start_index + len;
6418 if index < fragment_end_index {
6419 return fragment_start_x;
6420 }
6421 fragment_start_x += size.width;
6422 fragment_start_index = fragment_end_index;
6423 }
6424 }
6425 }
6426
6427 fragment_start_x
6428 }
6429
6430 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
6431 let mut fragment_start_x = Pixels::ZERO;
6432 let mut fragment_start_index = 0;
6433
6434 for fragment in &self.fragments {
6435 match fragment {
6436 LineFragment::Text(shaped_line) => {
6437 let fragment_end_x = fragment_start_x + shaped_line.width;
6438 if x < fragment_end_x {
6439 return Some(
6440 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
6441 );
6442 }
6443 fragment_start_x = fragment_end_x;
6444 fragment_start_index += shaped_line.len;
6445 }
6446 LineFragment::Element { len, size, .. } => {
6447 let fragment_end_x = fragment_start_x + size.width;
6448 if x < fragment_end_x {
6449 return Some(fragment_start_index);
6450 }
6451 fragment_start_index += len;
6452 fragment_start_x = fragment_end_x;
6453 }
6454 }
6455 }
6456
6457 None
6458 }
6459
6460 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
6461 let mut fragment_start_index = 0;
6462
6463 for fragment in &self.fragments {
6464 match fragment {
6465 LineFragment::Text(shaped_line) => {
6466 let fragment_end_index = fragment_start_index + shaped_line.len;
6467 if index < fragment_end_index {
6468 return shaped_line.font_id_for_index(index - fragment_start_index);
6469 }
6470 fragment_start_index = fragment_end_index;
6471 }
6472 LineFragment::Element { len, .. } => {
6473 let fragment_end_index = fragment_start_index + len;
6474 if index < fragment_end_index {
6475 return None;
6476 }
6477 fragment_start_index = fragment_end_index;
6478 }
6479 }
6480 }
6481
6482 None
6483 }
6484}
6485
6486#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6487enum Invisible {
6488 /// A tab character
6489 ///
6490 /// A tab character is internally represented by spaces (configured by the user's tab width)
6491 /// aligned to the nearest column, so it's necessary to store the start and end offset for
6492 /// adjacency checks.
6493 Tab {
6494 line_start_offset: usize,
6495 line_end_offset: usize,
6496 },
6497 Whitespace {
6498 line_offset: usize,
6499 },
6500}
6501
6502impl EditorElement {
6503 /// Returns the rem size to use when rendering the [`EditorElement`].
6504 ///
6505 /// This allows UI elements to scale based on the `buffer_font_size`.
6506 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
6507 match self.editor.read(cx).mode {
6508 EditorMode::Full => {
6509 let buffer_font_size = self.style.text.font_size;
6510 match buffer_font_size {
6511 AbsoluteLength::Pixels(pixels) => {
6512 let rem_size_scale = {
6513 // Our default UI font size is 14px on a 16px base scale.
6514 // This means the default UI font size is 0.875rems.
6515 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
6516
6517 // We then determine the delta between a single rem and the default font
6518 // size scale.
6519 let default_font_size_delta = 1. - default_font_size_scale;
6520
6521 // Finally, we add this delta to 1rem to get the scale factor that
6522 // should be used to scale up the UI.
6523 1. + default_font_size_delta
6524 };
6525
6526 Some(pixels * rem_size_scale)
6527 }
6528 AbsoluteLength::Rems(rems) => {
6529 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
6530 }
6531 }
6532 }
6533 // We currently use single-line and auto-height editors in UI contexts,
6534 // so we don't want to scale everything with the buffer font size, as it
6535 // ends up looking off.
6536 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => None,
6537 }
6538 }
6539}
6540
6541impl Element for EditorElement {
6542 type RequestLayoutState = ();
6543 type PrepaintState = EditorLayout;
6544
6545 fn id(&self) -> Option<ElementId> {
6546 None
6547 }
6548
6549 fn request_layout(
6550 &mut self,
6551 _: Option<&GlobalElementId>,
6552 window: &mut Window,
6553 cx: &mut App,
6554 ) -> (gpui::LayoutId, ()) {
6555 let rem_size = self.rem_size(cx);
6556 window.with_rem_size(rem_size, |window| {
6557 self.editor.update(cx, |editor, cx| {
6558 editor.set_style(self.style.clone(), window, cx);
6559
6560 let layout_id = match editor.mode {
6561 EditorMode::SingleLine { auto_width } => {
6562 let rem_size = window.rem_size();
6563
6564 let height = self.style.text.line_height_in_pixels(rem_size);
6565 if auto_width {
6566 let editor_handle = cx.entity().clone();
6567 let style = self.style.clone();
6568 window.request_measured_layout(
6569 Style::default(),
6570 move |_, _, window, cx| {
6571 let editor_snapshot = editor_handle
6572 .update(cx, |editor, cx| editor.snapshot(window, cx));
6573 let line = Self::layout_lines(
6574 DisplayRow(0)..DisplayRow(1),
6575 &editor_snapshot,
6576 &style,
6577 px(f32::MAX),
6578 |_| false, // Single lines never soft wrap
6579 window,
6580 cx,
6581 )
6582 .pop()
6583 .unwrap();
6584
6585 let font_id =
6586 window.text_system().resolve_font(&style.text.font());
6587 let font_size =
6588 style.text.font_size.to_pixels(window.rem_size());
6589 let em_width =
6590 window.text_system().em_width(font_id, font_size).unwrap();
6591
6592 size(line.width + em_width, height)
6593 },
6594 )
6595 } else {
6596 let mut style = Style::default();
6597 style.size.height = height.into();
6598 style.size.width = relative(1.).into();
6599 window.request_layout(style, None, cx)
6600 }
6601 }
6602 EditorMode::AutoHeight { max_lines } => {
6603 let editor_handle = cx.entity().clone();
6604 let max_line_number_width =
6605 self.max_line_number_width(&editor.snapshot(window, cx), window, cx);
6606 window.request_measured_layout(
6607 Style::default(),
6608 move |known_dimensions, available_space, window, cx| {
6609 editor_handle
6610 .update(cx, |editor, cx| {
6611 compute_auto_height_layout(
6612 editor,
6613 max_lines,
6614 max_line_number_width,
6615 known_dimensions,
6616 available_space.width,
6617 window,
6618 cx,
6619 )
6620 })
6621 .unwrap_or_default()
6622 },
6623 )
6624 }
6625 EditorMode::Full => {
6626 let mut style = Style::default();
6627 style.size.width = relative(1.).into();
6628 style.size.height = relative(1.).into();
6629 window.request_layout(style, None, cx)
6630 }
6631 };
6632
6633 (layout_id, ())
6634 })
6635 })
6636 }
6637
6638 fn prepaint(
6639 &mut self,
6640 _: Option<&GlobalElementId>,
6641 bounds: Bounds<Pixels>,
6642 _: &mut Self::RequestLayoutState,
6643 window: &mut Window,
6644 cx: &mut App,
6645 ) -> Self::PrepaintState {
6646 let text_style = TextStyleRefinement {
6647 font_size: Some(self.style.text.font_size),
6648 line_height: Some(self.style.text.line_height),
6649 ..Default::default()
6650 };
6651 let focus_handle = self.editor.focus_handle(cx);
6652 window.set_view_id(self.editor.entity_id());
6653 window.set_focus_handle(&focus_handle, cx);
6654
6655 let rem_size = self.rem_size(cx);
6656 window.with_rem_size(rem_size, |window| {
6657 window.with_text_style(Some(text_style), |window| {
6658 window.with_content_mask(Some(ContentMask { bounds }), |window| {
6659 let mut snapshot = self
6660 .editor
6661 .update(cx, |editor, cx| editor.snapshot(window, cx));
6662 let style = self.style.clone();
6663
6664 let font_id = window.text_system().resolve_font(&style.text.font());
6665 let font_size = style.text.font_size.to_pixels(window.rem_size());
6666 let line_height = style.text.line_height_in_pixels(window.rem_size());
6667 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
6668 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
6669
6670 let letter_size = size(em_width, line_height);
6671
6672 let gutter_dimensions = snapshot
6673 .gutter_dimensions(
6674 font_id,
6675 font_size,
6676 self.max_line_number_width(&snapshot, window, cx),
6677 cx,
6678 )
6679 .unwrap_or_default();
6680 let text_width = bounds.size.width - gutter_dimensions.width;
6681
6682 let editor_width = text_width - gutter_dimensions.margin - em_width;
6683
6684 snapshot = self.editor.update(cx, |editor, cx| {
6685 editor.last_bounds = Some(bounds);
6686 editor.gutter_dimensions = gutter_dimensions;
6687 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
6688
6689 if matches!(editor.mode, EditorMode::AutoHeight { .. }) {
6690 snapshot
6691 } else {
6692 let wrap_width = match editor.soft_wrap_mode(cx) {
6693 SoftWrap::GitDiff => None,
6694 SoftWrap::None => Some((MAX_LINE_LEN / 2) as f32 * em_advance),
6695 SoftWrap::EditorWidth => Some(editor_width),
6696 SoftWrap::Column(column) => Some(column as f32 * em_advance),
6697 SoftWrap::Bounded(column) => {
6698 Some(editor_width.min(column as f32 * em_advance))
6699 }
6700 };
6701
6702 if editor.set_wrap_width(wrap_width, cx) {
6703 editor.snapshot(window, cx)
6704 } else {
6705 snapshot
6706 }
6707 }
6708 });
6709
6710 let wrap_guides = self
6711 .editor
6712 .read(cx)
6713 .wrap_guides(cx)
6714 .iter()
6715 .map(|(guide, active)| (self.column_pixels(*guide, window, cx), *active))
6716 .collect::<SmallVec<[_; 2]>>();
6717
6718 let hitbox = window.insert_hitbox(bounds, false);
6719 let gutter_hitbox =
6720 window.insert_hitbox(gutter_bounds(bounds, gutter_dimensions), false);
6721 let text_hitbox = window.insert_hitbox(
6722 Bounds {
6723 origin: gutter_hitbox.top_right(),
6724 size: size(text_width, bounds.size.height),
6725 },
6726 false,
6727 );
6728 // Offset the content_bounds from the text_bounds by the gutter margin (which
6729 // is roughly half a character wide) to make hit testing work more like how we want.
6730 let content_origin =
6731 text_hitbox.origin + point(gutter_dimensions.margin, Pixels::ZERO);
6732
6733 let scrollbar_bounds =
6734 Bounds::from_corners(content_origin, bounds.bottom_right());
6735
6736 let height_in_lines = scrollbar_bounds.size.height / line_height;
6737
6738 // NOTE: The max row number in the current file, minus one
6739 let max_row = snapshot.max_point().row().as_f32();
6740
6741 // NOTE: The max scroll position for the top of the window
6742 let max_scroll_top = if matches!(snapshot.mode, EditorMode::AutoHeight { .. }) {
6743 (max_row - height_in_lines + 1.).max(0.)
6744 } else {
6745 let settings = EditorSettings::get_global(cx);
6746 match settings.scroll_beyond_last_line {
6747 ScrollBeyondLastLine::OnePage => max_row,
6748 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
6749 ScrollBeyondLastLine::VerticalScrollMargin => {
6750 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
6751 .max(0.)
6752 }
6753 }
6754 };
6755
6756 // TODO: Autoscrolling for both axes
6757 let mut autoscroll_request = None;
6758 let mut autoscroll_containing_element = false;
6759 let mut autoscroll_horizontally = false;
6760 self.editor.update(cx, |editor, cx| {
6761 autoscroll_request = editor.autoscroll_request();
6762 autoscroll_containing_element =
6763 autoscroll_request.is_some() || editor.has_pending_selection();
6764 // TODO: Is this horizontal or vertical?!
6765 autoscroll_horizontally = editor.autoscroll_vertically(
6766 bounds,
6767 line_height,
6768 max_scroll_top,
6769 window,
6770 cx,
6771 );
6772 snapshot = editor.snapshot(window, cx);
6773 });
6774
6775 let mut scroll_position = snapshot.scroll_position();
6776 // The scroll position is a fractional point, the whole number of which represents
6777 // the top of the window in terms of display rows.
6778 let start_row = DisplayRow(scroll_position.y as u32);
6779 let max_row = snapshot.max_point().row();
6780 let end_row = cmp::min(
6781 (scroll_position.y + height_in_lines).ceil() as u32,
6782 max_row.next_row().0,
6783 );
6784 let end_row = DisplayRow(end_row);
6785
6786 let row_infos = snapshot
6787 .row_infos(start_row)
6788 .take((start_row..end_row).len())
6789 .collect::<Vec<RowInfo>>();
6790 let is_row_soft_wrapped = |row: usize| {
6791 row_infos
6792 .get(row)
6793 .map_or(true, |info| info.buffer_row.is_none())
6794 };
6795
6796 let start_anchor = if start_row == Default::default() {
6797 Anchor::min()
6798 } else {
6799 snapshot.buffer_snapshot.anchor_before(
6800 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
6801 )
6802 };
6803 let end_anchor = if end_row > max_row {
6804 Anchor::max()
6805 } else {
6806 snapshot.buffer_snapshot.anchor_before(
6807 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
6808 )
6809 };
6810
6811 let mut highlighted_rows = self
6812 .editor
6813 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
6814
6815 for (ix, row_info) in row_infos.iter().enumerate() {
6816 let color = match row_info.diff_status {
6817 Some(DiffHunkStatus::Added) => style.status.created_background,
6818 Some(DiffHunkStatus::Removed) => style.status.deleted_background,
6819 _ => continue,
6820 };
6821 highlighted_rows
6822 .entry(start_row + DisplayRow(ix as u32))
6823 .or_insert(color);
6824 }
6825
6826 let highlighted_ranges = self.editor.read(cx).background_highlights_in_range(
6827 start_anchor..end_anchor,
6828 &snapshot.display_snapshot,
6829 cx.theme().colors(),
6830 );
6831 let highlighted_gutter_ranges =
6832 self.editor.read(cx).gutter_highlights_in_range(
6833 start_anchor..end_anchor,
6834 &snapshot.display_snapshot,
6835 cx,
6836 );
6837
6838 let redacted_ranges = self.editor.read(cx).redacted_ranges(
6839 start_anchor..end_anchor,
6840 &snapshot.display_snapshot,
6841 cx,
6842 );
6843
6844 let (local_selections, selected_buffer_ids): (
6845 Vec<Selection<Point>>,
6846 Vec<BufferId>,
6847 ) = self.editor.update(cx, |editor, cx| {
6848 let all_selections = editor.selections.all::<Point>(cx);
6849 let selected_buffer_ids = if editor.is_singleton(cx) {
6850 Vec::new()
6851 } else {
6852 let mut selected_buffer_ids = Vec::with_capacity(all_selections.len());
6853
6854 for selection in all_selections {
6855 for buffer_id in snapshot
6856 .buffer_snapshot
6857 .buffer_ids_for_range(selection.range())
6858 {
6859 if selected_buffer_ids.last() != Some(&buffer_id) {
6860 selected_buffer_ids.push(buffer_id);
6861 }
6862 }
6863 }
6864
6865 selected_buffer_ids
6866 };
6867
6868 let mut selections = editor
6869 .selections
6870 .disjoint_in_range(start_anchor..end_anchor, cx);
6871 selections.extend(editor.selections.pending(cx));
6872
6873 (selections, selected_buffer_ids)
6874 });
6875
6876 let (selections, active_rows, newest_selection_head) = self.layout_selections(
6877 start_anchor,
6878 end_anchor,
6879 &local_selections,
6880 &snapshot,
6881 start_row,
6882 end_row,
6883 window,
6884 cx,
6885 );
6886
6887 let line_numbers = self.layout_line_numbers(
6888 Some(&gutter_hitbox),
6889 gutter_dimensions,
6890 line_height,
6891 scroll_position,
6892 start_row..end_row,
6893 &row_infos,
6894 newest_selection_head,
6895 &snapshot,
6896 window,
6897 cx,
6898 );
6899
6900 let mut crease_toggles =
6901 window.with_element_namespace("crease_toggles", |window| {
6902 self.layout_crease_toggles(
6903 start_row..end_row,
6904 &row_infos,
6905 &active_rows,
6906 &snapshot,
6907 window,
6908 cx,
6909 )
6910 });
6911 let crease_trailers =
6912 window.with_element_namespace("crease_trailers", |window| {
6913 self.layout_crease_trailers(
6914 row_infos.iter().copied(),
6915 &snapshot,
6916 window,
6917 cx,
6918 )
6919 });
6920
6921 let display_hunks = self.layout_gutter_diff_hunks(
6922 line_height,
6923 &gutter_hitbox,
6924 start_row..end_row,
6925 &snapshot,
6926 window,
6927 cx,
6928 );
6929
6930 let mut line_layouts = Self::layout_lines(
6931 start_row..end_row,
6932 &snapshot,
6933 &self.style,
6934 editor_width,
6935 is_row_soft_wrapped,
6936 window,
6937 cx,
6938 );
6939
6940 let longest_line_blame_width = self
6941 .editor
6942 .update(cx, |editor, cx| {
6943 if !editor.show_git_blame_inline {
6944 return None;
6945 }
6946 let blame = editor.blame.as_ref()?;
6947 let blame_entry = blame
6948 .update(cx, |blame, cx| {
6949 let row_infos =
6950 snapshot.row_infos(snapshot.longest_row()).next()?;
6951 blame.blame_for_rows(&[row_infos], cx).next()
6952 })
6953 .flatten()?;
6954 let workspace = editor.workspace.as_ref().map(|(w, _)| w.to_owned());
6955 let mut element = render_inline_blame_entry(
6956 blame,
6957 blame_entry,
6958 &style,
6959 workspace,
6960 cx,
6961 );
6962 let inline_blame_padding = INLINE_BLAME_PADDING_EM_WIDTHS * em_advance;
6963 Some(
6964 element
6965 .layout_as_root(AvailableSpace::min_size(), window, cx)
6966 .width
6967 + inline_blame_padding,
6968 )
6969 })
6970 .unwrap_or(Pixels::ZERO);
6971
6972 let longest_line_width = layout_line(
6973 snapshot.longest_row(),
6974 &snapshot,
6975 &style,
6976 editor_width,
6977 is_row_soft_wrapped,
6978 window,
6979 cx,
6980 )
6981 .width;
6982
6983 let scrollbar_range_data = ScrollbarRangeData::new(
6984 scrollbar_bounds,
6985 letter_size,
6986 &snapshot,
6987 longest_line_width,
6988 longest_line_blame_width,
6989 &style,
6990 cx,
6991 );
6992
6993 let scroll_range_bounds = scrollbar_range_data.scroll_range;
6994 let mut scroll_width = scroll_range_bounds.size.width;
6995
6996 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
6997 snapshot.sticky_header_excerpt(start_row)
6998 } else {
6999 None
7000 };
7001 let sticky_header_excerpt_id =
7002 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
7003
7004 let blocks = window.with_element_namespace("blocks", |window| {
7005 self.render_blocks(
7006 start_row..end_row,
7007 &snapshot,
7008 &hitbox,
7009 &text_hitbox,
7010 editor_width,
7011 &mut scroll_width,
7012 &gutter_dimensions,
7013 em_width,
7014 gutter_dimensions.full_width(),
7015 line_height,
7016 &line_layouts,
7017 &local_selections,
7018 &selected_buffer_ids,
7019 is_row_soft_wrapped,
7020 sticky_header_excerpt_id,
7021 window,
7022 cx,
7023 )
7024 });
7025 let mut blocks = match blocks {
7026 Ok(blocks) => blocks,
7027 Err(resized_blocks) => {
7028 self.editor.update(cx, |editor, cx| {
7029 editor.resize_blocks(resized_blocks, autoscroll_request, cx)
7030 });
7031 return self.prepaint(None, bounds, &mut (), window, cx);
7032 }
7033 };
7034
7035 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
7036 window.with_element_namespace("blocks", |window| {
7037 self.layout_sticky_buffer_header(
7038 sticky_header_excerpt,
7039 scroll_position.y,
7040 line_height,
7041 &snapshot,
7042 &hitbox,
7043 &selected_buffer_ids,
7044 window,
7045 cx,
7046 )
7047 })
7048 });
7049
7050 let start_buffer_row =
7051 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
7052 let end_buffer_row =
7053 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
7054
7055 let scroll_max = point(
7056 ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7057 max_row.as_f32(),
7058 );
7059
7060 self.editor.update(cx, |editor, cx| {
7061 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7062
7063 let autoscrolled = if autoscroll_horizontally {
7064 editor.autoscroll_horizontally(
7065 start_row,
7066 editor_width - (letter_size.width / 2.0),
7067 scroll_width,
7068 em_width,
7069 &line_layouts,
7070 cx,
7071 )
7072 } else {
7073 false
7074 };
7075
7076 if clamped || autoscrolled {
7077 snapshot = editor.snapshot(window, cx);
7078 scroll_position = snapshot.scroll_position();
7079 }
7080 });
7081
7082 let scroll_pixel_position = point(
7083 scroll_position.x * em_width,
7084 scroll_position.y * line_height,
7085 );
7086
7087 let indent_guides = self.layout_indent_guides(
7088 content_origin,
7089 text_hitbox.origin,
7090 start_buffer_row..end_buffer_row,
7091 scroll_pixel_position,
7092 line_height,
7093 &snapshot,
7094 window,
7095 cx,
7096 );
7097
7098 let crease_trailers =
7099 window.with_element_namespace("crease_trailers", |window| {
7100 self.prepaint_crease_trailers(
7101 crease_trailers,
7102 &line_layouts,
7103 line_height,
7104 content_origin,
7105 scroll_pixel_position,
7106 em_width,
7107 window,
7108 cx,
7109 )
7110 });
7111
7112 let mut inline_blame = None;
7113 if let Some(newest_selection_head) = newest_selection_head {
7114 let display_row = newest_selection_head.row();
7115 if (start_row..end_row).contains(&display_row) {
7116 let line_ix = display_row.minus(start_row) as usize;
7117 let row_info = &row_infos[line_ix];
7118 let line_layout = &line_layouts[line_ix];
7119 let crease_trailer_layout = crease_trailers[line_ix].as_ref();
7120 inline_blame = self.layout_inline_blame(
7121 display_row,
7122 row_info,
7123 line_layout,
7124 crease_trailer_layout,
7125 em_width,
7126 content_origin,
7127 scroll_pixel_position,
7128 line_height,
7129 window,
7130 cx,
7131 );
7132 }
7133 }
7134
7135 let blamed_display_rows = self.layout_blame_entries(
7136 &row_infos,
7137 em_width,
7138 scroll_position,
7139 line_height,
7140 &gutter_hitbox,
7141 gutter_dimensions.git_blame_entries_width,
7142 window,
7143 cx,
7144 );
7145
7146 let scroll_max = point(
7147 ((scroll_width - scrollbar_bounds.size.width) / em_width).max(0.0),
7148 max_scroll_top,
7149 );
7150
7151 self.editor.update(cx, |editor, cx| {
7152 let clamped = editor.scroll_manager.clamp_scroll_left(scroll_max.x);
7153
7154 let autoscrolled = if autoscroll_horizontally {
7155 editor.autoscroll_horizontally(
7156 start_row,
7157 editor_width - (letter_size.width / 2.0),
7158 scroll_width,
7159 em_width,
7160 &line_layouts,
7161 cx,
7162 )
7163 } else {
7164 false
7165 };
7166
7167 if clamped || autoscrolled {
7168 snapshot = editor.snapshot(window, cx);
7169 scroll_position = snapshot.scroll_position();
7170 }
7171 });
7172
7173 let line_elements = self.prepaint_lines(
7174 start_row,
7175 &mut line_layouts,
7176 line_height,
7177 scroll_pixel_position,
7178 content_origin,
7179 window,
7180 cx,
7181 );
7182
7183 let mut block_start_rows = HashSet::default();
7184
7185 window.with_element_namespace("blocks", |window| {
7186 self.layout_blocks(
7187 &mut blocks,
7188 &mut block_start_rows,
7189 &hitbox,
7190 line_height,
7191 scroll_pixel_position,
7192 window,
7193 cx,
7194 );
7195 });
7196
7197 let cursors = self.collect_cursors(&snapshot, cx);
7198 let visible_row_range = start_row..end_row;
7199 let non_visible_cursors = cursors
7200 .iter()
7201 .any(move |c| !visible_row_range.contains(&c.0.row()));
7202
7203 let visible_cursors = self.layout_visible_cursors(
7204 &snapshot,
7205 &selections,
7206 &block_start_rows,
7207 start_row..end_row,
7208 &line_layouts,
7209 &text_hitbox,
7210 content_origin,
7211 scroll_position,
7212 scroll_pixel_position,
7213 line_height,
7214 em_width,
7215 em_advance,
7216 autoscroll_containing_element,
7217 window,
7218 cx,
7219 );
7220
7221 let scrollbars_layout = self.layout_scrollbars(
7222 &snapshot,
7223 scrollbar_range_data,
7224 scroll_position,
7225 non_visible_cursors,
7226 window,
7227 cx,
7228 );
7229
7230 let gutter_settings = EditorSettings::get_global(cx).gutter;
7231
7232 let rows_with_hunk_bounds = display_hunks
7233 .iter()
7234 .filter_map(|(hunk, hitbox)| Some((hunk, hitbox.as_ref()?.bounds)))
7235 .fold(
7236 HashMap::default(),
7237 |mut rows_with_hunk_bounds, (hunk, bounds)| {
7238 match hunk {
7239 DisplayDiffHunk::Folded { display_row } => {
7240 rows_with_hunk_bounds.insert(*display_row, bounds);
7241 }
7242 DisplayDiffHunk::Unfolded {
7243 display_row_range, ..
7244 } => {
7245 for display_row in display_row_range.iter_rows() {
7246 rows_with_hunk_bounds.insert(display_row, bounds);
7247 }
7248 }
7249 }
7250 rows_with_hunk_bounds
7251 },
7252 );
7253 let mut code_actions_indicator = None;
7254 if let Some(newest_selection_head) = newest_selection_head {
7255 let newest_selection_point =
7256 newest_selection_head.to_point(&snapshot.display_snapshot);
7257
7258 if (start_row..end_row).contains(&newest_selection_head.row()) {
7259 self.layout_cursor_popovers(
7260 line_height,
7261 &text_hitbox,
7262 content_origin,
7263 start_row,
7264 scroll_pixel_position,
7265 &line_layouts,
7266 newest_selection_head,
7267 newest_selection_point,
7268 &style,
7269 window,
7270 cx,
7271 );
7272
7273 let show_code_actions = snapshot
7274 .show_code_actions
7275 .unwrap_or(gutter_settings.code_actions);
7276 if show_code_actions {
7277 let newest_selection_point =
7278 newest_selection_head.to_point(&snapshot.display_snapshot);
7279 if !snapshot
7280 .is_line_folded(MultiBufferRow(newest_selection_point.row))
7281 {
7282 let buffer = snapshot.buffer_snapshot.buffer_line_for_row(
7283 MultiBufferRow(newest_selection_point.row),
7284 );
7285 if let Some((buffer, range)) = buffer {
7286 let buffer_id = buffer.remote_id();
7287 let row = range.start.row;
7288 let has_test_indicator = self
7289 .editor
7290 .read(cx)
7291 .tasks
7292 .contains_key(&(buffer_id, row));
7293
7294 if !has_test_indicator {
7295 code_actions_indicator = self
7296 .layout_code_actions_indicator(
7297 line_height,
7298 newest_selection_head,
7299 scroll_pixel_position,
7300 &gutter_dimensions,
7301 &gutter_hitbox,
7302 &rows_with_hunk_bounds,
7303 window,
7304 cx,
7305 );
7306 }
7307 }
7308 }
7309 }
7310 }
7311 }
7312
7313 self.layout_gutter_menu(
7314 line_height,
7315 &text_hitbox,
7316 content_origin,
7317 scroll_pixel_position,
7318 gutter_dimensions.width - gutter_dimensions.left_padding,
7319 window,
7320 cx,
7321 );
7322
7323 let test_indicators = if gutter_settings.runnables {
7324 self.layout_run_indicators(
7325 line_height,
7326 start_row..end_row,
7327 scroll_pixel_position,
7328 &gutter_dimensions,
7329 &gutter_hitbox,
7330 &rows_with_hunk_bounds,
7331 &snapshot,
7332 window,
7333 cx,
7334 )
7335 } else {
7336 Vec::new()
7337 };
7338
7339 self.layout_signature_help(
7340 &hitbox,
7341 content_origin,
7342 scroll_pixel_position,
7343 newest_selection_head,
7344 start_row,
7345 &line_layouts,
7346 line_height,
7347 em_width,
7348 window,
7349 cx,
7350 );
7351
7352 if !cx.has_active_drag() {
7353 self.layout_hover_popovers(
7354 &snapshot,
7355 &hitbox,
7356 &text_hitbox,
7357 start_row..end_row,
7358 content_origin,
7359 scroll_pixel_position,
7360 &line_layouts,
7361 line_height,
7362 em_width,
7363 window,
7364 cx,
7365 );
7366 }
7367
7368 let inline_completion_popover = self.layout_inline_completion_popover(
7369 &text_hitbox.bounds,
7370 &snapshot,
7371 start_row..end_row,
7372 scroll_position.y,
7373 scroll_position.y + height_in_lines,
7374 &line_layouts,
7375 line_height,
7376 scroll_pixel_position,
7377 newest_selection_head,
7378 editor_width,
7379 &style,
7380 window,
7381 cx,
7382 );
7383
7384 let mouse_context_menu = self.layout_mouse_context_menu(
7385 &snapshot,
7386 start_row..end_row,
7387 content_origin,
7388 window,
7389 cx,
7390 );
7391
7392 window.with_element_namespace("crease_toggles", |window| {
7393 self.prepaint_crease_toggles(
7394 &mut crease_toggles,
7395 line_height,
7396 &gutter_dimensions,
7397 gutter_settings,
7398 scroll_pixel_position,
7399 &gutter_hitbox,
7400 window,
7401 cx,
7402 )
7403 });
7404
7405 let invisible_symbol_font_size = font_size / 2.;
7406 let tab_invisible = window
7407 .text_system()
7408 .shape_line(
7409 "→".into(),
7410 invisible_symbol_font_size,
7411 &[TextRun {
7412 len: "→".len(),
7413 font: self.style.text.font(),
7414 color: cx.theme().colors().editor_invisible,
7415 background_color: None,
7416 underline: None,
7417 strikethrough: None,
7418 }],
7419 )
7420 .unwrap();
7421 let space_invisible = window
7422 .text_system()
7423 .shape_line(
7424 "•".into(),
7425 invisible_symbol_font_size,
7426 &[TextRun {
7427 len: "•".len(),
7428 font: self.style.text.font(),
7429 color: cx.theme().colors().editor_invisible,
7430 background_color: None,
7431 underline: None,
7432 strikethrough: None,
7433 }],
7434 )
7435 .unwrap();
7436
7437 let mode = snapshot.mode;
7438
7439 let position_map = Rc::new(PositionMap {
7440 size: bounds.size,
7441 scroll_pixel_position,
7442 scroll_max,
7443 line_layouts,
7444 line_height,
7445 em_width,
7446 em_advance,
7447 snapshot,
7448 gutter_hitbox: gutter_hitbox.clone(),
7449 text_hitbox: text_hitbox.clone(),
7450 });
7451
7452 self.editor.update(cx, |editor, _| {
7453 editor.last_position_map = Some(position_map.clone())
7454 });
7455
7456 let hunk_controls = self.layout_diff_hunk_controls(
7457 start_row..end_row,
7458 &row_infos,
7459 &text_hitbox,
7460 &position_map,
7461 newest_selection_head,
7462 line_height,
7463 scroll_pixel_position,
7464 &display_hunks,
7465 self.editor.clone(),
7466 window,
7467 cx,
7468 );
7469
7470 EditorLayout {
7471 mode,
7472 position_map,
7473 visible_display_row_range: start_row..end_row,
7474 wrap_guides,
7475 indent_guides,
7476 hitbox,
7477 gutter_hitbox,
7478 display_hunks,
7479 content_origin,
7480 scrollbars_layout,
7481 active_rows,
7482 highlighted_rows,
7483 highlighted_ranges,
7484 highlighted_gutter_ranges,
7485 redacted_ranges,
7486 line_elements,
7487 line_numbers,
7488 blamed_display_rows,
7489 inline_blame,
7490 blocks,
7491 cursors,
7492 visible_cursors,
7493 selections,
7494 inline_completion_popover,
7495 diff_hunk_controls: hunk_controls,
7496 mouse_context_menu,
7497 test_indicators,
7498 code_actions_indicator,
7499 crease_toggles,
7500 crease_trailers,
7501 tab_invisible,
7502 space_invisible,
7503 sticky_buffer_header,
7504 }
7505 })
7506 })
7507 })
7508 }
7509
7510 fn paint(
7511 &mut self,
7512 _: Option<&GlobalElementId>,
7513 bounds: Bounds<gpui::Pixels>,
7514 _: &mut Self::RequestLayoutState,
7515 layout: &mut Self::PrepaintState,
7516 window: &mut Window,
7517 cx: &mut App,
7518 ) {
7519 let focus_handle = self.editor.focus_handle(cx);
7520 let key_context = self
7521 .editor
7522 .update(cx, |editor, cx| editor.key_context(window, cx));
7523
7524 window.set_key_context(key_context);
7525 window.handle_input(
7526 &focus_handle,
7527 ElementInputHandler::new(bounds, self.editor.clone()),
7528 cx,
7529 );
7530 self.register_actions(window, cx);
7531 self.register_key_listeners(window, cx, layout);
7532
7533 let text_style = TextStyleRefinement {
7534 font_size: Some(self.style.text.font_size),
7535 line_height: Some(self.style.text.line_height),
7536 ..Default::default()
7537 };
7538 let rem_size = self.rem_size(cx);
7539 window.with_rem_size(rem_size, |window| {
7540 window.with_text_style(Some(text_style), |window| {
7541 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7542 self.paint_mouse_listeners(layout, window, cx);
7543 self.paint_background(layout, window, cx);
7544 self.paint_indent_guides(layout, window, cx);
7545
7546 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7547 self.paint_blamed_display_rows(layout, window, cx);
7548 self.paint_line_numbers(layout, window, cx);
7549 }
7550
7551 self.paint_text(layout, window, cx);
7552
7553 if layout.gutter_hitbox.size.width > Pixels::ZERO {
7554 self.paint_gutter_highlights(layout, window, cx);
7555 self.paint_gutter_indicators(layout, window, cx);
7556 }
7557
7558 if !layout.blocks.is_empty() {
7559 window.with_element_namespace("blocks", |window| {
7560 self.paint_blocks(layout, window, cx);
7561 });
7562 }
7563
7564 window.with_element_namespace("blocks", |window| {
7565 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
7566 sticky_header.paint(window, cx)
7567 }
7568 });
7569
7570 self.paint_scrollbars(layout, window, cx);
7571 self.paint_inline_completion_popover(layout, window, cx);
7572 self.paint_mouse_context_menu(layout, window, cx);
7573 });
7574 })
7575 })
7576 }
7577}
7578
7579pub(super) fn gutter_bounds(
7580 editor_bounds: Bounds<Pixels>,
7581 gutter_dimensions: GutterDimensions,
7582) -> Bounds<Pixels> {
7583 Bounds {
7584 origin: editor_bounds.origin,
7585 size: size(gutter_dimensions.width, editor_bounds.size.height),
7586 }
7587}
7588
7589struct ScrollbarRangeData {
7590 scrollbar_bounds: Bounds<Pixels>,
7591 scroll_range: Bounds<Pixels>,
7592 letter_size: Size<Pixels>,
7593}
7594
7595impl ScrollbarRangeData {
7596 pub fn new(
7597 scrollbar_bounds: Bounds<Pixels>,
7598 letter_size: Size<Pixels>,
7599 snapshot: &EditorSnapshot,
7600 longest_line_width: Pixels,
7601 longest_line_blame_width: Pixels,
7602 style: &EditorStyle,
7603
7604 cx: &mut App,
7605 ) -> ScrollbarRangeData {
7606 // TODO: Simplify this function down, it requires a lot of parameters
7607 let max_row = snapshot.max_point().row();
7608 let text_bounds_size = size(longest_line_width, max_row.0 as f32 * letter_size.height);
7609
7610 let scrollbar_width = style.scrollbar_width;
7611
7612 let settings = EditorSettings::get_global(cx);
7613 let scroll_beyond_last_line: Pixels = match settings.scroll_beyond_last_line {
7614 ScrollBeyondLastLine::OnePage => px(scrollbar_bounds.size.height / letter_size.height),
7615 ScrollBeyondLastLine::Off => px(1.),
7616 ScrollBeyondLastLine::VerticalScrollMargin => px(1.0 + settings.vertical_scroll_margin),
7617 };
7618
7619 let overscroll = size(
7620 scrollbar_width + (letter_size.width / 2.0) + longest_line_blame_width,
7621 letter_size.height * scroll_beyond_last_line,
7622 );
7623
7624 let scroll_range = Bounds {
7625 origin: scrollbar_bounds.origin,
7626 size: text_bounds_size + overscroll,
7627 };
7628
7629 ScrollbarRangeData {
7630 scrollbar_bounds,
7631 scroll_range,
7632 letter_size,
7633 }
7634 }
7635}
7636
7637impl IntoElement for EditorElement {
7638 type Element = Self;
7639
7640 fn into_element(self) -> Self::Element {
7641 self
7642 }
7643}
7644
7645pub struct EditorLayout {
7646 position_map: Rc<PositionMap>,
7647 hitbox: Hitbox,
7648 gutter_hitbox: Hitbox,
7649 content_origin: gpui::Point<Pixels>,
7650 scrollbars_layout: AxisPair<Option<ScrollbarLayout>>,
7651 mode: EditorMode,
7652 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
7653 indent_guides: Option<Vec<IndentGuideLayout>>,
7654 visible_display_row_range: Range<DisplayRow>,
7655 active_rows: BTreeMap<DisplayRow, bool>,
7656 highlighted_rows: BTreeMap<DisplayRow, Hsla>,
7657 line_elements: SmallVec<[AnyElement; 1]>,
7658 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
7659 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
7660 blamed_display_rows: Option<Vec<AnyElement>>,
7661 inline_blame: Option<AnyElement>,
7662 blocks: Vec<BlockLayout>,
7663 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7664 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
7665 redacted_ranges: Vec<Range<DisplayPoint>>,
7666 cursors: Vec<(DisplayPoint, Hsla)>,
7667 visible_cursors: Vec<CursorLayout>,
7668 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
7669 code_actions_indicator: Option<AnyElement>,
7670 test_indicators: Vec<AnyElement>,
7671 crease_toggles: Vec<Option<AnyElement>>,
7672 diff_hunk_controls: Vec<AnyElement>,
7673 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
7674 inline_completion_popover: Option<AnyElement>,
7675 mouse_context_menu: Option<AnyElement>,
7676 tab_invisible: ShapedLine,
7677 space_invisible: ShapedLine,
7678 sticky_buffer_header: Option<AnyElement>,
7679}
7680
7681impl EditorLayout {
7682 fn line_end_overshoot(&self) -> Pixels {
7683 0.15 * self.position_map.line_height
7684 }
7685}
7686
7687struct LineNumberLayout {
7688 shaped_line: ShapedLine,
7689 hitbox: Option<Hitbox>,
7690 display_row: DisplayRow,
7691}
7692
7693struct ColoredRange<T> {
7694 start: T,
7695 end: T,
7696 color: Hsla,
7697}
7698
7699#[derive(Clone)]
7700struct ScrollbarLayout {
7701 hitbox: Hitbox,
7702 visible_range: Range<f32>,
7703 visible: bool,
7704 text_unit_size: Pixels,
7705 thumb_size: Pixels,
7706 axis: Axis,
7707}
7708
7709impl ScrollbarLayout {
7710 const BORDER_WIDTH: Pixels = px(1.0);
7711 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
7712 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
7713 // const MIN_THUMB_HEIGHT: Pixels = px(20.0);
7714
7715 fn thumb_bounds(&self) -> Bounds<Pixels> {
7716 match self.axis {
7717 Axis::Vertical => {
7718 let thumb_top = self.y_for_row(self.visible_range.start);
7719 let thumb_bottom = thumb_top + self.thumb_size;
7720 Bounds::from_corners(
7721 point(self.hitbox.left(), thumb_top),
7722 point(self.hitbox.right(), thumb_bottom),
7723 )
7724 }
7725 Axis::Horizontal => {
7726 let thumb_left =
7727 self.hitbox.left() + self.visible_range.start * self.text_unit_size;
7728 let thumb_right = thumb_left + self.thumb_size;
7729 Bounds::from_corners(
7730 point(thumb_left, self.hitbox.top()),
7731 point(thumb_right, self.hitbox.bottom()),
7732 )
7733 }
7734 }
7735 }
7736
7737 fn y_for_row(&self, row: f32) -> Pixels {
7738 self.hitbox.top() + row * self.text_unit_size
7739 }
7740
7741 fn marker_quads_for_ranges(
7742 &self,
7743 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
7744 column: Option<usize>,
7745 ) -> Vec<PaintQuad> {
7746 struct MinMax {
7747 min: Pixels,
7748 max: Pixels,
7749 }
7750 let (x_range, height_limit) = if let Some(column) = column {
7751 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
7752 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
7753 let end = start + column_width;
7754 (
7755 Range { start, end },
7756 MinMax {
7757 min: Self::MIN_MARKER_HEIGHT,
7758 max: px(f32::MAX),
7759 },
7760 )
7761 } else {
7762 (
7763 Range {
7764 start: Self::BORDER_WIDTH,
7765 end: self.hitbox.size.width,
7766 },
7767 MinMax {
7768 min: Self::LINE_MARKER_HEIGHT,
7769 max: Self::LINE_MARKER_HEIGHT,
7770 },
7771 )
7772 };
7773
7774 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
7775 let mut pixel_ranges = row_ranges
7776 .into_iter()
7777 .map(|range| {
7778 let start_y = row_to_y(range.start);
7779 let end_y = row_to_y(range.end)
7780 + self
7781 .text_unit_size
7782 .max(height_limit.min)
7783 .min(height_limit.max);
7784 ColoredRange {
7785 start: start_y,
7786 end: end_y,
7787 color: range.color,
7788 }
7789 })
7790 .peekable();
7791
7792 let mut quads = Vec::new();
7793 while let Some(mut pixel_range) = pixel_ranges.next() {
7794 while let Some(next_pixel_range) = pixel_ranges.peek() {
7795 if pixel_range.end >= next_pixel_range.start - px(1.0)
7796 && pixel_range.color == next_pixel_range.color
7797 {
7798 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
7799 pixel_ranges.next();
7800 } else {
7801 break;
7802 }
7803 }
7804
7805 let bounds = Bounds::from_corners(
7806 point(x_range.start, pixel_range.start),
7807 point(x_range.end, pixel_range.end),
7808 );
7809 quads.push(quad(
7810 bounds,
7811 Corners::default(),
7812 pixel_range.color,
7813 Edges::default(),
7814 Hsla::transparent_black(),
7815 ));
7816 }
7817
7818 quads
7819 }
7820}
7821
7822struct CreaseTrailerLayout {
7823 element: AnyElement,
7824 bounds: Bounds<Pixels>,
7825}
7826
7827pub(crate) struct PositionMap {
7828 pub size: Size<Pixels>,
7829 pub line_height: Pixels,
7830 pub scroll_pixel_position: gpui::Point<Pixels>,
7831 pub scroll_max: gpui::Point<f32>,
7832 pub em_width: Pixels,
7833 pub em_advance: Pixels,
7834 pub line_layouts: Vec<LineWithInvisibles>,
7835 pub snapshot: EditorSnapshot,
7836 pub text_hitbox: Hitbox,
7837 pub gutter_hitbox: Hitbox,
7838}
7839
7840#[derive(Debug, Copy, Clone)]
7841pub struct PointForPosition {
7842 pub previous_valid: DisplayPoint,
7843 pub next_valid: DisplayPoint,
7844 pub exact_unclipped: DisplayPoint,
7845 pub column_overshoot_after_line_end: u32,
7846}
7847
7848impl PointForPosition {
7849 pub fn as_valid(&self) -> Option<DisplayPoint> {
7850 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
7851 Some(self.previous_valid)
7852 } else {
7853 None
7854 }
7855 }
7856}
7857
7858impl PositionMap {
7859 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
7860 let text_bounds = self.text_hitbox.bounds;
7861 let scroll_position = self.snapshot.scroll_position();
7862 let position = position - text_bounds.origin;
7863 let y = position.y.max(px(0.)).min(self.size.height);
7864 let x = position.x + (scroll_position.x * self.em_width);
7865 let row = ((y / self.line_height) + scroll_position.y) as u32;
7866
7867 let (column, x_overshoot_after_line_end) = if let Some(line) = self
7868 .line_layouts
7869 .get(row as usize - scroll_position.y as usize)
7870 {
7871 if let Some(ix) = line.index_for_x(x) {
7872 (ix as u32, px(0.))
7873 } else {
7874 (line.len as u32, px(0.).max(x - line.width))
7875 }
7876 } else {
7877 (0, x)
7878 };
7879
7880 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
7881 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
7882 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
7883
7884 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
7885 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
7886 PointForPosition {
7887 previous_valid,
7888 next_valid,
7889 exact_unclipped,
7890 column_overshoot_after_line_end,
7891 }
7892 }
7893}
7894
7895struct BlockLayout {
7896 id: BlockId,
7897 row: Option<DisplayRow>,
7898 element: AnyElement,
7899 available_space: Size<AvailableSpace>,
7900 style: BlockStyle,
7901}
7902
7903fn layout_line(
7904 row: DisplayRow,
7905 snapshot: &EditorSnapshot,
7906 style: &EditorStyle,
7907 text_width: Pixels,
7908 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
7909 window: &mut Window,
7910 cx: &mut App,
7911) -> LineWithInvisibles {
7912 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
7913 LineWithInvisibles::from_chunks(
7914 chunks,
7915 &style,
7916 MAX_LINE_LEN,
7917 1,
7918 snapshot.mode,
7919 text_width,
7920 is_row_soft_wrapped,
7921 window,
7922 cx,
7923 )
7924 .pop()
7925 .unwrap()
7926}
7927
7928#[derive(Debug)]
7929pub struct IndentGuideLayout {
7930 origin: gpui::Point<Pixels>,
7931 length: Pixels,
7932 single_indent_width: Pixels,
7933 depth: u32,
7934 active: bool,
7935 settings: IndentGuideSettings,
7936}
7937
7938pub struct CursorLayout {
7939 origin: gpui::Point<Pixels>,
7940 block_width: Pixels,
7941 line_height: Pixels,
7942 color: Hsla,
7943 shape: CursorShape,
7944 block_text: Option<ShapedLine>,
7945 cursor_name: Option<AnyElement>,
7946}
7947
7948#[derive(Debug)]
7949pub struct CursorName {
7950 string: SharedString,
7951 color: Hsla,
7952 is_top_row: bool,
7953}
7954
7955impl CursorLayout {
7956 pub fn new(
7957 origin: gpui::Point<Pixels>,
7958 block_width: Pixels,
7959 line_height: Pixels,
7960 color: Hsla,
7961 shape: CursorShape,
7962 block_text: Option<ShapedLine>,
7963 ) -> CursorLayout {
7964 CursorLayout {
7965 origin,
7966 block_width,
7967 line_height,
7968 color,
7969 shape,
7970 block_text,
7971 cursor_name: None,
7972 }
7973 }
7974
7975 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
7976 Bounds {
7977 origin: self.origin + origin,
7978 size: size(self.block_width, self.line_height),
7979 }
7980 }
7981
7982 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
7983 match self.shape {
7984 CursorShape::Bar => Bounds {
7985 origin: self.origin + origin,
7986 size: size(px(2.0), self.line_height),
7987 },
7988 CursorShape::Block | CursorShape::Hollow => Bounds {
7989 origin: self.origin + origin,
7990 size: size(self.block_width, self.line_height),
7991 },
7992 CursorShape::Underline => Bounds {
7993 origin: self.origin
7994 + origin
7995 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
7996 size: size(self.block_width, px(2.0)),
7997 },
7998 }
7999 }
8000
8001 pub fn layout(
8002 &mut self,
8003 origin: gpui::Point<Pixels>,
8004 cursor_name: Option<CursorName>,
8005 window: &mut Window,
8006 cx: &mut App,
8007 ) {
8008 if let Some(cursor_name) = cursor_name {
8009 let bounds = self.bounds(origin);
8010 let text_size = self.line_height / 1.5;
8011
8012 let name_origin = if cursor_name.is_top_row {
8013 point(bounds.right() - px(1.), bounds.top())
8014 } else {
8015 match self.shape {
8016 CursorShape::Bar => point(
8017 bounds.right() - px(2.),
8018 bounds.top() - text_size / 2. - px(1.),
8019 ),
8020 _ => point(
8021 bounds.right() - px(1.),
8022 bounds.top() - text_size / 2. - px(1.),
8023 ),
8024 }
8025 };
8026 let mut name_element = div()
8027 .bg(self.color)
8028 .text_size(text_size)
8029 .px_0p5()
8030 .line_height(text_size + px(2.))
8031 .text_color(cursor_name.color)
8032 .child(cursor_name.string.clone())
8033 .into_any_element();
8034
8035 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
8036
8037 self.cursor_name = Some(name_element);
8038 }
8039 }
8040
8041 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
8042 let bounds = self.bounds(origin);
8043
8044 //Draw background or border quad
8045 let cursor = if matches!(self.shape, CursorShape::Hollow) {
8046 outline(bounds, self.color)
8047 } else {
8048 fill(bounds, self.color)
8049 };
8050
8051 if let Some(name) = &mut self.cursor_name {
8052 name.paint(window, cx);
8053 }
8054
8055 window.paint_quad(cursor);
8056
8057 if let Some(block_text) = &self.block_text {
8058 block_text
8059 .paint(self.origin + origin, self.line_height, window, cx)
8060 .log_err();
8061 }
8062 }
8063
8064 pub fn shape(&self) -> CursorShape {
8065 self.shape
8066 }
8067}
8068
8069#[derive(Debug)]
8070pub struct HighlightedRange {
8071 pub start_y: Pixels,
8072 pub line_height: Pixels,
8073 pub lines: Vec<HighlightedRangeLine>,
8074 pub color: Hsla,
8075 pub corner_radius: Pixels,
8076}
8077
8078#[derive(Debug)]
8079pub struct HighlightedRangeLine {
8080 pub start_x: Pixels,
8081 pub end_x: Pixels,
8082}
8083
8084impl HighlightedRange {
8085 pub fn paint(&self, bounds: Bounds<Pixels>, window: &mut Window) {
8086 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
8087 self.paint_lines(self.start_y, &self.lines[0..1], bounds, window);
8088 self.paint_lines(
8089 self.start_y + self.line_height,
8090 &self.lines[1..],
8091 bounds,
8092 window,
8093 );
8094 } else {
8095 self.paint_lines(self.start_y, &self.lines, bounds, window);
8096 }
8097 }
8098
8099 fn paint_lines(
8100 &self,
8101 start_y: Pixels,
8102 lines: &[HighlightedRangeLine],
8103 _bounds: Bounds<Pixels>,
8104 window: &mut Window,
8105 ) {
8106 if lines.is_empty() {
8107 return;
8108 }
8109
8110 let first_line = lines.first().unwrap();
8111 let last_line = lines.last().unwrap();
8112
8113 let first_top_left = point(first_line.start_x, start_y);
8114 let first_top_right = point(first_line.end_x, start_y);
8115
8116 let curve_height = point(Pixels::ZERO, self.corner_radius);
8117 let curve_width = |start_x: Pixels, end_x: Pixels| {
8118 let max = (end_x - start_x) / 2.;
8119 let width = if max < self.corner_radius {
8120 max
8121 } else {
8122 self.corner_radius
8123 };
8124
8125 point(width, Pixels::ZERO)
8126 };
8127
8128 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
8129 let mut builder = gpui::PathBuilder::fill();
8130 builder.move_to(first_top_right - top_curve_width);
8131 builder.curve_to(first_top_right + curve_height, first_top_right);
8132
8133 let mut iter = lines.iter().enumerate().peekable();
8134 while let Some((ix, line)) = iter.next() {
8135 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
8136
8137 if let Some((_, next_line)) = iter.peek() {
8138 let next_top_right = point(next_line.end_x, bottom_right.y);
8139
8140 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
8141 Ordering::Equal => {
8142 builder.line_to(bottom_right);
8143 }
8144 Ordering::Less => {
8145 let curve_width = curve_width(next_top_right.x, bottom_right.x);
8146 builder.line_to(bottom_right - curve_height);
8147 if self.corner_radius > Pixels::ZERO {
8148 builder.curve_to(bottom_right - curve_width, bottom_right);
8149 }
8150 builder.line_to(next_top_right + curve_width);
8151 if self.corner_radius > Pixels::ZERO {
8152 builder.curve_to(next_top_right + curve_height, next_top_right);
8153 }
8154 }
8155 Ordering::Greater => {
8156 let curve_width = curve_width(bottom_right.x, next_top_right.x);
8157 builder.line_to(bottom_right - curve_height);
8158 if self.corner_radius > Pixels::ZERO {
8159 builder.curve_to(bottom_right + curve_width, bottom_right);
8160 }
8161 builder.line_to(next_top_right - curve_width);
8162 if self.corner_radius > Pixels::ZERO {
8163 builder.curve_to(next_top_right + curve_height, next_top_right);
8164 }
8165 }
8166 }
8167 } else {
8168 let curve_width = curve_width(line.start_x, line.end_x);
8169 builder.line_to(bottom_right - curve_height);
8170 if self.corner_radius > Pixels::ZERO {
8171 builder.curve_to(bottom_right - curve_width, bottom_right);
8172 }
8173
8174 let bottom_left = point(line.start_x, bottom_right.y);
8175 builder.line_to(bottom_left + curve_width);
8176 if self.corner_radius > Pixels::ZERO {
8177 builder.curve_to(bottom_left - curve_height, bottom_left);
8178 }
8179 }
8180 }
8181
8182 if first_line.start_x > last_line.start_x {
8183 let curve_width = curve_width(last_line.start_x, first_line.start_x);
8184 let second_top_left = point(last_line.start_x, start_y + self.line_height);
8185 builder.line_to(second_top_left + curve_height);
8186 if self.corner_radius > Pixels::ZERO {
8187 builder.curve_to(second_top_left + curve_width, second_top_left);
8188 }
8189 let first_bottom_left = point(first_line.start_x, second_top_left.y);
8190 builder.line_to(first_bottom_left - curve_width);
8191 if self.corner_radius > Pixels::ZERO {
8192 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
8193 }
8194 }
8195
8196 builder.line_to(first_top_left + curve_height);
8197 if self.corner_radius > Pixels::ZERO {
8198 builder.curve_to(first_top_left + top_curve_width, first_top_left);
8199 }
8200 builder.line_to(first_top_right - top_curve_width);
8201
8202 if let Ok(path) = builder.build() {
8203 window.paint_path(path, self.color);
8204 }
8205 }
8206}
8207
8208enum CursorPopoverType {
8209 CodeContextMenu,
8210 EditPrediction,
8211}
8212
8213pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8214 (delta.pow(1.5) / 100.0).into()
8215}
8216
8217fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
8218 (delta.pow(1.2) / 300.0).into()
8219}
8220
8221pub fn register_action<T: Action>(
8222 editor: &Entity<Editor>,
8223 window: &mut Window,
8224 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
8225) {
8226 let editor = editor.clone();
8227 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
8228 let action = action.downcast_ref().unwrap();
8229 if phase == DispatchPhase::Bubble {
8230 editor.update(cx, |editor, cx| {
8231 listener(editor, action, window, cx);
8232 })
8233 }
8234 })
8235}
8236
8237fn compute_auto_height_layout(
8238 editor: &mut Editor,
8239 max_lines: usize,
8240 max_line_number_width: Pixels,
8241 known_dimensions: Size<Option<Pixels>>,
8242 available_width: AvailableSpace,
8243 window: &mut Window,
8244 cx: &mut Context<Editor>,
8245) -> Option<Size<Pixels>> {
8246 let width = known_dimensions.width.or({
8247 if let AvailableSpace::Definite(available_width) = available_width {
8248 Some(available_width)
8249 } else {
8250 None
8251 }
8252 })?;
8253 if let Some(height) = known_dimensions.height {
8254 return Some(size(width, height));
8255 }
8256
8257 let style = editor.style.as_ref().unwrap();
8258 let font_id = window.text_system().resolve_font(&style.text.font());
8259 let font_size = style.text.font_size.to_pixels(window.rem_size());
8260 let line_height = style.text.line_height_in_pixels(window.rem_size());
8261 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8262
8263 let mut snapshot = editor.snapshot(window, cx);
8264 let gutter_dimensions = snapshot
8265 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
8266 .unwrap_or_default();
8267
8268 editor.gutter_dimensions = gutter_dimensions;
8269 let text_width = width - gutter_dimensions.width;
8270 let overscroll = size(em_width, px(0.));
8271
8272 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
8273 if editor.set_wrap_width(Some(editor_width), cx) {
8274 snapshot = editor.snapshot(window, cx);
8275 }
8276
8277 let scroll_height = Pixels::from(snapshot.max_point().row().next_row().0) * line_height;
8278 let height = scroll_height
8279 .max(line_height)
8280 .min(line_height * max_lines as f32);
8281
8282 Some(size(width, height))
8283}
8284
8285#[cfg(test)]
8286mod tests {
8287 use super::*;
8288 use crate::{
8289 display_map::{BlockPlacement, BlockProperties},
8290 editor_tests::{init_test, update_test_language_settings},
8291 Editor, MultiBuffer,
8292 };
8293 use gpui::{TestAppContext, VisualTestContext};
8294 use language::language_settings;
8295 use log::info;
8296 use similar::DiffableStr;
8297 use std::num::NonZeroU32;
8298 use util::test::sample_text;
8299
8300 #[gpui::test]
8301 fn test_shape_line_numbers(cx: &mut TestAppContext) {
8302 init_test(cx, |_| {});
8303 let window = cx.add_window(|window, cx| {
8304 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
8305 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8306 });
8307
8308 let editor = window.root(cx).unwrap();
8309 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
8310 let line_height = window
8311 .update(cx, |_, window, _| {
8312 style.text.line_height_in_pixels(window.rem_size())
8313 })
8314 .unwrap();
8315 let element = EditorElement::new(&editor, style);
8316 let snapshot = window
8317 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
8318 .unwrap();
8319
8320 let layouts = cx
8321 .update_window(*window, |_, window, cx| {
8322 element.layout_line_numbers(
8323 None,
8324 GutterDimensions {
8325 left_padding: Pixels::ZERO,
8326 right_padding: Pixels::ZERO,
8327 width: px(30.0),
8328 margin: Pixels::ZERO,
8329 git_blame_entries_width: None,
8330 },
8331 line_height,
8332 gpui::Point::default(),
8333 DisplayRow(0)..DisplayRow(6),
8334 &(0..6)
8335 .map(|row| RowInfo {
8336 buffer_row: Some(row),
8337 ..Default::default()
8338 })
8339 .collect::<Vec<_>>(),
8340 Some(DisplayPoint::new(DisplayRow(0), 0)),
8341 &snapshot,
8342 window,
8343 cx,
8344 )
8345 })
8346 .unwrap();
8347 assert_eq!(layouts.len(), 6);
8348
8349 let relative_rows = window
8350 .update(cx, |editor, window, cx| {
8351 let snapshot = editor.snapshot(window, cx);
8352 element.calculate_relative_line_numbers(
8353 &snapshot,
8354 &(DisplayRow(0)..DisplayRow(6)),
8355 Some(DisplayRow(3)),
8356 )
8357 })
8358 .unwrap();
8359 assert_eq!(relative_rows[&DisplayRow(0)], 3);
8360 assert_eq!(relative_rows[&DisplayRow(1)], 2);
8361 assert_eq!(relative_rows[&DisplayRow(2)], 1);
8362 // current line has no relative number
8363 assert_eq!(relative_rows[&DisplayRow(4)], 1);
8364 assert_eq!(relative_rows[&DisplayRow(5)], 2);
8365
8366 // works if cursor is before screen
8367 let relative_rows = window
8368 .update(cx, |editor, window, cx| {
8369 let snapshot = editor.snapshot(window, cx);
8370 element.calculate_relative_line_numbers(
8371 &snapshot,
8372 &(DisplayRow(3)..DisplayRow(6)),
8373 Some(DisplayRow(1)),
8374 )
8375 })
8376 .unwrap();
8377 assert_eq!(relative_rows.len(), 3);
8378 assert_eq!(relative_rows[&DisplayRow(3)], 2);
8379 assert_eq!(relative_rows[&DisplayRow(4)], 3);
8380 assert_eq!(relative_rows[&DisplayRow(5)], 4);
8381
8382 // works if cursor is after screen
8383 let relative_rows = window
8384 .update(cx, |editor, window, cx| {
8385 let snapshot = editor.snapshot(window, cx);
8386 element.calculate_relative_line_numbers(
8387 &snapshot,
8388 &(DisplayRow(0)..DisplayRow(3)),
8389 Some(DisplayRow(6)),
8390 )
8391 })
8392 .unwrap();
8393 assert_eq!(relative_rows.len(), 3);
8394 assert_eq!(relative_rows[&DisplayRow(0)], 5);
8395 assert_eq!(relative_rows[&DisplayRow(1)], 4);
8396 assert_eq!(relative_rows[&DisplayRow(2)], 3);
8397 }
8398
8399 #[gpui::test]
8400 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
8401 init_test(cx, |_| {});
8402
8403 let window = cx.add_window(|window, cx| {
8404 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
8405 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8406 });
8407 let cx = &mut VisualTestContext::from_window(*window, cx);
8408 let editor = window.root(cx).unwrap();
8409 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8410
8411 window
8412 .update(cx, |editor, window, cx| {
8413 editor.cursor_shape = CursorShape::Block;
8414 editor.change_selections(None, window, cx, |s| {
8415 s.select_ranges([
8416 Point::new(0, 0)..Point::new(1, 0),
8417 Point::new(3, 2)..Point::new(3, 3),
8418 Point::new(5, 6)..Point::new(6, 0),
8419 ]);
8420 });
8421 })
8422 .unwrap();
8423
8424 let (_, state) = cx.draw(
8425 point(px(500.), px(500.)),
8426 size(px(500.), px(500.)),
8427 |_, _| EditorElement::new(&editor, style),
8428 );
8429
8430 assert_eq!(state.selections.len(), 1);
8431 let local_selections = &state.selections[0].1;
8432 assert_eq!(local_selections.len(), 3);
8433 // moves cursor back one line
8434 assert_eq!(
8435 local_selections[0].head,
8436 DisplayPoint::new(DisplayRow(0), 6)
8437 );
8438 assert_eq!(
8439 local_selections[0].range,
8440 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
8441 );
8442
8443 // moves cursor back one column
8444 assert_eq!(
8445 local_selections[1].range,
8446 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
8447 );
8448 assert_eq!(
8449 local_selections[1].head,
8450 DisplayPoint::new(DisplayRow(3), 2)
8451 );
8452
8453 // leaves cursor on the max point
8454 assert_eq!(
8455 local_selections[2].range,
8456 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
8457 );
8458 assert_eq!(
8459 local_selections[2].head,
8460 DisplayPoint::new(DisplayRow(6), 0)
8461 );
8462
8463 // active lines does not include 1 (even though the range of the selection does)
8464 assert_eq!(
8465 state.active_rows.keys().cloned().collect::<Vec<_>>(),
8466 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
8467 );
8468
8469 // multi-buffer support
8470 // in DisplayPoint coordinates, this is what we're dealing with:
8471 // 0: [[file
8472 // 1: header
8473 // 2: section]]
8474 // 3: aaaaaa
8475 // 4: bbbbbb
8476 // 5: cccccc
8477 // 6:
8478 // 7: [[footer]]
8479 // 8: [[header]]
8480 // 9: ffffff
8481 // 10: gggggg
8482 // 11: hhhhhh
8483 // 12:
8484 // 13: [[footer]]
8485 // 14: [[file
8486 // 15: header
8487 // 16: section]]
8488 // 17: bbbbbb
8489 // 18: cccccc
8490 // 19: dddddd
8491 // 20: [[footer]]
8492 let window = cx.add_window(|window, cx| {
8493 let buffer = MultiBuffer::build_multi(
8494 [
8495 (
8496 &(sample_text(8, 6, 'a') + "\n"),
8497 vec![
8498 Point::new(0, 0)..Point::new(3, 0),
8499 Point::new(4, 0)..Point::new(7, 0),
8500 ],
8501 ),
8502 (
8503 &(sample_text(8, 6, 'a') + "\n"),
8504 vec![Point::new(1, 0)..Point::new(3, 0)],
8505 ),
8506 ],
8507 cx,
8508 );
8509 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8510 });
8511 let editor = window.root(cx).unwrap();
8512 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8513 let _state = window.update(cx, |editor, window, cx| {
8514 editor.cursor_shape = CursorShape::Block;
8515 editor.change_selections(None, window, cx, |s| {
8516 s.select_display_ranges([
8517 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0),
8518 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0),
8519 ]);
8520 });
8521 });
8522
8523 let (_, state) = cx.draw(
8524 point(px(500.), px(500.)),
8525 size(px(500.), px(500.)),
8526 |_, _| EditorElement::new(&editor, style),
8527 );
8528 assert_eq!(state.selections.len(), 1);
8529 let local_selections = &state.selections[0].1;
8530 assert_eq!(local_selections.len(), 2);
8531
8532 // moves cursor on excerpt boundary back a line
8533 // and doesn't allow selection to bleed through
8534 assert_eq!(
8535 local_selections[0].range,
8536 DisplayPoint::new(DisplayRow(4), 0)..DisplayPoint::new(DisplayRow(7), 0)
8537 );
8538 assert_eq!(
8539 local_selections[0].head,
8540 DisplayPoint::new(DisplayRow(6), 0)
8541 );
8542 // moves cursor on buffer boundary back two lines
8543 // and doesn't allow selection to bleed through
8544 assert_eq!(
8545 local_selections[1].range,
8546 DisplayPoint::new(DisplayRow(10), 0)..DisplayPoint::new(DisplayRow(13), 0)
8547 );
8548 assert_eq!(
8549 local_selections[1].head,
8550 DisplayPoint::new(DisplayRow(12), 0)
8551 );
8552 }
8553
8554 #[gpui::test]
8555 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
8556 init_test(cx, |_| {});
8557
8558 let window = cx.add_window(|window, cx| {
8559 let buffer = MultiBuffer::build_simple("", cx);
8560 Editor::new(EditorMode::Full, buffer, None, true, window, cx)
8561 });
8562 let cx = &mut VisualTestContext::from_window(*window, cx);
8563 let editor = window.root(cx).unwrap();
8564 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8565 window
8566 .update(cx, |editor, window, cx| {
8567 editor.set_placeholder_text("hello", cx);
8568 editor.insert_blocks(
8569 [BlockProperties {
8570 style: BlockStyle::Fixed,
8571 placement: BlockPlacement::Above(Anchor::min()),
8572 height: 3,
8573 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
8574 priority: 0,
8575 }],
8576 None,
8577 cx,
8578 );
8579
8580 // Blur the editor so that it displays placeholder text.
8581 window.blur();
8582 })
8583 .unwrap();
8584
8585 let (_, state) = cx.draw(
8586 point(px(500.), px(500.)),
8587 size(px(500.), px(500.)),
8588 |_, _| EditorElement::new(&editor, style),
8589 );
8590 assert_eq!(state.position_map.line_layouts.len(), 4);
8591 assert_eq!(state.line_numbers.len(), 1);
8592 assert_eq!(
8593 state
8594 .line_numbers
8595 .get(&MultiBufferRow(0))
8596 .and_then(|line_number| line_number.shaped_line.text.as_str()),
8597 Some("1")
8598 );
8599 }
8600
8601 #[gpui::test]
8602 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
8603 const TAB_SIZE: u32 = 4;
8604
8605 let input_text = "\t \t|\t| a b";
8606 let expected_invisibles = vec![
8607 Invisible::Tab {
8608 line_start_offset: 0,
8609 line_end_offset: TAB_SIZE as usize,
8610 },
8611 Invisible::Whitespace {
8612 line_offset: TAB_SIZE as usize,
8613 },
8614 Invisible::Tab {
8615 line_start_offset: TAB_SIZE as usize + 1,
8616 line_end_offset: TAB_SIZE as usize * 2,
8617 },
8618 Invisible::Tab {
8619 line_start_offset: TAB_SIZE as usize * 2 + 1,
8620 line_end_offset: TAB_SIZE as usize * 3,
8621 },
8622 Invisible::Whitespace {
8623 line_offset: TAB_SIZE as usize * 3 + 1,
8624 },
8625 Invisible::Whitespace {
8626 line_offset: TAB_SIZE as usize * 3 + 3,
8627 },
8628 ];
8629 assert_eq!(
8630 expected_invisibles.len(),
8631 input_text
8632 .chars()
8633 .filter(|initial_char| initial_char.is_whitespace())
8634 .count(),
8635 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8636 );
8637
8638 for show_line_numbers in [true, false] {
8639 init_test(cx, |s| {
8640 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8641 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
8642 });
8643
8644 let actual_invisibles = collect_invisibles_from_new_editor(
8645 cx,
8646 EditorMode::Full,
8647 input_text,
8648 px(500.0),
8649 show_line_numbers,
8650 );
8651
8652 assert_eq!(expected_invisibles, actual_invisibles);
8653 }
8654 }
8655
8656 #[gpui::test]
8657 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
8658 init_test(cx, |s| {
8659 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8660 s.defaults.tab_size = NonZeroU32::new(4);
8661 });
8662
8663 for editor_mode_without_invisibles in [
8664 EditorMode::SingleLine { auto_width: false },
8665 EditorMode::AutoHeight { max_lines: 100 },
8666 ] {
8667 for show_line_numbers in [true, false] {
8668 let invisibles = collect_invisibles_from_new_editor(
8669 cx,
8670 editor_mode_without_invisibles,
8671 "\t\t\t| | a b",
8672 px(500.0),
8673 show_line_numbers,
8674 );
8675 assert!(invisibles.is_empty(),
8676 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
8677 }
8678 }
8679 }
8680
8681 #[gpui::test]
8682 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
8683 let tab_size = 4;
8684 let input_text = "a\tbcd ".repeat(9);
8685 let repeated_invisibles = [
8686 Invisible::Tab {
8687 line_start_offset: 1,
8688 line_end_offset: tab_size as usize,
8689 },
8690 Invisible::Whitespace {
8691 line_offset: tab_size as usize + 3,
8692 },
8693 Invisible::Whitespace {
8694 line_offset: tab_size as usize + 4,
8695 },
8696 Invisible::Whitespace {
8697 line_offset: tab_size as usize + 5,
8698 },
8699 Invisible::Whitespace {
8700 line_offset: tab_size as usize + 6,
8701 },
8702 Invisible::Whitespace {
8703 line_offset: tab_size as usize + 7,
8704 },
8705 ];
8706 let expected_invisibles = std::iter::once(repeated_invisibles)
8707 .cycle()
8708 .take(9)
8709 .flatten()
8710 .collect::<Vec<_>>();
8711 assert_eq!(
8712 expected_invisibles.len(),
8713 input_text
8714 .chars()
8715 .filter(|initial_char| initial_char.is_whitespace())
8716 .count(),
8717 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
8718 );
8719 info!("Expected invisibles: {expected_invisibles:?}");
8720
8721 init_test(cx, |_| {});
8722
8723 // Put the same string with repeating whitespace pattern into editors of various size,
8724 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
8725 let resize_step = 10.0;
8726 let mut editor_width = 200.0;
8727 while editor_width <= 1000.0 {
8728 for show_line_numbers in [true, false] {
8729 update_test_language_settings(cx, |s| {
8730 s.defaults.tab_size = NonZeroU32::new(tab_size);
8731 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
8732 s.defaults.preferred_line_length = Some(editor_width as u32);
8733 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
8734 });
8735
8736 let actual_invisibles = collect_invisibles_from_new_editor(
8737 cx,
8738 EditorMode::Full,
8739 &input_text,
8740 px(editor_width),
8741 show_line_numbers,
8742 );
8743
8744 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
8745 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
8746 let mut i = 0;
8747 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
8748 i = actual_index;
8749 match expected_invisibles.get(i) {
8750 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
8751 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
8752 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
8753 _ => {
8754 panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
8755 }
8756 },
8757 None => {
8758 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
8759 }
8760 }
8761 }
8762 let missing_expected_invisibles = &expected_invisibles[i + 1..];
8763 assert!(
8764 missing_expected_invisibles.is_empty(),
8765 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
8766 );
8767
8768 editor_width += resize_step;
8769 }
8770 }
8771 }
8772
8773 fn collect_invisibles_from_new_editor(
8774 cx: &mut TestAppContext,
8775 editor_mode: EditorMode,
8776 input_text: &str,
8777 editor_width: Pixels,
8778 show_line_numbers: bool,
8779 ) -> Vec<Invisible> {
8780 info!(
8781 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
8782 editor_width.0
8783 );
8784 let window = cx.add_window(|window, cx| {
8785 let buffer = MultiBuffer::build_simple(input_text, cx);
8786 Editor::new(editor_mode, buffer, None, true, window, cx)
8787 });
8788 let cx = &mut VisualTestContext::from_window(*window, cx);
8789 let editor = window.root(cx).unwrap();
8790
8791 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
8792 window
8793 .update(cx, |editor, _, cx| {
8794 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
8795 editor.set_wrap_width(Some(editor_width), cx);
8796 editor.set_show_line_numbers(show_line_numbers, cx);
8797 })
8798 .unwrap();
8799 let (_, state) = cx.draw(
8800 point(px(500.), px(500.)),
8801 size(px(500.), px(500.)),
8802 |_, _| EditorElement::new(&editor, style),
8803 );
8804 state
8805 .position_map
8806 .line_layouts
8807 .iter()
8808 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
8809 .cloned()
8810 .collect()
8811 }
8812}
8813
8814fn diff_hunk_controls(
8815 row: u32,
8816 hunk_range: Range<Anchor>,
8817 line_height: Pixels,
8818 editor: &Entity<Editor>,
8819 cx: &mut App,
8820) -> AnyElement {
8821 h_flex()
8822 .h(line_height)
8823 .mr_1()
8824 .gap_1()
8825 .px_1()
8826 .pb_1()
8827 .border_b_1()
8828 .border_color(cx.theme().colors().border_variant)
8829 .rounded_b_lg()
8830 .bg(cx.theme().colors().editor_background)
8831 .gap_1()
8832 .child(
8833 IconButton::new(("next-hunk", row as u64), IconName::ArrowDown)
8834 .shape(IconButtonShape::Square)
8835 .icon_size(IconSize::Small)
8836 // .disabled(!has_multiple_hunks)
8837 .tooltip({
8838 let focus_handle = editor.focus_handle(cx);
8839 move |window, cx| {
8840 Tooltip::for_action_in("Next Hunk", &GoToHunk, &focus_handle, window, cx)
8841 }
8842 })
8843 .on_click({
8844 let editor = editor.clone();
8845 move |_event, window, cx| {
8846 editor.update(cx, |editor, cx| {
8847 let snapshot = editor.snapshot(window, cx);
8848 let position = hunk_range.end.to_point(&snapshot.buffer_snapshot);
8849 editor.go_to_hunk_after_position(&snapshot, position, window, cx);
8850 editor.expand_selected_diff_hunks(cx);
8851 });
8852 }
8853 }),
8854 )
8855 .child(
8856 IconButton::new(("prev-hunk", row as u64), IconName::ArrowUp)
8857 .shape(IconButtonShape::Square)
8858 .icon_size(IconSize::Small)
8859 // .disabled(!has_multiple_hunks)
8860 .tooltip({
8861 let focus_handle = editor.focus_handle(cx);
8862 move |window, cx| {
8863 Tooltip::for_action_in(
8864 "Previous Hunk",
8865 &GoToPrevHunk,
8866 &focus_handle,
8867 window,
8868 cx,
8869 )
8870 }
8871 })
8872 .on_click({
8873 let editor = editor.clone();
8874 move |_event, window, cx| {
8875 editor.update(cx, |editor, cx| {
8876 let snapshot = editor.snapshot(window, cx);
8877 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
8878 editor.go_to_hunk_before_position(&snapshot, point, window, cx);
8879 editor.expand_selected_diff_hunks(cx);
8880 });
8881 }
8882 }),
8883 )
8884 .child(
8885 IconButton::new("discard", IconName::Undo)
8886 .shape(IconButtonShape::Square)
8887 .icon_size(IconSize::Small)
8888 .tooltip({
8889 let focus_handle = editor.focus_handle(cx);
8890 move |window, cx| {
8891 Tooltip::for_action_in(
8892 "Discard Hunk",
8893 &RevertSelectedHunks,
8894 &focus_handle,
8895 window,
8896 cx,
8897 )
8898 }
8899 })
8900 .on_click({
8901 let editor = editor.clone();
8902 move |_event, window, cx| {
8903 editor.update(cx, |editor, cx| {
8904 let snapshot = editor.snapshot(window, cx);
8905 let point = hunk_range.start.to_point(&snapshot.buffer_snapshot);
8906 editor.revert_hunks_in_ranges([point..point].into_iter(), window, cx);
8907 });
8908 }
8909 }),
8910 )
8911 .into_any_element()
8912}