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