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