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