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