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