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