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