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