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