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