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