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