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