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