1use crate::{
2 ActiveDiagnostic, BlockId, CURSORS_VISIBLE_FOR, ChunkRendererContext, ChunkReplacement,
3 CodeActionSource, ColumnarMode, ConflictsOurs, ConflictsOursMarker, ConflictsOuter,
4 ConflictsTheirs, ConflictsTheirsMarker, ContextMenuPlacement, CursorShape, CustomBlockId,
5 DisplayDiffHunk, DisplayPoint, DisplayRow, DocumentHighlightRead, DocumentHighlightWrite,
6 EditDisplayMode, EditPrediction, Editor, EditorMode, EditorSettings, EditorSnapshot,
7 EditorStyle, FILE_HEADER_HEIGHT, FocusedBlock, GutterDimensions, HalfPageDown, HalfPageUp,
8 HandleInput, HoveredCursor, InlayHintRefreshReason, JumpData, LineDown, LineHighlight, LineUp,
9 MAX_LINE_LEN, MINIMAP_FONT_SIZE, MULTI_BUFFER_EXCERPT_HEADER_HEIGHT, OpenExcerpts, PageDown,
10 PageUp, PhantomBreakpointIndicator, Point, RowExt, RowRangeExt, SelectPhase,
11 SelectedTextHighlight, Selection, SelectionDragState, SoftWrap, StickyHeaderExcerpt, ToPoint,
12 ToggleFold, ToggleFoldAll,
13 code_context_menus::{CodeActionsMenu, MENU_ASIDE_MAX_WIDTH, MENU_ASIDE_MIN_WIDTH, MENU_GAP},
14 display_map::{
15 Block, BlockContext, BlockStyle, ChunkRendererId, DisplaySnapshot, EditorMargins,
16 HighlightKey, HighlightedChunk, ToDisplayPoint,
17 },
18 editor_settings::{
19 CurrentLineHighlight, DocumentColorsRenderMode, DoubleClickInMultibuffer, Minimap,
20 MinimapThumb, MinimapThumbBorder, ScrollBeyondLastLine, ScrollbarAxes,
21 ScrollbarDiagnostics, ShowMinimap,
22 },
23 git::blame::{BlameRenderer, GitBlame, GlobalBlameRenderer},
24 hover_popover::{
25 self, HOVER_POPOVER_GAP, MIN_POPOVER_CHARACTER_WIDTH, MIN_POPOVER_LINE_HEIGHT,
26 POPOVER_RIGHT_OFFSET, hover_at,
27 },
28 inlay_hint_settings,
29 items::BufferSearchHighlights,
30 mouse_context_menu::{self, MenuPosition},
31 scroll::{ActiveScrollbarState, ScrollbarThumbState, scroll_amount::ScrollAmount},
32};
33use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
34use collections::{BTreeMap, HashMap};
35use file_icons::FileIcons;
36use git::{
37 Oid,
38 blame::{BlameEntry, ParsedCommitMessage},
39 status::FileStatus,
40};
41use gpui::{
42 Action, Along, AnyElement, App, AppContext, AvailableSpace, Axis as ScrollbarAxis, BorderStyle,
43 Bounds, ClickEvent, ClipboardItem, ContentMask, Context, Corner, Corners, CursorStyle,
44 DispatchPhase, Edges, Element, ElementInputHandler, Entity, Focusable as _, FontId,
45 GlobalElementId, Hitbox, HitboxBehavior, Hsla, InteractiveElement, IntoElement, IsZero,
46 KeybindingKeystroke, Length, ModifiersChangedEvent, MouseButton, MouseClickEvent,
47 MouseDownEvent, MouseMoveEvent, MouseUpEvent, PaintQuad, ParentElement, Pixels, ScrollDelta,
48 ScrollHandle, ScrollWheelEvent, ShapedLine, SharedString, Size, StatefulInteractiveElement,
49 Style, Styled, TextRun, TextStyleRefinement, WeakEntity, Window, anchored, deferred, div, fill,
50 linear_color_stop, linear_gradient, outline, point, px, quad, relative, size, solid_background,
51 transparent_black,
52};
53use itertools::Itertools;
54use language::language_settings::{
55 IndentGuideBackgroundColoring, IndentGuideColoring, IndentGuideSettings, ShowWhitespaceSetting,
56};
57use markdown::Markdown;
58use multi_buffer::{
59 Anchor, ExcerptId, ExcerptInfo, ExpandExcerptDirection, ExpandInfo, MultiBufferPoint,
60 MultiBufferRow, RowInfo,
61};
62
63use project::{
64 Entry, ProjectPath,
65 debugger::breakpoint_store::{Breakpoint, BreakpointSessionState},
66 project_settings::{GitGutterSetting, GitHunkStyleSetting, ProjectSettings},
67};
68use settings::Settings;
69use smallvec::{SmallVec, smallvec};
70use std::{
71 any::TypeId,
72 borrow::Cow,
73 cmp::{self, Ordering},
74 fmt::{self, Write},
75 iter, mem,
76 ops::{Deref, Range},
77 path::{self, Path},
78 rc::Rc,
79 sync::Arc,
80 time::{Duration, Instant},
81};
82use sum_tree::Bias;
83use text::{BufferId, SelectionGoal};
84use theme::{ActiveTheme, Appearance, BufferLineHeight, PlayerColor};
85use ui::utils::ensure_minimum_contrast;
86use ui::{
87 ButtonLike, ContextMenu, Indicator, KeyBinding, POPOVER_Y_PADDING, Tooltip, h_flex, prelude::*,
88 right_click_menu, scrollbars::ShowScrollbar,
89};
90use unicode_segmentation::UnicodeSegmentation;
91use util::post_inc;
92use util::{RangeExt, ResultExt, debug_panic};
93use workspace::{
94 CollaboratorId, ItemSettings, OpenInTerminal, OpenTerminal, RevealInProjectPanel, Workspace,
95 item::Item, notifications::NotifyTaskExt,
96};
97
98/// Determines what kinds of highlights should be applied to a lines background.
99#[derive(Clone, Copy, Default)]
100struct LineHighlightSpec {
101 selection: bool,
102 breakpoint: bool,
103 _active_stack_frame: bool,
104}
105
106#[derive(Debug)]
107struct SelectionLayout {
108 head: DisplayPoint,
109 cursor_shape: CursorShape,
110 is_newest: bool,
111 is_local: bool,
112 range: Range<DisplayPoint>,
113 active_rows: Range<DisplayRow>,
114 user_name: Option<SharedString>,
115}
116
117struct InlineBlameLayout {
118 element: AnyElement,
119 bounds: Bounds<Pixels>,
120 buffer_id: BufferId,
121 entry: BlameEntry,
122}
123
124impl SelectionLayout {
125 fn new<T: ToPoint + ToDisplayPoint + Clone>(
126 selection: Selection<T>,
127 line_mode: bool,
128 cursor_shape: CursorShape,
129 map: &DisplaySnapshot,
130 is_newest: bool,
131 is_local: bool,
132 user_name: Option<SharedString>,
133 ) -> Self {
134 let point_selection = selection.map(|p| p.to_point(&map.buffer_snapshot));
135 let display_selection = point_selection.map(|p| p.to_display_point(map));
136 let mut range = display_selection.range();
137 let mut head = display_selection.head();
138 let mut active_rows = map.prev_line_boundary(point_selection.start).1.row()
139 ..map.next_line_boundary(point_selection.end).1.row();
140
141 // vim visual line mode
142 if line_mode {
143 let point_range = map.expand_to_line(point_selection.range());
144 range = point_range.start.to_display_point(map)..point_range.end.to_display_point(map);
145 }
146
147 // any vim visual mode (including line mode)
148 if (cursor_shape == CursorShape::Block || cursor_shape == CursorShape::Hollow)
149 && !range.is_empty()
150 && !selection.reversed
151 {
152 if head.column() > 0 {
153 head = map.clip_point(DisplayPoint::new(head.row(), head.column() - 1), Bias::Left)
154 } else if head.row().0 > 0 && head != map.max_point() {
155 head = map.clip_point(
156 DisplayPoint::new(
157 head.row().previous_row(),
158 map.line_len(head.row().previous_row()),
159 ),
160 Bias::Left,
161 );
162 // updating range.end is a no-op unless you're cursor is
163 // on the newline containing a multi-buffer divider
164 // in which case the clip_point may have moved the head up
165 // an additional row.
166 range.end = DisplayPoint::new(head.row().next_row(), 0);
167 active_rows.end = head.row();
168 }
169 }
170
171 Self {
172 head,
173 cursor_shape,
174 is_newest,
175 is_local,
176 range,
177 active_rows,
178 user_name,
179 }
180 }
181}
182
183pub struct EditorElement {
184 editor: Entity<Editor>,
185 style: EditorStyle,
186}
187
188type DisplayRowDelta = u32;
189
190impl EditorElement {
191 pub(crate) const SCROLLBAR_WIDTH: Pixels = px(15.);
192
193 pub fn new(editor: &Entity<Editor>, style: EditorStyle) -> Self {
194 Self {
195 editor: editor.clone(),
196 style,
197 }
198 }
199
200 fn register_actions(&self, window: &mut Window, cx: &mut App) {
201 let editor = &self.editor;
202 editor.update(cx, |editor, cx| {
203 for action in editor.editor_actions.borrow().values() {
204 (action)(editor, window, cx)
205 }
206 });
207
208 crate::rust_analyzer_ext::apply_related_actions(editor, window, cx);
209 crate::clangd_ext::apply_related_actions(editor, window, cx);
210
211 register_action(editor, window, Editor::open_context_menu);
212 register_action(editor, window, Editor::move_left);
213 register_action(editor, window, Editor::move_right);
214 register_action(editor, window, Editor::move_down);
215 register_action(editor, window, Editor::move_down_by_lines);
216 register_action(editor, window, Editor::select_down_by_lines);
217 register_action(editor, window, Editor::move_up);
218 register_action(editor, window, Editor::move_up_by_lines);
219 register_action(editor, window, Editor::select_up_by_lines);
220 register_action(editor, window, Editor::select_page_down);
221 register_action(editor, window, Editor::select_page_up);
222 register_action(editor, window, Editor::cancel);
223 register_action(editor, window, Editor::newline);
224 register_action(editor, window, Editor::newline_above);
225 register_action(editor, window, Editor::newline_below);
226 register_action(editor, window, Editor::backspace);
227 register_action(editor, window, Editor::blame_hover);
228 register_action(editor, window, Editor::delete);
229 register_action(editor, window, Editor::tab);
230 register_action(editor, window, Editor::backtab);
231 register_action(editor, window, Editor::indent);
232 register_action(editor, window, Editor::outdent);
233 register_action(editor, window, Editor::autoindent);
234 register_action(editor, window, Editor::delete_line);
235 register_action(editor, window, Editor::join_lines);
236 register_action(editor, window, Editor::sort_lines_by_length);
237 register_action(editor, window, Editor::sort_lines_case_sensitive);
238 register_action(editor, window, Editor::sort_lines_case_insensitive);
239 register_action(editor, window, Editor::reverse_lines);
240 register_action(editor, window, Editor::shuffle_lines);
241 register_action(editor, window, Editor::convert_indentation_to_spaces);
242 register_action(editor, window, Editor::convert_indentation_to_tabs);
243 register_action(editor, window, Editor::convert_to_upper_case);
244 register_action(editor, window, Editor::convert_to_lower_case);
245 register_action(editor, window, Editor::convert_to_title_case);
246 register_action(editor, window, Editor::convert_to_snake_case);
247 register_action(editor, window, Editor::convert_to_kebab_case);
248 register_action(editor, window, Editor::convert_to_upper_camel_case);
249 register_action(editor, window, Editor::convert_to_lower_camel_case);
250 register_action(editor, window, Editor::convert_to_opposite_case);
251 register_action(editor, window, Editor::convert_to_sentence_case);
252 register_action(editor, window, Editor::toggle_case);
253 register_action(editor, window, Editor::convert_to_rot13);
254 register_action(editor, window, Editor::convert_to_rot47);
255 register_action(editor, window, Editor::delete_to_previous_word_start);
256 register_action(editor, window, Editor::delete_to_previous_subword_start);
257 register_action(editor, window, Editor::delete_to_next_word_end);
258 register_action(editor, window, Editor::delete_to_next_subword_end);
259 register_action(editor, window, Editor::delete_to_beginning_of_line);
260 register_action(editor, window, Editor::delete_to_end_of_line);
261 register_action(editor, window, Editor::cut_to_end_of_line);
262 register_action(editor, window, Editor::duplicate_line_up);
263 register_action(editor, window, Editor::duplicate_line_down);
264 register_action(editor, window, Editor::duplicate_selection);
265 register_action(editor, window, Editor::move_line_up);
266 register_action(editor, window, Editor::move_line_down);
267 register_action(editor, window, Editor::transpose);
268 register_action(editor, window, Editor::rewrap);
269 register_action(editor, window, Editor::cut);
270 register_action(editor, window, Editor::kill_ring_cut);
271 register_action(editor, window, Editor::kill_ring_yank);
272 register_action(editor, window, Editor::copy);
273 register_action(editor, window, Editor::copy_and_trim);
274 register_action(editor, window, Editor::diff_clipboard_with_selection);
275 register_action(editor, window, Editor::paste);
276 register_action(editor, window, Editor::undo);
277 register_action(editor, window, Editor::redo);
278 register_action(editor, window, Editor::move_page_up);
279 register_action(editor, window, Editor::move_page_down);
280 register_action(editor, window, Editor::next_screen);
281 register_action(editor, window, Editor::scroll_cursor_top);
282 register_action(editor, window, Editor::scroll_cursor_center);
283 register_action(editor, window, Editor::scroll_cursor_bottom);
284 register_action(editor, window, Editor::scroll_cursor_center_top_bottom);
285 register_action(editor, window, |editor, _: &LineDown, window, cx| {
286 editor.scroll_screen(&ScrollAmount::Line(1.), window, cx)
287 });
288 register_action(editor, window, |editor, _: &LineUp, window, cx| {
289 editor.scroll_screen(&ScrollAmount::Line(-1.), window, cx)
290 });
291 register_action(editor, window, |editor, _: &HalfPageDown, window, cx| {
292 editor.scroll_screen(&ScrollAmount::Page(0.5), window, cx)
293 });
294 register_action(
295 editor,
296 window,
297 |editor, HandleInput(text): &HandleInput, window, cx| {
298 if text.is_empty() {
299 return;
300 }
301 editor.handle_input(text, window, cx);
302 },
303 );
304 register_action(editor, window, |editor, _: &HalfPageUp, window, cx| {
305 editor.scroll_screen(&ScrollAmount::Page(-0.5), window, cx)
306 });
307 register_action(editor, window, |editor, _: &PageDown, window, cx| {
308 editor.scroll_screen(&ScrollAmount::Page(1.), window, cx)
309 });
310 register_action(editor, window, |editor, _: &PageUp, window, cx| {
311 editor.scroll_screen(&ScrollAmount::Page(-1.), window, cx)
312 });
313 register_action(editor, window, Editor::move_to_previous_word_start);
314 register_action(editor, window, Editor::move_to_previous_subword_start);
315 register_action(editor, window, Editor::move_to_next_word_end);
316 register_action(editor, window, Editor::move_to_next_subword_end);
317 register_action(editor, window, Editor::move_to_beginning_of_line);
318 register_action(editor, window, Editor::move_to_end_of_line);
319 register_action(editor, window, Editor::move_to_start_of_paragraph);
320 register_action(editor, window, Editor::move_to_end_of_paragraph);
321 register_action(editor, window, Editor::move_to_beginning);
322 register_action(editor, window, Editor::move_to_end);
323 register_action(editor, window, Editor::move_to_start_of_excerpt);
324 register_action(editor, window, Editor::move_to_start_of_next_excerpt);
325 register_action(editor, window, Editor::move_to_end_of_excerpt);
326 register_action(editor, window, Editor::move_to_end_of_previous_excerpt);
327 register_action(editor, window, Editor::select_up);
328 register_action(editor, window, Editor::select_down);
329 register_action(editor, window, Editor::select_left);
330 register_action(editor, window, Editor::select_right);
331 register_action(editor, window, Editor::select_to_previous_word_start);
332 register_action(editor, window, Editor::select_to_previous_subword_start);
333 register_action(editor, window, Editor::select_to_next_word_end);
334 register_action(editor, window, Editor::select_to_next_subword_end);
335 register_action(editor, window, Editor::select_to_beginning_of_line);
336 register_action(editor, window, Editor::select_to_end_of_line);
337 register_action(editor, window, Editor::select_to_start_of_paragraph);
338 register_action(editor, window, Editor::select_to_end_of_paragraph);
339 register_action(editor, window, Editor::select_to_start_of_excerpt);
340 register_action(editor, window, Editor::select_to_start_of_next_excerpt);
341 register_action(editor, window, Editor::select_to_end_of_excerpt);
342 register_action(editor, window, Editor::select_to_end_of_previous_excerpt);
343 register_action(editor, window, Editor::select_to_beginning);
344 register_action(editor, window, Editor::select_to_end);
345 register_action(editor, window, Editor::select_all);
346 register_action(editor, window, |editor, action, window, cx| {
347 editor.select_all_matches(action, window, cx).log_err();
348 });
349 register_action(editor, window, Editor::select_line);
350 register_action(editor, window, Editor::split_selection_into_lines);
351 register_action(editor, window, Editor::add_selection_above);
352 register_action(editor, window, Editor::add_selection_below);
353 register_action(editor, window, |editor, action, window, cx| {
354 editor.select_next(action, window, cx).log_err();
355 });
356 register_action(editor, window, |editor, action, window, cx| {
357 editor.select_previous(action, window, cx).log_err();
358 });
359 register_action(editor, window, |editor, action, window, cx| {
360 editor.find_next_match(action, window, cx).log_err();
361 });
362 register_action(editor, window, |editor, action, window, cx| {
363 editor.find_previous_match(action, window, cx).log_err();
364 });
365 register_action(editor, window, Editor::toggle_comments);
366 register_action(editor, window, Editor::select_larger_syntax_node);
367 register_action(editor, window, Editor::select_smaller_syntax_node);
368 register_action(editor, window, Editor::select_next_syntax_node);
369 register_action(editor, window, Editor::select_prev_syntax_node);
370 register_action(editor, window, Editor::unwrap_syntax_node);
371 register_action(editor, window, Editor::select_enclosing_symbol);
372 register_action(editor, window, Editor::move_to_enclosing_bracket);
373 register_action(editor, window, Editor::undo_selection);
374 register_action(editor, window, Editor::redo_selection);
375 if !editor.read(cx).is_singleton(cx) {
376 register_action(editor, window, Editor::expand_excerpts);
377 register_action(editor, window, Editor::expand_excerpts_up);
378 register_action(editor, window, Editor::expand_excerpts_down);
379 }
380 register_action(editor, window, Editor::go_to_diagnostic);
381 register_action(editor, window, Editor::go_to_prev_diagnostic);
382 register_action(editor, window, Editor::go_to_next_hunk);
383 register_action(editor, window, Editor::go_to_prev_hunk);
384 register_action(editor, window, Editor::go_to_next_document_highlight);
385 register_action(editor, window, Editor::go_to_prev_document_highlight);
386 register_action(editor, window, |editor, action, window, cx| {
387 editor
388 .go_to_definition(action, window, cx)
389 .detach_and_log_err(cx);
390 });
391 register_action(editor, window, |editor, action, window, cx| {
392 editor
393 .go_to_definition_split(action, window, cx)
394 .detach_and_log_err(cx);
395 });
396 register_action(editor, window, |editor, action, window, cx| {
397 editor
398 .go_to_declaration(action, window, cx)
399 .detach_and_log_err(cx);
400 });
401 register_action(editor, window, |editor, action, window, cx| {
402 editor
403 .go_to_declaration_split(action, window, cx)
404 .detach_and_log_err(cx);
405 });
406 register_action(editor, window, |editor, action, window, cx| {
407 editor
408 .go_to_implementation(action, window, cx)
409 .detach_and_log_err(cx);
410 });
411 register_action(editor, window, |editor, action, window, cx| {
412 editor
413 .go_to_implementation_split(action, window, cx)
414 .detach_and_log_err(cx);
415 });
416 register_action(editor, window, |editor, action, window, cx| {
417 editor
418 .go_to_type_definition(action, window, cx)
419 .detach_and_log_err(cx);
420 });
421 register_action(editor, window, |editor, action, window, cx| {
422 editor
423 .go_to_type_definition_split(action, window, cx)
424 .detach_and_log_err(cx);
425 });
426 register_action(editor, window, Editor::open_url);
427 register_action(editor, window, Editor::open_selected_filename);
428 register_action(editor, window, Editor::fold);
429 register_action(editor, window, Editor::fold_at_level);
430 register_action(editor, window, Editor::fold_all);
431 register_action(editor, window, Editor::fold_function_bodies);
432 register_action(editor, window, Editor::fold_recursive);
433 register_action(editor, window, Editor::toggle_fold);
434 register_action(editor, window, Editor::toggle_fold_recursive);
435 register_action(editor, window, Editor::toggle_fold_all);
436 register_action(editor, window, Editor::unfold_lines);
437 register_action(editor, window, Editor::unfold_recursive);
438 register_action(editor, window, Editor::unfold_all);
439 register_action(editor, window, Editor::fold_selected_ranges);
440 register_action(editor, window, Editor::set_mark);
441 register_action(editor, window, Editor::swap_selection_ends);
442 register_action(editor, window, Editor::show_completions);
443 register_action(editor, window, Editor::show_word_completions);
444 register_action(editor, window, Editor::toggle_code_actions);
445 register_action(editor, window, Editor::open_excerpts);
446 register_action(editor, window, Editor::open_excerpts_in_split);
447 register_action(editor, window, Editor::open_proposed_changes_editor);
448 register_action(editor, window, Editor::toggle_soft_wrap);
449 register_action(editor, window, Editor::toggle_tab_bar);
450 register_action(editor, window, Editor::toggle_line_numbers);
451 register_action(editor, window, Editor::toggle_relative_line_numbers);
452 register_action(editor, window, Editor::toggle_indent_guides);
453 register_action(editor, window, Editor::toggle_inlay_hints);
454 register_action(editor, window, Editor::toggle_edit_predictions);
455 if editor.read(cx).diagnostics_enabled() {
456 register_action(editor, window, Editor::toggle_diagnostics);
457 }
458 if editor.read(cx).inline_diagnostics_enabled() {
459 register_action(editor, window, Editor::toggle_inline_diagnostics);
460 }
461 if editor.read(cx).supports_minimap(cx) {
462 register_action(editor, window, Editor::toggle_minimap);
463 }
464 register_action(editor, window, hover_popover::hover);
465 register_action(editor, window, Editor::reveal_in_finder);
466 register_action(editor, window, Editor::copy_path);
467 register_action(editor, window, Editor::copy_relative_path);
468 register_action(editor, window, Editor::copy_file_name);
469 register_action(editor, window, Editor::copy_file_name_without_extension);
470 register_action(editor, window, Editor::copy_highlight_json);
471 register_action(editor, window, Editor::copy_permalink_to_line);
472 register_action(editor, window, Editor::open_permalink_to_line);
473 register_action(editor, window, Editor::copy_file_location);
474 register_action(editor, window, Editor::toggle_git_blame);
475 register_action(editor, window, Editor::toggle_git_blame_inline);
476 register_action(editor, window, Editor::open_git_blame_commit);
477 register_action(editor, window, Editor::toggle_selected_diff_hunks);
478 register_action(editor, window, Editor::toggle_staged_selected_diff_hunks);
479 register_action(editor, window, Editor::stage_and_next);
480 register_action(editor, window, Editor::unstage_and_next);
481 register_action(editor, window, Editor::expand_all_diff_hunks);
482 register_action(editor, window, Editor::go_to_previous_change);
483 register_action(editor, window, Editor::go_to_next_change);
484
485 register_action(editor, window, |editor, action, window, cx| {
486 if let Some(task) = editor.format(action, window, cx) {
487 task.detach_and_notify_err(window, cx);
488 } else {
489 cx.propagate();
490 }
491 });
492 register_action(editor, window, |editor, action, window, cx| {
493 if let Some(task) = editor.format_selections(action, window, cx) {
494 task.detach_and_notify_err(window, cx);
495 } else {
496 cx.propagate();
497 }
498 });
499 register_action(editor, window, |editor, action, window, cx| {
500 if let Some(task) = editor.organize_imports(action, window, cx) {
501 task.detach_and_notify_err(window, cx);
502 } else {
503 cx.propagate();
504 }
505 });
506 register_action(editor, window, Editor::restart_language_server);
507 register_action(editor, window, Editor::stop_language_server);
508 register_action(editor, window, Editor::show_character_palette);
509 register_action(editor, window, |editor, action, window, cx| {
510 if let Some(task) = editor.confirm_completion(action, window, cx) {
511 task.detach_and_notify_err(window, cx);
512 } else {
513 cx.propagate();
514 }
515 });
516 register_action(editor, window, |editor, action, window, cx| {
517 if let Some(task) = editor.confirm_completion_replace(action, window, cx) {
518 task.detach_and_notify_err(window, cx);
519 } else {
520 cx.propagate();
521 }
522 });
523 register_action(editor, window, |editor, action, window, cx| {
524 if let Some(task) = editor.confirm_completion_insert(action, window, cx) {
525 task.detach_and_notify_err(window, cx);
526 } else {
527 cx.propagate();
528 }
529 });
530 register_action(editor, window, |editor, action, window, cx| {
531 if let Some(task) = editor.compose_completion(action, window, cx) {
532 task.detach_and_notify_err(window, cx);
533 } else {
534 cx.propagate();
535 }
536 });
537 register_action(editor, window, |editor, action, window, cx| {
538 if let Some(task) = editor.confirm_code_action(action, window, cx) {
539 task.detach_and_notify_err(window, cx);
540 } else {
541 cx.propagate();
542 }
543 });
544 register_action(editor, window, |editor, action, window, cx| {
545 if let Some(task) = editor.rename(action, window, cx) {
546 task.detach_and_notify_err(window, cx);
547 } else {
548 cx.propagate();
549 }
550 });
551 register_action(editor, window, |editor, action, window, cx| {
552 if let Some(task) = editor.confirm_rename(action, window, cx) {
553 task.detach_and_notify_err(window, cx);
554 } else {
555 cx.propagate();
556 }
557 });
558 register_action(editor, window, |editor, action, window, cx| {
559 if let Some(task) = editor.find_all_references(action, window, cx) {
560 task.detach_and_log_err(cx);
561 } else {
562 cx.propagate();
563 }
564 });
565 register_action(editor, window, Editor::show_signature_help);
566 register_action(editor, window, Editor::signature_help_prev);
567 register_action(editor, window, Editor::signature_help_next);
568 register_action(editor, window, Editor::next_edit_prediction);
569 register_action(editor, window, Editor::previous_edit_prediction);
570 register_action(editor, window, Editor::show_edit_prediction);
571 register_action(editor, window, Editor::context_menu_first);
572 register_action(editor, window, Editor::context_menu_prev);
573 register_action(editor, window, Editor::context_menu_next);
574 register_action(editor, window, Editor::context_menu_last);
575 register_action(editor, window, Editor::display_cursor_names);
576 register_action(editor, window, Editor::unique_lines_case_insensitive);
577 register_action(editor, window, Editor::unique_lines_case_sensitive);
578 register_action(editor, window, Editor::accept_partial_edit_prediction);
579 register_action(editor, window, Editor::accept_edit_prediction);
580 register_action(editor, window, Editor::restore_file);
581 register_action(editor, window, Editor::git_restore);
582 register_action(editor, window, Editor::apply_all_diff_hunks);
583 register_action(editor, window, Editor::apply_selected_diff_hunks);
584 register_action(editor, window, Editor::open_active_item_in_terminal);
585 register_action(editor, window, Editor::reload_file);
586 register_action(editor, window, Editor::spawn_nearest_task);
587 register_action(editor, window, Editor::insert_uuid_v4);
588 register_action(editor, window, Editor::insert_uuid_v7);
589 register_action(editor, window, Editor::open_selections_in_multibuffer);
590 register_action(editor, window, Editor::toggle_breakpoint);
591 register_action(editor, window, Editor::edit_log_breakpoint);
592 register_action(editor, window, Editor::enable_breakpoint);
593 register_action(editor, window, Editor::disable_breakpoint);
594 if editor.read(cx).enable_wrap_selections_in_tag(cx) {
595 register_action(editor, window, Editor::wrap_selections_in_tag);
596 }
597 }
598
599 fn register_key_listeners(&self, window: &mut Window, _: &mut App, layout: &EditorLayout) {
600 let position_map = layout.position_map.clone();
601 window.on_key_event({
602 let editor = self.editor.clone();
603 move |event: &ModifiersChangedEvent, phase, window, cx| {
604 if phase != DispatchPhase::Bubble {
605 return;
606 }
607 editor.update(cx, |editor, cx| {
608 let inlay_hint_settings = inlay_hint_settings(
609 editor.selections.newest_anchor().head(),
610 &editor.buffer.read(cx).snapshot(cx),
611 cx,
612 );
613
614 if let Some(inlay_modifiers) = inlay_hint_settings
615 .toggle_on_modifiers_press
616 .as_ref()
617 .filter(|modifiers| modifiers.modified())
618 {
619 editor.refresh_inlay_hints(
620 InlayHintRefreshReason::ModifiersChanged(
621 inlay_modifiers == &event.modifiers,
622 ),
623 cx,
624 );
625 }
626
627 if editor.hover_state.focused(window, cx) {
628 return;
629 }
630
631 editor.handle_modifiers_changed(event.modifiers, &position_map, window, cx);
632 })
633 }
634 });
635 }
636
637 fn mouse_left_down(
638 editor: &mut Editor,
639 event: &MouseDownEvent,
640 hovered_hunk: Option<Range<Anchor>>,
641 position_map: &PositionMap,
642 line_numbers: &HashMap<MultiBufferRow, LineNumberLayout>,
643 window: &mut Window,
644 cx: &mut Context<Editor>,
645 ) {
646 if window.default_prevented() {
647 return;
648 }
649
650 let text_hitbox = &position_map.text_hitbox;
651 let gutter_hitbox = &position_map.gutter_hitbox;
652 let point_for_position = position_map.point_for_position(event.position);
653 let mut click_count = event.click_count;
654 let mut modifiers = event.modifiers;
655
656 if let Some(hovered_hunk) = hovered_hunk {
657 editor.toggle_single_diff_hunk(hovered_hunk, cx);
658 cx.notify();
659 return;
660 } else if gutter_hitbox.is_hovered(window) {
661 click_count = 3; // Simulate triple-click when clicking the gutter to select lines
662 } else if !text_hitbox.is_hovered(window) {
663 return;
664 }
665
666 if EditorSettings::get_global(cx)
667 .drag_and_drop_selection
668 .enabled
669 && click_count == 1
670 {
671 let newest_anchor = editor.selections.newest_anchor();
672 let snapshot = editor.snapshot(window, cx);
673 let selection = newest_anchor.map(|anchor| anchor.to_display_point(&snapshot));
674 if point_for_position.intersects_selection(&selection) {
675 editor.selection_drag_state = SelectionDragState::ReadyToDrag {
676 selection: newest_anchor.clone(),
677 click_position: event.position,
678 mouse_down_time: Instant::now(),
679 };
680 cx.stop_propagation();
681 return;
682 }
683 }
684
685 let is_singleton = editor.buffer().read(cx).is_singleton();
686
687 if click_count == 2 && !is_singleton {
688 match EditorSettings::get_global(cx).double_click_in_multibuffer {
689 DoubleClickInMultibuffer::Select => {
690 // do nothing special on double click, all selection logic is below
691 }
692 DoubleClickInMultibuffer::Open => {
693 if modifiers.alt {
694 // if double click is made with alt, pretend it's a regular double click without opening and alt,
695 // and run the selection logic.
696 modifiers.alt = false;
697 } else {
698 let scroll_position_row =
699 position_map.scroll_pixel_position.y / position_map.line_height;
700 let display_row = (((event.position - gutter_hitbox.bounds.origin).y
701 + position_map.scroll_pixel_position.y)
702 / position_map.line_height)
703 as u32;
704 let multi_buffer_row = position_map
705 .snapshot
706 .display_point_to_point(
707 DisplayPoint::new(DisplayRow(display_row), 0),
708 Bias::Right,
709 )
710 .row;
711 let line_offset_from_top = display_row - scroll_position_row as u32;
712 // if double click is made without alt, open the corresponding excerp
713 editor.open_excerpts_common(
714 Some(JumpData::MultiBufferRow {
715 row: MultiBufferRow(multi_buffer_row),
716 line_offset_from_top,
717 }),
718 false,
719 window,
720 cx,
721 );
722 return;
723 }
724 }
725 }
726 }
727
728 let position = point_for_position.previous_valid;
729 if let Some(mode) = Editor::columnar_selection_mode(&modifiers, cx) {
730 editor.select(
731 SelectPhase::BeginColumnar {
732 position,
733 reset: match mode {
734 ColumnarMode::FromMouse => true,
735 ColumnarMode::FromSelection => false,
736 },
737 mode,
738 goal_column: point_for_position.exact_unclipped.column(),
739 },
740 window,
741 cx,
742 );
743 } else if modifiers.shift && !modifiers.control && !modifiers.alt && !modifiers.secondary()
744 {
745 editor.select(
746 SelectPhase::Extend {
747 position,
748 click_count,
749 },
750 window,
751 cx,
752 );
753 } else {
754 editor.select(
755 SelectPhase::Begin {
756 position,
757 add: Editor::multi_cursor_modifier(true, &modifiers, cx),
758 click_count,
759 },
760 window,
761 cx,
762 );
763 }
764 cx.stop_propagation();
765
766 if !is_singleton {
767 let display_row = (((event.position - gutter_hitbox.bounds.origin).y
768 + position_map.scroll_pixel_position.y)
769 / position_map.line_height) as u32;
770 let multi_buffer_row = position_map
771 .snapshot
772 .display_point_to_point(DisplayPoint::new(DisplayRow(display_row), 0), Bias::Right)
773 .row;
774 if line_numbers
775 .get(&MultiBufferRow(multi_buffer_row))
776 .and_then(|line_number| line_number.hitbox.as_ref())
777 .is_some_and(|hitbox| hitbox.contains(&event.position))
778 {
779 let scroll_position_row =
780 position_map.scroll_pixel_position.y / position_map.line_height;
781 let line_offset_from_top = display_row - scroll_position_row as u32;
782
783 editor.open_excerpts_common(
784 Some(JumpData::MultiBufferRow {
785 row: MultiBufferRow(multi_buffer_row),
786 line_offset_from_top,
787 }),
788 modifiers.alt,
789 window,
790 cx,
791 );
792 cx.stop_propagation();
793 }
794 }
795 }
796
797 fn mouse_right_down(
798 editor: &mut Editor,
799 event: &MouseDownEvent,
800 position_map: &PositionMap,
801 window: &mut Window,
802 cx: &mut Context<Editor>,
803 ) {
804 if position_map.gutter_hitbox.is_hovered(window) {
805 let gutter_right_padding = editor.gutter_dimensions.right_padding;
806 let hitbox = &position_map.gutter_hitbox;
807
808 if event.position.x <= hitbox.bounds.right() - gutter_right_padding {
809 let point_for_position = position_map.point_for_position(event.position);
810 editor.set_breakpoint_context_menu(
811 point_for_position.previous_valid.row(),
812 None,
813 event.position,
814 window,
815 cx,
816 );
817 }
818 return;
819 }
820
821 if !position_map.text_hitbox.is_hovered(window) {
822 return;
823 }
824
825 let point_for_position = position_map.point_for_position(event.position);
826 mouse_context_menu::deploy_context_menu(
827 editor,
828 Some(event.position),
829 point_for_position.previous_valid,
830 window,
831 cx,
832 );
833 cx.stop_propagation();
834 }
835
836 fn mouse_middle_down(
837 editor: &mut Editor,
838 event: &MouseDownEvent,
839 position_map: &PositionMap,
840 window: &mut Window,
841 cx: &mut Context<Editor>,
842 ) {
843 if !position_map.text_hitbox.is_hovered(window) || window.default_prevented() {
844 return;
845 }
846
847 let point_for_position = position_map.point_for_position(event.position);
848 let position = point_for_position.previous_valid;
849
850 editor.select(
851 SelectPhase::BeginColumnar {
852 position,
853 reset: true,
854 mode: ColumnarMode::FromMouse,
855 goal_column: point_for_position.exact_unclipped.column(),
856 },
857 window,
858 cx,
859 );
860 }
861
862 fn mouse_up(
863 editor: &mut Editor,
864 event: &MouseUpEvent,
865 position_map: &PositionMap,
866 window: &mut Window,
867 cx: &mut Context<Editor>,
868 ) {
869 let text_hitbox = &position_map.text_hitbox;
870 let end_selection = editor.has_pending_selection();
871 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
872 let point_for_position = position_map.point_for_position(event.position);
873
874 match editor.selection_drag_state {
875 SelectionDragState::ReadyToDrag {
876 selection: _,
877 ref click_position,
878 mouse_down_time: _,
879 } => {
880 if event.position == *click_position {
881 editor.select(
882 SelectPhase::Begin {
883 position: point_for_position.previous_valid,
884 add: false,
885 click_count: 1, // ready to drag state only occurs on click count 1
886 },
887 window,
888 cx,
889 );
890 editor.selection_drag_state = SelectionDragState::None;
891 cx.stop_propagation();
892 return;
893 } else {
894 debug_panic!("drag state can never be in ready state after drag")
895 }
896 }
897 SelectionDragState::Dragging { ref selection, .. } => {
898 let snapshot = editor.snapshot(window, cx);
899 let selection_display = selection.map(|anchor| anchor.to_display_point(&snapshot));
900 if !point_for_position.intersects_selection(&selection_display)
901 && text_hitbox.is_hovered(window)
902 {
903 let is_cut = !(cfg!(target_os = "macos") && event.modifiers.alt
904 || cfg!(not(target_os = "macos")) && event.modifiers.control);
905 editor.move_selection_on_drop(
906 &selection.clone(),
907 point_for_position.previous_valid,
908 is_cut,
909 window,
910 cx,
911 );
912 }
913 editor.selection_drag_state = SelectionDragState::None;
914 cx.stop_propagation();
915 cx.notify();
916 return;
917 }
918 _ => {}
919 }
920
921 if end_selection {
922 editor.select(SelectPhase::End, window, cx);
923 }
924
925 if end_selection && pending_nonempty_selections {
926 cx.stop_propagation();
927 } else if cfg!(any(target_os = "linux", target_os = "freebsd"))
928 && event.button == MouseButton::Middle
929 {
930 #[allow(
931 clippy::collapsible_if,
932 clippy::needless_return,
933 reason = "The cfg-block below makes this a false positive"
934 )]
935 if !text_hitbox.is_hovered(window) || editor.read_only(cx) {
936 return;
937 }
938
939 #[cfg(any(target_os = "linux", target_os = "freebsd"))]
940 if EditorSettings::get_global(cx).middle_click_paste {
941 if let Some(text) = cx.read_from_primary().and_then(|item| item.text()) {
942 let point_for_position = position_map.point_for_position(event.position);
943 let position = point_for_position.previous_valid;
944
945 editor.select(
946 SelectPhase::Begin {
947 position,
948 add: false,
949 click_count: 1,
950 },
951 window,
952 cx,
953 );
954 editor.insert(&text, window, cx);
955 }
956 cx.stop_propagation()
957 }
958 }
959 }
960
961 fn click(
962 editor: &mut Editor,
963 event: &ClickEvent,
964 position_map: &PositionMap,
965 window: &mut Window,
966 cx: &mut Context<Editor>,
967 ) {
968 let text_hitbox = &position_map.text_hitbox;
969 let pending_nonempty_selections = editor.has_pending_nonempty_selection();
970
971 let hovered_link_modifier = Editor::multi_cursor_modifier(false, &event.modifiers(), cx);
972
973 if let Some(mouse_position) = event.mouse_position()
974 && !pending_nonempty_selections
975 && hovered_link_modifier
976 && text_hitbox.is_hovered(window)
977 {
978 let point = position_map.point_for_position(mouse_position);
979 editor.handle_click_hovered_link(point, event.modifiers(), window, cx);
980 editor.selection_drag_state = SelectionDragState::None;
981
982 cx.stop_propagation();
983 }
984 }
985
986 fn mouse_dragged(
987 editor: &mut Editor,
988 event: &MouseMoveEvent,
989 position_map: &PositionMap,
990 window: &mut Window,
991 cx: &mut Context<Editor>,
992 ) {
993 if !editor.has_pending_selection()
994 && matches!(editor.selection_drag_state, SelectionDragState::None)
995 {
996 return;
997 }
998
999 let point_for_position = position_map.point_for_position(event.position);
1000 let text_hitbox = &position_map.text_hitbox;
1001
1002 let scroll_delta = {
1003 let text_bounds = text_hitbox.bounds;
1004 let mut scroll_delta = gpui::Point::<f32>::default();
1005 let vertical_margin = position_map.line_height.min(text_bounds.size.height / 3.0);
1006 let top = text_bounds.origin.y + vertical_margin;
1007 let bottom = text_bounds.bottom_left().y - vertical_margin;
1008 if event.position.y < top {
1009 scroll_delta.y = -scale_vertical_mouse_autoscroll_delta(top - event.position.y);
1010 }
1011 if event.position.y > bottom {
1012 scroll_delta.y = scale_vertical_mouse_autoscroll_delta(event.position.y - bottom);
1013 }
1014
1015 // We need horizontal width of text
1016 let style = editor.style.clone().unwrap_or_default();
1017 let font_id = window.text_system().resolve_font(&style.text.font());
1018 let font_size = style.text.font_size.to_pixels(window.rem_size());
1019 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
1020
1021 let scroll_margin_x = EditorSettings::get_global(cx).horizontal_scroll_margin;
1022
1023 let scroll_space: Pixels = scroll_margin_x * em_width;
1024
1025 let left = text_bounds.origin.x + scroll_space;
1026 let right = text_bounds.top_right().x - scroll_space;
1027
1028 if event.position.x < left {
1029 scroll_delta.x = -scale_horizontal_mouse_autoscroll_delta(left - event.position.x);
1030 }
1031 if event.position.x > right {
1032 scroll_delta.x = scale_horizontal_mouse_autoscroll_delta(event.position.x - right);
1033 }
1034 scroll_delta
1035 };
1036
1037 if !editor.has_pending_selection() {
1038 let drop_anchor = position_map
1039 .snapshot
1040 .display_point_to_anchor(point_for_position.previous_valid, Bias::Left);
1041 match editor.selection_drag_state {
1042 SelectionDragState::Dragging {
1043 ref mut drop_cursor,
1044 ref mut hide_drop_cursor,
1045 ..
1046 } => {
1047 drop_cursor.start = drop_anchor;
1048 drop_cursor.end = drop_anchor;
1049 *hide_drop_cursor = !text_hitbox.is_hovered(window);
1050 editor.apply_scroll_delta(scroll_delta, window, cx);
1051 cx.notify();
1052 }
1053 SelectionDragState::ReadyToDrag {
1054 ref selection,
1055 ref click_position,
1056 ref mouse_down_time,
1057 } => {
1058 let drag_and_drop_delay = Duration::from_millis(
1059 EditorSettings::get_global(cx).drag_and_drop_selection.delay,
1060 );
1061 if mouse_down_time.elapsed() >= drag_and_drop_delay {
1062 let drop_cursor = Selection {
1063 id: post_inc(&mut editor.selections.next_selection_id()),
1064 start: drop_anchor,
1065 end: drop_anchor,
1066 reversed: false,
1067 goal: SelectionGoal::None,
1068 };
1069 editor.selection_drag_state = SelectionDragState::Dragging {
1070 selection: selection.clone(),
1071 drop_cursor,
1072 hide_drop_cursor: false,
1073 };
1074 editor.apply_scroll_delta(scroll_delta, window, cx);
1075 cx.notify();
1076 } else {
1077 let click_point = position_map.point_for_position(*click_position);
1078 editor.selection_drag_state = SelectionDragState::None;
1079 editor.select(
1080 SelectPhase::Begin {
1081 position: click_point.previous_valid,
1082 add: false,
1083 click_count: 1,
1084 },
1085 window,
1086 cx,
1087 );
1088 editor.select(
1089 SelectPhase::Update {
1090 position: point_for_position.previous_valid,
1091 goal_column: point_for_position.exact_unclipped.column(),
1092 scroll_delta,
1093 },
1094 window,
1095 cx,
1096 );
1097 }
1098 }
1099 _ => {}
1100 }
1101 } else {
1102 editor.select(
1103 SelectPhase::Update {
1104 position: point_for_position.previous_valid,
1105 goal_column: point_for_position.exact_unclipped.column(),
1106 scroll_delta,
1107 },
1108 window,
1109 cx,
1110 );
1111 }
1112 }
1113
1114 fn mouse_moved(
1115 editor: &mut Editor,
1116 event: &MouseMoveEvent,
1117 position_map: &PositionMap,
1118 window: &mut Window,
1119 cx: &mut Context<Editor>,
1120 ) {
1121 let text_hitbox = &position_map.text_hitbox;
1122 let gutter_hitbox = &position_map.gutter_hitbox;
1123 let modifiers = event.modifiers;
1124 let text_hovered = text_hitbox.is_hovered(window);
1125 let gutter_hovered = gutter_hitbox.is_hovered(window);
1126 editor.set_gutter_hovered(gutter_hovered, cx);
1127 editor.show_mouse_cursor(cx);
1128
1129 let point_for_position = position_map.point_for_position(event.position);
1130 let valid_point = point_for_position.previous_valid;
1131
1132 let hovered_diff_control = position_map
1133 .diff_hunk_control_bounds
1134 .iter()
1135 .find(|(_, bounds)| bounds.contains(&event.position))
1136 .map(|(row, _)| *row);
1137
1138 let hovered_diff_hunk_row = if let Some(control_row) = hovered_diff_control {
1139 Some(control_row)
1140 } else if text_hovered {
1141 let current_row = valid_point.row();
1142 position_map.display_hunks.iter().find_map(|(hunk, _)| {
1143 if let DisplayDiffHunk::Unfolded {
1144 display_row_range, ..
1145 } = hunk
1146 {
1147 if display_row_range.contains(¤t_row) {
1148 Some(display_row_range.start)
1149 } else {
1150 None
1151 }
1152 } else {
1153 None
1154 }
1155 })
1156 } else {
1157 None
1158 };
1159
1160 if hovered_diff_hunk_row != editor.hovered_diff_hunk_row {
1161 editor.hovered_diff_hunk_row = hovered_diff_hunk_row;
1162 cx.notify();
1163 }
1164
1165 if let Some((bounds, buffer_id, blame_entry)) = &position_map.inline_blame_bounds {
1166 let mouse_over_inline_blame = bounds.contains(&event.position);
1167 let mouse_over_popover = editor
1168 .inline_blame_popover
1169 .as_ref()
1170 .and_then(|state| state.popover_bounds)
1171 .is_some_and(|bounds| bounds.contains(&event.position));
1172 let keyboard_grace = editor
1173 .inline_blame_popover
1174 .as_ref()
1175 .is_some_and(|state| state.keyboard_grace);
1176
1177 if mouse_over_inline_blame || mouse_over_popover {
1178 editor.show_blame_popover(*buffer_id, blame_entry, event.position, false, cx);
1179 } else if !keyboard_grace {
1180 editor.hide_blame_popover(cx);
1181 }
1182 } else {
1183 editor.hide_blame_popover(cx);
1184 }
1185
1186 let breakpoint_indicator = if gutter_hovered {
1187 let buffer_anchor = position_map
1188 .snapshot
1189 .display_point_to_anchor(valid_point, Bias::Left);
1190
1191 if let Some((buffer_snapshot, file)) = position_map
1192 .snapshot
1193 .buffer_snapshot
1194 .buffer_for_excerpt(buffer_anchor.excerpt_id)
1195 .and_then(|buffer| buffer.file().map(|file| (buffer, file)))
1196 {
1197 let as_point = text::ToPoint::to_point(&buffer_anchor.text_anchor, buffer_snapshot);
1198
1199 let is_visible = editor
1200 .gutter_breakpoint_indicator
1201 .0
1202 .is_some_and(|indicator| indicator.is_active);
1203
1204 let has_existing_breakpoint =
1205 editor.breakpoint_store.as_ref().is_some_and(|store| {
1206 let Some(project) = &editor.project else {
1207 return false;
1208 };
1209 let Some(abs_path) = project.read(cx).absolute_path(
1210 &ProjectPath {
1211 path: file.path().clone(),
1212 worktree_id: file.worktree_id(cx),
1213 },
1214 cx,
1215 ) else {
1216 return false;
1217 };
1218 store
1219 .read(cx)
1220 .breakpoint_at_row(&abs_path, as_point.row, cx)
1221 .is_some()
1222 });
1223
1224 if !is_visible {
1225 editor.gutter_breakpoint_indicator.1.get_or_insert_with(|| {
1226 cx.spawn(async move |this, cx| {
1227 cx.background_executor()
1228 .timer(Duration::from_millis(200))
1229 .await;
1230
1231 this.update(cx, |this, cx| {
1232 if let Some(indicator) = this.gutter_breakpoint_indicator.0.as_mut()
1233 {
1234 indicator.is_active = true;
1235 cx.notify();
1236 }
1237 })
1238 .ok();
1239 })
1240 });
1241 }
1242
1243 Some(PhantomBreakpointIndicator {
1244 display_row: valid_point.row(),
1245 is_active: is_visible,
1246 collides_with_existing_breakpoint: has_existing_breakpoint,
1247 })
1248 } else {
1249 editor.gutter_breakpoint_indicator.1 = None;
1250 None
1251 }
1252 } else {
1253 editor.gutter_breakpoint_indicator.1 = None;
1254 None
1255 };
1256
1257 if &breakpoint_indicator != &editor.gutter_breakpoint_indicator.0 {
1258 editor.gutter_breakpoint_indicator.0 = breakpoint_indicator;
1259 cx.notify();
1260 }
1261
1262 // Don't trigger hover popover if mouse is hovering over context menu
1263 if text_hovered {
1264 editor.update_hovered_link(
1265 point_for_position,
1266 &position_map.snapshot,
1267 modifiers,
1268 window,
1269 cx,
1270 );
1271
1272 if let Some(point) = point_for_position.as_valid() {
1273 let anchor = position_map
1274 .snapshot
1275 .buffer_snapshot
1276 .anchor_before(point.to_offset(&position_map.snapshot, Bias::Left));
1277 hover_at(editor, Some(anchor), window, cx);
1278 Self::update_visible_cursor(editor, point, position_map, window, cx);
1279 } else {
1280 hover_at(editor, None, window, cx);
1281 }
1282 } else {
1283 editor.hide_hovered_link(cx);
1284 hover_at(editor, None, window, cx);
1285 }
1286 }
1287
1288 fn update_visible_cursor(
1289 editor: &mut Editor,
1290 point: DisplayPoint,
1291 position_map: &PositionMap,
1292 window: &mut Window,
1293 cx: &mut Context<Editor>,
1294 ) {
1295 let snapshot = &position_map.snapshot;
1296 let Some(hub) = editor.collaboration_hub() else {
1297 return;
1298 };
1299 let start = snapshot.display_snapshot.clip_point(
1300 DisplayPoint::new(point.row(), point.column().saturating_sub(1)),
1301 Bias::Left,
1302 );
1303 let end = snapshot.display_snapshot.clip_point(
1304 DisplayPoint::new(
1305 point.row(),
1306 (point.column() + 1).min(snapshot.line_len(point.row())),
1307 ),
1308 Bias::Right,
1309 );
1310
1311 let range = snapshot
1312 .buffer_snapshot
1313 .anchor_at(start.to_point(&snapshot.display_snapshot), Bias::Left)
1314 ..snapshot
1315 .buffer_snapshot
1316 .anchor_at(end.to_point(&snapshot.display_snapshot), Bias::Right);
1317
1318 let Some(selection) = snapshot.remote_selections_in_range(&range, hub, cx).next() else {
1319 return;
1320 };
1321 let key = crate::HoveredCursor {
1322 replica_id: selection.replica_id,
1323 selection_id: selection.selection.id,
1324 };
1325 editor.hovered_cursors.insert(
1326 key.clone(),
1327 cx.spawn_in(window, async move |editor, cx| {
1328 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
1329 editor
1330 .update(cx, |editor, cx| {
1331 editor.hovered_cursors.remove(&key);
1332 cx.notify();
1333 })
1334 .ok();
1335 }),
1336 );
1337 cx.notify()
1338 }
1339
1340 fn layout_selections(
1341 &self,
1342 start_anchor: Anchor,
1343 end_anchor: Anchor,
1344 local_selections: &[Selection<Point>],
1345 snapshot: &EditorSnapshot,
1346 start_row: DisplayRow,
1347 end_row: DisplayRow,
1348 window: &mut Window,
1349 cx: &mut App,
1350 ) -> (
1351 Vec<(PlayerColor, Vec<SelectionLayout>)>,
1352 BTreeMap<DisplayRow, LineHighlightSpec>,
1353 Option<DisplayPoint>,
1354 ) {
1355 let mut selections: Vec<(PlayerColor, Vec<SelectionLayout>)> = Vec::new();
1356 let mut active_rows = BTreeMap::new();
1357 let mut newest_selection_head = None;
1358
1359 let Some(editor_with_selections) = self.editor_with_selections(cx) else {
1360 return (selections, active_rows, newest_selection_head);
1361 };
1362
1363 editor_with_selections.update(cx, |editor, cx| {
1364 if editor.show_local_selections {
1365 let mut layouts = Vec::new();
1366 let newest = editor.selections.newest(cx);
1367 for selection in local_selections.iter().cloned() {
1368 let is_empty = selection.start == selection.end;
1369 let is_newest = selection == newest;
1370
1371 let layout = SelectionLayout::new(
1372 selection,
1373 editor.selections.line_mode,
1374 editor.cursor_shape,
1375 &snapshot.display_snapshot,
1376 is_newest,
1377 editor.leader_id.is_none(),
1378 None,
1379 );
1380 if is_newest {
1381 newest_selection_head = Some(layout.head);
1382 }
1383
1384 for row in cmp::max(layout.active_rows.start.0, start_row.0)
1385 ..=cmp::min(layout.active_rows.end.0, end_row.0)
1386 {
1387 let contains_non_empty_selection = active_rows
1388 .entry(DisplayRow(row))
1389 .or_insert_with(LineHighlightSpec::default);
1390 contains_non_empty_selection.selection |= !is_empty;
1391 }
1392 layouts.push(layout);
1393 }
1394
1395 let player = editor.current_user_player_color(cx);
1396 selections.push((player, layouts));
1397
1398 if let SelectionDragState::Dragging {
1399 ref selection,
1400 ref drop_cursor,
1401 ref hide_drop_cursor,
1402 } = editor.selection_drag_state
1403 && !hide_drop_cursor
1404 && (drop_cursor
1405 .start
1406 .cmp(&selection.start, &snapshot.buffer_snapshot)
1407 .eq(&Ordering::Less)
1408 || drop_cursor
1409 .end
1410 .cmp(&selection.end, &snapshot.buffer_snapshot)
1411 .eq(&Ordering::Greater))
1412 {
1413 let drag_cursor_layout = SelectionLayout::new(
1414 drop_cursor.clone(),
1415 false,
1416 CursorShape::Bar,
1417 &snapshot.display_snapshot,
1418 false,
1419 false,
1420 None,
1421 );
1422 let absent_color = cx.theme().players().absent();
1423 selections.push((absent_color, vec![drag_cursor_layout]));
1424 }
1425 }
1426
1427 if let Some(collaboration_hub) = &editor.collaboration_hub {
1428 // When following someone, render the local selections in their color.
1429 if let Some(leader_id) = editor.leader_id {
1430 match leader_id {
1431 CollaboratorId::PeerId(peer_id) => {
1432 if let Some(collaborator) =
1433 collaboration_hub.collaborators(cx).get(&peer_id)
1434 && let Some(participant_index) = collaboration_hub
1435 .user_participant_indices(cx)
1436 .get(&collaborator.user_id)
1437 && let Some((local_selection_style, _)) = selections.first_mut()
1438 {
1439 *local_selection_style = cx
1440 .theme()
1441 .players()
1442 .color_for_participant(participant_index.0);
1443 }
1444 }
1445 CollaboratorId::Agent => {
1446 if let Some((local_selection_style, _)) = selections.first_mut() {
1447 *local_selection_style = cx.theme().players().agent();
1448 }
1449 }
1450 }
1451 }
1452
1453 let mut remote_selections = HashMap::default();
1454 for selection in snapshot.remote_selections_in_range(
1455 &(start_anchor..end_anchor),
1456 collaboration_hub.as_ref(),
1457 cx,
1458 ) {
1459 // Don't re-render the leader's selections, since the local selections
1460 // match theirs.
1461 if Some(selection.collaborator_id) == editor.leader_id {
1462 continue;
1463 }
1464 let key = HoveredCursor {
1465 replica_id: selection.replica_id,
1466 selection_id: selection.selection.id,
1467 };
1468
1469 let is_shown =
1470 editor.show_cursor_names || editor.hovered_cursors.contains_key(&key);
1471
1472 remote_selections
1473 .entry(selection.replica_id)
1474 .or_insert((selection.color, Vec::new()))
1475 .1
1476 .push(SelectionLayout::new(
1477 selection.selection,
1478 selection.line_mode,
1479 selection.cursor_shape,
1480 &snapshot.display_snapshot,
1481 false,
1482 false,
1483 if is_shown { selection.user_name } else { None },
1484 ));
1485 }
1486
1487 selections.extend(remote_selections.into_values());
1488 } else if !editor.is_focused(window) && editor.show_cursor_when_unfocused {
1489 let layouts = snapshot
1490 .buffer_snapshot
1491 .selections_in_range(&(start_anchor..end_anchor), true)
1492 .map(move |(_, line_mode, cursor_shape, selection)| {
1493 SelectionLayout::new(
1494 selection,
1495 line_mode,
1496 cursor_shape,
1497 &snapshot.display_snapshot,
1498 false,
1499 false,
1500 None,
1501 )
1502 })
1503 .collect::<Vec<_>>();
1504 let player = editor.current_user_player_color(cx);
1505 selections.push((player, layouts));
1506 }
1507 });
1508
1509 #[cfg(debug_assertions)]
1510 Self::layout_debug_ranges(
1511 &mut selections,
1512 start_anchor..end_anchor,
1513 &snapshot.display_snapshot,
1514 cx,
1515 );
1516
1517 (selections, active_rows, newest_selection_head)
1518 }
1519
1520 fn collect_cursors(
1521 &self,
1522 snapshot: &EditorSnapshot,
1523 cx: &mut App,
1524 ) -> Vec<(DisplayPoint, Hsla)> {
1525 let editor = self.editor.read(cx);
1526 let mut cursors = Vec::new();
1527 let mut skip_local = false;
1528 let mut add_cursor = |anchor: Anchor, color| {
1529 cursors.push((anchor.to_display_point(&snapshot.display_snapshot), color));
1530 };
1531 // Remote cursors
1532 if let Some(collaboration_hub) = &editor.collaboration_hub {
1533 for remote_selection in snapshot.remote_selections_in_range(
1534 &(Anchor::min()..Anchor::max()),
1535 collaboration_hub.deref(),
1536 cx,
1537 ) {
1538 add_cursor(
1539 remote_selection.selection.head(),
1540 remote_selection.color.cursor,
1541 );
1542 if Some(remote_selection.collaborator_id) == editor.leader_id {
1543 skip_local = true;
1544 }
1545 }
1546 }
1547 // Local cursors
1548 if !skip_local {
1549 let color = cx.theme().players().local().cursor;
1550 editor
1551 .selections
1552 .disjoint_anchors()
1553 .iter()
1554 .for_each(|selection| {
1555 add_cursor(selection.head(), color);
1556 });
1557 if let Some(ref selection) = editor.selections.pending_anchor() {
1558 add_cursor(selection.head(), color);
1559 }
1560 }
1561 cursors
1562 }
1563
1564 fn layout_visible_cursors(
1565 &self,
1566 snapshot: &EditorSnapshot,
1567 selections: &[(PlayerColor, Vec<SelectionLayout>)],
1568 row_block_types: &HashMap<DisplayRow, bool>,
1569 visible_display_row_range: Range<DisplayRow>,
1570 line_layouts: &[LineWithInvisibles],
1571 text_hitbox: &Hitbox,
1572 content_origin: gpui::Point<Pixels>,
1573 scroll_position: gpui::Point<f32>,
1574 scroll_pixel_position: gpui::Point<Pixels>,
1575 line_height: Pixels,
1576 em_width: Pixels,
1577 em_advance: Pixels,
1578 autoscroll_containing_element: bool,
1579 window: &mut Window,
1580 cx: &mut App,
1581 ) -> Vec<CursorLayout> {
1582 let mut autoscroll_bounds = None;
1583 let cursor_layouts = self.editor.update(cx, |editor, cx| {
1584 let mut cursors = Vec::new();
1585
1586 let show_local_cursors = editor.show_local_cursors(window, cx);
1587
1588 for (player_color, selections) in selections {
1589 for selection in selections {
1590 let cursor_position = selection.head;
1591
1592 let in_range = visible_display_row_range.contains(&cursor_position.row());
1593 if (selection.is_local && !show_local_cursors)
1594 || !in_range
1595 || row_block_types.get(&cursor_position.row()) == Some(&true)
1596 {
1597 continue;
1598 }
1599
1600 let cursor_row_layout = &line_layouts
1601 [cursor_position.row().minus(visible_display_row_range.start) as usize];
1602 let cursor_column = cursor_position.column() as usize;
1603
1604 let cursor_character_x = cursor_row_layout.x_for_index(cursor_column);
1605 let mut block_width =
1606 cursor_row_layout.x_for_index(cursor_column + 1) - cursor_character_x;
1607 if block_width == Pixels::ZERO {
1608 block_width = em_advance;
1609 }
1610 let block_text = if let CursorShape::Block = selection.cursor_shape {
1611 snapshot
1612 .grapheme_at(cursor_position)
1613 .or_else(|| {
1614 if snapshot.is_empty() {
1615 snapshot.placeholder_text().and_then(|s| {
1616 s.graphemes(true).next().map(|s| s.to_string().into())
1617 })
1618 } else {
1619 None
1620 }
1621 })
1622 .map(|text| {
1623 let len = text.len();
1624
1625 let font = cursor_row_layout
1626 .font_id_for_index(cursor_column)
1627 .and_then(|cursor_font_id| {
1628 window.text_system().get_font_for_id(cursor_font_id)
1629 })
1630 .unwrap_or(self.style.text.font());
1631
1632 // Invert the text color for the block cursor. Ensure that the text
1633 // color is opaque enough to be visible against the background color.
1634 //
1635 // 0.75 is an arbitrary threshold to determine if the background color is
1636 // opaque enough to use as a text color.
1637 //
1638 // TODO: In the future we should ensure themes have a `text_inverse` color.
1639 let color = if cx.theme().colors().editor_background.a < 0.75 {
1640 match cx.theme().appearance {
1641 Appearance::Dark => Hsla::black(),
1642 Appearance::Light => Hsla::white(),
1643 }
1644 } else {
1645 cx.theme().colors().editor_background
1646 };
1647
1648 window.text_system().shape_line(
1649 text,
1650 cursor_row_layout.font_size,
1651 &[TextRun {
1652 len,
1653 font,
1654 color,
1655 background_color: None,
1656 strikethrough: None,
1657 underline: None,
1658 }],
1659 None,
1660 )
1661 })
1662 } else {
1663 None
1664 };
1665
1666 let x = cursor_character_x - scroll_pixel_position.x;
1667 let y = (cursor_position.row().as_f32()
1668 - scroll_pixel_position.y / line_height)
1669 * line_height;
1670 if selection.is_newest {
1671 editor.pixel_position_of_newest_cursor = Some(point(
1672 text_hitbox.origin.x + x + block_width / 2.,
1673 text_hitbox.origin.y + y + line_height / 2.,
1674 ));
1675
1676 if autoscroll_containing_element {
1677 let top = text_hitbox.origin.y
1678 + (cursor_position.row().as_f32() - scroll_position.y - 3.).max(0.)
1679 * line_height;
1680 let left = text_hitbox.origin.x
1681 + (cursor_position.column() as f32 - scroll_position.x - 3.)
1682 .max(0.)
1683 * em_width;
1684
1685 let bottom = text_hitbox.origin.y
1686 + (cursor_position.row().as_f32() - scroll_position.y + 4.)
1687 * line_height;
1688 let right = text_hitbox.origin.x
1689 + (cursor_position.column() as f32 - scroll_position.x + 4.)
1690 * em_width;
1691
1692 autoscroll_bounds =
1693 Some(Bounds::from_corners(point(left, top), point(right, bottom)))
1694 }
1695 }
1696
1697 let mut cursor = CursorLayout {
1698 color: player_color.cursor,
1699 block_width,
1700 origin: point(x, y),
1701 line_height,
1702 shape: selection.cursor_shape,
1703 block_text,
1704 cursor_name: None,
1705 };
1706 let cursor_name = selection.user_name.clone().map(|name| CursorName {
1707 string: name,
1708 color: self.style.background,
1709 is_top_row: cursor_position.row().0 == 0,
1710 });
1711 cursor.layout(content_origin, cursor_name, window, cx);
1712 cursors.push(cursor);
1713 }
1714 }
1715
1716 cursors
1717 });
1718
1719 if let Some(bounds) = autoscroll_bounds {
1720 window.request_autoscroll(bounds);
1721 }
1722
1723 cursor_layouts
1724 }
1725
1726 fn layout_scrollbars(
1727 &self,
1728 snapshot: &EditorSnapshot,
1729 scrollbar_layout_information: &ScrollbarLayoutInformation,
1730 content_offset: gpui::Point<Pixels>,
1731 scroll_position: gpui::Point<f32>,
1732 non_visible_cursors: bool,
1733 right_margin: Pixels,
1734 editor_width: Pixels,
1735 window: &mut Window,
1736 cx: &mut App,
1737 ) -> Option<EditorScrollbars> {
1738 let show_scrollbars = self.editor.read(cx).show_scrollbars;
1739 if (!show_scrollbars.horizontal && !show_scrollbars.vertical)
1740 || self.style.scrollbar_width.is_zero()
1741 {
1742 return None;
1743 }
1744
1745 // If a drag took place after we started dragging the scrollbar,
1746 // cancel the scrollbar drag.
1747 if cx.has_active_drag() {
1748 self.editor.update(cx, |editor, cx| {
1749 editor.scroll_manager.reset_scrollbar_state(cx)
1750 });
1751 }
1752
1753 let editor_settings = EditorSettings::get_global(cx);
1754 let scrollbar_settings = editor_settings.scrollbar;
1755 let show_scrollbars = match scrollbar_settings.show {
1756 ShowScrollbar::Auto => {
1757 let editor = self.editor.read(cx);
1758 let is_singleton = editor.is_singleton(cx);
1759 // Git
1760 (is_singleton && scrollbar_settings.git_diff && snapshot.buffer_snapshot.has_diff_hunks())
1761 ||
1762 // Buffer Search Results
1763 (is_singleton && scrollbar_settings.search_results && editor.has_background_highlights::<BufferSearchHighlights>())
1764 ||
1765 // Selected Text Occurrences
1766 (is_singleton && scrollbar_settings.selected_text && editor.has_background_highlights::<SelectedTextHighlight>())
1767 ||
1768 // Selected Symbol Occurrences
1769 (is_singleton && scrollbar_settings.selected_symbol && (editor.has_background_highlights::<DocumentHighlightRead>() || editor.has_background_highlights::<DocumentHighlightWrite>()))
1770 ||
1771 // Diagnostics
1772 (is_singleton && scrollbar_settings.diagnostics != ScrollbarDiagnostics::None && snapshot.buffer_snapshot.has_diagnostics())
1773 ||
1774 // Cursors out of sight
1775 non_visible_cursors
1776 ||
1777 // Scrollmanager
1778 editor.scroll_manager.scrollbars_visible()
1779 }
1780 ShowScrollbar::System => self.editor.read(cx).scroll_manager.scrollbars_visible(),
1781 ShowScrollbar::Always => true,
1782 ShowScrollbar::Never => return None,
1783 };
1784
1785 // The horizontal scrollbar is usually slightly offset to align nicely with
1786 // indent guides. However, this offset is not needed if indent guides are
1787 // disabled for the current editor.
1788 let content_offset = self
1789 .editor
1790 .read(cx)
1791 .show_indent_guides
1792 .is_none_or(|should_show| should_show)
1793 .then_some(content_offset)
1794 .unwrap_or_default();
1795
1796 Some(EditorScrollbars::from_scrollbar_axes(
1797 ScrollbarAxes {
1798 horizontal: scrollbar_settings.axes.horizontal
1799 && self.editor.read(cx).show_scrollbars.horizontal,
1800 vertical: scrollbar_settings.axes.vertical
1801 && self.editor.read(cx).show_scrollbars.vertical,
1802 },
1803 scrollbar_layout_information,
1804 content_offset,
1805 scroll_position,
1806 self.style.scrollbar_width,
1807 right_margin,
1808 editor_width,
1809 show_scrollbars,
1810 self.editor.read(cx).scroll_manager.active_scrollbar_state(),
1811 window,
1812 ))
1813 }
1814
1815 fn layout_minimap(
1816 &self,
1817 snapshot: &EditorSnapshot,
1818 minimap_width: Pixels,
1819 scroll_position: gpui::Point<f32>,
1820 scrollbar_layout_information: &ScrollbarLayoutInformation,
1821 scrollbar_layout: Option<&EditorScrollbars>,
1822 window: &mut Window,
1823 cx: &mut App,
1824 ) -> Option<MinimapLayout> {
1825 let minimap_editor = self.editor.read(cx).minimap().cloned()?;
1826
1827 let minimap_settings = EditorSettings::get_global(cx).minimap;
1828
1829 if minimap_settings.on_active_editor() {
1830 let active_editor = self.editor.read(cx).workspace().and_then(|ws| {
1831 ws.read(cx)
1832 .active_pane()
1833 .read(cx)
1834 .active_item()
1835 .and_then(|i| i.act_as::<Editor>(cx))
1836 });
1837 if active_editor.is_some_and(|e| e != self.editor) {
1838 return None;
1839 }
1840 }
1841
1842 if !snapshot.mode.is_full()
1843 || minimap_width.is_zero()
1844 || matches!(
1845 minimap_settings.show,
1846 ShowMinimap::Auto if scrollbar_layout.is_none_or(|layout| !layout.visible)
1847 )
1848 {
1849 return None;
1850 }
1851
1852 const MINIMAP_AXIS: ScrollbarAxis = ScrollbarAxis::Vertical;
1853
1854 let ScrollbarLayoutInformation {
1855 editor_bounds,
1856 scroll_range,
1857 glyph_grid_cell,
1858 } = scrollbar_layout_information;
1859
1860 let line_height = glyph_grid_cell.height;
1861 let scroll_position = scroll_position.along(MINIMAP_AXIS);
1862
1863 let top_right_anchor = scrollbar_layout
1864 .and_then(|layout| layout.vertical.as_ref())
1865 .map(|vertical_scrollbar| vertical_scrollbar.hitbox.origin)
1866 .unwrap_or_else(|| editor_bounds.top_right());
1867
1868 let thumb_state = self
1869 .editor
1870 .read_with(cx, |editor, _| editor.scroll_manager.minimap_thumb_state());
1871
1872 let show_thumb = match minimap_settings.thumb {
1873 MinimapThumb::Always => true,
1874 MinimapThumb::Hover => thumb_state.is_some(),
1875 };
1876
1877 let minimap_bounds = Bounds::from_corner_and_size(
1878 Corner::TopRight,
1879 top_right_anchor,
1880 size(minimap_width, editor_bounds.size.height),
1881 );
1882 let minimap_line_height = self.get_minimap_line_height(
1883 minimap_editor
1884 .read(cx)
1885 .text_style_refinement
1886 .as_ref()
1887 .and_then(|refinement| refinement.font_size)
1888 .unwrap_or(MINIMAP_FONT_SIZE),
1889 window,
1890 cx,
1891 );
1892 let minimap_height = minimap_bounds.size.height;
1893
1894 let visible_editor_lines = editor_bounds.size.height / line_height;
1895 let total_editor_lines = scroll_range.height / line_height;
1896 let minimap_lines = minimap_height / minimap_line_height;
1897
1898 let minimap_scroll_top = MinimapLayout::calculate_minimap_top_offset(
1899 total_editor_lines,
1900 visible_editor_lines,
1901 minimap_lines,
1902 scroll_position,
1903 );
1904
1905 let layout = ScrollbarLayout::for_minimap(
1906 window.insert_hitbox(minimap_bounds, HitboxBehavior::Normal),
1907 visible_editor_lines,
1908 total_editor_lines,
1909 minimap_line_height,
1910 scroll_position,
1911 minimap_scroll_top,
1912 show_thumb,
1913 )
1914 .with_thumb_state(thumb_state);
1915
1916 minimap_editor.update(cx, |editor, cx| {
1917 editor.set_scroll_position(point(0., minimap_scroll_top), window, cx)
1918 });
1919
1920 // Required for the drop shadow to be visible
1921 const PADDING_OFFSET: Pixels = px(4.);
1922
1923 let mut minimap = div()
1924 .size_full()
1925 .shadow_xs()
1926 .px(PADDING_OFFSET)
1927 .child(minimap_editor)
1928 .into_any_element();
1929
1930 let extended_bounds = minimap_bounds.extend(Edges {
1931 right: PADDING_OFFSET,
1932 left: PADDING_OFFSET,
1933 ..Default::default()
1934 });
1935 minimap.layout_as_root(extended_bounds.size.into(), window, cx);
1936 window.with_absolute_element_offset(extended_bounds.origin, |window| {
1937 minimap.prepaint(window, cx)
1938 });
1939
1940 Some(MinimapLayout {
1941 minimap,
1942 thumb_layout: layout,
1943 thumb_border_style: minimap_settings.thumb_border,
1944 minimap_line_height,
1945 minimap_scroll_top,
1946 max_scroll_top: total_editor_lines,
1947 })
1948 }
1949
1950 fn get_minimap_line_height(
1951 &self,
1952 font_size: AbsoluteLength,
1953 window: &mut Window,
1954 cx: &mut App,
1955 ) -> Pixels {
1956 let rem_size = self.rem_size(cx).unwrap_or(window.rem_size());
1957 let mut text_style = self.style.text.clone();
1958 text_style.font_size = font_size;
1959 text_style.line_height_in_pixels(rem_size)
1960 }
1961
1962 fn get_minimap_width(
1963 &self,
1964 minimap_settings: &Minimap,
1965 scrollbars_shown: bool,
1966 text_width: Pixels,
1967 em_width: Pixels,
1968 font_size: Pixels,
1969 rem_size: Pixels,
1970 cx: &App,
1971 ) -> Option<Pixels> {
1972 if minimap_settings.show == ShowMinimap::Auto && !scrollbars_shown {
1973 return None;
1974 }
1975
1976 let minimap_font_size = self.editor.read_with(cx, |editor, cx| {
1977 editor.minimap().map(|minimap_editor| {
1978 minimap_editor
1979 .read(cx)
1980 .text_style_refinement
1981 .as_ref()
1982 .and_then(|refinement| refinement.font_size)
1983 .unwrap_or(MINIMAP_FONT_SIZE)
1984 })
1985 })?;
1986
1987 let minimap_em_width = em_width * (minimap_font_size.to_pixels(rem_size) / font_size);
1988
1989 let minimap_width = (text_width * MinimapLayout::MINIMAP_WIDTH_PCT)
1990 .min(minimap_em_width * minimap_settings.max_width_columns.get() as f32);
1991
1992 (minimap_width >= minimap_em_width * MinimapLayout::MINIMAP_MIN_WIDTH_COLUMNS)
1993 .then_some(minimap_width)
1994 }
1995
1996 fn prepaint_crease_toggles(
1997 &self,
1998 crease_toggles: &mut [Option<AnyElement>],
1999 line_height: Pixels,
2000 gutter_dimensions: &GutterDimensions,
2001 gutter_settings: crate::editor_settings::Gutter,
2002 scroll_pixel_position: gpui::Point<Pixels>,
2003 gutter_hitbox: &Hitbox,
2004 window: &mut Window,
2005 cx: &mut App,
2006 ) {
2007 for (ix, crease_toggle) in crease_toggles.iter_mut().enumerate() {
2008 if let Some(crease_toggle) = crease_toggle {
2009 debug_assert!(gutter_settings.folds);
2010 let available_space = size(
2011 AvailableSpace::MinContent,
2012 AvailableSpace::Definite(line_height * 0.55),
2013 );
2014 let crease_toggle_size = crease_toggle.layout_as_root(available_space, window, cx);
2015
2016 let position = point(
2017 gutter_dimensions.width - gutter_dimensions.right_padding,
2018 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
2019 );
2020 let centering_offset = point(
2021 (gutter_dimensions.fold_area_width() - crease_toggle_size.width) / 2.,
2022 (line_height - crease_toggle_size.height) / 2.,
2023 );
2024 let origin = gutter_hitbox.origin + position + centering_offset;
2025 crease_toggle.prepaint_as_root(origin, available_space, window, cx);
2026 }
2027 }
2028 }
2029
2030 fn prepaint_expand_toggles(
2031 &self,
2032 expand_toggles: &mut [Option<(AnyElement, gpui::Point<Pixels>)>],
2033 window: &mut Window,
2034 cx: &mut App,
2035 ) {
2036 for (expand_toggle, origin) in expand_toggles.iter_mut().flatten() {
2037 let available_space = size(AvailableSpace::MinContent, AvailableSpace::MinContent);
2038 expand_toggle.layout_as_root(available_space, window, cx);
2039 expand_toggle.prepaint_as_root(*origin, available_space, window, cx);
2040 }
2041 }
2042
2043 fn prepaint_crease_trailers(
2044 &self,
2045 trailers: Vec<Option<AnyElement>>,
2046 lines: &[LineWithInvisibles],
2047 line_height: Pixels,
2048 content_origin: gpui::Point<Pixels>,
2049 scroll_pixel_position: gpui::Point<Pixels>,
2050 em_width: Pixels,
2051 window: &mut Window,
2052 cx: &mut App,
2053 ) -> Vec<Option<CreaseTrailerLayout>> {
2054 trailers
2055 .into_iter()
2056 .enumerate()
2057 .map(|(ix, element)| {
2058 let mut element = element?;
2059 let available_space = size(
2060 AvailableSpace::MinContent,
2061 AvailableSpace::Definite(line_height),
2062 );
2063 let size = element.layout_as_root(available_space, window, cx);
2064
2065 let line = &lines[ix];
2066 let padding = if line.width == Pixels::ZERO {
2067 Pixels::ZERO
2068 } else {
2069 4. * em_width
2070 };
2071 let position = point(
2072 scroll_pixel_position.x + line.width + padding,
2073 ix as f32 * line_height - (scroll_pixel_position.y % line_height),
2074 );
2075 let centering_offset = point(px(0.), (line_height - size.height) / 2.);
2076 let origin = content_origin + position + centering_offset;
2077 element.prepaint_as_root(origin, available_space, window, cx);
2078 Some(CreaseTrailerLayout {
2079 element,
2080 bounds: Bounds::new(origin, size),
2081 })
2082 })
2083 .collect()
2084 }
2085
2086 // Folds contained in a hunk are ignored apart from shrinking visual size
2087 // If a fold contains any hunks then that fold line is marked as modified
2088 fn layout_gutter_diff_hunks(
2089 &self,
2090 line_height: Pixels,
2091 gutter_hitbox: &Hitbox,
2092 display_rows: Range<DisplayRow>,
2093 snapshot: &EditorSnapshot,
2094 window: &mut Window,
2095 cx: &mut App,
2096 ) -> Vec<(DisplayDiffHunk, Option<Hitbox>)> {
2097 let folded_buffers = self.editor.read(cx).folded_buffers(cx);
2098 let mut display_hunks = snapshot
2099 .display_diff_hunks_for_rows(display_rows, folded_buffers)
2100 .map(|hunk| (hunk, None))
2101 .collect::<Vec<_>>();
2102 let git_gutter_setting = ProjectSettings::get_global(cx)
2103 .git
2104 .git_gutter
2105 .unwrap_or_default();
2106 if let GitGutterSetting::TrackedFiles = git_gutter_setting {
2107 for (hunk, hitbox) in &mut display_hunks {
2108 if matches!(hunk, DisplayDiffHunk::Unfolded { .. }) {
2109 let hunk_bounds =
2110 Self::diff_hunk_bounds(snapshot, line_height, gutter_hitbox.bounds, hunk);
2111 *hitbox = Some(window.insert_hitbox(hunk_bounds, HitboxBehavior::BlockMouse));
2112 }
2113 }
2114 }
2115
2116 display_hunks
2117 }
2118
2119 fn layout_inline_diagnostics(
2120 &self,
2121 line_layouts: &[LineWithInvisibles],
2122 crease_trailers: &[Option<CreaseTrailerLayout>],
2123 row_block_types: &HashMap<DisplayRow, bool>,
2124 content_origin: gpui::Point<Pixels>,
2125 scroll_pixel_position: gpui::Point<Pixels>,
2126 edit_prediction_popover_origin: Option<gpui::Point<Pixels>>,
2127 start_row: DisplayRow,
2128 end_row: DisplayRow,
2129 line_height: Pixels,
2130 em_width: Pixels,
2131 style: &EditorStyle,
2132 window: &mut Window,
2133 cx: &mut App,
2134 ) -> HashMap<DisplayRow, AnyElement> {
2135 let max_severity = match self
2136 .editor
2137 .read(cx)
2138 .inline_diagnostics_enabled()
2139 .then(|| {
2140 ProjectSettings::get_global(cx)
2141 .diagnostics
2142 .inline
2143 .max_severity
2144 .unwrap_or_else(|| self.editor.read(cx).diagnostics_max_severity)
2145 .into_lsp()
2146 })
2147 .flatten()
2148 {
2149 Some(max_severity) => max_severity,
2150 None => return HashMap::default(),
2151 };
2152
2153 let active_diagnostics_group =
2154 if let ActiveDiagnostic::Group(group) = &self.editor.read(cx).active_diagnostics {
2155 Some(group.group_id)
2156 } else {
2157 None
2158 };
2159
2160 let diagnostics_by_rows = self.editor.update(cx, |editor, cx| {
2161 let snapshot = editor.snapshot(window, cx);
2162 editor
2163 .inline_diagnostics
2164 .iter()
2165 .filter(|(_, diagnostic)| diagnostic.severity <= max_severity)
2166 .filter(|(_, diagnostic)| match active_diagnostics_group {
2167 Some(active_diagnostics_group) => {
2168 // Active diagnostics are all shown in the editor already, no need to display them inline
2169 diagnostic.group_id != active_diagnostics_group
2170 }
2171 None => true,
2172 })
2173 .map(|(point, diag)| (point.to_display_point(&snapshot), diag.clone()))
2174 .skip_while(|(point, _)| point.row() < start_row)
2175 .take_while(|(point, _)| point.row() < end_row)
2176 .filter(|(point, _)| !row_block_types.contains_key(&point.row()))
2177 .fold(HashMap::default(), |mut acc, (point, diagnostic)| {
2178 acc.entry(point.row())
2179 .or_insert_with(Vec::new)
2180 .push(diagnostic);
2181 acc
2182 })
2183 });
2184
2185 if diagnostics_by_rows.is_empty() {
2186 return HashMap::default();
2187 }
2188
2189 let severity_to_color = |sev: &lsp::DiagnosticSeverity| match sev {
2190 &lsp::DiagnosticSeverity::ERROR => Color::Error,
2191 &lsp::DiagnosticSeverity::WARNING => Color::Warning,
2192 &lsp::DiagnosticSeverity::INFORMATION => Color::Info,
2193 &lsp::DiagnosticSeverity::HINT => Color::Hint,
2194 _ => Color::Error,
2195 };
2196
2197 let padding = ProjectSettings::get_global(cx).diagnostics.inline.padding as f32 * em_width;
2198 let min_x = self.column_pixels(
2199 ProjectSettings::get_global(cx)
2200 .diagnostics
2201 .inline
2202 .min_column as usize,
2203 window,
2204 );
2205
2206 let mut elements = HashMap::default();
2207 for (row, mut diagnostics) in diagnostics_by_rows {
2208 diagnostics.sort_by_key(|diagnostic| {
2209 (
2210 diagnostic.severity,
2211 std::cmp::Reverse(diagnostic.is_primary),
2212 diagnostic.start.row,
2213 diagnostic.start.column,
2214 )
2215 });
2216
2217 let Some(diagnostic_to_render) = diagnostics
2218 .iter()
2219 .find(|diagnostic| diagnostic.is_primary)
2220 .or_else(|| diagnostics.first())
2221 else {
2222 continue;
2223 };
2224
2225 let pos_y = content_origin.y
2226 + line_height * (row.0 as f32 - scroll_pixel_position.y / line_height);
2227
2228 let window_ix = row.0.saturating_sub(start_row.0) as usize;
2229 let pos_x = {
2230 let crease_trailer_layout = &crease_trailers[window_ix];
2231 let line_layout = &line_layouts[window_ix];
2232
2233 let line_end = if let Some(crease_trailer) = crease_trailer_layout {
2234 crease_trailer.bounds.right()
2235 } else {
2236 content_origin.x - scroll_pixel_position.x + line_layout.width
2237 };
2238
2239 let padded_line = line_end + padding;
2240 let min_start = content_origin.x - scroll_pixel_position.x + min_x;
2241
2242 cmp::max(padded_line, min_start)
2243 };
2244
2245 let behind_edit_prediction_popover = edit_prediction_popover_origin
2246 .as_ref()
2247 .is_some_and(|edit_prediction_popover_origin| {
2248 (pos_y..pos_y + line_height).contains(&edit_prediction_popover_origin.y)
2249 });
2250 let opacity = if behind_edit_prediction_popover {
2251 0.5
2252 } else {
2253 1.0
2254 };
2255
2256 let mut element = h_flex()
2257 .id(("diagnostic", row.0))
2258 .h(line_height)
2259 .w_full()
2260 .px_1()
2261 .rounded_xs()
2262 .opacity(opacity)
2263 .bg(severity_to_color(&diagnostic_to_render.severity)
2264 .color(cx)
2265 .opacity(0.05))
2266 .text_color(severity_to_color(&diagnostic_to_render.severity).color(cx))
2267 .text_sm()
2268 .font_family(style.text.font().family)
2269 .child(diagnostic_to_render.message.clone())
2270 .into_any();
2271
2272 element.prepaint_as_root(point(pos_x, pos_y), AvailableSpace::min_size(), window, cx);
2273
2274 elements.insert(row, element);
2275 }
2276
2277 elements
2278 }
2279
2280 fn layout_inline_code_actions(
2281 &self,
2282 display_point: DisplayPoint,
2283 content_origin: gpui::Point<Pixels>,
2284 scroll_pixel_position: gpui::Point<Pixels>,
2285 line_height: Pixels,
2286 snapshot: &EditorSnapshot,
2287 window: &mut Window,
2288 cx: &mut App,
2289 ) -> Option<AnyElement> {
2290 if !snapshot
2291 .show_code_actions
2292 .unwrap_or(EditorSettings::get_global(cx).inline_code_actions)
2293 {
2294 return None;
2295 }
2296
2297 let icon_size = ui::IconSize::XSmall;
2298 let mut button = self.editor.update(cx, |editor, cx| {
2299 editor.available_code_actions.as_ref()?;
2300 let active = editor
2301 .context_menu
2302 .borrow()
2303 .as_ref()
2304 .and_then(|menu| {
2305 if let crate::CodeContextMenu::CodeActions(CodeActionsMenu {
2306 deployed_from,
2307 ..
2308 }) = menu
2309 {
2310 deployed_from.as_ref()
2311 } else {
2312 None
2313 }
2314 })
2315 .is_some_and(|source| matches!(source, CodeActionSource::Indicator(..)));
2316 Some(editor.render_inline_code_actions(icon_size, display_point.row(), active, cx))
2317 })?;
2318
2319 let buffer_point = display_point.to_point(&snapshot.display_snapshot);
2320
2321 // do not show code action for folded line
2322 if snapshot.is_line_folded(MultiBufferRow(buffer_point.row)) {
2323 return None;
2324 }
2325
2326 // do not show code action for blank line with cursor
2327 let line_indent = snapshot
2328 .display_snapshot
2329 .buffer_snapshot
2330 .line_indent_for_row(MultiBufferRow(buffer_point.row));
2331 if line_indent.is_line_blank() {
2332 return None;
2333 }
2334
2335 const INLINE_SLOT_CHAR_LIMIT: u32 = 4;
2336 const MAX_ALTERNATE_DISTANCE: u32 = 8;
2337
2338 let excerpt_id = snapshot
2339 .display_snapshot
2340 .buffer_snapshot
2341 .excerpt_containing(buffer_point..buffer_point)
2342 .map(|excerpt| excerpt.id());
2343
2344 let is_valid_row = |row_candidate: u32| -> bool {
2345 // move to other row if folded row
2346 if snapshot.is_line_folded(MultiBufferRow(row_candidate)) {
2347 return false;
2348 }
2349 if buffer_point.row == row_candidate {
2350 // move to other row if cursor is in slot
2351 if buffer_point.column < INLINE_SLOT_CHAR_LIMIT {
2352 return false;
2353 }
2354 } else {
2355 let candidate_point = MultiBufferPoint {
2356 row: row_candidate,
2357 column: 0,
2358 };
2359 let candidate_excerpt_id = snapshot
2360 .display_snapshot
2361 .buffer_snapshot
2362 .excerpt_containing(candidate_point..candidate_point)
2363 .map(|excerpt| excerpt.id());
2364 // move to other row if different excerpt
2365 if excerpt_id != candidate_excerpt_id {
2366 return false;
2367 }
2368 }
2369 let line_indent = snapshot
2370 .display_snapshot
2371 .buffer_snapshot
2372 .line_indent_for_row(MultiBufferRow(row_candidate));
2373 // use this row if it's blank
2374 if line_indent.is_line_blank() {
2375 true
2376 } else {
2377 // use this row if code starts after slot
2378 let indent_size = snapshot
2379 .display_snapshot
2380 .buffer_snapshot
2381 .indent_size_for_line(MultiBufferRow(row_candidate));
2382 indent_size.len >= INLINE_SLOT_CHAR_LIMIT
2383 }
2384 };
2385
2386 let new_buffer_row = if is_valid_row(buffer_point.row) {
2387 Some(buffer_point.row)
2388 } else {
2389 let max_row = snapshot.display_snapshot.buffer_snapshot.max_point().row;
2390 (1..=MAX_ALTERNATE_DISTANCE).find_map(|offset| {
2391 let row_above = buffer_point.row.saturating_sub(offset);
2392 let row_below = buffer_point.row + offset;
2393 if row_above != buffer_point.row && is_valid_row(row_above) {
2394 Some(row_above)
2395 } else if row_below <= max_row && is_valid_row(row_below) {
2396 Some(row_below)
2397 } else {
2398 None
2399 }
2400 })
2401 }?;
2402
2403 let new_display_row = snapshot
2404 .display_snapshot
2405 .point_to_display_point(
2406 Point {
2407 row: new_buffer_row,
2408 column: buffer_point.column,
2409 },
2410 text::Bias::Left,
2411 )
2412 .row();
2413
2414 let start_y = content_origin.y
2415 + ((new_display_row.as_f32() - (scroll_pixel_position.y / line_height)) * line_height)
2416 + (line_height / 2.0)
2417 - (icon_size.square(window, cx) / 2.);
2418 let start_x = content_origin.x - scroll_pixel_position.x + (window.rem_size() * 0.1);
2419
2420 let absolute_offset = gpui::point(start_x, start_y);
2421 button.layout_as_root(gpui::AvailableSpace::min_size(), window, cx);
2422 button.prepaint_as_root(
2423 absolute_offset,
2424 gpui::AvailableSpace::min_size(),
2425 window,
2426 cx,
2427 );
2428 Some(button)
2429 }
2430
2431 fn layout_inline_blame(
2432 &self,
2433 display_row: DisplayRow,
2434 row_info: &RowInfo,
2435 line_layout: &LineWithInvisibles,
2436 crease_trailer: Option<&CreaseTrailerLayout>,
2437 em_width: Pixels,
2438 content_origin: gpui::Point<Pixels>,
2439 scroll_pixel_position: gpui::Point<Pixels>,
2440 line_height: Pixels,
2441 text_hitbox: &Hitbox,
2442 window: &mut Window,
2443 cx: &mut App,
2444 ) -> Option<InlineBlameLayout> {
2445 if !self
2446 .editor
2447 .update(cx, |editor, cx| editor.render_git_blame_inline(window, cx))
2448 {
2449 return None;
2450 }
2451
2452 let editor = self.editor.read(cx);
2453 let blame = editor.blame.clone()?;
2454 let padding = {
2455 const INLINE_ACCEPT_SUGGESTION_EM_WIDTHS: f32 = 14.;
2456
2457 let mut padding = ProjectSettings::get_global(cx)
2458 .git
2459 .inline_blame
2460 .unwrap_or_default()
2461 .padding as f32;
2462
2463 if let Some(edit_prediction) = editor.active_edit_prediction.as_ref()
2464 && let EditPrediction::Edit {
2465 display_mode: EditDisplayMode::TabAccept,
2466 ..
2467 } = &edit_prediction.completion
2468 {
2469 padding += INLINE_ACCEPT_SUGGESTION_EM_WIDTHS
2470 }
2471
2472 padding * em_width
2473 };
2474
2475 let (buffer_id, entry) = blame
2476 .update(cx, |blame, cx| {
2477 blame.blame_for_rows(&[*row_info], cx).next()
2478 })
2479 .flatten()?;
2480
2481 let mut element = render_inline_blame_entry(entry.clone(), &self.style, cx)?;
2482
2483 let start_y = content_origin.y
2484 + line_height * (display_row.as_f32() - scroll_pixel_position.y / line_height);
2485
2486 let start_x = {
2487 let line_end = if let Some(crease_trailer) = crease_trailer {
2488 crease_trailer.bounds.right()
2489 } else {
2490 content_origin.x - scroll_pixel_position.x + line_layout.width
2491 };
2492
2493 let padded_line_end = line_end + padding;
2494
2495 let min_column_in_pixels = ProjectSettings::get_global(cx)
2496 .git
2497 .inline_blame
2498 .map(|settings| settings.min_column)
2499 .map(|col| self.column_pixels(col as usize, window))
2500 .unwrap_or(px(0.));
2501 let min_start = content_origin.x - scroll_pixel_position.x + min_column_in_pixels;
2502
2503 cmp::max(padded_line_end, min_start)
2504 };
2505
2506 let absolute_offset = point(start_x, start_y);
2507 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
2508 let bounds = Bounds::new(absolute_offset, size);
2509
2510 self.layout_blame_entry_popover(
2511 entry.clone(),
2512 blame,
2513 line_height,
2514 text_hitbox,
2515 row_info.buffer_id?,
2516 window,
2517 cx,
2518 );
2519
2520 element.prepaint_as_root(absolute_offset, AvailableSpace::min_size(), window, cx);
2521
2522 Some(InlineBlameLayout {
2523 element,
2524 bounds,
2525 buffer_id,
2526 entry,
2527 })
2528 }
2529
2530 fn layout_blame_entry_popover(
2531 &self,
2532 blame_entry: BlameEntry,
2533 blame: Entity<GitBlame>,
2534 line_height: Pixels,
2535 text_hitbox: &Hitbox,
2536 buffer: BufferId,
2537 window: &mut Window,
2538 cx: &mut App,
2539 ) {
2540 let Some((popover_state, target_point)) = self.editor.read_with(cx, |editor, _| {
2541 editor
2542 .inline_blame_popover
2543 .as_ref()
2544 .map(|state| (state.popover_state.clone(), state.position))
2545 }) else {
2546 return;
2547 };
2548
2549 let workspace = self
2550 .editor
2551 .read_with(cx, |editor, _| editor.workspace().map(|w| w.downgrade()));
2552
2553 let maybe_element = workspace.and_then(|workspace| {
2554 render_blame_entry_popover(
2555 blame_entry,
2556 popover_state.scroll_handle,
2557 popover_state.commit_message,
2558 popover_state.markdown,
2559 workspace,
2560 &blame,
2561 buffer,
2562 window,
2563 cx,
2564 )
2565 });
2566
2567 if let Some(mut element) = maybe_element {
2568 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
2569 let overall_height = size.height + HOVER_POPOVER_GAP;
2570 let popover_origin = if target_point.y > overall_height {
2571 point(target_point.x, target_point.y - size.height)
2572 } else {
2573 point(
2574 target_point.x,
2575 target_point.y + line_height + HOVER_POPOVER_GAP,
2576 )
2577 };
2578
2579 let horizontal_offset = (text_hitbox.top_right().x
2580 - POPOVER_RIGHT_OFFSET
2581 - (popover_origin.x + size.width))
2582 .min(Pixels::ZERO);
2583
2584 let origin = point(popover_origin.x + horizontal_offset, popover_origin.y);
2585 let popover_bounds = Bounds::new(origin, size);
2586
2587 self.editor.update(cx, |editor, _| {
2588 if let Some(state) = &mut editor.inline_blame_popover {
2589 state.popover_bounds = Some(popover_bounds);
2590 }
2591 });
2592
2593 window.defer_draw(element, origin, 2);
2594 }
2595 }
2596
2597 fn layout_blame_entries(
2598 &self,
2599 buffer_rows: &[RowInfo],
2600 em_width: Pixels,
2601 scroll_position: gpui::Point<f32>,
2602 line_height: Pixels,
2603 gutter_hitbox: &Hitbox,
2604 max_width: Option<Pixels>,
2605 window: &mut Window,
2606 cx: &mut App,
2607 ) -> Option<Vec<AnyElement>> {
2608 if !self
2609 .editor
2610 .update(cx, |editor, cx| editor.render_git_blame_gutter(cx))
2611 {
2612 return None;
2613 }
2614
2615 let blame = self.editor.read(cx).blame.clone()?;
2616 let workspace = self.editor.read(cx).workspace()?;
2617 let blamed_rows: Vec<_> = blame.update(cx, |blame, cx| {
2618 blame.blame_for_rows(buffer_rows, cx).collect()
2619 });
2620
2621 let width = if let Some(max_width) = max_width {
2622 AvailableSpace::Definite(max_width)
2623 } else {
2624 AvailableSpace::MaxContent
2625 };
2626 let scroll_top = scroll_position.y * line_height;
2627 let start_x = em_width;
2628
2629 let mut last_used_color: Option<(PlayerColor, Oid)> = None;
2630 let blame_renderer = cx.global::<GlobalBlameRenderer>().0.clone();
2631
2632 let shaped_lines = blamed_rows
2633 .into_iter()
2634 .enumerate()
2635 .flat_map(|(ix, blame_entry)| {
2636 let (buffer_id, blame_entry) = blame_entry?;
2637 let mut element = render_blame_entry(
2638 ix,
2639 &blame,
2640 blame_entry,
2641 &self.style,
2642 &mut last_used_color,
2643 self.editor.clone(),
2644 workspace.clone(),
2645 buffer_id,
2646 blame_renderer.clone(),
2647 cx,
2648 )?;
2649
2650 let start_y = ix as f32 * line_height - (scroll_top % line_height);
2651 let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
2652
2653 element.prepaint_as_root(
2654 absolute_offset,
2655 size(width, AvailableSpace::MinContent),
2656 window,
2657 cx,
2658 );
2659
2660 Some(element)
2661 })
2662 .collect();
2663
2664 Some(shaped_lines)
2665 }
2666
2667 fn layout_indent_guides(
2668 &self,
2669 content_origin: gpui::Point<Pixels>,
2670 text_origin: gpui::Point<Pixels>,
2671 visible_buffer_range: Range<MultiBufferRow>,
2672 scroll_pixel_position: gpui::Point<Pixels>,
2673 line_height: Pixels,
2674 snapshot: &DisplaySnapshot,
2675 window: &mut Window,
2676 cx: &mut App,
2677 ) -> Option<Vec<IndentGuideLayout>> {
2678 let indent_guides = self.editor.update(cx, |editor, cx| {
2679 editor.indent_guides(visible_buffer_range, snapshot, cx)
2680 })?;
2681
2682 let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
2683 editor
2684 .find_active_indent_guide_indices(&indent_guides, snapshot, window, cx)
2685 .unwrap_or_default()
2686 });
2687
2688 Some(
2689 indent_guides
2690 .into_iter()
2691 .enumerate()
2692 .filter_map(|(i, indent_guide)| {
2693 let single_indent_width =
2694 self.column_pixels(indent_guide.tab_size as usize, window);
2695 let total_width = single_indent_width * indent_guide.depth as f32;
2696 let start_x = content_origin.x + total_width - scroll_pixel_position.x;
2697 if start_x >= text_origin.x {
2698 let (offset_y, length) = Self::calculate_indent_guide_bounds(
2699 indent_guide.start_row..indent_guide.end_row,
2700 line_height,
2701 snapshot,
2702 );
2703
2704 let start_y = content_origin.y + offset_y - scroll_pixel_position.y;
2705
2706 Some(IndentGuideLayout {
2707 origin: point(start_x, start_y),
2708 length,
2709 single_indent_width,
2710 depth: indent_guide.depth,
2711 active: active_indent_guide_indices.contains(&i),
2712 settings: indent_guide.settings,
2713 })
2714 } else {
2715 None
2716 }
2717 })
2718 .collect(),
2719 )
2720 }
2721
2722 fn layout_wrap_guides(
2723 &self,
2724 em_advance: Pixels,
2725 scroll_position: gpui::Point<f32>,
2726 content_origin: gpui::Point<Pixels>,
2727 scrollbar_layout: Option<&EditorScrollbars>,
2728 vertical_scrollbar_width: Pixels,
2729 hitbox: &Hitbox,
2730 window: &Window,
2731 cx: &App,
2732 ) -> SmallVec<[(Pixels, bool); 2]> {
2733 let scroll_left = scroll_position.x * em_advance;
2734 let content_origin = content_origin.x;
2735 let horizontal_offset = content_origin - scroll_left;
2736 let vertical_scrollbar_width = scrollbar_layout
2737 .and_then(|layout| layout.visible.then_some(vertical_scrollbar_width))
2738 .unwrap_or_default();
2739
2740 self.editor
2741 .read(cx)
2742 .wrap_guides(cx)
2743 .into_iter()
2744 .flat_map(|(guide, active)| {
2745 let wrap_position = self.column_pixels(guide, window);
2746 let wrap_guide_x = wrap_position + horizontal_offset;
2747 let display_wrap_guide = wrap_guide_x >= content_origin
2748 && wrap_guide_x <= hitbox.bounds.right() - vertical_scrollbar_width;
2749
2750 display_wrap_guide.then_some((wrap_guide_x, active))
2751 })
2752 .collect()
2753 }
2754
2755 fn calculate_indent_guide_bounds(
2756 row_range: Range<MultiBufferRow>,
2757 line_height: Pixels,
2758 snapshot: &DisplaySnapshot,
2759 ) -> (gpui::Pixels, gpui::Pixels) {
2760 let start_point = Point::new(row_range.start.0, 0);
2761 let end_point = Point::new(row_range.end.0, 0);
2762
2763 let row_range = start_point.to_display_point(snapshot).row()
2764 ..end_point.to_display_point(snapshot).row();
2765
2766 let mut prev_line = start_point;
2767 prev_line.row = prev_line.row.saturating_sub(1);
2768 let prev_line = prev_line.to_display_point(snapshot).row();
2769
2770 let mut cons_line = end_point;
2771 cons_line.row += 1;
2772 let cons_line = cons_line.to_display_point(snapshot).row();
2773
2774 let mut offset_y = row_range.start.0 as f32 * line_height;
2775 let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
2776
2777 // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
2778 if row_range.end == cons_line {
2779 length += line_height;
2780 }
2781
2782 // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
2783 // we want to extend the indent guide to the start of the block.
2784 let mut block_height = 0;
2785 let mut block_offset = 0;
2786 let mut found_excerpt_header = false;
2787 for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
2788 if matches!(
2789 block,
2790 Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
2791 ) {
2792 found_excerpt_header = true;
2793 break;
2794 }
2795 block_offset += block.height();
2796 block_height += block.height();
2797 }
2798 if !found_excerpt_header {
2799 offset_y -= block_offset as f32 * line_height;
2800 length += block_height as f32 * line_height;
2801 }
2802
2803 // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
2804 // we want to ensure that the indent guide stops before the excerpt header.
2805 let mut block_height = 0;
2806 let mut found_excerpt_header = false;
2807 for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
2808 if matches!(
2809 block,
2810 Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
2811 ) {
2812 found_excerpt_header = true;
2813 }
2814 block_height += block.height();
2815 }
2816 if found_excerpt_header {
2817 length -= block_height as f32 * line_height;
2818 }
2819
2820 (offset_y, length)
2821 }
2822
2823 fn layout_breakpoints(
2824 &self,
2825 line_height: Pixels,
2826 range: Range<DisplayRow>,
2827 scroll_pixel_position: gpui::Point<Pixels>,
2828 gutter_dimensions: &GutterDimensions,
2829 gutter_hitbox: &Hitbox,
2830 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
2831 snapshot: &EditorSnapshot,
2832 breakpoints: HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
2833 row_infos: &[RowInfo],
2834 window: &mut Window,
2835 cx: &mut App,
2836 ) -> Vec<AnyElement> {
2837 self.editor.update(cx, |editor, cx| {
2838 breakpoints
2839 .into_iter()
2840 .filter_map(|(display_row, (text_anchor, bp, state))| {
2841 if row_infos
2842 .get((display_row.0.saturating_sub(range.start.0)) as usize)
2843 .is_some_and(|row_info| {
2844 row_info.expand_info.is_some()
2845 || row_info
2846 .diff_status
2847 .is_some_and(|status| status.is_deleted())
2848 })
2849 {
2850 return None;
2851 }
2852
2853 if range.start > display_row || range.end < display_row {
2854 return None;
2855 }
2856
2857 let row =
2858 MultiBufferRow(DisplayPoint::new(display_row, 0).to_point(snapshot).row);
2859 if snapshot.is_line_folded(row) {
2860 return None;
2861 }
2862
2863 let button = editor.render_breakpoint(text_anchor, display_row, &bp, state, cx);
2864
2865 let button = prepaint_gutter_button(
2866 button,
2867 display_row,
2868 line_height,
2869 gutter_dimensions,
2870 scroll_pixel_position,
2871 gutter_hitbox,
2872 display_hunks,
2873 window,
2874 cx,
2875 );
2876 Some(button)
2877 })
2878 .collect_vec()
2879 })
2880 }
2881
2882 #[allow(clippy::too_many_arguments)]
2883 fn layout_run_indicators(
2884 &self,
2885 line_height: Pixels,
2886 range: Range<DisplayRow>,
2887 row_infos: &[RowInfo],
2888 scroll_pixel_position: gpui::Point<Pixels>,
2889 gutter_dimensions: &GutterDimensions,
2890 gutter_hitbox: &Hitbox,
2891 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
2892 snapshot: &EditorSnapshot,
2893 breakpoints: &mut HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
2894 window: &mut Window,
2895 cx: &mut App,
2896 ) -> Vec<AnyElement> {
2897 self.editor.update(cx, |editor, cx| {
2898 let active_task_indicator_row =
2899 // TODO: add edit button on the right side of each row in the context menu
2900 if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
2901 deployed_from,
2902 actions,
2903 ..
2904 })) = editor.context_menu.borrow().as_ref()
2905 {
2906 actions
2907 .tasks()
2908 .map(|tasks| tasks.position.to_display_point(snapshot).row())
2909 .or_else(|| match deployed_from {
2910 Some(CodeActionSource::Indicator(row)) => Some(*row),
2911 _ => None,
2912 })
2913 } else {
2914 None
2915 };
2916
2917 let offset_range_start =
2918 snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left);
2919
2920 let offset_range_end =
2921 snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
2922
2923 editor
2924 .tasks
2925 .iter()
2926 .filter_map(|(_, tasks)| {
2927 let multibuffer_point = tasks.offset.to_point(&snapshot.buffer_snapshot);
2928 if multibuffer_point < offset_range_start
2929 || multibuffer_point > offset_range_end
2930 {
2931 return None;
2932 }
2933 let multibuffer_row = MultiBufferRow(multibuffer_point.row);
2934 let buffer_folded = snapshot
2935 .buffer_snapshot
2936 .buffer_line_for_row(multibuffer_row)
2937 .map(|(buffer_snapshot, _)| buffer_snapshot.remote_id())
2938 .map(|buffer_id| editor.is_buffer_folded(buffer_id, cx))
2939 .unwrap_or(false);
2940 if buffer_folded {
2941 return None;
2942 }
2943
2944 if snapshot.is_line_folded(multibuffer_row) {
2945 // Skip folded indicators, unless it's the starting line of a fold.
2946 if multibuffer_row
2947 .0
2948 .checked_sub(1)
2949 .is_some_and(|previous_row| {
2950 snapshot.is_line_folded(MultiBufferRow(previous_row))
2951 })
2952 {
2953 return None;
2954 }
2955 }
2956
2957 let display_row = multibuffer_point.to_display_point(snapshot).row();
2958 if !range.contains(&display_row) {
2959 return None;
2960 }
2961 if row_infos
2962 .get((display_row - range.start).0 as usize)
2963 .is_some_and(|row_info| row_info.expand_info.is_some())
2964 {
2965 return None;
2966 }
2967
2968 let button = editor.render_run_indicator(
2969 &self.style,
2970 Some(display_row) == active_task_indicator_row,
2971 display_row,
2972 breakpoints.remove(&display_row),
2973 cx,
2974 );
2975
2976 let button = prepaint_gutter_button(
2977 button,
2978 display_row,
2979 line_height,
2980 gutter_dimensions,
2981 scroll_pixel_position,
2982 gutter_hitbox,
2983 display_hunks,
2984 window,
2985 cx,
2986 );
2987 Some(button)
2988 })
2989 .collect_vec()
2990 })
2991 }
2992
2993 fn layout_expand_toggles(
2994 &self,
2995 gutter_hitbox: &Hitbox,
2996 gutter_dimensions: GutterDimensions,
2997 em_width: Pixels,
2998 line_height: Pixels,
2999 scroll_position: gpui::Point<f32>,
3000 buffer_rows: &[RowInfo],
3001 window: &mut Window,
3002 cx: &mut App,
3003 ) -> Vec<Option<(AnyElement, gpui::Point<Pixels>)>> {
3004 if self.editor.read(cx).disable_expand_excerpt_buttons {
3005 return vec![];
3006 }
3007
3008 let editor_font_size = self.style.text.font_size.to_pixels(window.rem_size()) * 1.2;
3009
3010 let scroll_top = scroll_position.y * line_height;
3011
3012 let max_line_number_length = self
3013 .editor
3014 .read(cx)
3015 .buffer()
3016 .read(cx)
3017 .snapshot(cx)
3018 .widest_line_number()
3019 .ilog10()
3020 + 1;
3021
3022 buffer_rows
3023 .iter()
3024 .enumerate()
3025 .map(|(ix, row_info)| {
3026 let ExpandInfo {
3027 excerpt_id,
3028 direction,
3029 } = row_info.expand_info?;
3030
3031 let icon_name = match direction {
3032 ExpandExcerptDirection::Up => IconName::ExpandUp,
3033 ExpandExcerptDirection::Down => IconName::ExpandDown,
3034 ExpandExcerptDirection::UpAndDown => IconName::ExpandVertical,
3035 };
3036
3037 let git_gutter_width = Self::gutter_strip_width(line_height);
3038 let available_width = gutter_dimensions.left_padding - git_gutter_width;
3039
3040 let editor = self.editor.clone();
3041 let is_wide = max_line_number_length
3042 >= EditorSettings::get_global(cx).gutter.min_line_number_digits as u32
3043 && row_info
3044 .buffer_row
3045 .is_some_and(|row| (row + 1).ilog10() + 1 == max_line_number_length)
3046 || gutter_dimensions.right_padding == px(0.);
3047
3048 let width = if is_wide {
3049 available_width - px(2.)
3050 } else {
3051 available_width + em_width - px(2.)
3052 };
3053
3054 let toggle = IconButton::new(("expand", ix), icon_name)
3055 .icon_color(Color::Custom(cx.theme().colors().editor_line_number))
3056 .selected_icon_color(Color::Custom(cx.theme().colors().editor_foreground))
3057 .icon_size(IconSize::Custom(rems(editor_font_size / window.rem_size())))
3058 .width(width)
3059 .on_click(move |_, window, cx| {
3060 editor.update(cx, |editor, cx| {
3061 editor.expand_excerpt(excerpt_id, direction, window, cx);
3062 });
3063 })
3064 .tooltip(Tooltip::for_action_title(
3065 "Expand Excerpt",
3066 &crate::actions::ExpandExcerpts::default(),
3067 ))
3068 .into_any_element();
3069
3070 let position = point(
3071 git_gutter_width + px(1.),
3072 ix as f32 * line_height - (scroll_top % line_height) + px(1.),
3073 );
3074 let origin = gutter_hitbox.origin + position;
3075
3076 Some((toggle, origin))
3077 })
3078 .collect()
3079 }
3080
3081 fn calculate_relative_line_numbers(
3082 &self,
3083 snapshot: &EditorSnapshot,
3084 rows: &Range<DisplayRow>,
3085 relative_to: Option<DisplayRow>,
3086 ) -> HashMap<DisplayRow, DisplayRowDelta> {
3087 let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
3088 let Some(relative_to) = relative_to else {
3089 return relative_rows;
3090 };
3091
3092 let start = rows.start.min(relative_to);
3093 let end = rows.end.max(relative_to);
3094
3095 let buffer_rows = snapshot
3096 .row_infos(start)
3097 .take(1 + end.minus(start) as usize)
3098 .collect::<Vec<_>>();
3099
3100 let head_idx = relative_to.minus(start);
3101 let mut delta = 1;
3102 let mut i = head_idx + 1;
3103 while i < buffer_rows.len() as u32 {
3104 if buffer_rows[i as usize].buffer_row.is_some() {
3105 if rows.contains(&DisplayRow(i + start.0)) {
3106 relative_rows.insert(DisplayRow(i + start.0), delta);
3107 }
3108 delta += 1;
3109 }
3110 i += 1;
3111 }
3112 delta = 1;
3113 i = head_idx.min(buffer_rows.len() as u32 - 1);
3114 while i > 0 && buffer_rows[i as usize].buffer_row.is_none() {
3115 i -= 1;
3116 }
3117
3118 while i > 0 {
3119 i -= 1;
3120 if buffer_rows[i as usize].buffer_row.is_some() {
3121 if rows.contains(&DisplayRow(i + start.0)) {
3122 relative_rows.insert(DisplayRow(i + start.0), delta);
3123 }
3124 delta += 1;
3125 }
3126 }
3127
3128 relative_rows
3129 }
3130
3131 fn layout_line_numbers(
3132 &self,
3133 gutter_hitbox: Option<&Hitbox>,
3134 gutter_dimensions: GutterDimensions,
3135 line_height: Pixels,
3136 scroll_position: gpui::Point<f32>,
3137 rows: Range<DisplayRow>,
3138 buffer_rows: &[RowInfo],
3139 active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
3140 newest_selection_head: Option<DisplayPoint>,
3141 snapshot: &EditorSnapshot,
3142 window: &mut Window,
3143 cx: &mut App,
3144 ) -> Arc<HashMap<MultiBufferRow, LineNumberLayout>> {
3145 let include_line_numbers = snapshot
3146 .show_line_numbers
3147 .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
3148 if !include_line_numbers {
3149 return Arc::default();
3150 }
3151
3152 let (newest_selection_head, is_relative) = self.editor.update(cx, |editor, cx| {
3153 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
3154 let newest = editor.selections.newest::<Point>(cx);
3155 SelectionLayout::new(
3156 newest,
3157 editor.selections.line_mode,
3158 editor.cursor_shape,
3159 &snapshot.display_snapshot,
3160 true,
3161 true,
3162 None,
3163 )
3164 .head
3165 });
3166 let is_relative = editor.should_use_relative_line_numbers(cx);
3167 (newest_selection_head, is_relative)
3168 });
3169
3170 let relative_to = if is_relative {
3171 Some(newest_selection_head.row())
3172 } else {
3173 None
3174 };
3175 let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
3176 let mut line_number = String::new();
3177 let line_numbers = buffer_rows
3178 .iter()
3179 .enumerate()
3180 .flat_map(|(ix, row_info)| {
3181 let display_row = DisplayRow(rows.start.0 + ix as u32);
3182 line_number.clear();
3183 let non_relative_number = row_info.buffer_row? + 1;
3184 let number = relative_rows
3185 .get(&display_row)
3186 .unwrap_or(&non_relative_number);
3187 write!(&mut line_number, "{number}").unwrap();
3188 if row_info
3189 .diff_status
3190 .is_some_and(|status| status.is_deleted())
3191 {
3192 return None;
3193 }
3194
3195 let color = active_rows
3196 .get(&display_row)
3197 .map(|spec| {
3198 if spec.breakpoint {
3199 cx.theme().colors().debugger_accent
3200 } else {
3201 cx.theme().colors().editor_active_line_number
3202 }
3203 })
3204 .unwrap_or_else(|| cx.theme().colors().editor_line_number);
3205 let shaped_line =
3206 self.shape_line_number(SharedString::from(&line_number), color, window);
3207 let scroll_top = scroll_position.y * line_height;
3208 let line_origin = gutter_hitbox.map(|hitbox| {
3209 hitbox.origin
3210 + point(
3211 hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
3212 ix as f32 * line_height - (scroll_top % line_height),
3213 )
3214 });
3215
3216 #[cfg(not(test))]
3217 let hitbox = line_origin.map(|line_origin| {
3218 window.insert_hitbox(
3219 Bounds::new(line_origin, size(shaped_line.width, line_height)),
3220 HitboxBehavior::Normal,
3221 )
3222 });
3223 #[cfg(test)]
3224 let hitbox = {
3225 let _ = line_origin;
3226 None
3227 };
3228
3229 let multi_buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
3230 let multi_buffer_row = MultiBufferRow(multi_buffer_row);
3231 let line_number = LineNumberLayout {
3232 shaped_line,
3233 hitbox,
3234 };
3235 Some((multi_buffer_row, line_number))
3236 })
3237 .collect();
3238 Arc::new(line_numbers)
3239 }
3240
3241 fn layout_crease_toggles(
3242 &self,
3243 rows: Range<DisplayRow>,
3244 row_infos: &[RowInfo],
3245 active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
3246 snapshot: &EditorSnapshot,
3247 window: &mut Window,
3248 cx: &mut App,
3249 ) -> Vec<Option<AnyElement>> {
3250 let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
3251 && snapshot.mode.is_full()
3252 && self.editor.read(cx).is_singleton(cx);
3253 if include_fold_statuses {
3254 row_infos
3255 .iter()
3256 .enumerate()
3257 .map(|(ix, info)| {
3258 if info.expand_info.is_some() {
3259 return None;
3260 }
3261 let row = info.multibuffer_row?;
3262 let display_row = DisplayRow(rows.start.0 + ix as u32);
3263 let active = active_rows.contains_key(&display_row);
3264
3265 snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
3266 })
3267 .collect()
3268 } else {
3269 Vec::new()
3270 }
3271 }
3272
3273 fn layout_crease_trailers(
3274 &self,
3275 buffer_rows: impl IntoIterator<Item = RowInfo>,
3276 snapshot: &EditorSnapshot,
3277 window: &mut Window,
3278 cx: &mut App,
3279 ) -> Vec<Option<AnyElement>> {
3280 buffer_rows
3281 .into_iter()
3282 .map(|row_info| {
3283 if row_info.expand_info.is_some() {
3284 return None;
3285 }
3286 if let Some(row) = row_info.multibuffer_row {
3287 snapshot.render_crease_trailer(row, window, cx)
3288 } else {
3289 None
3290 }
3291 })
3292 .collect()
3293 }
3294
3295 fn bg_segments_per_row(
3296 rows: Range<DisplayRow>,
3297 selections: &[(PlayerColor, Vec<SelectionLayout>)],
3298 highlight_ranges: &[(Range<DisplayPoint>, Hsla)],
3299 base_background: Hsla,
3300 ) -> Vec<Vec<(Range<DisplayPoint>, Hsla)>> {
3301 if rows.start >= rows.end {
3302 return Vec::new();
3303 }
3304 if !base_background.is_opaque() {
3305 // We don't actually know what color is behind this editor.
3306 return Vec::new();
3307 }
3308 let highlight_iter = highlight_ranges.iter().cloned();
3309 let selection_iter = selections.iter().flat_map(|(player_color, layouts)| {
3310 let color = player_color.selection;
3311 layouts.iter().filter_map(move |selection_layout| {
3312 if selection_layout.range.start != selection_layout.range.end {
3313 Some((selection_layout.range.clone(), color))
3314 } else {
3315 None
3316 }
3317 })
3318 });
3319 let mut per_row_map = vec![Vec::new(); rows.len()];
3320 for (range, color) in highlight_iter.chain(selection_iter) {
3321 let covered_rows = if range.end.column() == 0 {
3322 cmp::max(range.start.row(), rows.start)..cmp::min(range.end.row(), rows.end)
3323 } else {
3324 cmp::max(range.start.row(), rows.start)
3325 ..cmp::min(range.end.row().next_row(), rows.end)
3326 };
3327 for row in covered_rows.iter_rows() {
3328 let seg_start = if row == range.start.row() {
3329 range.start
3330 } else {
3331 DisplayPoint::new(row, 0)
3332 };
3333 let seg_end = if row == range.end.row() && range.end.column() != 0 {
3334 range.end
3335 } else {
3336 DisplayPoint::new(row, u32::MAX)
3337 };
3338 let ix = row.minus(rows.start) as usize;
3339 debug_assert!(row >= rows.start && row < rows.end);
3340 debug_assert!(ix < per_row_map.len());
3341 per_row_map[ix].push((seg_start..seg_end, color));
3342 }
3343 }
3344 for row_segments in per_row_map.iter_mut() {
3345 if row_segments.is_empty() {
3346 continue;
3347 }
3348 let segments = mem::take(row_segments);
3349 let merged = Self::merge_overlapping_ranges(segments, base_background);
3350 *row_segments = merged;
3351 }
3352 per_row_map
3353 }
3354
3355 /// Merge overlapping ranges by splitting at all range boundaries and blending colors where
3356 /// multiple ranges overlap. The result contains non-overlapping ranges ordered from left to right.
3357 ///
3358 /// Expects `start.row() == end.row()` for each range.
3359 fn merge_overlapping_ranges(
3360 ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3361 base_background: Hsla,
3362 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
3363 struct Boundary {
3364 pos: DisplayPoint,
3365 is_start: bool,
3366 index: usize,
3367 color: Hsla,
3368 }
3369
3370 let mut boundaries: SmallVec<[Boundary; 16]> = SmallVec::with_capacity(ranges.len() * 2);
3371 for (index, (range, color)) in ranges.iter().enumerate() {
3372 debug_assert!(
3373 range.start.row() == range.end.row(),
3374 "expects single-row ranges"
3375 );
3376 if range.start < range.end {
3377 boundaries.push(Boundary {
3378 pos: range.start,
3379 is_start: true,
3380 index,
3381 color: *color,
3382 });
3383 boundaries.push(Boundary {
3384 pos: range.end,
3385 is_start: false,
3386 index,
3387 color: *color,
3388 });
3389 }
3390 }
3391
3392 if boundaries.is_empty() {
3393 return Vec::new();
3394 }
3395
3396 boundaries
3397 .sort_unstable_by(|a, b| a.pos.cmp(&b.pos).then_with(|| a.is_start.cmp(&b.is_start)));
3398
3399 let mut processed_ranges: Vec<(Range<DisplayPoint>, Hsla)> = Vec::new();
3400 let mut active_ranges: SmallVec<[(usize, Hsla); 8]> = SmallVec::new();
3401
3402 let mut i = 0;
3403 let mut start_pos = boundaries[0].pos;
3404
3405 let boundaries_len = boundaries.len();
3406 while i < boundaries_len {
3407 let current_boundary_pos = boundaries[i].pos;
3408 if start_pos < current_boundary_pos {
3409 if !active_ranges.is_empty() {
3410 let mut color = base_background;
3411 for &(_, c) in &active_ranges {
3412 color = Hsla::blend(color, c);
3413 }
3414 if let Some((last_range, last_color)) = processed_ranges.last_mut() {
3415 if *last_color == color && last_range.end == start_pos {
3416 last_range.end = current_boundary_pos;
3417 } else {
3418 processed_ranges.push((start_pos..current_boundary_pos, color));
3419 }
3420 } else {
3421 processed_ranges.push((start_pos..current_boundary_pos, color));
3422 }
3423 }
3424 }
3425 while i < boundaries_len && boundaries[i].pos == current_boundary_pos {
3426 let active_range = &boundaries[i];
3427 if active_range.is_start {
3428 let idx = active_range.index;
3429 let pos = active_ranges
3430 .binary_search_by_key(&idx, |(i, _)| *i)
3431 .unwrap_or_else(|p| p);
3432 active_ranges.insert(pos, (idx, active_range.color));
3433 } else {
3434 let idx = active_range.index;
3435 if let Ok(pos) = active_ranges.binary_search_by_key(&idx, |(i, _)| *i) {
3436 active_ranges.remove(pos);
3437 }
3438 }
3439 i += 1;
3440 }
3441 start_pos = current_boundary_pos;
3442 }
3443
3444 processed_ranges
3445 }
3446
3447 fn layout_lines(
3448 rows: Range<DisplayRow>,
3449 snapshot: &EditorSnapshot,
3450 style: &EditorStyle,
3451 editor_width: Pixels,
3452 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3453 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
3454 window: &mut Window,
3455 cx: &mut App,
3456 ) -> Vec<LineWithInvisibles> {
3457 if rows.start >= rows.end {
3458 return Vec::new();
3459 }
3460
3461 // Show the placeholder when the editor is empty
3462 if snapshot.is_empty() {
3463 let font_size = style.text.font_size.to_pixels(window.rem_size());
3464 let placeholder_color = cx.theme().colors().text_placeholder;
3465 let placeholder_text = snapshot.placeholder_text();
3466
3467 let placeholder_lines = placeholder_text
3468 .as_ref()
3469 .map_or(Vec::new(), |text| text.split('\n').collect::<Vec<_>>());
3470
3471 let placeholder_line_count = placeholder_lines.len();
3472
3473 placeholder_lines
3474 .into_iter()
3475 .skip(rows.start.0 as usize)
3476 .chain(iter::repeat(""))
3477 .take(cmp::max(rows.len(), placeholder_line_count))
3478 .map(move |line| {
3479 let run = TextRun {
3480 len: line.len(),
3481 font: style.text.font(),
3482 color: placeholder_color,
3483 background_color: None,
3484 underline: None,
3485 strikethrough: None,
3486 };
3487 let line = window.text_system().shape_line(
3488 line.to_string().into(),
3489 font_size,
3490 &[run],
3491 None,
3492 );
3493 LineWithInvisibles {
3494 width: line.width,
3495 len: line.len,
3496 fragments: smallvec![LineFragment::Text(line)],
3497 invisibles: Vec::new(),
3498 font_size,
3499 }
3500 })
3501 .collect()
3502 } else {
3503 let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
3504 LineWithInvisibles::from_chunks(
3505 chunks,
3506 style,
3507 MAX_LINE_LEN,
3508 rows.len(),
3509 &snapshot.mode,
3510 editor_width,
3511 is_row_soft_wrapped,
3512 bg_segments_per_row,
3513 window,
3514 cx,
3515 )
3516 }
3517 }
3518
3519 fn prepaint_lines(
3520 &self,
3521 start_row: DisplayRow,
3522 line_layouts: &mut [LineWithInvisibles],
3523 line_height: Pixels,
3524 scroll_pixel_position: gpui::Point<Pixels>,
3525 content_origin: gpui::Point<Pixels>,
3526 window: &mut Window,
3527 cx: &mut App,
3528 ) -> SmallVec<[AnyElement; 1]> {
3529 let mut line_elements = SmallVec::new();
3530 for (ix, line) in line_layouts.iter_mut().enumerate() {
3531 let row = start_row + DisplayRow(ix as u32);
3532 line.prepaint(
3533 line_height,
3534 scroll_pixel_position,
3535 row,
3536 content_origin,
3537 &mut line_elements,
3538 window,
3539 cx,
3540 );
3541 }
3542 line_elements
3543 }
3544
3545 fn render_block(
3546 &self,
3547 block: &Block,
3548 available_width: AvailableSpace,
3549 block_id: BlockId,
3550 block_row_start: DisplayRow,
3551 snapshot: &EditorSnapshot,
3552 text_x: Pixels,
3553 rows: &Range<DisplayRow>,
3554 line_layouts: &[LineWithInvisibles],
3555 editor_margins: &EditorMargins,
3556 line_height: Pixels,
3557 em_width: Pixels,
3558 text_hitbox: &Hitbox,
3559 editor_width: Pixels,
3560 scroll_width: &mut Pixels,
3561 resized_blocks: &mut HashMap<CustomBlockId, u32>,
3562 row_block_types: &mut HashMap<DisplayRow, bool>,
3563 selections: &[Selection<Point>],
3564 selected_buffer_ids: &Vec<BufferId>,
3565 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3566 sticky_header_excerpt_id: Option<ExcerptId>,
3567 window: &mut Window,
3568 cx: &mut App,
3569 ) -> Option<(AnyElement, Size<Pixels>, DisplayRow, Pixels)> {
3570 let mut x_position = None;
3571 let mut element = match block {
3572 Block::Custom(custom) => {
3573 let block_start = custom.start().to_point(&snapshot.buffer_snapshot);
3574 let block_end = custom.end().to_point(&snapshot.buffer_snapshot);
3575 if block.place_near() && snapshot.is_line_folded(MultiBufferRow(block_start.row)) {
3576 return None;
3577 }
3578 let align_to = block_start.to_display_point(snapshot);
3579 let x_and_width = |layout: &LineWithInvisibles| {
3580 Some((
3581 text_x + layout.x_for_index(align_to.column() as usize),
3582 text_x + layout.width,
3583 ))
3584 };
3585 let line_ix = align_to.row().0.checked_sub(rows.start.0);
3586 x_position =
3587 if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
3588 x_and_width(layout)
3589 } else {
3590 x_and_width(&layout_line(
3591 align_to.row(),
3592 snapshot,
3593 &self.style,
3594 editor_width,
3595 is_row_soft_wrapped,
3596 window,
3597 cx,
3598 ))
3599 };
3600
3601 let anchor_x = x_position.unwrap().0;
3602
3603 let selected = selections
3604 .binary_search_by(|selection| {
3605 if selection.end <= block_start {
3606 Ordering::Less
3607 } else if selection.start >= block_end {
3608 Ordering::Greater
3609 } else {
3610 Ordering::Equal
3611 }
3612 })
3613 .is_ok();
3614
3615 div()
3616 .size_full()
3617 .child(custom.render(&mut BlockContext {
3618 window,
3619 app: cx,
3620 anchor_x,
3621 margins: editor_margins,
3622 line_height,
3623 em_width,
3624 block_id,
3625 selected,
3626 max_width: text_hitbox.size.width.max(*scroll_width),
3627 editor_style: &self.style,
3628 }))
3629 .into_any()
3630 }
3631
3632 Block::FoldedBuffer {
3633 first_excerpt,
3634 height,
3635 ..
3636 } => {
3637 let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
3638 let result = v_flex().id(block_id).w_full().pr(editor_margins.right);
3639
3640 let jump_data = header_jump_data(snapshot, block_row_start, *height, first_excerpt);
3641 result
3642 .child(self.render_buffer_header(
3643 first_excerpt,
3644 true,
3645 selected,
3646 false,
3647 jump_data,
3648 window,
3649 cx,
3650 ))
3651 .into_any_element()
3652 }
3653
3654 Block::ExcerptBoundary { .. } => {
3655 let color = cx.theme().colors().clone();
3656 let mut result = v_flex().id(block_id).w_full();
3657
3658 result = result.child(
3659 h_flex().relative().child(
3660 div()
3661 .top(line_height / 2.)
3662 .absolute()
3663 .w_full()
3664 .h_px()
3665 .bg(color.border_variant),
3666 ),
3667 );
3668
3669 result.into_any()
3670 }
3671
3672 Block::BufferHeader { excerpt, height } => {
3673 let mut result = v_flex().id(block_id).w_full();
3674
3675 let jump_data = header_jump_data(snapshot, block_row_start, *height, excerpt);
3676
3677 if sticky_header_excerpt_id != Some(excerpt.id) {
3678 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3679
3680 result = result.child(div().pr(editor_margins.right).child(
3681 self.render_buffer_header(
3682 excerpt, false, selected, false, jump_data, window, cx,
3683 ),
3684 ));
3685 } else {
3686 result =
3687 result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
3688 }
3689
3690 result.into_any()
3691 }
3692 };
3693
3694 // Discover the element's content height, then round up to the nearest multiple of line height.
3695 let preliminary_size = element.layout_as_root(
3696 size(available_width, AvailableSpace::MinContent),
3697 window,
3698 cx,
3699 );
3700 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
3701 let final_size = if preliminary_size.height == quantized_height {
3702 preliminary_size
3703 } else {
3704 element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
3705 };
3706 let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
3707
3708 let mut row = block_row_start;
3709 let mut x_offset = px(0.);
3710 let mut is_block = true;
3711
3712 if let BlockId::Custom(custom_block_id) = block_id
3713 && block.has_height()
3714 {
3715 if block.place_near()
3716 && let Some((x_target, line_width)) = x_position
3717 {
3718 let margin = em_width * 2;
3719 if line_width + final_size.width + margin
3720 < editor_width + editor_margins.gutter.full_width()
3721 && !row_block_types.contains_key(&(row - 1))
3722 && element_height_in_lines == 1
3723 {
3724 x_offset = line_width + margin;
3725 row = row - 1;
3726 is_block = false;
3727 element_height_in_lines = 0;
3728 row_block_types.insert(row, is_block);
3729 } else {
3730 let max_offset =
3731 editor_width + editor_margins.gutter.full_width() - final_size.width;
3732 let min_offset = (x_target + em_width - final_size.width)
3733 .max(editor_margins.gutter.full_width());
3734 x_offset = x_target.min(max_offset).max(min_offset);
3735 }
3736 };
3737 if element_height_in_lines != block.height() {
3738 resized_blocks.insert(custom_block_id, element_height_in_lines);
3739 }
3740 }
3741 for i in 0..element_height_in_lines {
3742 row_block_types.insert(row + i, is_block);
3743 }
3744
3745 Some((element, final_size, row, x_offset))
3746 }
3747
3748 fn render_buffer_header(
3749 &self,
3750 for_excerpt: &ExcerptInfo,
3751 is_folded: bool,
3752 is_selected: bool,
3753 is_sticky: bool,
3754 jump_data: JumpData,
3755 window: &mut Window,
3756 cx: &mut App,
3757 ) -> impl IntoElement {
3758 let editor = self.editor.read(cx);
3759 let multi_buffer = editor.buffer.read(cx);
3760 let file_status = multi_buffer
3761 .all_diff_hunks_expanded()
3762 .then(|| {
3763 editor
3764 .project
3765 .as_ref()?
3766 .read(cx)
3767 .status_for_buffer_id(for_excerpt.buffer_id, cx)
3768 })
3769 .flatten();
3770 let indicator = multi_buffer
3771 .buffer(for_excerpt.buffer_id)
3772 .and_then(|buffer| {
3773 let buffer = buffer.read(cx);
3774 let indicator_color = match (buffer.has_conflict(), buffer.is_dirty()) {
3775 (true, _) => Some(Color::Warning),
3776 (_, true) => Some(Color::Accent),
3777 (false, false) => None,
3778 };
3779 indicator_color.map(|indicator_color| Indicator::dot().color(indicator_color))
3780 });
3781
3782 let include_root = editor
3783 .project
3784 .as_ref()
3785 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
3786 .unwrap_or_default();
3787 let can_open_excerpts = Editor::can_open_excerpts_in_file(for_excerpt.buffer.file());
3788 let relative_path = for_excerpt.buffer.resolve_file_path(cx, include_root);
3789 let filename = relative_path
3790 .as_ref()
3791 .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
3792 let parent_path = relative_path.as_ref().and_then(|path| {
3793 Some(path.parent()?.to_string_lossy().to_string() + std::path::MAIN_SEPARATOR_STR)
3794 });
3795 let focus_handle = editor.focus_handle(cx);
3796 let colors = cx.theme().colors();
3797
3798 let header = div()
3799 .p_1()
3800 .w_full()
3801 .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
3802 .child(
3803 h_flex()
3804 .size_full()
3805 .gap_2()
3806 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
3807 .pl_0p5()
3808 .pr_5()
3809 .rounded_sm()
3810 .when(is_sticky, |el| el.shadow_md())
3811 .border_1()
3812 .map(|div| {
3813 let border_color = if is_selected
3814 && is_folded
3815 && focus_handle.contains_focused(window, cx)
3816 {
3817 colors.border_focused
3818 } else {
3819 colors.border
3820 };
3821 div.border_color(border_color)
3822 })
3823 .bg(colors.editor_subheader_background)
3824 .hover(|style| style.bg(colors.element_hover))
3825 .map(|header| {
3826 let editor = self.editor.clone();
3827 let buffer_id = for_excerpt.buffer_id;
3828 let toggle_chevron_icon =
3829 FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
3830 header.child(
3831 div()
3832 .hover(|style| style.bg(colors.element_selected))
3833 .rounded_xs()
3834 .child(
3835 ButtonLike::new("toggle-buffer-fold")
3836 .style(ui::ButtonStyle::Transparent)
3837 .height(px(28.).into())
3838 .width(px(28.))
3839 .children(toggle_chevron_icon)
3840 .tooltip({
3841 let focus_handle = focus_handle.clone();
3842 move |window, cx| {
3843 Tooltip::with_meta_in(
3844 "Toggle Excerpt Fold",
3845 Some(&ToggleFold),
3846 "Alt+click to toggle all",
3847 &focus_handle,
3848 window,
3849 cx,
3850 )
3851 }
3852 })
3853 .on_click(move |event, window, cx| {
3854 if event.modifiers().alt {
3855 // Alt+click toggles all buffers
3856 editor.update(cx, |editor, cx| {
3857 editor.toggle_fold_all(
3858 &ToggleFoldAll,
3859 window,
3860 cx,
3861 );
3862 });
3863 } else {
3864 // Regular click toggles single buffer
3865 if is_folded {
3866 editor.update(cx, |editor, cx| {
3867 editor.unfold_buffer(buffer_id, cx);
3868 });
3869 } else {
3870 editor.update(cx, |editor, cx| {
3871 editor.fold_buffer(buffer_id, cx);
3872 });
3873 }
3874 }
3875 }),
3876 ),
3877 )
3878 })
3879 .children(
3880 editor
3881 .addons
3882 .values()
3883 .filter_map(|addon| {
3884 addon.render_buffer_header_controls(for_excerpt, window, cx)
3885 })
3886 .take(1),
3887 )
3888 .child(
3889 h_flex()
3890 .size(Pixels(12.0))
3891 .justify_center()
3892 .children(indicator),
3893 )
3894 .child(
3895 h_flex()
3896 .cursor_pointer()
3897 .id("path header block")
3898 .size_full()
3899 .justify_between()
3900 .overflow_hidden()
3901 .child(
3902 h_flex()
3903 .gap_2()
3904 .map(|path_header| {
3905 let filename = filename
3906 .map(SharedString::from)
3907 .unwrap_or_else(|| "untitled".into());
3908
3909 path_header
3910 .when(ItemSettings::get_global(cx).file_icons, |el| {
3911 let path = path::Path::new(filename.as_str());
3912 let icon = FileIcons::get_icon(path, cx)
3913 .unwrap_or_default();
3914 let icon =
3915 Icon::from_path(icon).color(Color::Muted);
3916 el.child(icon)
3917 })
3918 .child(Label::new(filename).single_line().when_some(
3919 file_status,
3920 |el, status| {
3921 el.color(if status.is_conflicted() {
3922 Color::Conflict
3923 } else if status.is_modified() {
3924 Color::Modified
3925 } else if status.is_deleted() {
3926 Color::Disabled
3927 } else {
3928 Color::Created
3929 })
3930 .when(status.is_deleted(), |el| {
3931 el.strikethrough()
3932 })
3933 },
3934 ))
3935 })
3936 .when_some(parent_path, |then, path| {
3937 then.child(div().child(path).text_color(
3938 if file_status.is_some_and(FileStatus::is_deleted) {
3939 colors.text_disabled
3940 } else {
3941 colors.text_muted
3942 },
3943 ))
3944 }),
3945 )
3946 .when(
3947 can_open_excerpts && is_selected && relative_path.is_some(),
3948 |el| {
3949 el.child(
3950 h_flex()
3951 .id("jump-to-file-button")
3952 .gap_2p5()
3953 .child(Label::new("Jump To File"))
3954 .children(
3955 KeyBinding::for_action_in(
3956 &OpenExcerpts,
3957 &focus_handle,
3958 window,
3959 cx,
3960 )
3961 .map(|binding| binding.into_any_element()),
3962 ),
3963 )
3964 },
3965 )
3966 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
3967 .on_click(window.listener_for(&self.editor, {
3968 move |editor, e: &ClickEvent, window, cx| {
3969 editor.open_excerpts_common(
3970 Some(jump_data.clone()),
3971 e.modifiers().secondary(),
3972 window,
3973 cx,
3974 );
3975 }
3976 })),
3977 ),
3978 );
3979
3980 let file = for_excerpt.buffer.file().cloned();
3981 let editor = self.editor.clone();
3982 right_click_menu("buffer-header-context-menu")
3983 .trigger(move |_, _, _| header)
3984 .menu(move |window, cx| {
3985 let menu_context = focus_handle.clone();
3986 let editor = editor.clone();
3987 let file = file.clone();
3988 ContextMenu::build(window, cx, move |mut menu, window, cx| {
3989 if let Some(file) = file
3990 && let Some(project) = editor.read(cx).project()
3991 && let Some(worktree) =
3992 project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
3993 {
3994 let worktree = worktree.read(cx);
3995 let relative_path = file.path();
3996 let entry_for_path = worktree.entry_for_path(relative_path);
3997 let abs_path = entry_for_path.map(|e| {
3998 e.canonical_path.as_deref().map_or_else(
3999 || worktree.abs_path().join(relative_path),
4000 Path::to_path_buf,
4001 )
4002 });
4003 let has_relative_path = worktree.root_entry().is_some_and(Entry::is_dir);
4004
4005 let parent_abs_path = abs_path
4006 .as_ref()
4007 .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
4008 let relative_path = has_relative_path
4009 .then_some(relative_path)
4010 .map(ToOwned::to_owned);
4011
4012 let visible_in_project_panel =
4013 relative_path.is_some() && worktree.is_visible();
4014 let reveal_in_project_panel = entry_for_path
4015 .filter(|_| visible_in_project_panel)
4016 .map(|entry| entry.id);
4017 menu = menu
4018 .when_some(abs_path, |menu, abs_path| {
4019 menu.entry(
4020 "Copy Path",
4021 Some(Box::new(zed_actions::workspace::CopyPath)),
4022 window.handler_for(&editor, move |_, _, cx| {
4023 cx.write_to_clipboard(ClipboardItem::new_string(
4024 abs_path.to_string_lossy().to_string(),
4025 ));
4026 }),
4027 )
4028 })
4029 .when_some(relative_path, |menu, relative_path| {
4030 menu.entry(
4031 "Copy Relative Path",
4032 Some(Box::new(zed_actions::workspace::CopyRelativePath)),
4033 window.handler_for(&editor, move |_, _, cx| {
4034 cx.write_to_clipboard(ClipboardItem::new_string(
4035 relative_path.to_string_lossy().to_string(),
4036 ));
4037 }),
4038 )
4039 })
4040 .when(
4041 reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
4042 |menu| menu.separator(),
4043 )
4044 .when_some(reveal_in_project_panel, |menu, entry_id| {
4045 menu.entry(
4046 "Reveal In Project Panel",
4047 Some(Box::new(RevealInProjectPanel::default())),
4048 window.handler_for(&editor, move |editor, _, cx| {
4049 if let Some(project) = &mut editor.project {
4050 project.update(cx, |_, cx| {
4051 cx.emit(project::Event::RevealInProjectPanel(
4052 entry_id,
4053 ))
4054 });
4055 }
4056 }),
4057 )
4058 })
4059 .when_some(parent_abs_path, |menu, parent_abs_path| {
4060 menu.entry(
4061 "Open in Terminal",
4062 Some(Box::new(OpenInTerminal)),
4063 window.handler_for(&editor, move |_, window, cx| {
4064 window.dispatch_action(
4065 OpenTerminal {
4066 working_directory: parent_abs_path.clone(),
4067 }
4068 .boxed_clone(),
4069 cx,
4070 );
4071 }),
4072 )
4073 });
4074 }
4075
4076 menu.context(menu_context)
4077 })
4078 })
4079 }
4080
4081 fn render_blocks(
4082 &self,
4083 rows: Range<DisplayRow>,
4084 snapshot: &EditorSnapshot,
4085 hitbox: &Hitbox,
4086 text_hitbox: &Hitbox,
4087 editor_width: Pixels,
4088 scroll_width: &mut Pixels,
4089 editor_margins: &EditorMargins,
4090 em_width: Pixels,
4091 text_x: Pixels,
4092 line_height: Pixels,
4093 line_layouts: &mut [LineWithInvisibles],
4094 selections: &[Selection<Point>],
4095 selected_buffer_ids: &Vec<BufferId>,
4096 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4097 sticky_header_excerpt_id: Option<ExcerptId>,
4098 window: &mut Window,
4099 cx: &mut App,
4100 ) -> Result<(Vec<BlockLayout>, HashMap<DisplayRow, bool>), HashMap<CustomBlockId, u32>> {
4101 let (fixed_blocks, non_fixed_blocks) = snapshot
4102 .blocks_in_range(rows.clone())
4103 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
4104
4105 let mut focused_block = self
4106 .editor
4107 .update(cx, |editor, _| editor.take_focused_block());
4108 let mut fixed_block_max_width = Pixels::ZERO;
4109 let mut blocks = Vec::new();
4110 let mut resized_blocks = HashMap::default();
4111 let mut row_block_types = HashMap::default();
4112
4113 for (row, block) in fixed_blocks {
4114 let block_id = block.id();
4115
4116 if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
4117 focused_block = None;
4118 }
4119
4120 if let Some((element, element_size, row, x_offset)) = self.render_block(
4121 block,
4122 AvailableSpace::MinContent,
4123 block_id,
4124 row,
4125 snapshot,
4126 text_x,
4127 &rows,
4128 line_layouts,
4129 editor_margins,
4130 line_height,
4131 em_width,
4132 text_hitbox,
4133 editor_width,
4134 scroll_width,
4135 &mut resized_blocks,
4136 &mut row_block_types,
4137 selections,
4138 selected_buffer_ids,
4139 is_row_soft_wrapped,
4140 sticky_header_excerpt_id,
4141 window,
4142 cx,
4143 ) {
4144 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
4145 blocks.push(BlockLayout {
4146 id: block_id,
4147 x_offset,
4148 row: Some(row),
4149 element,
4150 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
4151 style: BlockStyle::Fixed,
4152 overlaps_gutter: true,
4153 is_buffer_header: block.is_buffer_header(),
4154 });
4155 }
4156 }
4157
4158 for (row, block) in non_fixed_blocks {
4159 let style = block.style();
4160 let width = match (style, block.place_near()) {
4161 (_, true) => AvailableSpace::MinContent,
4162 (BlockStyle::Sticky, _) => hitbox.size.width.into(),
4163 (BlockStyle::Flex, _) => hitbox
4164 .size
4165 .width
4166 .max(fixed_block_max_width)
4167 .max(editor_margins.gutter.width + *scroll_width)
4168 .into(),
4169 (BlockStyle::Fixed, _) => unreachable!(),
4170 };
4171 let block_id = block.id();
4172
4173 if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
4174 focused_block = None;
4175 }
4176
4177 if let Some((element, element_size, row, x_offset)) = self.render_block(
4178 block,
4179 width,
4180 block_id,
4181 row,
4182 snapshot,
4183 text_x,
4184 &rows,
4185 line_layouts,
4186 editor_margins,
4187 line_height,
4188 em_width,
4189 text_hitbox,
4190 editor_width,
4191 scroll_width,
4192 &mut resized_blocks,
4193 &mut row_block_types,
4194 selections,
4195 selected_buffer_ids,
4196 is_row_soft_wrapped,
4197 sticky_header_excerpt_id,
4198 window,
4199 cx,
4200 ) {
4201 blocks.push(BlockLayout {
4202 id: block_id,
4203 x_offset,
4204 row: Some(row),
4205 element,
4206 available_space: size(width, element_size.height.into()),
4207 style,
4208 overlaps_gutter: !block.place_near(),
4209 is_buffer_header: block.is_buffer_header(),
4210 });
4211 }
4212 }
4213
4214 if let Some(focused_block) = focused_block
4215 && let Some(focus_handle) = focused_block.focus_handle.upgrade()
4216 && focus_handle.is_focused(window)
4217 && let Some(block) = snapshot.block_for_id(focused_block.id)
4218 {
4219 let style = block.style();
4220 let width = match style {
4221 BlockStyle::Fixed => AvailableSpace::MinContent,
4222 BlockStyle::Flex => AvailableSpace::Definite(
4223 hitbox
4224 .size
4225 .width
4226 .max(fixed_block_max_width)
4227 .max(editor_margins.gutter.width + *scroll_width),
4228 ),
4229 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
4230 };
4231
4232 if let Some((element, element_size, _, x_offset)) = self.render_block(
4233 &block,
4234 width,
4235 focused_block.id,
4236 rows.end,
4237 snapshot,
4238 text_x,
4239 &rows,
4240 line_layouts,
4241 editor_margins,
4242 line_height,
4243 em_width,
4244 text_hitbox,
4245 editor_width,
4246 scroll_width,
4247 &mut resized_blocks,
4248 &mut row_block_types,
4249 selections,
4250 selected_buffer_ids,
4251 is_row_soft_wrapped,
4252 sticky_header_excerpt_id,
4253 window,
4254 cx,
4255 ) {
4256 blocks.push(BlockLayout {
4257 id: block.id(),
4258 x_offset,
4259 row: None,
4260 element,
4261 available_space: size(width, element_size.height.into()),
4262 style,
4263 overlaps_gutter: true,
4264 is_buffer_header: block.is_buffer_header(),
4265 });
4266 }
4267 }
4268
4269 if resized_blocks.is_empty() {
4270 *scroll_width =
4271 (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
4272 Ok((blocks, row_block_types))
4273 } else {
4274 Err(resized_blocks)
4275 }
4276 }
4277
4278 fn layout_blocks(
4279 &self,
4280 blocks: &mut Vec<BlockLayout>,
4281 hitbox: &Hitbox,
4282 line_height: Pixels,
4283 scroll_pixel_position: gpui::Point<Pixels>,
4284 window: &mut Window,
4285 cx: &mut App,
4286 ) {
4287 for block in blocks {
4288 let mut origin = if let Some(row) = block.row {
4289 hitbox.origin
4290 + point(
4291 block.x_offset,
4292 row.as_f32() * line_height - scroll_pixel_position.y,
4293 )
4294 } else {
4295 // Position the block outside the visible area
4296 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
4297 };
4298
4299 if !matches!(block.style, BlockStyle::Sticky) {
4300 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
4301 }
4302
4303 let focus_handle =
4304 block
4305 .element
4306 .prepaint_as_root(origin, block.available_space, window, cx);
4307
4308 if let Some(focus_handle) = focus_handle {
4309 self.editor.update(cx, |editor, _cx| {
4310 editor.set_focused_block(FocusedBlock {
4311 id: block.id,
4312 focus_handle: focus_handle.downgrade(),
4313 });
4314 });
4315 }
4316 }
4317 }
4318
4319 fn layout_sticky_buffer_header(
4320 &self,
4321 StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
4322 scroll_position: f32,
4323 line_height: Pixels,
4324 right_margin: Pixels,
4325 snapshot: &EditorSnapshot,
4326 hitbox: &Hitbox,
4327 selected_buffer_ids: &Vec<BufferId>,
4328 blocks: &[BlockLayout],
4329 window: &mut Window,
4330 cx: &mut App,
4331 ) -> AnyElement {
4332 let jump_data = header_jump_data(
4333 snapshot,
4334 DisplayRow(scroll_position as u32),
4335 FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
4336 excerpt,
4337 );
4338
4339 let editor_bg_color = cx.theme().colors().editor_background;
4340
4341 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
4342
4343 let available_width = hitbox.bounds.size.width - right_margin;
4344
4345 let mut header = v_flex()
4346 .w_full()
4347 .relative()
4348 .child(
4349 div()
4350 .w(available_width)
4351 .h(FILE_HEADER_HEIGHT as f32 * line_height)
4352 .bg(linear_gradient(
4353 0.,
4354 linear_color_stop(editor_bg_color.opacity(0.), 0.),
4355 linear_color_stop(editor_bg_color, 0.6),
4356 ))
4357 .absolute()
4358 .top_0(),
4359 )
4360 .child(
4361 self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
4362 .into_any_element(),
4363 )
4364 .into_any_element();
4365
4366 let mut origin = hitbox.origin;
4367 // Move floating header up to avoid colliding with the next buffer header.
4368 for block in blocks.iter() {
4369 if !block.is_buffer_header {
4370 continue;
4371 }
4372
4373 let Some(display_row) = block.row.filter(|row| row.0 > scroll_position as u32) else {
4374 continue;
4375 };
4376
4377 let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
4378 let offset = scroll_position - max_row as f32;
4379
4380 if offset > 0.0 {
4381 origin.y -= offset * line_height;
4382 }
4383 break;
4384 }
4385
4386 let size = size(
4387 AvailableSpace::Definite(available_width),
4388 AvailableSpace::MinContent,
4389 );
4390
4391 header.prepaint_as_root(origin, size, window, cx);
4392
4393 header
4394 }
4395
4396 fn layout_cursor_popovers(
4397 &self,
4398 line_height: Pixels,
4399 text_hitbox: &Hitbox,
4400 content_origin: gpui::Point<Pixels>,
4401 right_margin: Pixels,
4402 start_row: DisplayRow,
4403 scroll_pixel_position: gpui::Point<Pixels>,
4404 line_layouts: &[LineWithInvisibles],
4405 cursor: DisplayPoint,
4406 cursor_point: Point,
4407 style: &EditorStyle,
4408 window: &mut Window,
4409 cx: &mut App,
4410 ) -> Option<ContextMenuLayout> {
4411 let mut min_menu_height = Pixels::ZERO;
4412 let mut max_menu_height = Pixels::ZERO;
4413 let mut height_above_menu = Pixels::ZERO;
4414 let height_below_menu = Pixels::ZERO;
4415 let mut edit_prediction_popover_visible = false;
4416 let mut context_menu_visible = false;
4417 let context_menu_placement;
4418
4419 {
4420 let editor = self.editor.read(cx);
4421 if editor.edit_prediction_visible_in_cursor_popover(editor.has_active_edit_prediction())
4422 {
4423 height_above_menu +=
4424 editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
4425 edit_prediction_popover_visible = true;
4426 }
4427
4428 if editor.context_menu_visible()
4429 && let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin()
4430 {
4431 let (min_height_in_lines, max_height_in_lines) = editor
4432 .context_menu_options
4433 .as_ref()
4434 .map_or((3, 12), |options| {
4435 (options.min_entries_visible, options.max_entries_visible)
4436 });
4437
4438 min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4439 max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4440 context_menu_visible = true;
4441 }
4442 context_menu_placement = editor
4443 .context_menu_options
4444 .as_ref()
4445 .and_then(|options| options.placement.clone());
4446 }
4447
4448 let visible = edit_prediction_popover_visible || context_menu_visible;
4449 if !visible {
4450 return None;
4451 }
4452
4453 let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
4454 let target_position = content_origin
4455 + gpui::Point {
4456 x: cmp::max(
4457 px(0.),
4458 cursor_row_layout.x_for_index(cursor.column() as usize)
4459 - scroll_pixel_position.x,
4460 ),
4461 y: cmp::max(
4462 px(0.),
4463 cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
4464 ),
4465 };
4466
4467 let viewport_bounds =
4468 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4469 right: -right_margin - MENU_GAP,
4470 ..Default::default()
4471 });
4472
4473 let min_height = height_above_menu + min_menu_height + height_below_menu;
4474 let max_height = height_above_menu + max_menu_height + height_below_menu;
4475 let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
4476 target_position,
4477 line_height,
4478 min_height,
4479 max_height,
4480 context_menu_placement,
4481 text_hitbox,
4482 viewport_bounds,
4483 window,
4484 cx,
4485 |height, max_width_for_stable_x, y_flipped, window, cx| {
4486 // First layout the menu to get its size - others can be at least this wide.
4487 let context_menu = if context_menu_visible {
4488 let menu_height = if y_flipped {
4489 height - height_below_menu
4490 } else {
4491 height - height_above_menu
4492 };
4493 let mut element = self
4494 .render_context_menu(line_height, menu_height, window, cx)
4495 .expect("Visible context menu should always render.");
4496 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4497 Some((CursorPopoverType::CodeContextMenu, element, size))
4498 } else {
4499 None
4500 };
4501 let min_width = context_menu
4502 .as_ref()
4503 .map_or(px(0.), |(_, _, size)| size.width);
4504 let max_width = max_width_for_stable_x.max(
4505 context_menu
4506 .as_ref()
4507 .map_or(px(0.), |(_, _, size)| size.width),
4508 );
4509
4510 let edit_prediction = if edit_prediction_popover_visible {
4511 self.editor.update(cx, move |editor, cx| {
4512 let accept_binding =
4513 editor.accept_edit_prediction_keybind(false, window, cx);
4514 let mut element = editor.render_edit_prediction_cursor_popover(
4515 min_width,
4516 max_width,
4517 cursor_point,
4518 style,
4519 accept_binding.keystroke(),
4520 window,
4521 cx,
4522 )?;
4523 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4524 Some((CursorPopoverType::EditPrediction, element, size))
4525 })
4526 } else {
4527 None
4528 };
4529 vec![edit_prediction, context_menu]
4530 .into_iter()
4531 .flatten()
4532 .collect::<Vec<_>>()
4533 },
4534 )?;
4535
4536 let (menu_ix, (_, menu_bounds)) = laid_out_popovers
4537 .iter()
4538 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
4539 let last_ix = laid_out_popovers.len() - 1;
4540 let menu_is_last = menu_ix == last_ix;
4541 let first_popover_bounds = laid_out_popovers[0].1;
4542 let last_popover_bounds = laid_out_popovers[last_ix].1;
4543
4544 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
4545 // right, and otherwise it goes below or to the right.
4546 let mut target_bounds = Bounds::from_corners(
4547 first_popover_bounds.origin,
4548 last_popover_bounds.bottom_right(),
4549 );
4550 target_bounds.size.width = menu_bounds.size.width;
4551
4552 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
4553 // based on this is preferred for layout stability.
4554 let mut max_target_bounds = target_bounds;
4555 max_target_bounds.size.height = max_height;
4556 if y_flipped {
4557 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
4558 }
4559
4560 // Add spacing around `target_bounds` and `max_target_bounds`.
4561 let mut extend_amount = Edges::all(MENU_GAP);
4562 if y_flipped {
4563 extend_amount.bottom = line_height;
4564 } else {
4565 extend_amount.top = line_height;
4566 }
4567 let target_bounds = target_bounds.extend(extend_amount);
4568 let max_target_bounds = max_target_bounds.extend(extend_amount);
4569
4570 let must_place_above_or_below =
4571 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
4572 laid_out_popovers[menu_ix + 1..]
4573 .iter()
4574 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
4575 } else {
4576 false
4577 };
4578
4579 let aside_bounds = self.layout_context_menu_aside(
4580 y_flipped,
4581 *menu_bounds,
4582 target_bounds,
4583 max_target_bounds,
4584 max_menu_height,
4585 must_place_above_or_below,
4586 text_hitbox,
4587 viewport_bounds,
4588 window,
4589 cx,
4590 );
4591
4592 if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
4593 if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
4594 Some(*bounds)
4595 } else {
4596 None
4597 }
4598 }) {
4599 let bounds = if let Some(aside_bounds) = aside_bounds {
4600 menu_bounds.union(&aside_bounds)
4601 } else {
4602 menu_bounds
4603 };
4604 return Some(ContextMenuLayout { y_flipped, bounds });
4605 }
4606
4607 None
4608 }
4609
4610 fn layout_gutter_menu(
4611 &self,
4612 line_height: Pixels,
4613 text_hitbox: &Hitbox,
4614 content_origin: gpui::Point<Pixels>,
4615 right_margin: Pixels,
4616 scroll_pixel_position: gpui::Point<Pixels>,
4617 gutter_overshoot: Pixels,
4618 window: &mut Window,
4619 cx: &mut App,
4620 ) {
4621 let editor = self.editor.read(cx);
4622 if !editor.context_menu_visible() {
4623 return;
4624 }
4625 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
4626 editor.context_menu_origin()
4627 else {
4628 return;
4629 };
4630 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
4631 // indicator than just a plain first column of the text field.
4632 let target_position = content_origin
4633 + gpui::Point {
4634 x: -gutter_overshoot,
4635 y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
4636 };
4637
4638 let (min_height_in_lines, max_height_in_lines) = editor
4639 .context_menu_options
4640 .as_ref()
4641 .map_or((3, 12), |options| {
4642 (options.min_entries_visible, options.max_entries_visible)
4643 });
4644
4645 let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4646 let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4647 let viewport_bounds =
4648 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4649 right: -right_margin - MENU_GAP,
4650 ..Default::default()
4651 });
4652 self.layout_popovers_above_or_below_line(
4653 target_position,
4654 line_height,
4655 min_height,
4656 max_height,
4657 editor
4658 .context_menu_options
4659 .as_ref()
4660 .and_then(|options| options.placement.clone()),
4661 text_hitbox,
4662 viewport_bounds,
4663 window,
4664 cx,
4665 move |height, _max_width_for_stable_x, _, window, cx| {
4666 let mut element = self
4667 .render_context_menu(line_height, height, window, cx)
4668 .expect("Visible context menu should always render.");
4669 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4670 vec![(CursorPopoverType::CodeContextMenu, element, size)]
4671 },
4672 );
4673 }
4674
4675 fn layout_popovers_above_or_below_line(
4676 &self,
4677 target_position: gpui::Point<Pixels>,
4678 line_height: Pixels,
4679 min_height: Pixels,
4680 max_height: Pixels,
4681 placement: Option<ContextMenuPlacement>,
4682 text_hitbox: &Hitbox,
4683 viewport_bounds: Bounds<Pixels>,
4684 window: &mut Window,
4685 cx: &mut App,
4686 make_sized_popovers: impl FnOnce(
4687 Pixels,
4688 Pixels,
4689 bool,
4690 &mut Window,
4691 &mut App,
4692 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
4693 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
4694 let text_style = TextStyleRefinement {
4695 line_height: Some(DefiniteLength::Fraction(
4696 BufferLineHeight::Comfortable.value(),
4697 )),
4698 ..Default::default()
4699 };
4700 window.with_text_style(Some(text_style), |window| {
4701 // If the max height won't fit below and there is more space above, put it above the line.
4702 let bottom_y_when_flipped = target_position.y - line_height;
4703 let available_above = bottom_y_when_flipped - text_hitbox.top();
4704 let available_below = text_hitbox.bottom() - target_position.y;
4705 let y_overflows_below = max_height > available_below;
4706 let mut y_flipped = match placement {
4707 Some(ContextMenuPlacement::Above) => true,
4708 Some(ContextMenuPlacement::Below) => false,
4709 None => y_overflows_below && available_above > available_below,
4710 };
4711 let mut height = cmp::min(
4712 max_height,
4713 if y_flipped {
4714 available_above
4715 } else {
4716 available_below
4717 },
4718 );
4719
4720 // If the min height doesn't fit within text bounds, instead fit within the window.
4721 if height < min_height {
4722 let available_above = bottom_y_when_flipped;
4723 let available_below = viewport_bounds.bottom() - target_position.y;
4724 let (y_flipped_override, height_override) = match placement {
4725 Some(ContextMenuPlacement::Above) => {
4726 (true, cmp::min(available_above, min_height))
4727 }
4728 Some(ContextMenuPlacement::Below) => {
4729 (false, cmp::min(available_below, min_height))
4730 }
4731 None => {
4732 if available_below > min_height {
4733 (false, min_height)
4734 } else if available_above > min_height {
4735 (true, min_height)
4736 } else if available_above > available_below {
4737 (true, available_above)
4738 } else {
4739 (false, available_below)
4740 }
4741 }
4742 };
4743 y_flipped = y_flipped_override;
4744 height = height_override;
4745 }
4746
4747 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
4748
4749 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
4750 // for very narrow windows.
4751 let popovers =
4752 make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
4753 if popovers.is_empty() {
4754 return None;
4755 }
4756
4757 let max_width = popovers
4758 .iter()
4759 .map(|(_, _, size)| size.width)
4760 .max()
4761 .unwrap_or_default();
4762
4763 let mut current_position = gpui::Point {
4764 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
4765 // overflow. Include space for the scrollbar.
4766 x: target_position
4767 .x
4768 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
4769 y: if y_flipped {
4770 bottom_y_when_flipped
4771 } else {
4772 target_position.y
4773 },
4774 };
4775
4776 let mut laid_out_popovers = popovers
4777 .into_iter()
4778 .map(|(popover_type, element, size)| {
4779 if y_flipped {
4780 current_position.y -= size.height;
4781 }
4782 let position = current_position;
4783 window.defer_draw(element, current_position, 1);
4784 if !y_flipped {
4785 current_position.y += size.height + MENU_GAP;
4786 } else {
4787 current_position.y -= MENU_GAP;
4788 }
4789 (popover_type, Bounds::new(position, size))
4790 })
4791 .collect::<Vec<_>>();
4792
4793 if y_flipped {
4794 laid_out_popovers.reverse();
4795 }
4796
4797 Some((laid_out_popovers, y_flipped))
4798 })
4799 }
4800
4801 fn layout_context_menu_aside(
4802 &self,
4803 y_flipped: bool,
4804 menu_bounds: Bounds<Pixels>,
4805 target_bounds: Bounds<Pixels>,
4806 max_target_bounds: Bounds<Pixels>,
4807 max_height: Pixels,
4808 must_place_above_or_below: bool,
4809 text_hitbox: &Hitbox,
4810 viewport_bounds: Bounds<Pixels>,
4811 window: &mut Window,
4812 cx: &mut App,
4813 ) -> Option<Bounds<Pixels>> {
4814 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
4815 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
4816 && !must_place_above_or_below
4817 {
4818 let max_width = cmp::min(
4819 available_within_viewport.right - px(1.),
4820 MENU_ASIDE_MAX_WIDTH,
4821 );
4822 let mut aside = self.render_context_menu_aside(
4823 size(max_width, max_height - POPOVER_Y_PADDING),
4824 window,
4825 cx,
4826 )?;
4827 let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
4828 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
4829 Some((aside, right_position, size))
4830 } else {
4831 let max_size = size(
4832 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
4833 // won't be needed here.
4834 cmp::min(
4835 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
4836 viewport_bounds.right(),
4837 ),
4838 cmp::min(
4839 max_height,
4840 cmp::max(
4841 available_within_viewport.top,
4842 available_within_viewport.bottom,
4843 ),
4844 ) - POPOVER_Y_PADDING,
4845 );
4846 let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
4847 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
4848
4849 let top_position = point(
4850 menu_bounds.origin.x,
4851 target_bounds.top() - actual_size.height,
4852 );
4853 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
4854
4855 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
4856 // Prefer to fit on the same side of the line as the menu, then on the other side of
4857 // the line.
4858 if !y_flipped && wanted.height < available.bottom {
4859 Some(bottom_position)
4860 } else if !y_flipped && wanted.height < available.top {
4861 Some(top_position)
4862 } else if y_flipped && wanted.height < available.top {
4863 Some(top_position)
4864 } else if y_flipped && wanted.height < available.bottom {
4865 Some(bottom_position)
4866 } else {
4867 None
4868 }
4869 };
4870
4871 // Prefer choosing a direction using max sizes rather than actual size for stability.
4872 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
4873 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
4874 let aside_position = fit_within(available_within_text, wanted)
4875 // Fallback: fit max size in window.
4876 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
4877 // Fallback: fit actual size in window.
4878 .or_else(|| fit_within(available_within_viewport, actual_size));
4879
4880 aside_position.map(|position| (aside, position, actual_size))
4881 };
4882
4883 // Skip drawing if it doesn't fit anywhere.
4884 if let Some((aside, position, size)) = positioned_aside {
4885 let aside_bounds = Bounds::new(position, size);
4886 window.defer_draw(aside, position, 2);
4887 return Some(aside_bounds);
4888 }
4889
4890 None
4891 }
4892
4893 fn render_context_menu(
4894 &self,
4895 line_height: Pixels,
4896 height: Pixels,
4897 window: &mut Window,
4898 cx: &mut App,
4899 ) -> Option<AnyElement> {
4900 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
4901 self.editor.update(cx, |editor, cx| {
4902 editor.render_context_menu(&self.style, max_height_in_lines, window, cx)
4903 })
4904 }
4905
4906 fn render_context_menu_aside(
4907 &self,
4908 max_size: Size<Pixels>,
4909 window: &mut Window,
4910 cx: &mut App,
4911 ) -> Option<AnyElement> {
4912 if max_size.width < px(100.) || max_size.height < px(12.) {
4913 None
4914 } else {
4915 self.editor.update(cx, |editor, cx| {
4916 editor.render_context_menu_aside(max_size, window, cx)
4917 })
4918 }
4919 }
4920
4921 fn layout_mouse_context_menu(
4922 &self,
4923 editor_snapshot: &EditorSnapshot,
4924 visible_range: Range<DisplayRow>,
4925 content_origin: gpui::Point<Pixels>,
4926 window: &mut Window,
4927 cx: &mut App,
4928 ) -> Option<AnyElement> {
4929 let position = self.editor.update(cx, |editor, _cx| {
4930 let visible_start_point = editor.display_to_pixel_point(
4931 DisplayPoint::new(visible_range.start, 0),
4932 editor_snapshot,
4933 window,
4934 )?;
4935 let visible_end_point = editor.display_to_pixel_point(
4936 DisplayPoint::new(visible_range.end, 0),
4937 editor_snapshot,
4938 window,
4939 )?;
4940
4941 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4942 let (source_display_point, position) = match mouse_context_menu.position {
4943 MenuPosition::PinnedToScreen(point) => (None, point),
4944 MenuPosition::PinnedToEditor { source, offset } => {
4945 let source_display_point = source.to_display_point(editor_snapshot);
4946 let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
4947 let position = content_origin + source_point + offset;
4948 (Some(source_display_point), position)
4949 }
4950 };
4951
4952 let source_included = source_display_point.is_none_or(|source_display_point| {
4953 visible_range
4954 .to_inclusive()
4955 .contains(&source_display_point.row())
4956 });
4957 let position_included =
4958 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
4959 if !source_included && !position_included {
4960 None
4961 } else {
4962 Some(position)
4963 }
4964 })?;
4965
4966 let text_style = TextStyleRefinement {
4967 line_height: Some(DefiniteLength::Fraction(
4968 BufferLineHeight::Comfortable.value(),
4969 )),
4970 ..Default::default()
4971 };
4972 window.with_text_style(Some(text_style), |window| {
4973 let mut element = self.editor.read_with(cx, |editor, _| {
4974 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4975 let context_menu = mouse_context_menu.context_menu.clone();
4976
4977 Some(
4978 deferred(
4979 anchored()
4980 .position(position)
4981 .child(context_menu)
4982 .anchor(Corner::TopLeft)
4983 .snap_to_window_with_margin(px(8.)),
4984 )
4985 .with_priority(1)
4986 .into_any(),
4987 )
4988 })?;
4989
4990 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
4991 Some(element)
4992 })
4993 }
4994
4995 fn layout_hover_popovers(
4996 &self,
4997 snapshot: &EditorSnapshot,
4998 hitbox: &Hitbox,
4999 visible_display_row_range: Range<DisplayRow>,
5000 content_origin: gpui::Point<Pixels>,
5001 scroll_pixel_position: gpui::Point<Pixels>,
5002 line_layouts: &[LineWithInvisibles],
5003 line_height: Pixels,
5004 em_width: Pixels,
5005 context_menu_layout: Option<ContextMenuLayout>,
5006 window: &mut Window,
5007 cx: &mut App,
5008 ) {
5009 struct MeasuredHoverPopover {
5010 element: AnyElement,
5011 size: Size<Pixels>,
5012 horizontal_offset: Pixels,
5013 }
5014
5015 let max_size = size(
5016 (120. * em_width) // Default size
5017 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5018 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5019 (16. * line_height) // Default size
5020 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5021 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5022 );
5023
5024 let hover_popovers = self.editor.update(cx, |editor, cx| {
5025 editor.hover_state.render(
5026 snapshot,
5027 visible_display_row_range.clone(),
5028 max_size,
5029 window,
5030 cx,
5031 )
5032 });
5033 let Some((position, hover_popovers)) = hover_popovers else {
5034 return;
5035 };
5036
5037 // This is safe because we check on layout whether the required row is available
5038 let hovered_row_layout =
5039 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
5040
5041 // Compute Hovered Point
5042 let x =
5043 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
5044 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
5045 let hovered_point = content_origin + point(x, y);
5046
5047 let mut overall_height = Pixels::ZERO;
5048 let mut measured_hover_popovers = Vec::new();
5049 for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
5050 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
5051 let horizontal_offset =
5052 (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
5053 .min(Pixels::ZERO);
5054 match position {
5055 itertools::Position::Middle | itertools::Position::Last => {
5056 overall_height += HOVER_POPOVER_GAP
5057 }
5058 _ => {}
5059 }
5060 overall_height += size.height;
5061 measured_hover_popovers.push(MeasuredHoverPopover {
5062 element: hover_popover,
5063 size,
5064 horizontal_offset,
5065 });
5066 }
5067
5068 fn draw_occluder(
5069 width: Pixels,
5070 origin: gpui::Point<Pixels>,
5071 window: &mut Window,
5072 cx: &mut App,
5073 ) {
5074 let mut occlusion = div()
5075 .size_full()
5076 .occlude()
5077 .on_mouse_move(|_, _, cx| cx.stop_propagation())
5078 .into_any_element();
5079 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
5080 window.defer_draw(occlusion, origin, 2);
5081 }
5082
5083 fn place_popovers_above(
5084 hovered_point: gpui::Point<Pixels>,
5085 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5086 window: &mut Window,
5087 cx: &mut App,
5088 ) {
5089 let mut current_y = hovered_point.y;
5090 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5091 let size = popover.size;
5092 let popover_origin = point(
5093 hovered_point.x + popover.horizontal_offset,
5094 current_y - size.height,
5095 );
5096
5097 window.defer_draw(popover.element, popover_origin, 2);
5098 if position != itertools::Position::Last {
5099 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
5100 draw_occluder(size.width, origin, window, cx);
5101 }
5102
5103 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5104 }
5105 }
5106
5107 fn place_popovers_below(
5108 hovered_point: gpui::Point<Pixels>,
5109 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5110 line_height: Pixels,
5111 window: &mut Window,
5112 cx: &mut App,
5113 ) {
5114 let mut current_y = hovered_point.y + line_height;
5115 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5116 let size = popover.size;
5117 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5118
5119 window.defer_draw(popover.element, popover_origin, 2);
5120 if position != itertools::Position::Last {
5121 let origin = point(popover_origin.x, popover_origin.y + size.height);
5122 draw_occluder(size.width, origin, window, cx);
5123 }
5124
5125 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5126 }
5127 }
5128
5129 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5130 context_menu_layout
5131 .as_ref()
5132 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5133 };
5134
5135 let can_place_above = {
5136 let mut bounds_above = Vec::new();
5137 let mut current_y = hovered_point.y;
5138 for popover in &measured_hover_popovers {
5139 let size = popover.size;
5140 let popover_origin = point(
5141 hovered_point.x + popover.horizontal_offset,
5142 current_y - size.height,
5143 );
5144 bounds_above.push(Bounds::new(popover_origin, size));
5145 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5146 }
5147 bounds_above
5148 .iter()
5149 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5150 };
5151
5152 let can_place_below = || {
5153 let mut bounds_below = Vec::new();
5154 let mut current_y = hovered_point.y + line_height;
5155 for popover in &measured_hover_popovers {
5156 let size = popover.size;
5157 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5158 bounds_below.push(Bounds::new(popover_origin, size));
5159 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5160 }
5161 bounds_below
5162 .iter()
5163 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5164 };
5165
5166 if can_place_above {
5167 // try placing above hovered point
5168 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5169 } else if can_place_below() {
5170 // try placing below hovered point
5171 place_popovers_below(
5172 hovered_point,
5173 measured_hover_popovers,
5174 line_height,
5175 window,
5176 cx,
5177 );
5178 } else {
5179 // try to place popovers around the context menu
5180 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5181 let total_width = measured_hover_popovers
5182 .iter()
5183 .map(|p| p.size.width)
5184 .max()
5185 .unwrap_or(Pixels::ZERO);
5186 let y_for_horizontal_positioning = if menu.y_flipped {
5187 menu.bounds.bottom() - overall_height
5188 } else {
5189 menu.bounds.top()
5190 };
5191 let possible_origins = vec![
5192 // left of context menu
5193 point(
5194 menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
5195 y_for_horizontal_positioning,
5196 ),
5197 // right of context menu
5198 point(
5199 menu.bounds.right() + HOVER_POPOVER_GAP,
5200 y_for_horizontal_positioning,
5201 ),
5202 // top of context menu
5203 point(
5204 menu.bounds.left(),
5205 menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
5206 ),
5207 // bottom of context menu
5208 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5209 ];
5210 possible_origins.into_iter().find(|&origin| {
5211 Bounds::new(origin, size(total_width, overall_height))
5212 .is_contained_within(hitbox)
5213 })
5214 });
5215 if let Some(origin) = origin_surrounding_menu {
5216 let mut current_y = origin.y;
5217 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5218 let size = popover.size;
5219 let popover_origin = point(origin.x, current_y);
5220
5221 window.defer_draw(popover.element, popover_origin, 2);
5222 if position != itertools::Position::Last {
5223 let origin = point(popover_origin.x, popover_origin.y + size.height);
5224 draw_occluder(size.width, origin, window, cx);
5225 }
5226
5227 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5228 }
5229 } else {
5230 // fallback to existing above/below cursor logic
5231 // this might overlap menu or overflow in rare case
5232 if can_place_above {
5233 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5234 } else {
5235 place_popovers_below(
5236 hovered_point,
5237 measured_hover_popovers,
5238 line_height,
5239 window,
5240 cx,
5241 );
5242 }
5243 }
5244 }
5245 }
5246
5247 fn layout_diff_hunk_controls(
5248 &self,
5249 row_range: Range<DisplayRow>,
5250 row_infos: &[RowInfo],
5251 text_hitbox: &Hitbox,
5252 newest_cursor_position: Option<DisplayPoint>,
5253 line_height: Pixels,
5254 right_margin: Pixels,
5255 scroll_pixel_position: gpui::Point<Pixels>,
5256 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5257 highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
5258 editor: Entity<Editor>,
5259 window: &mut Window,
5260 cx: &mut App,
5261 ) -> (Vec<AnyElement>, Vec<(DisplayRow, Bounds<Pixels>)>) {
5262 let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
5263 let hovered_diff_hunk_row = editor.read(cx).hovered_diff_hunk_row;
5264
5265 let mut controls = vec![];
5266 let mut control_bounds = vec![];
5267
5268 let active_positions = [
5269 hovered_diff_hunk_row.map(|row| DisplayPoint::new(row, 0)),
5270 newest_cursor_position,
5271 ];
5272
5273 for (hunk, _) in display_hunks {
5274 if let DisplayDiffHunk::Unfolded {
5275 display_row_range,
5276 multi_buffer_range,
5277 status,
5278 is_created_file,
5279 ..
5280 } = &hunk
5281 {
5282 if display_row_range.start < row_range.start
5283 || display_row_range.start >= row_range.end
5284 {
5285 continue;
5286 }
5287 if highlighted_rows
5288 .get(&display_row_range.start)
5289 .and_then(|highlight| highlight.type_id)
5290 .is_some_and(|type_id| {
5291 [
5292 TypeId::of::<ConflictsOuter>(),
5293 TypeId::of::<ConflictsOursMarker>(),
5294 TypeId::of::<ConflictsOurs>(),
5295 TypeId::of::<ConflictsTheirs>(),
5296 TypeId::of::<ConflictsTheirsMarker>(),
5297 ]
5298 .contains(&type_id)
5299 })
5300 {
5301 continue;
5302 }
5303 let row_ix = (display_row_range.start - row_range.start).0 as usize;
5304 if row_infos[row_ix].diff_status.is_none() {
5305 continue;
5306 }
5307 if row_infos[row_ix]
5308 .diff_status
5309 .is_some_and(|status| status.is_added())
5310 && !status.is_added()
5311 {
5312 continue;
5313 }
5314
5315 if active_positions
5316 .iter()
5317 .any(|p| p.is_some_and(|p| display_row_range.contains(&p.row())))
5318 {
5319 let y = display_row_range.start.as_f32() * line_height
5320 + text_hitbox.bounds.top()
5321 - scroll_pixel_position.y;
5322
5323 let mut element = render_diff_hunk_controls(
5324 display_row_range.start.0,
5325 status,
5326 multi_buffer_range.clone(),
5327 *is_created_file,
5328 line_height,
5329 &editor,
5330 window,
5331 cx,
5332 );
5333 let size =
5334 element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
5335
5336 let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
5337
5338 let bounds = Bounds::new(gpui::Point::new(x, y), size);
5339 control_bounds.push((display_row_range.start, bounds));
5340
5341 window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
5342 element.prepaint(window, cx)
5343 });
5344 controls.push(element);
5345 }
5346 }
5347 }
5348
5349 (controls, control_bounds)
5350 }
5351
5352 fn layout_signature_help(
5353 &self,
5354 hitbox: &Hitbox,
5355 content_origin: gpui::Point<Pixels>,
5356 scroll_pixel_position: gpui::Point<Pixels>,
5357 newest_selection_head: Option<DisplayPoint>,
5358 start_row: DisplayRow,
5359 line_layouts: &[LineWithInvisibles],
5360 line_height: Pixels,
5361 em_width: Pixels,
5362 context_menu_layout: Option<ContextMenuLayout>,
5363 window: &mut Window,
5364 cx: &mut App,
5365 ) {
5366 if !self.editor.focus_handle(cx).is_focused(window) {
5367 return;
5368 }
5369 let Some(newest_selection_head) = newest_selection_head else {
5370 return;
5371 };
5372
5373 let max_size = size(
5374 (120. * em_width) // Default size
5375 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5376 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5377 (16. * line_height) // Default size
5378 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5379 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5380 );
5381
5382 let maybe_element = self.editor.update(cx, |editor, cx| {
5383 if let Some(popover) = editor.signature_help_state.popover_mut() {
5384 let element = popover.render(max_size, window, cx);
5385 Some(element)
5386 } else {
5387 None
5388 }
5389 });
5390 let Some(mut element) = maybe_element else {
5391 return;
5392 };
5393
5394 let selection_row = newest_selection_head.row();
5395 let Some(cursor_row_layout) = (selection_row >= start_row)
5396 .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
5397 .flatten()
5398 else {
5399 return;
5400 };
5401
5402 let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
5403 - scroll_pixel_position.x;
5404 let target_y = selection_row.as_f32() * line_height - scroll_pixel_position.y;
5405 let target_point = content_origin + point(target_x, target_y);
5406
5407 let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
5408
5409 let (popover_bounds_above, popover_bounds_below) = {
5410 let horizontal_offset = (hitbox.top_right().x
5411 - POPOVER_RIGHT_OFFSET
5412 - (target_point.x + actual_size.width))
5413 .min(Pixels::ZERO);
5414 let initial_x = target_point.x + horizontal_offset;
5415 (
5416 Bounds::new(
5417 point(initial_x, target_point.y - actual_size.height),
5418 actual_size,
5419 ),
5420 Bounds::new(
5421 point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
5422 actual_size,
5423 ),
5424 )
5425 };
5426
5427 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5428 context_menu_layout
5429 .as_ref()
5430 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5431 };
5432
5433 let final_origin = if popover_bounds_above.is_contained_within(hitbox)
5434 && !intersects_menu(popover_bounds_above)
5435 {
5436 // try placing above cursor
5437 popover_bounds_above.origin
5438 } else if popover_bounds_below.is_contained_within(hitbox)
5439 && !intersects_menu(popover_bounds_below)
5440 {
5441 // try placing below cursor
5442 popover_bounds_below.origin
5443 } else {
5444 // try surrounding context menu if exists
5445 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5446 let y_for_horizontal_positioning = if menu.y_flipped {
5447 menu.bounds.bottom() - actual_size.height
5448 } else {
5449 menu.bounds.top()
5450 };
5451 let possible_origins = vec![
5452 // left of context menu
5453 point(
5454 menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
5455 y_for_horizontal_positioning,
5456 ),
5457 // right of context menu
5458 point(
5459 menu.bounds.right() + HOVER_POPOVER_GAP,
5460 y_for_horizontal_positioning,
5461 ),
5462 // top of context menu
5463 point(
5464 menu.bounds.left(),
5465 menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
5466 ),
5467 // bottom of context menu
5468 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5469 ];
5470 possible_origins
5471 .into_iter()
5472 .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
5473 });
5474 origin_surrounding_menu.unwrap_or_else(|| {
5475 // fallback to existing above/below cursor logic
5476 // this might overlap menu or overflow in rare case
5477 if popover_bounds_above.is_contained_within(hitbox) {
5478 popover_bounds_above.origin
5479 } else {
5480 popover_bounds_below.origin
5481 }
5482 })
5483 };
5484
5485 window.defer_draw(element, final_origin, 2);
5486 }
5487
5488 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5489 window.paint_layer(layout.hitbox.bounds, |window| {
5490 let scroll_top = layout.position_map.snapshot.scroll_position().y;
5491 let gutter_bg = cx.theme().colors().editor_gutter_background;
5492 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
5493 window.paint_quad(fill(
5494 layout.position_map.text_hitbox.bounds,
5495 self.style.background,
5496 ));
5497
5498 if matches!(
5499 layout.mode,
5500 EditorMode::Full { .. } | EditorMode::Minimap { .. }
5501 ) {
5502 let show_active_line_background = match layout.mode {
5503 EditorMode::Full {
5504 show_active_line_background,
5505 ..
5506 } => show_active_line_background,
5507 EditorMode::Minimap { .. } => true,
5508 _ => false,
5509 };
5510 let mut active_rows = layout.active_rows.iter().peekable();
5511 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
5512 let mut end_row = start_row.0;
5513 while active_rows
5514 .peek()
5515 .is_some_and(|(active_row, has_selection)| {
5516 active_row.0 == end_row + 1
5517 && has_selection.selection == contains_non_empty_selection.selection
5518 })
5519 {
5520 active_rows.next().unwrap();
5521 end_row += 1;
5522 }
5523
5524 if show_active_line_background && !contains_non_empty_selection.selection {
5525 let highlight_h_range =
5526 match layout.position_map.snapshot.current_line_highlight {
5527 CurrentLineHighlight::Gutter => Some(Range {
5528 start: layout.hitbox.left(),
5529 end: layout.gutter_hitbox.right(),
5530 }),
5531 CurrentLineHighlight::Line => Some(Range {
5532 start: layout.position_map.text_hitbox.bounds.left(),
5533 end: layout.position_map.text_hitbox.bounds.right(),
5534 }),
5535 CurrentLineHighlight::All => Some(Range {
5536 start: layout.hitbox.left(),
5537 end: layout.hitbox.right(),
5538 }),
5539 CurrentLineHighlight::None => None,
5540 };
5541 if let Some(range) = highlight_h_range {
5542 let active_line_bg = cx.theme().colors().editor_active_line_background;
5543 let bounds = Bounds {
5544 origin: point(
5545 range.start,
5546 layout.hitbox.origin.y
5547 + (start_row.as_f32() - scroll_top)
5548 * layout.position_map.line_height,
5549 ),
5550 size: size(
5551 range.end - range.start,
5552 layout.position_map.line_height
5553 * (end_row - start_row.0 + 1) as f32,
5554 ),
5555 };
5556 window.paint_quad(fill(bounds, active_line_bg));
5557 }
5558 }
5559 }
5560
5561 let mut paint_highlight = |highlight_row_start: DisplayRow,
5562 highlight_row_end: DisplayRow,
5563 highlight: crate::LineHighlight,
5564 edges| {
5565 let mut origin_x = layout.hitbox.left();
5566 let mut width = layout.hitbox.size.width;
5567 if !highlight.include_gutter {
5568 origin_x += layout.gutter_hitbox.size.width;
5569 width -= layout.gutter_hitbox.size.width;
5570 }
5571
5572 let origin = point(
5573 origin_x,
5574 layout.hitbox.origin.y
5575 + (highlight_row_start.as_f32() - scroll_top)
5576 * layout.position_map.line_height,
5577 );
5578 let size = size(
5579 width,
5580 layout.position_map.line_height
5581 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
5582 );
5583 let mut quad = fill(Bounds { origin, size }, highlight.background);
5584 if let Some(border_color) = highlight.border {
5585 quad.border_color = border_color;
5586 quad.border_widths = edges
5587 }
5588 window.paint_quad(quad);
5589 };
5590
5591 let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
5592 None;
5593 for (&new_row, &new_background) in &layout.highlighted_rows {
5594 match &mut current_paint {
5595 &mut Some((current_background, ref mut current_range, mut edges)) => {
5596 let new_range_started = current_background != new_background
5597 || current_range.end.next_row() != new_row;
5598 if new_range_started {
5599 if current_range.end.next_row() == new_row {
5600 edges.bottom = px(0.);
5601 };
5602 paint_highlight(
5603 current_range.start,
5604 current_range.end,
5605 current_background,
5606 edges,
5607 );
5608 let edges = Edges {
5609 top: if current_range.end.next_row() != new_row {
5610 px(1.)
5611 } else {
5612 px(0.)
5613 },
5614 bottom: px(1.),
5615 ..Default::default()
5616 };
5617 current_paint = Some((new_background, new_row..new_row, edges));
5618 continue;
5619 } else {
5620 current_range.end = current_range.end.next_row();
5621 }
5622 }
5623 None => {
5624 let edges = Edges {
5625 top: px(1.),
5626 bottom: px(1.),
5627 ..Default::default()
5628 };
5629 current_paint = Some((new_background, new_row..new_row, edges))
5630 }
5631 };
5632 }
5633 if let Some((color, range, edges)) = current_paint {
5634 paint_highlight(range.start, range.end, color, edges);
5635 }
5636
5637 for (guide_x, active) in layout.wrap_guides.iter() {
5638 let color = if *active {
5639 cx.theme().colors().editor_active_wrap_guide
5640 } else {
5641 cx.theme().colors().editor_wrap_guide
5642 };
5643 window.paint_quad(fill(
5644 Bounds {
5645 origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
5646 size: size(px(1.), layout.position_map.text_hitbox.size.height),
5647 },
5648 color,
5649 ));
5650 }
5651 }
5652 })
5653 }
5654
5655 fn paint_indent_guides(
5656 &mut self,
5657 layout: &mut EditorLayout,
5658 window: &mut Window,
5659 cx: &mut App,
5660 ) {
5661 let Some(indent_guides) = &layout.indent_guides else {
5662 return;
5663 };
5664
5665 let faded_color = |color: Hsla, alpha: f32| {
5666 let mut faded = color;
5667 faded.a = alpha;
5668 faded
5669 };
5670
5671 for indent_guide in indent_guides {
5672 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
5673 let settings = indent_guide.settings;
5674
5675 // TODO fixed for now, expose them through themes later
5676 const INDENT_AWARE_ALPHA: f32 = 0.2;
5677 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
5678 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
5679 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
5680
5681 let line_color = match (settings.coloring, indent_guide.active) {
5682 (IndentGuideColoring::Disabled, _) => None,
5683 (IndentGuideColoring::Fixed, false) => {
5684 Some(cx.theme().colors().editor_indent_guide)
5685 }
5686 (IndentGuideColoring::Fixed, true) => {
5687 Some(cx.theme().colors().editor_indent_guide_active)
5688 }
5689 (IndentGuideColoring::IndentAware, false) => {
5690 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
5691 }
5692 (IndentGuideColoring::IndentAware, true) => {
5693 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
5694 }
5695 };
5696
5697 let background_color = match (settings.background_coloring, indent_guide.active) {
5698 (IndentGuideBackgroundColoring::Disabled, _) => None,
5699 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
5700 indent_accent_colors,
5701 INDENT_AWARE_BACKGROUND_ALPHA,
5702 )),
5703 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
5704 indent_accent_colors,
5705 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
5706 )),
5707 };
5708
5709 let requested_line_width = if indent_guide.active {
5710 settings.active_line_width
5711 } else {
5712 settings.line_width
5713 }
5714 .clamp(1, 10);
5715 let mut line_indicator_width = 0.;
5716 if let Some(color) = line_color {
5717 window.paint_quad(fill(
5718 Bounds {
5719 origin: indent_guide.origin,
5720 size: size(px(requested_line_width as f32), indent_guide.length),
5721 },
5722 color,
5723 ));
5724 line_indicator_width = requested_line_width as f32;
5725 }
5726
5727 if let Some(color) = background_color {
5728 let width = indent_guide.single_indent_width - px(line_indicator_width);
5729 window.paint_quad(fill(
5730 Bounds {
5731 origin: point(
5732 indent_guide.origin.x + px(line_indicator_width),
5733 indent_guide.origin.y,
5734 ),
5735 size: size(width, indent_guide.length),
5736 },
5737 color,
5738 ));
5739 }
5740 }
5741 }
5742
5743 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5744 let is_singleton = self.editor.read(cx).is_singleton(cx);
5745
5746 let line_height = layout.position_map.line_height;
5747 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
5748
5749 for LineNumberLayout {
5750 shaped_line,
5751 hitbox,
5752 } in layout.line_numbers.values()
5753 {
5754 let Some(hitbox) = hitbox else {
5755 continue;
5756 };
5757
5758 let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
5759 let color = cx.theme().colors().editor_hover_line_number;
5760
5761 let line = self.shape_line_number(shaped_line.text.clone(), color, window);
5762 line.paint(hitbox.origin, line_height, window, cx).log_err()
5763 } else {
5764 shaped_line
5765 .paint(hitbox.origin, line_height, window, cx)
5766 .log_err()
5767 }) else {
5768 continue;
5769 };
5770
5771 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
5772 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
5773 if is_singleton {
5774 window.set_cursor_style(CursorStyle::IBeam, hitbox);
5775 } else {
5776 window.set_cursor_style(CursorStyle::PointingHand, hitbox);
5777 }
5778 }
5779 }
5780
5781 fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5782 if layout.display_hunks.is_empty() {
5783 return;
5784 }
5785
5786 let line_height = layout.position_map.line_height;
5787 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5788 for (hunk, hitbox) in &layout.display_hunks {
5789 let hunk_to_paint = match hunk {
5790 DisplayDiffHunk::Folded { .. } => {
5791 let hunk_bounds = Self::diff_hunk_bounds(
5792 &layout.position_map.snapshot,
5793 line_height,
5794 layout.gutter_hitbox.bounds,
5795 hunk,
5796 );
5797 Some((
5798 hunk_bounds,
5799 cx.theme().colors().version_control_modified,
5800 Corners::all(px(0.)),
5801 DiffHunkStatus::modified_none(),
5802 ))
5803 }
5804 DisplayDiffHunk::Unfolded {
5805 status,
5806 display_row_range,
5807 ..
5808 } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
5809 DiffHunkStatusKind::Added => (
5810 hunk_hitbox.bounds,
5811 cx.theme().colors().version_control_added,
5812 Corners::all(px(0.)),
5813 *status,
5814 ),
5815 DiffHunkStatusKind::Modified => (
5816 hunk_hitbox.bounds,
5817 cx.theme().colors().version_control_modified,
5818 Corners::all(px(0.)),
5819 *status,
5820 ),
5821 DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
5822 hunk_hitbox.bounds,
5823 cx.theme().colors().version_control_deleted,
5824 Corners::all(px(0.)),
5825 *status,
5826 ),
5827 DiffHunkStatusKind::Deleted => (
5828 Bounds::new(
5829 point(
5830 hunk_hitbox.origin.x - hunk_hitbox.size.width,
5831 hunk_hitbox.origin.y,
5832 ),
5833 size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
5834 ),
5835 cx.theme().colors().version_control_deleted,
5836 Corners::all(1. * line_height),
5837 *status,
5838 ),
5839 }),
5840 };
5841
5842 if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
5843 // Flatten the background color with the editor color to prevent
5844 // elements below transparent hunks from showing through
5845 let flattened_background_color = cx
5846 .theme()
5847 .colors()
5848 .editor_background
5849 .blend(background_color);
5850
5851 if !Self::diff_hunk_hollow(status, cx) {
5852 window.paint_quad(quad(
5853 hunk_bounds,
5854 corner_radii,
5855 flattened_background_color,
5856 Edges::default(),
5857 transparent_black(),
5858 BorderStyle::default(),
5859 ));
5860 } else {
5861 let flattened_unstaged_background_color = cx
5862 .theme()
5863 .colors()
5864 .editor_background
5865 .blend(background_color.opacity(0.3));
5866
5867 window.paint_quad(quad(
5868 hunk_bounds,
5869 corner_radii,
5870 flattened_unstaged_background_color,
5871 Edges::all(Pixels(1.0)),
5872 flattened_background_color,
5873 BorderStyle::Solid,
5874 ));
5875 }
5876 }
5877 }
5878 });
5879 }
5880
5881 fn gutter_strip_width(line_height: Pixels) -> Pixels {
5882 (0.275 * line_height).floor()
5883 }
5884
5885 fn diff_hunk_bounds(
5886 snapshot: &EditorSnapshot,
5887 line_height: Pixels,
5888 gutter_bounds: Bounds<Pixels>,
5889 hunk: &DisplayDiffHunk,
5890 ) -> Bounds<Pixels> {
5891 let scroll_position = snapshot.scroll_position();
5892 let scroll_top = scroll_position.y * line_height;
5893 let gutter_strip_width = Self::gutter_strip_width(line_height);
5894
5895 match hunk {
5896 DisplayDiffHunk::Folded { display_row, .. } => {
5897 let start_y = display_row.as_f32() * line_height - scroll_top;
5898 let end_y = start_y + line_height;
5899 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5900 let highlight_size = size(gutter_strip_width, end_y - start_y);
5901 Bounds::new(highlight_origin, highlight_size)
5902 }
5903 DisplayDiffHunk::Unfolded {
5904 display_row_range,
5905 status,
5906 ..
5907 } => {
5908 if status.is_deleted() && display_row_range.is_empty() {
5909 let row = display_row_range.start;
5910
5911 let offset = line_height / 2.;
5912 let start_y = row.as_f32() * line_height - offset - scroll_top;
5913 let end_y = start_y + line_height;
5914
5915 let width = (0.35 * line_height).floor();
5916 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5917 let highlight_size = size(width, end_y - start_y);
5918 Bounds::new(highlight_origin, highlight_size)
5919 } else {
5920 let start_row = display_row_range.start;
5921 let end_row = display_row_range.end;
5922 // If we're in a multibuffer, row range span might include an
5923 // excerpt header, so if we were to draw the marker straight away,
5924 // the hunk might include the rows of that header.
5925 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
5926 // Instead, we simply check whether the range we're dealing with includes
5927 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
5928 let end_row_in_current_excerpt = snapshot
5929 .blocks_in_range(start_row..end_row)
5930 .find_map(|(start_row, block)| {
5931 if matches!(
5932 block,
5933 Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
5934 ) {
5935 Some(start_row)
5936 } else {
5937 None
5938 }
5939 })
5940 .unwrap_or(end_row);
5941
5942 let start_y = start_row.as_f32() * line_height - scroll_top;
5943 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
5944
5945 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5946 let highlight_size = size(gutter_strip_width, end_y - start_y);
5947 Bounds::new(highlight_origin, highlight_size)
5948 }
5949 }
5950 }
5951 }
5952
5953 fn paint_gutter_indicators(
5954 &self,
5955 layout: &mut EditorLayout,
5956 window: &mut Window,
5957 cx: &mut App,
5958 ) {
5959 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5960 window.with_element_namespace("crease_toggles", |window| {
5961 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
5962 crease_toggle.paint(window, cx);
5963 }
5964 });
5965
5966 window.with_element_namespace("expand_toggles", |window| {
5967 for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
5968 expand_toggle.paint(window, cx);
5969 }
5970 });
5971
5972 for breakpoint in layout.breakpoints.iter_mut() {
5973 breakpoint.paint(window, cx);
5974 }
5975
5976 for test_indicator in layout.test_indicators.iter_mut() {
5977 test_indicator.paint(window, cx);
5978 }
5979 });
5980 }
5981
5982 fn paint_gutter_highlights(
5983 &self,
5984 layout: &mut EditorLayout,
5985 window: &mut Window,
5986 cx: &mut App,
5987 ) {
5988 for (_, hunk_hitbox) in &layout.display_hunks {
5989 if let Some(hunk_hitbox) = hunk_hitbox
5990 && !self
5991 .editor
5992 .read(cx)
5993 .buffer()
5994 .read(cx)
5995 .all_diff_hunks_expanded()
5996 {
5997 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
5998 }
5999 }
6000
6001 let show_git_gutter = layout
6002 .position_map
6003 .snapshot
6004 .show_git_diff_gutter
6005 .unwrap_or_else(|| {
6006 matches!(
6007 ProjectSettings::get_global(cx).git.git_gutter,
6008 Some(GitGutterSetting::TrackedFiles)
6009 )
6010 });
6011 if show_git_gutter {
6012 Self::paint_gutter_diff_hunks(layout, window, cx)
6013 }
6014
6015 let highlight_width = 0.275 * layout.position_map.line_height;
6016 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
6017 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6018 for (range, color) in &layout.highlighted_gutter_ranges {
6019 let start_row = if range.start.row() < layout.visible_display_row_range.start {
6020 layout.visible_display_row_range.start - DisplayRow(1)
6021 } else {
6022 range.start.row()
6023 };
6024 let end_row = if range.end.row() > layout.visible_display_row_range.end {
6025 layout.visible_display_row_range.end + DisplayRow(1)
6026 } else {
6027 range.end.row()
6028 };
6029
6030 let start_y = layout.gutter_hitbox.top()
6031 + start_row.0 as f32 * layout.position_map.line_height
6032 - layout.position_map.scroll_pixel_position.y;
6033 let end_y = layout.gutter_hitbox.top()
6034 + (end_row.0 + 1) as f32 * layout.position_map.line_height
6035 - layout.position_map.scroll_pixel_position.y;
6036 let bounds = Bounds::from_corners(
6037 point(layout.gutter_hitbox.left(), start_y),
6038 point(layout.gutter_hitbox.left() + highlight_width, end_y),
6039 );
6040 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
6041 }
6042 });
6043 }
6044
6045 fn paint_blamed_display_rows(
6046 &self,
6047 layout: &mut EditorLayout,
6048 window: &mut Window,
6049 cx: &mut App,
6050 ) {
6051 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
6052 return;
6053 };
6054
6055 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6056 for mut blame_element in blamed_display_rows.into_iter() {
6057 blame_element.paint(window, cx);
6058 }
6059 })
6060 }
6061
6062 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6063 window.with_content_mask(
6064 Some(ContentMask {
6065 bounds: layout.position_map.text_hitbox.bounds,
6066 }),
6067 |window| {
6068 let editor = self.editor.read(cx);
6069 if editor.mouse_cursor_hidden {
6070 window.set_window_cursor_style(CursorStyle::None);
6071 } else if let SelectionDragState::ReadyToDrag {
6072 mouse_down_time, ..
6073 } = &editor.selection_drag_state
6074 {
6075 let drag_and_drop_delay = Duration::from_millis(
6076 EditorSettings::get_global(cx).drag_and_drop_selection.delay,
6077 );
6078 if mouse_down_time.elapsed() >= drag_and_drop_delay {
6079 window.set_cursor_style(
6080 CursorStyle::DragCopy,
6081 &layout.position_map.text_hitbox,
6082 );
6083 }
6084 } else if matches!(
6085 editor.selection_drag_state,
6086 SelectionDragState::Dragging { .. }
6087 ) {
6088 window
6089 .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
6090 } else if editor
6091 .hovered_link_state
6092 .as_ref()
6093 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
6094 {
6095 window.set_cursor_style(
6096 CursorStyle::PointingHand,
6097 &layout.position_map.text_hitbox,
6098 );
6099 } else {
6100 window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
6101 };
6102
6103 self.paint_lines_background(layout, window, cx);
6104 let invisible_display_ranges = self.paint_highlights(layout, window, cx);
6105 self.paint_document_colors(layout, window);
6106 self.paint_lines(&invisible_display_ranges, layout, window, cx);
6107 self.paint_redactions(layout, window);
6108 self.paint_cursors(layout, window, cx);
6109 self.paint_inline_diagnostics(layout, window, cx);
6110 self.paint_inline_blame(layout, window, cx);
6111 self.paint_inline_code_actions(layout, window, cx);
6112 self.paint_diff_hunk_controls(layout, window, cx);
6113 window.with_element_namespace("crease_trailers", |window| {
6114 for trailer in layout.crease_trailers.iter_mut().flatten() {
6115 trailer.element.paint(window, cx);
6116 }
6117 });
6118 },
6119 )
6120 }
6121
6122 fn paint_highlights(
6123 &mut self,
6124 layout: &mut EditorLayout,
6125 window: &mut Window,
6126 cx: &mut App,
6127 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
6128 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6129 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
6130 let line_end_overshoot = 0.15 * layout.position_map.line_height;
6131 for (range, color) in &layout.highlighted_ranges {
6132 self.paint_highlighted_range(
6133 range.clone(),
6134 true,
6135 *color,
6136 Pixels::ZERO,
6137 line_end_overshoot,
6138 layout,
6139 window,
6140 );
6141 }
6142
6143 let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
6144 0.15 * layout.position_map.line_height
6145 } else {
6146 Pixels::ZERO
6147 };
6148
6149 for (player_color, selections) in &layout.selections {
6150 for selection in selections.iter() {
6151 self.paint_highlighted_range(
6152 selection.range.clone(),
6153 true,
6154 player_color.selection,
6155 corner_radius,
6156 corner_radius * 2.,
6157 layout,
6158 window,
6159 );
6160
6161 if selection.is_local && !selection.range.is_empty() {
6162 invisible_display_ranges.push(selection.range.clone());
6163 }
6164 }
6165 }
6166 invisible_display_ranges
6167 })
6168 }
6169
6170 fn paint_lines(
6171 &mut self,
6172 invisible_display_ranges: &[Range<DisplayPoint>],
6173 layout: &mut EditorLayout,
6174 window: &mut Window,
6175 cx: &mut App,
6176 ) {
6177 let whitespace_setting = self
6178 .editor
6179 .read(cx)
6180 .buffer
6181 .read(cx)
6182 .language_settings(cx)
6183 .show_whitespaces;
6184
6185 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6186 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6187 line_with_invisibles.draw(
6188 layout,
6189 row,
6190 layout.content_origin,
6191 whitespace_setting,
6192 invisible_display_ranges,
6193 window,
6194 cx,
6195 )
6196 }
6197
6198 for line_element in &mut layout.line_elements {
6199 line_element.paint(window, cx);
6200 }
6201 }
6202
6203 fn paint_lines_background(
6204 &mut self,
6205 layout: &mut EditorLayout,
6206 window: &mut Window,
6207 cx: &mut App,
6208 ) {
6209 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6210 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6211 line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
6212 }
6213 }
6214
6215 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
6216 if layout.redacted_ranges.is_empty() {
6217 return;
6218 }
6219
6220 let line_end_overshoot = layout.line_end_overshoot();
6221
6222 // A softer than perfect black
6223 let redaction_color = gpui::rgb(0x0e1111);
6224
6225 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6226 for range in layout.redacted_ranges.iter() {
6227 self.paint_highlighted_range(
6228 range.clone(),
6229 true,
6230 redaction_color.into(),
6231 Pixels::ZERO,
6232 line_end_overshoot,
6233 layout,
6234 window,
6235 );
6236 }
6237 });
6238 }
6239
6240 fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
6241 let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
6242 return;
6243 };
6244 if image_colors.is_empty()
6245 || colors_render_mode == &DocumentColorsRenderMode::None
6246 || colors_render_mode == &DocumentColorsRenderMode::Inlay
6247 {
6248 return;
6249 }
6250
6251 let line_end_overshoot = layout.line_end_overshoot();
6252
6253 for (range, color) in image_colors {
6254 match colors_render_mode {
6255 DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
6256 DocumentColorsRenderMode::Background => {
6257 self.paint_highlighted_range(
6258 range.clone(),
6259 true,
6260 *color,
6261 Pixels::ZERO,
6262 line_end_overshoot,
6263 layout,
6264 window,
6265 );
6266 }
6267 DocumentColorsRenderMode::Border => {
6268 self.paint_highlighted_range(
6269 range.clone(),
6270 false,
6271 *color,
6272 Pixels::ZERO,
6273 line_end_overshoot,
6274 layout,
6275 window,
6276 );
6277 }
6278 }
6279 }
6280 }
6281
6282 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6283 for cursor in &mut layout.visible_cursors {
6284 cursor.paint(layout.content_origin, window, cx);
6285 }
6286 }
6287
6288 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6289 let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
6290 return;
6291 };
6292 let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
6293
6294 for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
6295 let hitbox = &scrollbar_layout.hitbox;
6296 if scrollbars_layout.visible {
6297 let scrollbar_edges = match axis {
6298 ScrollbarAxis::Horizontal => Edges {
6299 top: Pixels::ZERO,
6300 right: Pixels::ZERO,
6301 bottom: Pixels::ZERO,
6302 left: Pixels::ZERO,
6303 },
6304 ScrollbarAxis::Vertical => Edges {
6305 top: Pixels::ZERO,
6306 right: Pixels::ZERO,
6307 bottom: Pixels::ZERO,
6308 left: ScrollbarLayout::BORDER_WIDTH,
6309 },
6310 };
6311
6312 window.paint_layer(hitbox.bounds, |window| {
6313 window.paint_quad(quad(
6314 hitbox.bounds,
6315 Corners::default(),
6316 cx.theme().colors().scrollbar_track_background,
6317 scrollbar_edges,
6318 cx.theme().colors().scrollbar_track_border,
6319 BorderStyle::Solid,
6320 ));
6321
6322 if axis == ScrollbarAxis::Vertical {
6323 let fast_markers =
6324 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
6325 // Refresh slow scrollbar markers in the background. Below, we
6326 // paint whatever markers have already been computed.
6327 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
6328
6329 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
6330 for marker in markers.iter().chain(&fast_markers) {
6331 let mut marker = marker.clone();
6332 marker.bounds.origin += hitbox.origin;
6333 window.paint_quad(marker);
6334 }
6335 }
6336
6337 if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
6338 let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
6339 ScrollbarThumbState::Dragging => {
6340 cx.theme().colors().scrollbar_thumb_active_background
6341 }
6342 ScrollbarThumbState::Hovered => {
6343 cx.theme().colors().scrollbar_thumb_hover_background
6344 }
6345 ScrollbarThumbState::Idle => {
6346 cx.theme().colors().scrollbar_thumb_background
6347 }
6348 };
6349 window.paint_quad(quad(
6350 thumb_bounds,
6351 Corners::default(),
6352 scrollbar_thumb_color,
6353 scrollbar_edges,
6354 cx.theme().colors().scrollbar_thumb_border,
6355 BorderStyle::Solid,
6356 ));
6357
6358 if any_scrollbar_dragged {
6359 window.set_window_cursor_style(CursorStyle::Arrow);
6360 } else {
6361 window.set_cursor_style(CursorStyle::Arrow, hitbox);
6362 }
6363 }
6364 })
6365 }
6366 }
6367
6368 window.on_mouse_event({
6369 let editor = self.editor.clone();
6370 let scrollbars_layout = scrollbars_layout.clone();
6371
6372 let mut mouse_position = window.mouse_position();
6373 move |event: &MouseMoveEvent, phase, window, cx| {
6374 if phase == DispatchPhase::Capture {
6375 return;
6376 }
6377
6378 editor.update(cx, |editor, cx| {
6379 if let Some((scrollbar_layout, axis)) = event
6380 .pressed_button
6381 .filter(|button| *button == MouseButton::Left)
6382 .and(editor.scroll_manager.dragging_scrollbar_axis())
6383 .and_then(|axis| {
6384 scrollbars_layout
6385 .iter_scrollbars()
6386 .find(|(_, a)| *a == axis)
6387 })
6388 {
6389 let ScrollbarLayout {
6390 hitbox,
6391 text_unit_size,
6392 ..
6393 } = scrollbar_layout;
6394
6395 let old_position = mouse_position.along(axis);
6396 let new_position = event.position.along(axis);
6397 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
6398 .contains(&old_position)
6399 {
6400 let position = editor.scroll_position(cx).apply_along(axis, |p| {
6401 (p + (new_position - old_position) / *text_unit_size).max(0.)
6402 });
6403 editor.set_scroll_position(position, window, cx);
6404 }
6405
6406 editor.scroll_manager.show_scrollbars(window, cx);
6407 cx.stop_propagation();
6408 } else if let Some((layout, axis)) = scrollbars_layout
6409 .get_hovered_axis(window)
6410 .filter(|_| !event.dragging())
6411 {
6412 if layout.thumb_hovered(&event.position) {
6413 editor
6414 .scroll_manager
6415 .set_hovered_scroll_thumb_axis(axis, cx);
6416 } else {
6417 editor.scroll_manager.reset_scrollbar_state(cx);
6418 }
6419
6420 editor.scroll_manager.show_scrollbars(window, cx);
6421 } else {
6422 editor.scroll_manager.reset_scrollbar_state(cx);
6423 }
6424
6425 mouse_position = event.position;
6426 })
6427 }
6428 });
6429
6430 if any_scrollbar_dragged {
6431 window.on_mouse_event({
6432 let editor = self.editor.clone();
6433 move |_: &MouseUpEvent, phase, window, cx| {
6434 if phase == DispatchPhase::Capture {
6435 return;
6436 }
6437
6438 editor.update(cx, |editor, cx| {
6439 if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
6440 editor
6441 .scroll_manager
6442 .set_hovered_scroll_thumb_axis(axis, cx);
6443 } else {
6444 editor.scroll_manager.reset_scrollbar_state(cx);
6445 }
6446 cx.stop_propagation();
6447 });
6448 }
6449 });
6450 } else {
6451 window.on_mouse_event({
6452 let editor = self.editor.clone();
6453
6454 move |event: &MouseDownEvent, phase, window, cx| {
6455 if phase == DispatchPhase::Capture {
6456 return;
6457 }
6458 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
6459 else {
6460 return;
6461 };
6462
6463 let ScrollbarLayout {
6464 hitbox,
6465 visible_range,
6466 text_unit_size,
6467 thumb_bounds,
6468 ..
6469 } = scrollbar_layout;
6470
6471 let Some(thumb_bounds) = thumb_bounds else {
6472 return;
6473 };
6474
6475 editor.update(cx, |editor, cx| {
6476 editor
6477 .scroll_manager
6478 .set_dragged_scroll_thumb_axis(axis, cx);
6479
6480 let event_position = event.position.along(axis);
6481
6482 if event_position < thumb_bounds.origin.along(axis)
6483 || thumb_bounds.bottom_right().along(axis) < event_position
6484 {
6485 let center_position = ((event_position - hitbox.origin.along(axis))
6486 / *text_unit_size)
6487 .round() as u32;
6488 let start_position = center_position.saturating_sub(
6489 (visible_range.end - visible_range.start) as u32 / 2,
6490 );
6491
6492 let position = editor
6493 .scroll_position(cx)
6494 .apply_along(axis, |_| start_position as f32);
6495
6496 editor.set_scroll_position(position, window, cx);
6497 } else {
6498 editor.scroll_manager.show_scrollbars(window, cx);
6499 }
6500
6501 cx.stop_propagation();
6502 });
6503 }
6504 });
6505 }
6506 }
6507
6508 fn collect_fast_scrollbar_markers(
6509 &self,
6510 layout: &EditorLayout,
6511 scrollbar_layout: &ScrollbarLayout,
6512 cx: &mut App,
6513 ) -> Vec<PaintQuad> {
6514 const LIMIT: usize = 100;
6515 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
6516 return vec![];
6517 }
6518 let cursor_ranges = layout
6519 .cursors
6520 .iter()
6521 .map(|(point, color)| ColoredRange {
6522 start: point.row(),
6523 end: point.row(),
6524 color: *color,
6525 })
6526 .collect_vec();
6527 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
6528 }
6529
6530 fn refresh_slow_scrollbar_markers(
6531 &self,
6532 layout: &EditorLayout,
6533 scrollbar_layout: &ScrollbarLayout,
6534 window: &mut Window,
6535 cx: &mut App,
6536 ) {
6537 self.editor.update(cx, |editor, cx| {
6538 if !editor.is_singleton(cx)
6539 || !editor
6540 .scrollbar_marker_state
6541 .should_refresh(scrollbar_layout.hitbox.size)
6542 {
6543 return;
6544 }
6545
6546 let scrollbar_layout = scrollbar_layout.clone();
6547 let background_highlights = editor.background_highlights.clone();
6548 let snapshot = layout.position_map.snapshot.clone();
6549 let theme = cx.theme().clone();
6550 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
6551
6552 editor.scrollbar_marker_state.dirty = false;
6553 editor.scrollbar_marker_state.pending_refresh =
6554 Some(cx.spawn_in(window, async move |editor, cx| {
6555 let scrollbar_size = scrollbar_layout.hitbox.size;
6556 let scrollbar_markers = cx
6557 .background_spawn(async move {
6558 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
6559 let mut marker_quads = Vec::new();
6560 if scrollbar_settings.git_diff {
6561 let marker_row_ranges =
6562 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
6563 let start_display_row =
6564 MultiBufferPoint::new(hunk.row_range.start.0, 0)
6565 .to_display_point(&snapshot.display_snapshot)
6566 .row();
6567 let mut end_display_row =
6568 MultiBufferPoint::new(hunk.row_range.end.0, 0)
6569 .to_display_point(&snapshot.display_snapshot)
6570 .row();
6571 if end_display_row != start_display_row {
6572 end_display_row.0 -= 1;
6573 }
6574 let color = match &hunk.status().kind {
6575 DiffHunkStatusKind::Added => {
6576 theme.colors().version_control_added
6577 }
6578 DiffHunkStatusKind::Modified => {
6579 theme.colors().version_control_modified
6580 }
6581 DiffHunkStatusKind::Deleted => {
6582 theme.colors().version_control_deleted
6583 }
6584 };
6585 ColoredRange {
6586 start: start_display_row,
6587 end: end_display_row,
6588 color,
6589 }
6590 });
6591
6592 marker_quads.extend(
6593 scrollbar_layout
6594 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
6595 );
6596 }
6597
6598 for (background_highlight_id, (_, background_ranges)) in
6599 background_highlights.iter()
6600 {
6601 let is_search_highlights = *background_highlight_id
6602 == HighlightKey::Type(TypeId::of::<BufferSearchHighlights>());
6603 let is_text_highlights = *background_highlight_id
6604 == HighlightKey::Type(TypeId::of::<SelectedTextHighlight>());
6605 let is_symbol_occurrences = *background_highlight_id
6606 == HighlightKey::Type(TypeId::of::<DocumentHighlightRead>())
6607 || *background_highlight_id
6608 == HighlightKey::Type(
6609 TypeId::of::<DocumentHighlightWrite>(),
6610 );
6611 if (is_search_highlights && scrollbar_settings.search_results)
6612 || (is_text_highlights && scrollbar_settings.selected_text)
6613 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
6614 {
6615 let mut color = theme.status().info;
6616 if is_symbol_occurrences {
6617 color.fade_out(0.5);
6618 }
6619 let marker_row_ranges = background_ranges.iter().map(|range| {
6620 let display_start = range
6621 .start
6622 .to_display_point(&snapshot.display_snapshot);
6623 let display_end =
6624 range.end.to_display_point(&snapshot.display_snapshot);
6625 ColoredRange {
6626 start: display_start.row(),
6627 end: display_end.row(),
6628 color,
6629 }
6630 });
6631 marker_quads.extend(
6632 scrollbar_layout
6633 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
6634 );
6635 }
6636 }
6637
6638 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
6639 let diagnostics = snapshot
6640 .buffer_snapshot
6641 .diagnostics_in_range::<Point>(Point::zero()..max_point)
6642 // Don't show diagnostics the user doesn't care about
6643 .filter(|diagnostic| {
6644 match (
6645 scrollbar_settings.diagnostics,
6646 diagnostic.diagnostic.severity,
6647 ) {
6648 (ScrollbarDiagnostics::All, _) => true,
6649 (
6650 ScrollbarDiagnostics::Error,
6651 lsp::DiagnosticSeverity::ERROR,
6652 ) => true,
6653 (
6654 ScrollbarDiagnostics::Warning,
6655 lsp::DiagnosticSeverity::ERROR
6656 | lsp::DiagnosticSeverity::WARNING,
6657 ) => true,
6658 (
6659 ScrollbarDiagnostics::Information,
6660 lsp::DiagnosticSeverity::ERROR
6661 | lsp::DiagnosticSeverity::WARNING
6662 | lsp::DiagnosticSeverity::INFORMATION,
6663 ) => true,
6664 (_, _) => false,
6665 }
6666 })
6667 // We want to sort by severity, in order to paint the most severe diagnostics last.
6668 .sorted_by_key(|diagnostic| {
6669 std::cmp::Reverse(diagnostic.diagnostic.severity)
6670 });
6671
6672 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
6673 let start_display = diagnostic
6674 .range
6675 .start
6676 .to_display_point(&snapshot.display_snapshot);
6677 let end_display = diagnostic
6678 .range
6679 .end
6680 .to_display_point(&snapshot.display_snapshot);
6681 let color = match diagnostic.diagnostic.severity {
6682 lsp::DiagnosticSeverity::ERROR => theme.status().error,
6683 lsp::DiagnosticSeverity::WARNING => theme.status().warning,
6684 lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
6685 _ => theme.status().hint,
6686 };
6687 ColoredRange {
6688 start: start_display.row(),
6689 end: end_display.row(),
6690 color,
6691 }
6692 });
6693 marker_quads.extend(
6694 scrollbar_layout
6695 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
6696 );
6697 }
6698
6699 Arc::from(marker_quads)
6700 })
6701 .await;
6702
6703 editor.update(cx, |editor, cx| {
6704 editor.scrollbar_marker_state.markers = scrollbar_markers;
6705 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
6706 editor.scrollbar_marker_state.pending_refresh = None;
6707 cx.notify();
6708 })?;
6709
6710 Ok(())
6711 }));
6712 });
6713 }
6714
6715 fn paint_highlighted_range(
6716 &self,
6717 range: Range<DisplayPoint>,
6718 fill: bool,
6719 color: Hsla,
6720 corner_radius: Pixels,
6721 line_end_overshoot: Pixels,
6722 layout: &EditorLayout,
6723 window: &mut Window,
6724 ) {
6725 let start_row = layout.visible_display_row_range.start;
6726 let end_row = layout.visible_display_row_range.end;
6727 if range.start != range.end {
6728 let row_range = if range.end.column() == 0 {
6729 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
6730 } else {
6731 cmp::max(range.start.row(), start_row)
6732 ..cmp::min(range.end.row().next_row(), end_row)
6733 };
6734
6735 let highlighted_range = HighlightedRange {
6736 color,
6737 line_height: layout.position_map.line_height,
6738 corner_radius,
6739 start_y: layout.content_origin.y
6740 + row_range.start.as_f32() * layout.position_map.line_height
6741 - layout.position_map.scroll_pixel_position.y,
6742 lines: row_range
6743 .iter_rows()
6744 .map(|row| {
6745 let line_layout =
6746 &layout.position_map.line_layouts[row.minus(start_row) as usize];
6747 HighlightedRangeLine {
6748 start_x: if row == range.start.row() {
6749 layout.content_origin.x
6750 + line_layout.x_for_index(range.start.column() as usize)
6751 - layout.position_map.scroll_pixel_position.x
6752 } else {
6753 layout.content_origin.x
6754 - layout.position_map.scroll_pixel_position.x
6755 },
6756 end_x: if row == range.end.row() {
6757 layout.content_origin.x
6758 + line_layout.x_for_index(range.end.column() as usize)
6759 - layout.position_map.scroll_pixel_position.x
6760 } else {
6761 layout.content_origin.x + line_layout.width + line_end_overshoot
6762 - layout.position_map.scroll_pixel_position.x
6763 },
6764 }
6765 })
6766 .collect(),
6767 };
6768
6769 highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
6770 }
6771 }
6772
6773 fn paint_inline_diagnostics(
6774 &mut self,
6775 layout: &mut EditorLayout,
6776 window: &mut Window,
6777 cx: &mut App,
6778 ) {
6779 for mut inline_diagnostic in layout.inline_diagnostics.drain() {
6780 inline_diagnostic.1.paint(window, cx);
6781 }
6782 }
6783
6784 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6785 if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
6786 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6787 blame_layout.element.paint(window, cx);
6788 })
6789 }
6790 }
6791
6792 fn paint_inline_code_actions(
6793 &mut self,
6794 layout: &mut EditorLayout,
6795 window: &mut Window,
6796 cx: &mut App,
6797 ) {
6798 if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
6799 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6800 inline_code_actions.paint(window, cx);
6801 })
6802 }
6803 }
6804
6805 fn paint_diff_hunk_controls(
6806 &mut self,
6807 layout: &mut EditorLayout,
6808 window: &mut Window,
6809 cx: &mut App,
6810 ) {
6811 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
6812 diff_hunk_control.paint(window, cx);
6813 }
6814 }
6815
6816 fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6817 if let Some(mut layout) = layout.minimap.take() {
6818 let minimap_hitbox = layout.thumb_layout.hitbox.clone();
6819 let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
6820
6821 window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
6822 window.with_element_namespace("minimap", |window| {
6823 layout.minimap.paint(window, cx);
6824 if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
6825 let minimap_thumb_color = match layout.thumb_layout.thumb_state {
6826 ScrollbarThumbState::Idle => {
6827 cx.theme().colors().minimap_thumb_background
6828 }
6829 ScrollbarThumbState::Hovered => {
6830 cx.theme().colors().minimap_thumb_hover_background
6831 }
6832 ScrollbarThumbState::Dragging => {
6833 cx.theme().colors().minimap_thumb_active_background
6834 }
6835 };
6836 let minimap_thumb_border = match layout.thumb_border_style {
6837 MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
6838 MinimapThumbBorder::LeftOnly => Edges {
6839 left: ScrollbarLayout::BORDER_WIDTH,
6840 ..Default::default()
6841 },
6842 MinimapThumbBorder::LeftOpen => Edges {
6843 right: ScrollbarLayout::BORDER_WIDTH,
6844 top: ScrollbarLayout::BORDER_WIDTH,
6845 bottom: ScrollbarLayout::BORDER_WIDTH,
6846 ..Default::default()
6847 },
6848 MinimapThumbBorder::RightOpen => Edges {
6849 left: ScrollbarLayout::BORDER_WIDTH,
6850 top: ScrollbarLayout::BORDER_WIDTH,
6851 bottom: ScrollbarLayout::BORDER_WIDTH,
6852 ..Default::default()
6853 },
6854 MinimapThumbBorder::None => Default::default(),
6855 };
6856
6857 window.paint_layer(minimap_hitbox.bounds, |window| {
6858 window.paint_quad(quad(
6859 thumb_bounds,
6860 Corners::default(),
6861 minimap_thumb_color,
6862 minimap_thumb_border,
6863 cx.theme().colors().minimap_thumb_border,
6864 BorderStyle::Solid,
6865 ));
6866 });
6867 }
6868 });
6869 });
6870
6871 if dragging_minimap {
6872 window.set_window_cursor_style(CursorStyle::Arrow);
6873 } else {
6874 window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
6875 }
6876
6877 let minimap_axis = ScrollbarAxis::Vertical;
6878 let pixels_per_line = (minimap_hitbox.size.height / layout.max_scroll_top)
6879 .min(layout.minimap_line_height);
6880
6881 let mut mouse_position = window.mouse_position();
6882
6883 window.on_mouse_event({
6884 let editor = self.editor.clone();
6885
6886 let minimap_hitbox = minimap_hitbox.clone();
6887
6888 move |event: &MouseMoveEvent, phase, window, cx| {
6889 if phase == DispatchPhase::Capture {
6890 return;
6891 }
6892
6893 editor.update(cx, |editor, cx| {
6894 if event.pressed_button == Some(MouseButton::Left)
6895 && editor.scroll_manager.is_dragging_minimap()
6896 {
6897 let old_position = mouse_position.along(minimap_axis);
6898 let new_position = event.position.along(minimap_axis);
6899 if (minimap_hitbox.origin.along(minimap_axis)
6900 ..minimap_hitbox.bottom_right().along(minimap_axis))
6901 .contains(&old_position)
6902 {
6903 let position =
6904 editor.scroll_position(cx).apply_along(minimap_axis, |p| {
6905 (p + (new_position - old_position) / pixels_per_line)
6906 .max(0.)
6907 });
6908 editor.set_scroll_position(position, window, cx);
6909 }
6910 cx.stop_propagation();
6911 } else if minimap_hitbox.is_hovered(window) {
6912 editor.scroll_manager.set_is_hovering_minimap_thumb(
6913 !event.dragging()
6914 && layout
6915 .thumb_layout
6916 .thumb_bounds
6917 .is_some_and(|bounds| bounds.contains(&event.position)),
6918 cx,
6919 );
6920
6921 // Stop hover events from propagating to the
6922 // underlying editor if the minimap hitbox is hovered
6923 if !event.dragging() {
6924 cx.stop_propagation();
6925 }
6926 } else {
6927 editor.scroll_manager.hide_minimap_thumb(cx);
6928 }
6929 mouse_position = event.position;
6930 });
6931 }
6932 });
6933
6934 if dragging_minimap {
6935 window.on_mouse_event({
6936 let editor = self.editor.clone();
6937 move |event: &MouseUpEvent, phase, window, cx| {
6938 if phase == DispatchPhase::Capture {
6939 return;
6940 }
6941
6942 editor.update(cx, |editor, cx| {
6943 if minimap_hitbox.is_hovered(window) {
6944 editor.scroll_manager.set_is_hovering_minimap_thumb(
6945 layout
6946 .thumb_layout
6947 .thumb_bounds
6948 .is_some_and(|bounds| bounds.contains(&event.position)),
6949 cx,
6950 );
6951 } else {
6952 editor.scroll_manager.hide_minimap_thumb(cx);
6953 }
6954 cx.stop_propagation();
6955 });
6956 }
6957 });
6958 } else {
6959 window.on_mouse_event({
6960 let editor = self.editor.clone();
6961
6962 move |event: &MouseDownEvent, phase, window, cx| {
6963 if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
6964 return;
6965 }
6966
6967 let event_position = event.position;
6968
6969 let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
6970 return;
6971 };
6972
6973 editor.update(cx, |editor, cx| {
6974 if !thumb_bounds.contains(&event_position) {
6975 let click_position =
6976 event_position.relative_to(&minimap_hitbox.origin).y;
6977
6978 let top_position = (click_position
6979 - thumb_bounds.size.along(minimap_axis) / 2.0)
6980 .max(Pixels::ZERO);
6981
6982 let scroll_offset = (layout.minimap_scroll_top
6983 + top_position / layout.minimap_line_height)
6984 .min(layout.max_scroll_top);
6985
6986 let scroll_position = editor
6987 .scroll_position(cx)
6988 .apply_along(minimap_axis, |_| scroll_offset);
6989 editor.set_scroll_position(scroll_position, window, cx);
6990 }
6991
6992 editor.scroll_manager.set_is_dragging_minimap(cx);
6993 cx.stop_propagation();
6994 });
6995 }
6996 });
6997 }
6998 }
6999 }
7000
7001 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
7002 for mut block in layout.blocks.drain(..) {
7003 if block.overlaps_gutter {
7004 block.element.paint(window, cx);
7005 } else {
7006 let mut bounds = layout.hitbox.bounds;
7007 bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
7008 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7009 block.element.paint(window, cx);
7010 })
7011 }
7012 }
7013 }
7014
7015 fn paint_edit_prediction_popover(
7016 &mut self,
7017 layout: &mut EditorLayout,
7018 window: &mut Window,
7019 cx: &mut App,
7020 ) {
7021 if let Some(edit_prediction_popover) = layout.edit_prediction_popover.as_mut() {
7022 edit_prediction_popover.paint(window, cx);
7023 }
7024 }
7025
7026 fn paint_mouse_context_menu(
7027 &mut self,
7028 layout: &mut EditorLayout,
7029 window: &mut Window,
7030 cx: &mut App,
7031 ) {
7032 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
7033 mouse_context_menu.paint(window, cx);
7034 }
7035 }
7036
7037 fn paint_scroll_wheel_listener(
7038 &mut self,
7039 layout: &EditorLayout,
7040 window: &mut Window,
7041 cx: &mut App,
7042 ) {
7043 window.on_mouse_event({
7044 let position_map = layout.position_map.clone();
7045 let editor = self.editor.clone();
7046 let hitbox = layout.hitbox.clone();
7047 let mut delta = ScrollDelta::default();
7048
7049 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
7050 // accidentally turn off their scrolling.
7051 let base_scroll_sensitivity =
7052 EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
7053
7054 // Use a minimum fast_scroll_sensitivity for same reason above
7055 let fast_scroll_sensitivity = EditorSettings::get_global(cx)
7056 .fast_scroll_sensitivity
7057 .max(0.01);
7058
7059 move |event: &ScrollWheelEvent, phase, window, cx| {
7060 let scroll_sensitivity = {
7061 if event.modifiers.alt {
7062 fast_scroll_sensitivity
7063 } else {
7064 base_scroll_sensitivity
7065 }
7066 };
7067
7068 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
7069 delta = delta.coalesce(event.delta);
7070 editor.update(cx, |editor, cx| {
7071 let position_map: &PositionMap = &position_map;
7072
7073 let line_height = position_map.line_height;
7074 let max_glyph_advance = position_map.em_advance;
7075 let (delta, axis) = match delta {
7076 gpui::ScrollDelta::Pixels(mut pixels) => {
7077 //Trackpad
7078 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
7079 (pixels, axis)
7080 }
7081
7082 gpui::ScrollDelta::Lines(lines) => {
7083 //Not trackpad
7084 let pixels =
7085 point(lines.x * max_glyph_advance, lines.y * line_height);
7086 (pixels, None)
7087 }
7088 };
7089
7090 let current_scroll_position = position_map.snapshot.scroll_position();
7091 let x = (current_scroll_position.x * max_glyph_advance
7092 - (delta.x * scroll_sensitivity))
7093 / max_glyph_advance;
7094 let y = (current_scroll_position.y * line_height
7095 - (delta.y * scroll_sensitivity))
7096 / line_height;
7097 let mut scroll_position =
7098 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
7099 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
7100 if forbid_vertical_scroll {
7101 scroll_position.y = current_scroll_position.y;
7102 }
7103
7104 if scroll_position != current_scroll_position {
7105 editor.scroll(scroll_position, axis, window, cx);
7106 cx.stop_propagation();
7107 } else if y < 0. {
7108 // Due to clamping, we may fail to detect cases of overscroll to the top;
7109 // We want the scroll manager to get an update in such cases and detect the change of direction
7110 // on the next frame.
7111 cx.notify();
7112 }
7113 });
7114 }
7115 }
7116 });
7117 }
7118
7119 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
7120 if layout.mode.is_minimap() {
7121 return;
7122 }
7123
7124 self.paint_scroll_wheel_listener(layout, window, cx);
7125
7126 window.on_mouse_event({
7127 let position_map = layout.position_map.clone();
7128 let editor = self.editor.clone();
7129 let diff_hunk_range =
7130 layout
7131 .display_hunks
7132 .iter()
7133 .find_map(|(hunk, hunk_hitbox)| match hunk {
7134 DisplayDiffHunk::Folded { .. } => None,
7135 DisplayDiffHunk::Unfolded {
7136 multi_buffer_range, ..
7137 } => {
7138 if hunk_hitbox
7139 .as_ref()
7140 .map(|hitbox| hitbox.is_hovered(window))
7141 .unwrap_or(false)
7142 {
7143 Some(multi_buffer_range.clone())
7144 } else {
7145 None
7146 }
7147 }
7148 });
7149 let line_numbers = layout.line_numbers.clone();
7150
7151 move |event: &MouseDownEvent, phase, window, cx| {
7152 if phase == DispatchPhase::Bubble {
7153 match event.button {
7154 MouseButton::Left => editor.update(cx, |editor, cx| {
7155 let pending_mouse_down = editor
7156 .pending_mouse_down
7157 .get_or_insert_with(Default::default)
7158 .clone();
7159
7160 *pending_mouse_down.borrow_mut() = Some(event.clone());
7161
7162 Self::mouse_left_down(
7163 editor,
7164 event,
7165 diff_hunk_range.clone(),
7166 &position_map,
7167 line_numbers.as_ref(),
7168 window,
7169 cx,
7170 );
7171 }),
7172 MouseButton::Right => editor.update(cx, |editor, cx| {
7173 Self::mouse_right_down(editor, event, &position_map, window, cx);
7174 }),
7175 MouseButton::Middle => editor.update(cx, |editor, cx| {
7176 Self::mouse_middle_down(editor, event, &position_map, window, cx);
7177 }),
7178 _ => {}
7179 };
7180 }
7181 }
7182 });
7183
7184 window.on_mouse_event({
7185 let editor = self.editor.clone();
7186 let position_map = layout.position_map.clone();
7187
7188 move |event: &MouseUpEvent, phase, window, cx| {
7189 if phase == DispatchPhase::Bubble {
7190 editor.update(cx, |editor, cx| {
7191 Self::mouse_up(editor, event, &position_map, window, cx)
7192 });
7193 }
7194 }
7195 });
7196
7197 window.on_mouse_event({
7198 let editor = self.editor.clone();
7199 let position_map = layout.position_map.clone();
7200 let mut captured_mouse_down = None;
7201
7202 move |event: &MouseUpEvent, phase, window, cx| match phase {
7203 // Clear the pending mouse down during the capture phase,
7204 // so that it happens even if another event handler stops
7205 // propagation.
7206 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
7207 let pending_mouse_down = editor
7208 .pending_mouse_down
7209 .get_or_insert_with(Default::default)
7210 .clone();
7211
7212 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
7213 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
7214 captured_mouse_down = pending_mouse_down.take();
7215 window.refresh();
7216 }
7217 }),
7218 // Fire click handlers during the bubble phase.
7219 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
7220 if let Some(mouse_down) = captured_mouse_down.take() {
7221 let event = ClickEvent::Mouse(MouseClickEvent {
7222 down: mouse_down,
7223 up: event.clone(),
7224 });
7225 Self::click(editor, &event, &position_map, window, cx);
7226 }
7227 }),
7228 }
7229 });
7230
7231 window.on_mouse_event({
7232 let position_map = layout.position_map.clone();
7233 let editor = self.editor.clone();
7234
7235 move |event: &MouseMoveEvent, phase, window, cx| {
7236 if phase == DispatchPhase::Bubble {
7237 editor.update(cx, |editor, cx| {
7238 if editor.hover_state.focused(window, cx) {
7239 return;
7240 }
7241 if event.pressed_button == Some(MouseButton::Left)
7242 || event.pressed_button == Some(MouseButton::Middle)
7243 {
7244 Self::mouse_dragged(editor, event, &position_map, window, cx)
7245 }
7246
7247 Self::mouse_moved(editor, event, &position_map, window, cx)
7248 });
7249 }
7250 }
7251 });
7252 }
7253
7254 fn column_pixels(&self, column: usize, window: &Window) -> Pixels {
7255 let style = &self.style;
7256 let font_size = style.text.font_size.to_pixels(window.rem_size());
7257 let layout = window.text_system().shape_line(
7258 SharedString::from(" ".repeat(column)),
7259 font_size,
7260 &[TextRun {
7261 len: column,
7262 font: style.text.font(),
7263 color: Hsla::default(),
7264 background_color: None,
7265 underline: None,
7266 strikethrough: None,
7267 }],
7268 None,
7269 );
7270
7271 layout.width
7272 }
7273
7274 fn max_line_number_width(&self, snapshot: &EditorSnapshot, window: &mut Window) -> Pixels {
7275 let digit_count = snapshot.widest_line_number().ilog10() + 1;
7276 self.column_pixels(digit_count as usize, window)
7277 }
7278
7279 fn shape_line_number(
7280 &self,
7281 text: SharedString,
7282 color: Hsla,
7283 window: &mut Window,
7284 ) -> ShapedLine {
7285 let run = TextRun {
7286 len: text.len(),
7287 font: self.style.text.font(),
7288 color,
7289 background_color: None,
7290 underline: None,
7291 strikethrough: None,
7292 };
7293 window.text_system().shape_line(
7294 text,
7295 self.style.text.font_size.to_pixels(window.rem_size()),
7296 &[run],
7297 None,
7298 )
7299 }
7300
7301 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
7302 let unstaged = status.has_secondary_hunk();
7303 let unstaged_hollow = ProjectSettings::get_global(cx)
7304 .git
7305 .hunk_style
7306 .is_some_and(|style| matches!(style, GitHunkStyleSetting::UnstagedHollow));
7307
7308 unstaged == unstaged_hollow
7309 }
7310
7311 #[cfg(debug_assertions)]
7312 fn layout_debug_ranges(
7313 selections: &mut Vec<(PlayerColor, Vec<SelectionLayout>)>,
7314 anchor_range: Range<Anchor>,
7315 display_snapshot: &DisplaySnapshot,
7316 cx: &App,
7317 ) {
7318 let theme = cx.theme();
7319 text::debug::GlobalDebugRanges::with_locked(|debug_ranges| {
7320 if debug_ranges.ranges.is_empty() {
7321 return;
7322 }
7323 let buffer_snapshot = &display_snapshot.buffer_snapshot;
7324 for (buffer, buffer_range, excerpt_id) in
7325 buffer_snapshot.range_to_buffer_ranges(anchor_range)
7326 {
7327 let buffer_range =
7328 buffer.anchor_after(buffer_range.start)..buffer.anchor_before(buffer_range.end);
7329 selections.extend(debug_ranges.ranges.iter().flat_map(|debug_range| {
7330 let player_color = theme
7331 .players()
7332 .color_for_participant(debug_range.occurrence_index as u32 + 1);
7333 debug_range.ranges.iter().filter_map(move |range| {
7334 if range.start.buffer_id != Some(buffer.remote_id()) {
7335 return None;
7336 }
7337 let clipped_start = range.start.max(&buffer_range.start, buffer);
7338 let clipped_end = range.end.min(&buffer_range.end, buffer);
7339 let range = buffer_snapshot.anchor_in_excerpt(excerpt_id, clipped_start)?
7340 ..buffer_snapshot.anchor_in_excerpt(excerpt_id, clipped_end)?;
7341 let start = range.start.to_display_point(display_snapshot);
7342 let end = range.end.to_display_point(display_snapshot);
7343 let selection_layout = SelectionLayout {
7344 head: start,
7345 range: start..end,
7346 cursor_shape: CursorShape::Bar,
7347 is_newest: false,
7348 is_local: false,
7349 active_rows: start.row()..end.row(),
7350 user_name: Some(SharedString::new(debug_range.value.clone())),
7351 };
7352 Some((player_color, vec![selection_layout]))
7353 })
7354 }));
7355 }
7356 });
7357 }
7358}
7359
7360fn header_jump_data(
7361 snapshot: &EditorSnapshot,
7362 block_row_start: DisplayRow,
7363 height: u32,
7364 for_excerpt: &ExcerptInfo,
7365) -> JumpData {
7366 let range = &for_excerpt.range;
7367 let buffer = &for_excerpt.buffer;
7368 let jump_anchor = range.primary.start;
7369
7370 let excerpt_start = range.context.start;
7371 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
7372 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
7373 0
7374 } else {
7375 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
7376 jump_position.row.saturating_sub(excerpt_start_point.row)
7377 };
7378
7379 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
7380 .saturating_sub(
7381 snapshot
7382 .scroll_anchor
7383 .scroll_position(&snapshot.display_snapshot)
7384 .y as u32,
7385 );
7386
7387 JumpData::MultiBufferPoint {
7388 excerpt_id: for_excerpt.id,
7389 anchor: jump_anchor,
7390 position: jump_position,
7391 line_offset_from_top,
7392 }
7393}
7394
7395pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
7396
7397impl AcceptEditPredictionBinding {
7398 pub fn keystroke(&self) -> Option<&KeybindingKeystroke> {
7399 if let Some(binding) = self.0.as_ref() {
7400 match &binding.keystrokes() {
7401 [keystroke, ..] => Some(keystroke),
7402 _ => None,
7403 }
7404 } else {
7405 None
7406 }
7407 }
7408}
7409
7410fn prepaint_gutter_button(
7411 button: IconButton,
7412 row: DisplayRow,
7413 line_height: Pixels,
7414 gutter_dimensions: &GutterDimensions,
7415 scroll_pixel_position: gpui::Point<Pixels>,
7416 gutter_hitbox: &Hitbox,
7417 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
7418 window: &mut Window,
7419 cx: &mut App,
7420) -> AnyElement {
7421 let mut button = button.into_any_element();
7422
7423 let available_space = size(
7424 AvailableSpace::MinContent,
7425 AvailableSpace::Definite(line_height),
7426 );
7427 let indicator_size = button.layout_as_root(available_space, window, cx);
7428
7429 let blame_width = gutter_dimensions.git_blame_entries_width;
7430 let gutter_width = display_hunks
7431 .binary_search_by(|(hunk, _)| match hunk {
7432 DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
7433 DisplayDiffHunk::Unfolded {
7434 display_row_range, ..
7435 } => {
7436 if display_row_range.end <= row {
7437 Ordering::Less
7438 } else if display_row_range.start > row {
7439 Ordering::Greater
7440 } else {
7441 Ordering::Equal
7442 }
7443 }
7444 })
7445 .ok()
7446 .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
7447 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
7448
7449 let mut x = left_offset;
7450 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
7451 - indicator_size.width
7452 - left_offset;
7453 x += available_width / 2.;
7454
7455 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
7456 y += (line_height - indicator_size.height) / 2.;
7457
7458 button.prepaint_as_root(
7459 gutter_hitbox.origin + point(x, y),
7460 available_space,
7461 window,
7462 cx,
7463 );
7464 button
7465}
7466
7467fn render_inline_blame_entry(
7468 blame_entry: BlameEntry,
7469 style: &EditorStyle,
7470 cx: &mut App,
7471) -> Option<AnyElement> {
7472 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7473 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
7474}
7475
7476fn render_blame_entry_popover(
7477 blame_entry: BlameEntry,
7478 scroll_handle: ScrollHandle,
7479 commit_message: Option<ParsedCommitMessage>,
7480 markdown: Entity<Markdown>,
7481 workspace: WeakEntity<Workspace>,
7482 blame: &Entity<GitBlame>,
7483 buffer: BufferId,
7484 window: &mut Window,
7485 cx: &mut App,
7486) -> Option<AnyElement> {
7487 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7488 let blame = blame.read(cx);
7489 let repository = blame.repository(cx, buffer)?;
7490 renderer.render_blame_entry_popover(
7491 blame_entry,
7492 scroll_handle,
7493 commit_message,
7494 markdown,
7495 repository,
7496 workspace,
7497 window,
7498 cx,
7499 )
7500}
7501
7502fn render_blame_entry(
7503 ix: usize,
7504 blame: &Entity<GitBlame>,
7505 blame_entry: BlameEntry,
7506 style: &EditorStyle,
7507 last_used_color: &mut Option<(PlayerColor, Oid)>,
7508 editor: Entity<Editor>,
7509 workspace: Entity<Workspace>,
7510 buffer: BufferId,
7511 renderer: Arc<dyn BlameRenderer>,
7512 cx: &mut App,
7513) -> Option<AnyElement> {
7514 let mut sha_color = cx
7515 .theme()
7516 .players()
7517 .color_for_participant(blame_entry.sha.into());
7518
7519 // If the last color we used is the same as the one we get for this line, but
7520 // the commit SHAs are different, then we try again to get a different color.
7521 match *last_used_color {
7522 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
7523 let index: u32 = blame_entry.sha.into();
7524 sha_color = cx.theme().players().color_for_participant(index + 1);
7525 }
7526 _ => {}
7527 };
7528 last_used_color.replace((sha_color, blame_entry.sha));
7529
7530 let blame = blame.read(cx);
7531 let details = blame.details_for_entry(buffer, &blame_entry);
7532 let repository = blame.repository(cx, buffer)?;
7533 renderer.render_blame_entry(
7534 &style.text,
7535 blame_entry,
7536 details,
7537 repository,
7538 workspace.downgrade(),
7539 editor,
7540 ix,
7541 sha_color.cursor,
7542 cx,
7543 )
7544}
7545
7546#[derive(Debug)]
7547pub(crate) struct LineWithInvisibles {
7548 fragments: SmallVec<[LineFragment; 1]>,
7549 invisibles: Vec<Invisible>,
7550 len: usize,
7551 pub(crate) width: Pixels,
7552 font_size: Pixels,
7553}
7554
7555enum LineFragment {
7556 Text(ShapedLine),
7557 Element {
7558 id: ChunkRendererId,
7559 element: Option<AnyElement>,
7560 size: Size<Pixels>,
7561 len: usize,
7562 },
7563}
7564
7565impl fmt::Debug for LineFragment {
7566 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7567 match self {
7568 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
7569 LineFragment::Element { size, len, .. } => f
7570 .debug_struct("Element")
7571 .field("size", size)
7572 .field("len", len)
7573 .finish(),
7574 }
7575 }
7576}
7577
7578impl LineWithInvisibles {
7579 fn from_chunks<'a>(
7580 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
7581 editor_style: &EditorStyle,
7582 max_line_len: usize,
7583 max_line_count: usize,
7584 editor_mode: &EditorMode,
7585 text_width: Pixels,
7586 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
7587 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
7588 window: &mut Window,
7589 cx: &mut App,
7590 ) -> Vec<Self> {
7591 let text_style = &editor_style.text;
7592 let mut layouts = Vec::with_capacity(max_line_count);
7593 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
7594 let mut line = String::new();
7595 let mut invisibles = Vec::new();
7596 let mut width = Pixels::ZERO;
7597 let mut len = 0;
7598 let mut styles = Vec::new();
7599 let mut non_whitespace_added = false;
7600 let mut row = 0;
7601 let mut line_exceeded_max_len = false;
7602 let font_size = text_style.font_size.to_pixels(window.rem_size());
7603 let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
7604
7605 let ellipsis = SharedString::from("β―");
7606
7607 for highlighted_chunk in chunks.chain([HighlightedChunk {
7608 text: "\n",
7609 style: None,
7610 is_tab: false,
7611 is_inlay: false,
7612 replacement: None,
7613 }]) {
7614 if let Some(replacement) = highlighted_chunk.replacement {
7615 if !line.is_empty() {
7616 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
7617 let text_runs: &[TextRun] = if segments.is_empty() {
7618 &styles
7619 } else {
7620 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast)
7621 };
7622 let shaped_line = window.text_system().shape_line(
7623 line.clone().into(),
7624 font_size,
7625 text_runs,
7626 None,
7627 );
7628 width += shaped_line.width;
7629 len += shaped_line.len;
7630 fragments.push(LineFragment::Text(shaped_line));
7631 line.clear();
7632 styles.clear();
7633 }
7634
7635 match replacement {
7636 ChunkReplacement::Renderer(renderer) => {
7637 let available_width = if renderer.constrain_width {
7638 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
7639 ellipsis.clone()
7640 } else {
7641 SharedString::from(Arc::from(highlighted_chunk.text))
7642 };
7643 let shaped_line = window.text_system().shape_line(
7644 chunk,
7645 font_size,
7646 &[text_style.to_run(highlighted_chunk.text.len())],
7647 None,
7648 );
7649 AvailableSpace::Definite(shaped_line.width)
7650 } else {
7651 AvailableSpace::MinContent
7652 };
7653
7654 let mut element = (renderer.render)(&mut ChunkRendererContext {
7655 context: cx,
7656 window,
7657 max_width: text_width,
7658 });
7659 let line_height = text_style.line_height_in_pixels(window.rem_size());
7660 let size = element.layout_as_root(
7661 size(available_width, AvailableSpace::Definite(line_height)),
7662 window,
7663 cx,
7664 );
7665
7666 width += size.width;
7667 len += highlighted_chunk.text.len();
7668 fragments.push(LineFragment::Element {
7669 id: renderer.id,
7670 element: Some(element),
7671 size,
7672 len: highlighted_chunk.text.len(),
7673 });
7674 }
7675 ChunkReplacement::Str(x) => {
7676 let text_style = if let Some(style) = highlighted_chunk.style {
7677 Cow::Owned(text_style.clone().highlight(style))
7678 } else {
7679 Cow::Borrowed(text_style)
7680 };
7681
7682 let run = TextRun {
7683 len: x.len(),
7684 font: text_style.font(),
7685 color: text_style.color,
7686 background_color: text_style.background_color,
7687 underline: text_style.underline,
7688 strikethrough: text_style.strikethrough,
7689 };
7690 let line_layout = window
7691 .text_system()
7692 .shape_line(x, font_size, &[run], None)
7693 .with_len(highlighted_chunk.text.len());
7694
7695 width += line_layout.width;
7696 len += highlighted_chunk.text.len();
7697 fragments.push(LineFragment::Text(line_layout))
7698 }
7699 }
7700 } else {
7701 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
7702 if ix > 0 {
7703 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
7704 let text_runs = if segments.is_empty() {
7705 &styles
7706 } else {
7707 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast)
7708 };
7709 let shaped_line = window.text_system().shape_line(
7710 line.clone().into(),
7711 font_size,
7712 text_runs,
7713 None,
7714 );
7715 width += shaped_line.width;
7716 len += shaped_line.len;
7717 fragments.push(LineFragment::Text(shaped_line));
7718 layouts.push(Self {
7719 width: mem::take(&mut width),
7720 len: mem::take(&mut len),
7721 fragments: mem::take(&mut fragments),
7722 invisibles: std::mem::take(&mut invisibles),
7723 font_size,
7724 });
7725
7726 line.clear();
7727 styles.clear();
7728 row += 1;
7729 line_exceeded_max_len = false;
7730 non_whitespace_added = false;
7731 if row == max_line_count {
7732 return layouts;
7733 }
7734 }
7735
7736 if !line_chunk.is_empty() && !line_exceeded_max_len {
7737 let text_style = if let Some(style) = highlighted_chunk.style {
7738 Cow::Owned(text_style.clone().highlight(style))
7739 } else {
7740 Cow::Borrowed(text_style)
7741 };
7742
7743 if line.len() + line_chunk.len() > max_line_len {
7744 let mut chunk_len = max_line_len - line.len();
7745 while !line_chunk.is_char_boundary(chunk_len) {
7746 chunk_len -= 1;
7747 }
7748 line_chunk = &line_chunk[..chunk_len];
7749 line_exceeded_max_len = true;
7750 }
7751
7752 styles.push(TextRun {
7753 len: line_chunk.len(),
7754 font: text_style.font(),
7755 color: text_style.color,
7756 background_color: text_style.background_color,
7757 underline: text_style.underline,
7758 strikethrough: text_style.strikethrough,
7759 });
7760
7761 if editor_mode.is_full() && !highlighted_chunk.is_inlay {
7762 // Line wrap pads its contents with fake whitespaces,
7763 // avoid printing them
7764 let is_soft_wrapped = is_row_soft_wrapped(row);
7765 if highlighted_chunk.is_tab {
7766 if non_whitespace_added || !is_soft_wrapped {
7767 invisibles.push(Invisible::Tab {
7768 line_start_offset: line.len(),
7769 line_end_offset: line.len() + line_chunk.len(),
7770 });
7771 }
7772 } else {
7773 invisibles.extend(line_chunk.char_indices().filter_map(
7774 |(index, c)| {
7775 let is_whitespace = c.is_whitespace();
7776 non_whitespace_added |= !is_whitespace;
7777 if is_whitespace
7778 && (non_whitespace_added || !is_soft_wrapped)
7779 {
7780 Some(Invisible::Whitespace {
7781 line_offset: line.len() + index,
7782 })
7783 } else {
7784 None
7785 }
7786 },
7787 ))
7788 }
7789 }
7790
7791 line.push_str(line_chunk);
7792 }
7793 }
7794 }
7795 }
7796
7797 layouts
7798 }
7799
7800 /// Takes text runs and non-overlapping left-to-right background ranges with color.
7801 /// Returns new text runs with adjusted contrast as per background ranges.
7802 fn split_runs_by_bg_segments(
7803 text_runs: &[TextRun],
7804 bg_segments: &[(Range<DisplayPoint>, Hsla)],
7805 min_contrast: f32,
7806 ) -> Vec<TextRun> {
7807 let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
7808 let mut line_col = 0usize;
7809 let mut segment_ix = 0usize;
7810
7811 for text_run in text_runs.iter() {
7812 let run_start_col = line_col;
7813 let run_end_col = run_start_col + text_run.len;
7814 while segment_ix < bg_segments.len()
7815 && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
7816 {
7817 segment_ix += 1;
7818 }
7819 let mut cursor_col = run_start_col;
7820 let mut local_segment_ix = segment_ix;
7821 while local_segment_ix < bg_segments.len() {
7822 let (range, segment_color) = &bg_segments[local_segment_ix];
7823 let segment_start_col = range.start.column() as usize;
7824 let segment_end_col = range.end.column() as usize;
7825 if segment_start_col >= run_end_col {
7826 break;
7827 }
7828 if segment_start_col > cursor_col {
7829 let span_len = segment_start_col - cursor_col;
7830 output_runs.push(TextRun {
7831 len: span_len,
7832 font: text_run.font.clone(),
7833 color: text_run.color,
7834 background_color: text_run.background_color,
7835 underline: text_run.underline,
7836 strikethrough: text_run.strikethrough,
7837 });
7838 cursor_col = segment_start_col;
7839 }
7840 let segment_slice_end_col = segment_end_col.min(run_end_col);
7841 if segment_slice_end_col > cursor_col {
7842 let new_text_color =
7843 ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
7844 output_runs.push(TextRun {
7845 len: segment_slice_end_col - cursor_col,
7846 font: text_run.font.clone(),
7847 color: new_text_color,
7848 background_color: text_run.background_color,
7849 underline: text_run.underline,
7850 strikethrough: text_run.strikethrough,
7851 });
7852 cursor_col = segment_slice_end_col;
7853 }
7854 if segment_end_col >= run_end_col {
7855 break;
7856 }
7857 local_segment_ix += 1;
7858 }
7859 if cursor_col < run_end_col {
7860 output_runs.push(TextRun {
7861 len: run_end_col - cursor_col,
7862 font: text_run.font.clone(),
7863 color: text_run.color,
7864 background_color: text_run.background_color,
7865 underline: text_run.underline,
7866 strikethrough: text_run.strikethrough,
7867 });
7868 }
7869 line_col = run_end_col;
7870 segment_ix = local_segment_ix;
7871 }
7872 output_runs
7873 }
7874
7875 fn prepaint(
7876 &mut self,
7877 line_height: Pixels,
7878 scroll_pixel_position: gpui::Point<Pixels>,
7879 row: DisplayRow,
7880 content_origin: gpui::Point<Pixels>,
7881 line_elements: &mut SmallVec<[AnyElement; 1]>,
7882 window: &mut Window,
7883 cx: &mut App,
7884 ) {
7885 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
7886 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
7887 for fragment in &mut self.fragments {
7888 match fragment {
7889 LineFragment::Text(line) => {
7890 fragment_origin.x += line.width;
7891 }
7892 LineFragment::Element { element, size, .. } => {
7893 let mut element = element
7894 .take()
7895 .expect("you can't prepaint LineWithInvisibles twice");
7896
7897 // Center the element vertically within the line.
7898 let mut element_origin = fragment_origin;
7899 element_origin.y += (line_height - size.height) / 2.;
7900 element.prepaint_at(element_origin, window, cx);
7901 line_elements.push(element);
7902
7903 fragment_origin.x += size.width;
7904 }
7905 }
7906 }
7907 }
7908
7909 fn draw(
7910 &self,
7911 layout: &EditorLayout,
7912 row: DisplayRow,
7913 content_origin: gpui::Point<Pixels>,
7914 whitespace_setting: ShowWhitespaceSetting,
7915 selection_ranges: &[Range<DisplayPoint>],
7916 window: &mut Window,
7917 cx: &mut App,
7918 ) {
7919 let line_height = layout.position_map.line_height;
7920 let line_y = line_height
7921 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7922
7923 let mut fragment_origin =
7924 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7925
7926 for fragment in &self.fragments {
7927 match fragment {
7928 LineFragment::Text(line) => {
7929 line.paint(fragment_origin, line_height, window, cx)
7930 .log_err();
7931 fragment_origin.x += line.width;
7932 }
7933 LineFragment::Element { size, .. } => {
7934 fragment_origin.x += size.width;
7935 }
7936 }
7937 }
7938
7939 self.draw_invisibles(
7940 selection_ranges,
7941 layout,
7942 content_origin,
7943 line_y,
7944 row,
7945 line_height,
7946 whitespace_setting,
7947 window,
7948 cx,
7949 );
7950 }
7951
7952 fn draw_background(
7953 &self,
7954 layout: &EditorLayout,
7955 row: DisplayRow,
7956 content_origin: gpui::Point<Pixels>,
7957 window: &mut Window,
7958 cx: &mut App,
7959 ) {
7960 let line_height = layout.position_map.line_height;
7961 let line_y = line_height
7962 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7963
7964 let mut fragment_origin =
7965 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7966
7967 for fragment in &self.fragments {
7968 match fragment {
7969 LineFragment::Text(line) => {
7970 line.paint_background(fragment_origin, line_height, window, cx)
7971 .log_err();
7972 fragment_origin.x += line.width;
7973 }
7974 LineFragment::Element { size, .. } => {
7975 fragment_origin.x += size.width;
7976 }
7977 }
7978 }
7979 }
7980
7981 fn draw_invisibles(
7982 &self,
7983 selection_ranges: &[Range<DisplayPoint>],
7984 layout: &EditorLayout,
7985 content_origin: gpui::Point<Pixels>,
7986 line_y: Pixels,
7987 row: DisplayRow,
7988 line_height: Pixels,
7989 whitespace_setting: ShowWhitespaceSetting,
7990 window: &mut Window,
7991 cx: &mut App,
7992 ) {
7993 let extract_whitespace_info = |invisible: &Invisible| {
7994 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
7995 Invisible::Tab {
7996 line_start_offset,
7997 line_end_offset,
7998 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
7999 Invisible::Whitespace { line_offset } => {
8000 (*line_offset, line_offset + 1, &layout.space_invisible)
8001 }
8002 };
8003
8004 let x_offset = self.x_for_index(token_offset);
8005 let invisible_offset =
8006 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
8007 let origin = content_origin
8008 + gpui::point(
8009 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
8010 line_y,
8011 );
8012
8013 (
8014 [token_offset, token_end_offset],
8015 Box::new(move |window: &mut Window, cx: &mut App| {
8016 invisible_symbol
8017 .paint(origin, line_height, window, cx)
8018 .log_err();
8019 }),
8020 )
8021 };
8022
8023 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
8024 match whitespace_setting {
8025 ShowWhitespaceSetting::None => (),
8026 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
8027 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
8028 let invisible_point = DisplayPoint::new(row, start as u32);
8029 if !selection_ranges
8030 .iter()
8031 .any(|region| region.start <= invisible_point && invisible_point < region.end)
8032 {
8033 return;
8034 }
8035
8036 paint(window, cx);
8037 }),
8038
8039 ShowWhitespaceSetting::Trailing => {
8040 let mut previous_start = self.len;
8041 for ([start, end], paint) in invisible_iter.rev() {
8042 if previous_start != end {
8043 break;
8044 }
8045 previous_start = start;
8046 paint(window, cx);
8047 }
8048 }
8049
8050 // For a whitespace to be on a boundary, any of the following conditions need to be met:
8051 // - It is a tab
8052 // - It is adjacent to an edge (start or end)
8053 // - It is adjacent to a whitespace (left or right)
8054 ShowWhitespaceSetting::Boundary => {
8055 // 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
8056 // the above cases.
8057 // Note: We zip in the original `invisibles` to check for tab equality
8058 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
8059 for (([start, end], paint), invisible) in
8060 invisible_iter.zip_eq(self.invisibles.iter())
8061 {
8062 let should_render = match (&last_seen, invisible) {
8063 (_, Invisible::Tab { .. }) => true,
8064 (Some((_, last_end, _)), _) => *last_end == start,
8065 _ => false,
8066 };
8067
8068 if should_render || start == 0 || end == self.len {
8069 paint(window, cx);
8070
8071 // Since we are scanning from the left, we will skip over the first available whitespace that is part
8072 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
8073 if let Some((should_render_last, last_end, paint_last)) = last_seen {
8074 // Note that we need to make sure that the last one is actually adjacent
8075 if !should_render_last && last_end == start {
8076 paint_last(window, cx);
8077 }
8078 }
8079 }
8080
8081 // Manually render anything within a selection
8082 let invisible_point = DisplayPoint::new(row, start as u32);
8083 if selection_ranges.iter().any(|region| {
8084 region.start <= invisible_point && invisible_point < region.end
8085 }) {
8086 paint(window, cx);
8087 }
8088
8089 last_seen = Some((should_render, end, paint));
8090 }
8091 }
8092 }
8093 }
8094
8095 pub fn x_for_index(&self, index: usize) -> Pixels {
8096 let mut fragment_start_x = Pixels::ZERO;
8097 let mut fragment_start_index = 0;
8098
8099 for fragment in &self.fragments {
8100 match fragment {
8101 LineFragment::Text(shaped_line) => {
8102 let fragment_end_index = fragment_start_index + shaped_line.len;
8103 if index < fragment_end_index {
8104 return fragment_start_x
8105 + shaped_line.x_for_index(index - fragment_start_index);
8106 }
8107 fragment_start_x += shaped_line.width;
8108 fragment_start_index = fragment_end_index;
8109 }
8110 LineFragment::Element { len, size, .. } => {
8111 let fragment_end_index = fragment_start_index + len;
8112 if index < fragment_end_index {
8113 return fragment_start_x;
8114 }
8115 fragment_start_x += size.width;
8116 fragment_start_index = fragment_end_index;
8117 }
8118 }
8119 }
8120
8121 fragment_start_x
8122 }
8123
8124 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
8125 let mut fragment_start_x = Pixels::ZERO;
8126 let mut fragment_start_index = 0;
8127
8128 for fragment in &self.fragments {
8129 match fragment {
8130 LineFragment::Text(shaped_line) => {
8131 let fragment_end_x = fragment_start_x + shaped_line.width;
8132 if x < fragment_end_x {
8133 return Some(
8134 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
8135 );
8136 }
8137 fragment_start_x = fragment_end_x;
8138 fragment_start_index += shaped_line.len;
8139 }
8140 LineFragment::Element { len, size, .. } => {
8141 let fragment_end_x = fragment_start_x + size.width;
8142 if x < fragment_end_x {
8143 return Some(fragment_start_index);
8144 }
8145 fragment_start_index += len;
8146 fragment_start_x = fragment_end_x;
8147 }
8148 }
8149 }
8150
8151 None
8152 }
8153
8154 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
8155 let mut fragment_start_index = 0;
8156
8157 for fragment in &self.fragments {
8158 match fragment {
8159 LineFragment::Text(shaped_line) => {
8160 let fragment_end_index = fragment_start_index + shaped_line.len;
8161 if index < fragment_end_index {
8162 return shaped_line.font_id_for_index(index - fragment_start_index);
8163 }
8164 fragment_start_index = fragment_end_index;
8165 }
8166 LineFragment::Element { len, .. } => {
8167 let fragment_end_index = fragment_start_index + len;
8168 if index < fragment_end_index {
8169 return None;
8170 }
8171 fragment_start_index = fragment_end_index;
8172 }
8173 }
8174 }
8175
8176 None
8177 }
8178}
8179
8180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8181enum Invisible {
8182 /// A tab character
8183 ///
8184 /// A tab character is internally represented by spaces (configured by the user's tab width)
8185 /// aligned to the nearest column, so it's necessary to store the start and end offset for
8186 /// adjacency checks.
8187 Tab {
8188 line_start_offset: usize,
8189 line_end_offset: usize,
8190 },
8191 Whitespace {
8192 line_offset: usize,
8193 },
8194}
8195
8196impl EditorElement {
8197 /// Returns the rem size to use when rendering the [`EditorElement`].
8198 ///
8199 /// This allows UI elements to scale based on the `buffer_font_size`.
8200 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
8201 match self.editor.read(cx).mode {
8202 EditorMode::Full {
8203 scale_ui_elements_with_buffer_font_size: true,
8204 ..
8205 }
8206 | EditorMode::Minimap { .. } => {
8207 let buffer_font_size = self.style.text.font_size;
8208 match buffer_font_size {
8209 AbsoluteLength::Pixels(pixels) => {
8210 let rem_size_scale = {
8211 // Our default UI font size is 14px on a 16px base scale.
8212 // This means the default UI font size is 0.875rems.
8213 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
8214
8215 // We then determine the delta between a single rem and the default font
8216 // size scale.
8217 let default_font_size_delta = 1. - default_font_size_scale;
8218
8219 // Finally, we add this delta to 1rem to get the scale factor that
8220 // should be used to scale up the UI.
8221 1. + default_font_size_delta
8222 };
8223
8224 Some(pixels * rem_size_scale)
8225 }
8226 AbsoluteLength::Rems(rems) => {
8227 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
8228 }
8229 }
8230 }
8231 // We currently use single-line and auto-height editors in UI contexts,
8232 // so we don't want to scale everything with the buffer font size, as it
8233 // ends up looking off.
8234 _ => None,
8235 }
8236 }
8237
8238 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
8239 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
8240 parent.upgrade()
8241 } else {
8242 Some(self.editor.clone())
8243 }
8244 }
8245}
8246
8247impl Element for EditorElement {
8248 type RequestLayoutState = ();
8249 type PrepaintState = EditorLayout;
8250
8251 fn id(&self) -> Option<ElementId> {
8252 None
8253 }
8254
8255 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
8256 None
8257 }
8258
8259 fn request_layout(
8260 &mut self,
8261 _: Option<&GlobalElementId>,
8262 _inspector_id: Option<&gpui::InspectorElementId>,
8263 window: &mut Window,
8264 cx: &mut App,
8265 ) -> (gpui::LayoutId, ()) {
8266 let rem_size = self.rem_size(cx);
8267 window.with_rem_size(rem_size, |window| {
8268 self.editor.update(cx, |editor, cx| {
8269 editor.set_style(self.style.clone(), window, cx);
8270
8271 let layout_id = match editor.mode {
8272 EditorMode::SingleLine => {
8273 let rem_size = window.rem_size();
8274 let height = self.style.text.line_height_in_pixels(rem_size);
8275 let mut style = Style::default();
8276 style.size.height = height.into();
8277 style.size.width = relative(1.).into();
8278 window.request_layout(style, None, cx)
8279 }
8280 EditorMode::AutoHeight {
8281 min_lines,
8282 max_lines,
8283 } => {
8284 let editor_handle = cx.entity();
8285 let max_line_number_width =
8286 self.max_line_number_width(&editor.snapshot(window, cx), window);
8287 window.request_measured_layout(
8288 Style::default(),
8289 move |known_dimensions, available_space, window, cx| {
8290 editor_handle
8291 .update(cx, |editor, cx| {
8292 compute_auto_height_layout(
8293 editor,
8294 min_lines,
8295 max_lines,
8296 max_line_number_width,
8297 known_dimensions,
8298 available_space.width,
8299 window,
8300 cx,
8301 )
8302 })
8303 .unwrap_or_default()
8304 },
8305 )
8306 }
8307 EditorMode::Minimap { .. } => {
8308 let mut style = Style::default();
8309 style.size.width = relative(1.).into();
8310 style.size.height = relative(1.).into();
8311 window.request_layout(style, None, cx)
8312 }
8313 EditorMode::Full {
8314 sized_by_content, ..
8315 } => {
8316 let mut style = Style::default();
8317 style.size.width = relative(1.).into();
8318 if sized_by_content {
8319 let snapshot = editor.snapshot(window, cx);
8320 let line_height =
8321 self.style.text.line_height_in_pixels(window.rem_size());
8322 let scroll_height =
8323 (snapshot.max_point().row().next_row().0 as f32) * line_height;
8324 style.size.height = scroll_height.into();
8325 } else {
8326 style.size.height = relative(1.).into();
8327 }
8328 window.request_layout(style, None, cx)
8329 }
8330 };
8331
8332 (layout_id, ())
8333 })
8334 })
8335 }
8336
8337 fn prepaint(
8338 &mut self,
8339 _: Option<&GlobalElementId>,
8340 _inspector_id: Option<&gpui::InspectorElementId>,
8341 bounds: Bounds<Pixels>,
8342 _: &mut Self::RequestLayoutState,
8343 window: &mut Window,
8344 cx: &mut App,
8345 ) -> Self::PrepaintState {
8346 let text_style = TextStyleRefinement {
8347 font_size: Some(self.style.text.font_size),
8348 line_height: Some(self.style.text.line_height),
8349 ..Default::default()
8350 };
8351
8352 let is_minimap = self.editor.read(cx).mode.is_minimap();
8353
8354 if !is_minimap {
8355 let focus_handle = self.editor.focus_handle(cx);
8356 window.set_view_id(self.editor.entity_id());
8357 window.set_focus_handle(&focus_handle, cx);
8358 }
8359
8360 let rem_size = self.rem_size(cx);
8361 window.with_rem_size(rem_size, |window| {
8362 window.with_text_style(Some(text_style), |window| {
8363 window.with_content_mask(Some(ContentMask { bounds }), |window| {
8364 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
8365 (editor.snapshot(window, cx), editor.read_only(cx))
8366 });
8367 let style = &self.style;
8368
8369 let rem_size = window.rem_size();
8370 let font_id = window.text_system().resolve_font(&style.text.font());
8371 let font_size = style.text.font_size.to_pixels(rem_size);
8372 let line_height = style.text.line_height_in_pixels(rem_size);
8373 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8374 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
8375 let glyph_grid_cell = size(em_advance, line_height);
8376
8377 let gutter_dimensions = snapshot
8378 .gutter_dimensions(
8379 font_id,
8380 font_size,
8381 self.max_line_number_width(&snapshot, window),
8382 cx,
8383 )
8384 .or_else(|| {
8385 self.editor.read(cx).offset_content.then(|| {
8386 GutterDimensions::default_with_margin(font_id, font_size, cx)
8387 })
8388 })
8389 .unwrap_or_default();
8390 let text_width = bounds.size.width - gutter_dimensions.width;
8391
8392 let settings = EditorSettings::get_global(cx);
8393 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
8394 let vertical_scrollbar_width = (scrollbars_shown
8395 && settings.scrollbar.axes.vertical
8396 && self.editor.read(cx).show_scrollbars.vertical)
8397 .then_some(style.scrollbar_width)
8398 .unwrap_or_default();
8399 let minimap_width = self
8400 .get_minimap_width(
8401 &settings.minimap,
8402 scrollbars_shown,
8403 text_width,
8404 em_width,
8405 font_size,
8406 rem_size,
8407 cx,
8408 )
8409 .unwrap_or_default();
8410
8411 let right_margin = minimap_width + vertical_scrollbar_width;
8412
8413 let editor_width =
8414 text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
8415 let editor_margins = EditorMargins {
8416 gutter: gutter_dimensions,
8417 right: right_margin,
8418 };
8419
8420 snapshot = self.editor.update(cx, |editor, cx| {
8421 editor.last_bounds = Some(bounds);
8422 editor.gutter_dimensions = gutter_dimensions;
8423 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
8424 editor.set_visible_column_count(editor_width / em_advance);
8425
8426 if matches!(
8427 editor.mode,
8428 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
8429 ) {
8430 snapshot
8431 } else {
8432 let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
8433 let wrap_width = match editor.soft_wrap_mode(cx) {
8434 SoftWrap::GitDiff => None,
8435 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
8436 SoftWrap::EditorWidth => Some(editor_width),
8437 SoftWrap::Column(column) => Some(wrap_width_for(column)),
8438 SoftWrap::Bounded(column) => {
8439 Some(editor_width.min(wrap_width_for(column)))
8440 }
8441 };
8442
8443 if editor.set_wrap_width(wrap_width, cx) {
8444 editor.snapshot(window, cx)
8445 } else {
8446 snapshot
8447 }
8448 }
8449 });
8450
8451 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
8452 let gutter_hitbox = window.insert_hitbox(
8453 gutter_bounds(bounds, gutter_dimensions),
8454 HitboxBehavior::Normal,
8455 );
8456 let text_hitbox = window.insert_hitbox(
8457 Bounds {
8458 origin: gutter_hitbox.top_right(),
8459 size: size(text_width, bounds.size.height),
8460 },
8461 HitboxBehavior::Normal,
8462 );
8463
8464 // Offset the content_bounds from the text_bounds by the gutter margin (which
8465 // is roughly half a character wide) to make hit testing work more like how we want.
8466 let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
8467 let content_origin = text_hitbox.origin + content_offset;
8468
8469 let height_in_lines = bounds.size.height / line_height;
8470 let max_row = snapshot.max_point().row().as_f32();
8471
8472 // The max scroll position for the top of the window
8473 let max_scroll_top = if matches!(
8474 snapshot.mode,
8475 EditorMode::SingleLine
8476 | EditorMode::AutoHeight { .. }
8477 | EditorMode::Full {
8478 sized_by_content: true,
8479 ..
8480 }
8481 ) {
8482 (max_row - height_in_lines + 1.).max(0.)
8483 } else {
8484 let settings = EditorSettings::get_global(cx);
8485 match settings.scroll_beyond_last_line {
8486 ScrollBeyondLastLine::OnePage => max_row,
8487 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
8488 ScrollBeyondLastLine::VerticalScrollMargin => {
8489 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
8490 .max(0.)
8491 }
8492 }
8493 };
8494
8495 let (
8496 autoscroll_request,
8497 autoscroll_containing_element,
8498 needs_horizontal_autoscroll,
8499 ) = self.editor.update(cx, |editor, cx| {
8500 let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
8501
8502 let autoscroll_containing_element =
8503 autoscroll_request.is_some() || editor.has_pending_selection();
8504
8505 let (needs_horizontal_autoscroll, was_scrolled) = editor
8506 .autoscroll_vertically(
8507 bounds,
8508 line_height,
8509 max_scroll_top,
8510 autoscroll_request,
8511 window,
8512 cx,
8513 );
8514 if was_scrolled.0 {
8515 snapshot = editor.snapshot(window, cx);
8516 }
8517 (
8518 autoscroll_request,
8519 autoscroll_containing_element,
8520 needs_horizontal_autoscroll,
8521 )
8522 });
8523
8524 let mut scroll_position = snapshot.scroll_position();
8525 // The scroll position is a fractional point, the whole number of which represents
8526 // the top of the window in terms of display rows.
8527 let start_row = DisplayRow(scroll_position.y as u32);
8528 let max_row = snapshot.max_point().row();
8529 let end_row = cmp::min(
8530 (scroll_position.y + height_in_lines).ceil() as u32,
8531 max_row.next_row().0,
8532 );
8533 let end_row = DisplayRow(end_row);
8534
8535 let row_infos = snapshot
8536 .row_infos(start_row)
8537 .take((start_row..end_row).len())
8538 .collect::<Vec<RowInfo>>();
8539 let is_row_soft_wrapped = |row: usize| {
8540 row_infos
8541 .get(row)
8542 .is_none_or(|info| info.buffer_row.is_none())
8543 };
8544
8545 let start_anchor = if start_row == Default::default() {
8546 Anchor::min()
8547 } else {
8548 snapshot.buffer_snapshot.anchor_before(
8549 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
8550 )
8551 };
8552 let end_anchor = if end_row > max_row {
8553 Anchor::max()
8554 } else {
8555 snapshot.buffer_snapshot.anchor_before(
8556 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
8557 )
8558 };
8559
8560 let mut highlighted_rows = self
8561 .editor
8562 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
8563
8564 let is_light = cx.theme().appearance().is_light();
8565
8566 for (ix, row_info) in row_infos.iter().enumerate() {
8567 let Some(diff_status) = row_info.diff_status else {
8568 continue;
8569 };
8570
8571 let background_color = match diff_status.kind {
8572 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
8573 DiffHunkStatusKind::Deleted => {
8574 cx.theme().colors().version_control_deleted
8575 }
8576 DiffHunkStatusKind::Modified => {
8577 debug_panic!("modified diff status for row info");
8578 continue;
8579 }
8580 };
8581
8582 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
8583
8584 let hollow_highlight = LineHighlight {
8585 background: (background_color.opacity(if is_light {
8586 0.08
8587 } else {
8588 0.06
8589 }))
8590 .into(),
8591 border: Some(if is_light {
8592 background_color.opacity(0.48)
8593 } else {
8594 background_color.opacity(0.36)
8595 }),
8596 include_gutter: true,
8597 type_id: None,
8598 };
8599
8600 let filled_highlight = LineHighlight {
8601 background: solid_background(background_color.opacity(hunk_opacity)),
8602 border: None,
8603 include_gutter: true,
8604 type_id: None,
8605 };
8606
8607 let background = if Self::diff_hunk_hollow(diff_status, cx) {
8608 hollow_highlight
8609 } else {
8610 filled_highlight
8611 };
8612
8613 highlighted_rows
8614 .entry(start_row + DisplayRow(ix as u32))
8615 .or_insert(background);
8616 }
8617
8618 let highlighted_ranges = self
8619 .editor_with_selections(cx)
8620 .map(|editor| {
8621 editor.read(cx).background_highlights_in_range(
8622 start_anchor..end_anchor,
8623 &snapshot.display_snapshot,
8624 cx.theme(),
8625 )
8626 })
8627 .unwrap_or_default();
8628 let highlighted_gutter_ranges =
8629 self.editor.read(cx).gutter_highlights_in_range(
8630 start_anchor..end_anchor,
8631 &snapshot.display_snapshot,
8632 cx,
8633 );
8634
8635 let document_colors = self
8636 .editor
8637 .read(cx)
8638 .colors
8639 .as_ref()
8640 .map(|colors| colors.editor_display_highlights(&snapshot));
8641 let redacted_ranges = self.editor.read(cx).redacted_ranges(
8642 start_anchor..end_anchor,
8643 &snapshot.display_snapshot,
8644 cx,
8645 );
8646
8647 let (local_selections, selected_buffer_ids): (
8648 Vec<Selection<Point>>,
8649 Vec<BufferId>,
8650 ) = self
8651 .editor_with_selections(cx)
8652 .map(|editor| {
8653 editor.update(cx, |editor, cx| {
8654 let all_selections = editor.selections.all::<Point>(cx);
8655 let selected_buffer_ids = if editor.is_singleton(cx) {
8656 Vec::new()
8657 } else {
8658 let mut selected_buffer_ids =
8659 Vec::with_capacity(all_selections.len());
8660
8661 for selection in all_selections {
8662 for buffer_id in snapshot
8663 .buffer_snapshot
8664 .buffer_ids_for_range(selection.range())
8665 {
8666 if selected_buffer_ids.last() != Some(&buffer_id) {
8667 selected_buffer_ids.push(buffer_id);
8668 }
8669 }
8670 }
8671
8672 selected_buffer_ids
8673 };
8674
8675 let mut selections = editor
8676 .selections
8677 .disjoint_in_range(start_anchor..end_anchor, cx);
8678 selections.extend(editor.selections.pending(cx));
8679
8680 (selections, selected_buffer_ids)
8681 })
8682 })
8683 .unwrap_or_default();
8684
8685 let (selections, mut active_rows, newest_selection_head) = self
8686 .layout_selections(
8687 start_anchor,
8688 end_anchor,
8689 &local_selections,
8690 &snapshot,
8691 start_row,
8692 end_row,
8693 window,
8694 cx,
8695 );
8696 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
8697 editor.active_breakpoints(start_row..end_row, window, cx)
8698 });
8699 for (display_row, (_, bp, state)) in &breakpoint_rows {
8700 if bp.is_enabled() && state.is_none_or(|s| s.verified) {
8701 active_rows.entry(*display_row).or_default().breakpoint = true;
8702 }
8703 }
8704
8705 let line_numbers = self.layout_line_numbers(
8706 Some(&gutter_hitbox),
8707 gutter_dimensions,
8708 line_height,
8709 scroll_position,
8710 start_row..end_row,
8711 &row_infos,
8712 &active_rows,
8713 newest_selection_head,
8714 &snapshot,
8715 window,
8716 cx,
8717 );
8718
8719 // We add the gutter breakpoint indicator to breakpoint_rows after painting
8720 // line numbers so we don't paint a line number debug accent color if a user
8721 // has their mouse over that line when a breakpoint isn't there
8722 self.editor.update(cx, |editor, _| {
8723 if let Some(phantom_breakpoint) = &mut editor
8724 .gutter_breakpoint_indicator
8725 .0
8726 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
8727 {
8728 // Is there a non-phantom breakpoint on this line?
8729 phantom_breakpoint.collides_with_existing_breakpoint = true;
8730 breakpoint_rows
8731 .entry(phantom_breakpoint.display_row)
8732 .or_insert_with(|| {
8733 let position = snapshot.display_point_to_anchor(
8734 DisplayPoint::new(phantom_breakpoint.display_row, 0),
8735 Bias::Right,
8736 );
8737 let breakpoint = Breakpoint::new_standard();
8738 phantom_breakpoint.collides_with_existing_breakpoint = false;
8739 (position, breakpoint, None)
8740 });
8741 }
8742 });
8743
8744 let mut expand_toggles =
8745 window.with_element_namespace("expand_toggles", |window| {
8746 self.layout_expand_toggles(
8747 &gutter_hitbox,
8748 gutter_dimensions,
8749 em_width,
8750 line_height,
8751 scroll_position,
8752 &row_infos,
8753 window,
8754 cx,
8755 )
8756 });
8757
8758 let mut crease_toggles =
8759 window.with_element_namespace("crease_toggles", |window| {
8760 self.layout_crease_toggles(
8761 start_row..end_row,
8762 &row_infos,
8763 &active_rows,
8764 &snapshot,
8765 window,
8766 cx,
8767 )
8768 });
8769 let crease_trailers =
8770 window.with_element_namespace("crease_trailers", |window| {
8771 self.layout_crease_trailers(
8772 row_infos.iter().copied(),
8773 &snapshot,
8774 window,
8775 cx,
8776 )
8777 });
8778
8779 let display_hunks = self.layout_gutter_diff_hunks(
8780 line_height,
8781 &gutter_hitbox,
8782 start_row..end_row,
8783 &snapshot,
8784 window,
8785 cx,
8786 );
8787
8788 let bg_segments_per_row = Self::bg_segments_per_row(
8789 start_row..end_row,
8790 &selections,
8791 &highlighted_ranges,
8792 self.style.background,
8793 );
8794
8795 let mut line_layouts = Self::layout_lines(
8796 start_row..end_row,
8797 &snapshot,
8798 &self.style,
8799 editor_width,
8800 is_row_soft_wrapped,
8801 &bg_segments_per_row,
8802 window,
8803 cx,
8804 );
8805 let new_renderer_widths = (!is_minimap).then(|| {
8806 line_layouts
8807 .iter()
8808 .flat_map(|layout| &layout.fragments)
8809 .filter_map(|fragment| {
8810 if let LineFragment::Element { id, size, .. } = fragment {
8811 Some((*id, size.width))
8812 } else {
8813 None
8814 }
8815 })
8816 });
8817 if new_renderer_widths.is_some_and(|new_renderer_widths| {
8818 self.editor.update(cx, |editor, cx| {
8819 editor.update_renderer_widths(new_renderer_widths, cx)
8820 })
8821 }) {
8822 // If the fold widths have changed, we need to prepaint
8823 // the element again to account for any changes in
8824 // wrapping.
8825 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8826 }
8827
8828 let longest_line_blame_width = self
8829 .editor
8830 .update(cx, |editor, cx| {
8831 if !editor.show_git_blame_inline {
8832 return None;
8833 }
8834 let blame = editor.blame.as_ref()?;
8835 let (_, blame_entry) = blame
8836 .update(cx, |blame, cx| {
8837 let row_infos =
8838 snapshot.row_infos(snapshot.longest_row()).next()?;
8839 blame.blame_for_rows(&[row_infos], cx).next()
8840 })
8841 .flatten()?;
8842 let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
8843 let inline_blame_padding = ProjectSettings::get_global(cx)
8844 .git
8845 .inline_blame
8846 .unwrap_or_default()
8847 .padding
8848 as f32
8849 * em_advance;
8850 Some(
8851 element
8852 .layout_as_root(AvailableSpace::min_size(), window, cx)
8853 .width
8854 + inline_blame_padding,
8855 )
8856 })
8857 .unwrap_or(Pixels::ZERO);
8858
8859 let longest_line_width = layout_line(
8860 snapshot.longest_row(),
8861 &snapshot,
8862 style,
8863 editor_width,
8864 is_row_soft_wrapped,
8865 window,
8866 cx,
8867 )
8868 .width;
8869
8870 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
8871 text_hitbox.bounds,
8872 glyph_grid_cell,
8873 size(longest_line_width, max_row.as_f32() * line_height),
8874 longest_line_blame_width,
8875 EditorSettings::get_global(cx),
8876 );
8877
8878 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
8879
8880 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
8881 snapshot.sticky_header_excerpt(scroll_position.y)
8882 } else {
8883 None
8884 };
8885 let sticky_header_excerpt_id =
8886 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
8887
8888 let blocks = (!is_minimap)
8889 .then(|| {
8890 window.with_element_namespace("blocks", |window| {
8891 self.render_blocks(
8892 start_row..end_row,
8893 &snapshot,
8894 &hitbox,
8895 &text_hitbox,
8896 editor_width,
8897 &mut scroll_width,
8898 &editor_margins,
8899 em_width,
8900 gutter_dimensions.full_width(),
8901 line_height,
8902 &mut line_layouts,
8903 &local_selections,
8904 &selected_buffer_ids,
8905 is_row_soft_wrapped,
8906 sticky_header_excerpt_id,
8907 window,
8908 cx,
8909 )
8910 })
8911 })
8912 .unwrap_or_else(|| Ok((Vec::default(), HashMap::default())));
8913 let (mut blocks, row_block_types) = match blocks {
8914 Ok(blocks) => blocks,
8915 Err(resized_blocks) => {
8916 self.editor.update(cx, |editor, cx| {
8917 editor.resize_blocks(
8918 resized_blocks,
8919 autoscroll_request.map(|(autoscroll, _)| autoscroll),
8920 cx,
8921 )
8922 });
8923 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8924 }
8925 };
8926
8927 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
8928 window.with_element_namespace("blocks", |window| {
8929 self.layout_sticky_buffer_header(
8930 sticky_header_excerpt,
8931 scroll_position.y,
8932 line_height,
8933 right_margin,
8934 &snapshot,
8935 &hitbox,
8936 &selected_buffer_ids,
8937 &blocks,
8938 window,
8939 cx,
8940 )
8941 })
8942 });
8943
8944 let start_buffer_row =
8945 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
8946 let end_buffer_row =
8947 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
8948
8949 let scroll_max = point(
8950 ((scroll_width - editor_width) / em_advance).max(0.0),
8951 max_scroll_top,
8952 );
8953
8954 self.editor.update(cx, |editor, cx| {
8955 if editor.scroll_manager.clamp_scroll_left(scroll_max.x) {
8956 scroll_position.x = scroll_position.x.min(scroll_max.x);
8957 }
8958
8959 if needs_horizontal_autoscroll.0
8960 && let Some(new_scroll_position) = editor.autoscroll_horizontally(
8961 start_row,
8962 editor_width,
8963 scroll_width,
8964 em_advance,
8965 &line_layouts,
8966 autoscroll_request,
8967 window,
8968 cx,
8969 )
8970 {
8971 scroll_position = new_scroll_position;
8972 }
8973 });
8974
8975 let scroll_pixel_position = point(
8976 scroll_position.x * em_advance,
8977 scroll_position.y * line_height,
8978 );
8979 let indent_guides = self.layout_indent_guides(
8980 content_origin,
8981 text_hitbox.origin,
8982 start_buffer_row..end_buffer_row,
8983 scroll_pixel_position,
8984 line_height,
8985 &snapshot,
8986 window,
8987 cx,
8988 );
8989
8990 let crease_trailers =
8991 window.with_element_namespace("crease_trailers", |window| {
8992 self.prepaint_crease_trailers(
8993 crease_trailers,
8994 &line_layouts,
8995 line_height,
8996 content_origin,
8997 scroll_pixel_position,
8998 em_width,
8999 window,
9000 cx,
9001 )
9002 });
9003
9004 let (edit_prediction_popover, edit_prediction_popover_origin) = self
9005 .editor
9006 .update(cx, |editor, cx| {
9007 editor.render_edit_prediction_popover(
9008 &text_hitbox.bounds,
9009 content_origin,
9010 right_margin,
9011 &snapshot,
9012 start_row..end_row,
9013 scroll_position.y,
9014 scroll_position.y + height_in_lines,
9015 &line_layouts,
9016 line_height,
9017 scroll_pixel_position,
9018 newest_selection_head,
9019 editor_width,
9020 style,
9021 window,
9022 cx,
9023 )
9024 })
9025 .unzip();
9026
9027 let mut inline_diagnostics = self.layout_inline_diagnostics(
9028 &line_layouts,
9029 &crease_trailers,
9030 &row_block_types,
9031 content_origin,
9032 scroll_pixel_position,
9033 edit_prediction_popover_origin,
9034 start_row,
9035 end_row,
9036 line_height,
9037 em_width,
9038 style,
9039 window,
9040 cx,
9041 );
9042
9043 let mut inline_blame_layout = None;
9044 let mut inline_code_actions = None;
9045 if let Some(newest_selection_head) = newest_selection_head {
9046 let display_row = newest_selection_head.row();
9047 if (start_row..end_row).contains(&display_row)
9048 && !row_block_types.contains_key(&display_row)
9049 {
9050 inline_code_actions = self.layout_inline_code_actions(
9051 newest_selection_head,
9052 content_origin,
9053 scroll_pixel_position,
9054 line_height,
9055 &snapshot,
9056 window,
9057 cx,
9058 );
9059
9060 let line_ix = display_row.minus(start_row) as usize;
9061 if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
9062 row_infos.get(line_ix),
9063 line_layouts.get(line_ix),
9064 crease_trailers.get(line_ix),
9065 ) {
9066 let crease_trailer_layout = crease_trailer.as_ref();
9067 if let Some(layout) = self.layout_inline_blame(
9068 display_row,
9069 row_info,
9070 line_layout,
9071 crease_trailer_layout,
9072 em_width,
9073 content_origin,
9074 scroll_pixel_position,
9075 line_height,
9076 &text_hitbox,
9077 window,
9078 cx,
9079 ) {
9080 inline_blame_layout = Some(layout);
9081 // Blame overrides inline diagnostics
9082 inline_diagnostics.remove(&display_row);
9083 }
9084 } else {
9085 log::error!(
9086 "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
9087 line_layouts.len(): {}, \
9088 crease_trailers.len(): {}",
9089 line_ix,
9090 row_infos.len(),
9091 line_layouts.len(),
9092 crease_trailers.len(),
9093 );
9094 }
9095 }
9096 }
9097
9098 let blamed_display_rows = self.layout_blame_entries(
9099 &row_infos,
9100 em_width,
9101 scroll_position,
9102 line_height,
9103 &gutter_hitbox,
9104 gutter_dimensions.git_blame_entries_width,
9105 window,
9106 cx,
9107 );
9108
9109 let line_elements = self.prepaint_lines(
9110 start_row,
9111 &mut line_layouts,
9112 line_height,
9113 scroll_pixel_position,
9114 content_origin,
9115 window,
9116 cx,
9117 );
9118
9119 window.with_element_namespace("blocks", |window| {
9120 self.layout_blocks(
9121 &mut blocks,
9122 &hitbox,
9123 line_height,
9124 scroll_pixel_position,
9125 window,
9126 cx,
9127 );
9128 });
9129
9130 let cursors = self.collect_cursors(&snapshot, cx);
9131 let visible_row_range = start_row..end_row;
9132 let non_visible_cursors = cursors
9133 .iter()
9134 .any(|c| !visible_row_range.contains(&c.0.row()));
9135
9136 let visible_cursors = self.layout_visible_cursors(
9137 &snapshot,
9138 &selections,
9139 &row_block_types,
9140 start_row..end_row,
9141 &line_layouts,
9142 &text_hitbox,
9143 content_origin,
9144 scroll_position,
9145 scroll_pixel_position,
9146 line_height,
9147 em_width,
9148 em_advance,
9149 autoscroll_containing_element,
9150 window,
9151 cx,
9152 );
9153
9154 let scrollbars_layout = self.layout_scrollbars(
9155 &snapshot,
9156 &scrollbar_layout_information,
9157 content_offset,
9158 scroll_position,
9159 non_visible_cursors,
9160 right_margin,
9161 editor_width,
9162 window,
9163 cx,
9164 );
9165
9166 let gutter_settings = EditorSettings::get_global(cx).gutter;
9167
9168 let context_menu_layout =
9169 if let Some(newest_selection_head) = newest_selection_head {
9170 let newest_selection_point =
9171 newest_selection_head.to_point(&snapshot.display_snapshot);
9172 if (start_row..end_row).contains(&newest_selection_head.row()) {
9173 self.layout_cursor_popovers(
9174 line_height,
9175 &text_hitbox,
9176 content_origin,
9177 right_margin,
9178 start_row,
9179 scroll_pixel_position,
9180 &line_layouts,
9181 newest_selection_head,
9182 newest_selection_point,
9183 style,
9184 window,
9185 cx,
9186 )
9187 } else {
9188 None
9189 }
9190 } else {
9191 None
9192 };
9193
9194 self.layout_gutter_menu(
9195 line_height,
9196 &text_hitbox,
9197 content_origin,
9198 right_margin,
9199 scroll_pixel_position,
9200 gutter_dimensions.width - gutter_dimensions.left_padding,
9201 window,
9202 cx,
9203 );
9204
9205 let test_indicators = if gutter_settings.runnables {
9206 self.layout_run_indicators(
9207 line_height,
9208 start_row..end_row,
9209 &row_infos,
9210 scroll_pixel_position,
9211 &gutter_dimensions,
9212 &gutter_hitbox,
9213 &display_hunks,
9214 &snapshot,
9215 &mut breakpoint_rows,
9216 window,
9217 cx,
9218 )
9219 } else {
9220 Vec::new()
9221 };
9222
9223 let show_breakpoints = snapshot
9224 .show_breakpoints
9225 .unwrap_or(gutter_settings.breakpoints);
9226 let breakpoints = if show_breakpoints {
9227 self.layout_breakpoints(
9228 line_height,
9229 start_row..end_row,
9230 scroll_pixel_position,
9231 &gutter_dimensions,
9232 &gutter_hitbox,
9233 &display_hunks,
9234 &snapshot,
9235 breakpoint_rows,
9236 &row_infos,
9237 window,
9238 cx,
9239 )
9240 } else {
9241 Vec::new()
9242 };
9243
9244 self.layout_signature_help(
9245 &hitbox,
9246 content_origin,
9247 scroll_pixel_position,
9248 newest_selection_head,
9249 start_row,
9250 &line_layouts,
9251 line_height,
9252 em_width,
9253 context_menu_layout,
9254 window,
9255 cx,
9256 );
9257
9258 if !cx.has_active_drag() {
9259 self.layout_hover_popovers(
9260 &snapshot,
9261 &hitbox,
9262 start_row..end_row,
9263 content_origin,
9264 scroll_pixel_position,
9265 &line_layouts,
9266 line_height,
9267 em_width,
9268 context_menu_layout,
9269 window,
9270 cx,
9271 );
9272 }
9273
9274 let mouse_context_menu = self.layout_mouse_context_menu(
9275 &snapshot,
9276 start_row..end_row,
9277 content_origin,
9278 window,
9279 cx,
9280 );
9281
9282 window.with_element_namespace("crease_toggles", |window| {
9283 self.prepaint_crease_toggles(
9284 &mut crease_toggles,
9285 line_height,
9286 &gutter_dimensions,
9287 gutter_settings,
9288 scroll_pixel_position,
9289 &gutter_hitbox,
9290 window,
9291 cx,
9292 )
9293 });
9294
9295 window.with_element_namespace("expand_toggles", |window| {
9296 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
9297 });
9298
9299 let wrap_guides = self.layout_wrap_guides(
9300 em_advance,
9301 scroll_position,
9302 content_origin,
9303 scrollbars_layout.as_ref(),
9304 vertical_scrollbar_width,
9305 &hitbox,
9306 window,
9307 cx,
9308 );
9309
9310 let minimap = window.with_element_namespace("minimap", |window| {
9311 self.layout_minimap(
9312 &snapshot,
9313 minimap_width,
9314 scroll_position,
9315 &scrollbar_layout_information,
9316 scrollbars_layout.as_ref(),
9317 window,
9318 cx,
9319 )
9320 });
9321
9322 let invisible_symbol_font_size = font_size / 2.;
9323 let whitespace_map = &self
9324 .editor
9325 .read(cx)
9326 .buffer
9327 .read(cx)
9328 .language_settings(cx)
9329 .whitespace_map;
9330
9331 let tab_char = whitespace_map.tab();
9332 let tab_len = tab_char.len();
9333 let tab_invisible = window.text_system().shape_line(
9334 tab_char,
9335 invisible_symbol_font_size,
9336 &[TextRun {
9337 len: tab_len,
9338 font: self.style.text.font(),
9339 color: cx.theme().colors().editor_invisible,
9340 background_color: None,
9341 underline: None,
9342 strikethrough: None,
9343 }],
9344 None,
9345 );
9346
9347 let space_char = whitespace_map.space();
9348 let space_len = space_char.len();
9349 let space_invisible = window.text_system().shape_line(
9350 space_char,
9351 invisible_symbol_font_size,
9352 &[TextRun {
9353 len: space_len,
9354 font: self.style.text.font(),
9355 color: cx.theme().colors().editor_invisible,
9356 background_color: None,
9357 underline: None,
9358 strikethrough: None,
9359 }],
9360 None,
9361 );
9362
9363 let mode = snapshot.mode.clone();
9364
9365 let (diff_hunk_controls, diff_hunk_control_bounds) = if is_read_only {
9366 (vec![], vec![])
9367 } else {
9368 self.layout_diff_hunk_controls(
9369 start_row..end_row,
9370 &row_infos,
9371 &text_hitbox,
9372 newest_selection_head,
9373 line_height,
9374 right_margin,
9375 scroll_pixel_position,
9376 &display_hunks,
9377 &highlighted_rows,
9378 self.editor.clone(),
9379 window,
9380 cx,
9381 )
9382 };
9383
9384 let position_map = Rc::new(PositionMap {
9385 size: bounds.size,
9386 visible_row_range,
9387 scroll_pixel_position,
9388 scroll_max,
9389 line_layouts,
9390 line_height,
9391 em_width,
9392 em_advance,
9393 snapshot,
9394 gutter_hitbox: gutter_hitbox.clone(),
9395 text_hitbox: text_hitbox.clone(),
9396 inline_blame_bounds: inline_blame_layout
9397 .as_ref()
9398 .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
9399 display_hunks: display_hunks.clone(),
9400 diff_hunk_control_bounds,
9401 });
9402
9403 self.editor.update(cx, |editor, _| {
9404 editor.last_position_map = Some(position_map.clone())
9405 });
9406
9407 EditorLayout {
9408 mode,
9409 position_map,
9410 visible_display_row_range: start_row..end_row,
9411 wrap_guides,
9412 indent_guides,
9413 hitbox,
9414 gutter_hitbox,
9415 display_hunks,
9416 content_origin,
9417 scrollbars_layout,
9418 minimap,
9419 active_rows,
9420 highlighted_rows,
9421 highlighted_ranges,
9422 highlighted_gutter_ranges,
9423 redacted_ranges,
9424 document_colors,
9425 line_elements,
9426 line_numbers,
9427 blamed_display_rows,
9428 inline_diagnostics,
9429 inline_blame_layout,
9430 inline_code_actions,
9431 blocks,
9432 cursors,
9433 visible_cursors,
9434 selections,
9435 edit_prediction_popover,
9436 diff_hunk_controls,
9437 mouse_context_menu,
9438 test_indicators,
9439 breakpoints,
9440 crease_toggles,
9441 crease_trailers,
9442 tab_invisible,
9443 space_invisible,
9444 sticky_buffer_header,
9445 expand_toggles,
9446 }
9447 })
9448 })
9449 })
9450 }
9451
9452 fn paint(
9453 &mut self,
9454 _: Option<&GlobalElementId>,
9455 _inspector_id: Option<&gpui::InspectorElementId>,
9456 bounds: Bounds<gpui::Pixels>,
9457 _: &mut Self::RequestLayoutState,
9458 layout: &mut Self::PrepaintState,
9459 window: &mut Window,
9460 cx: &mut App,
9461 ) {
9462 if !layout.mode.is_minimap() {
9463 let focus_handle = self.editor.focus_handle(cx);
9464 let key_context = self
9465 .editor
9466 .update(cx, |editor, cx| editor.key_context(window, cx));
9467
9468 window.set_key_context(key_context);
9469 window.handle_input(
9470 &focus_handle,
9471 ElementInputHandler::new(bounds, self.editor.clone()),
9472 cx,
9473 );
9474 self.register_actions(window, cx);
9475 self.register_key_listeners(window, cx, layout);
9476 }
9477
9478 let text_style = TextStyleRefinement {
9479 font_size: Some(self.style.text.font_size),
9480 line_height: Some(self.style.text.line_height),
9481 ..Default::default()
9482 };
9483 let rem_size = self.rem_size(cx);
9484 window.with_rem_size(rem_size, |window| {
9485 window.with_text_style(Some(text_style), |window| {
9486 window.with_content_mask(Some(ContentMask { bounds }), |window| {
9487 self.paint_mouse_listeners(layout, window, cx);
9488 self.paint_background(layout, window, cx);
9489 self.paint_indent_guides(layout, window, cx);
9490
9491 if layout.gutter_hitbox.size.width > Pixels::ZERO {
9492 self.paint_blamed_display_rows(layout, window, cx);
9493 self.paint_line_numbers(layout, window, cx);
9494 }
9495
9496 self.paint_text(layout, window, cx);
9497
9498 if layout.gutter_hitbox.size.width > Pixels::ZERO {
9499 self.paint_gutter_highlights(layout, window, cx);
9500 self.paint_gutter_indicators(layout, window, cx);
9501 }
9502
9503 if !layout.blocks.is_empty() {
9504 window.with_element_namespace("blocks", |window| {
9505 self.paint_blocks(layout, window, cx);
9506 });
9507 }
9508
9509 window.with_element_namespace("blocks", |window| {
9510 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
9511 sticky_header.paint(window, cx)
9512 }
9513 });
9514
9515 self.paint_minimap(layout, window, cx);
9516 self.paint_scrollbars(layout, window, cx);
9517 self.paint_edit_prediction_popover(layout, window, cx);
9518 self.paint_mouse_context_menu(layout, window, cx);
9519 });
9520 })
9521 })
9522 }
9523}
9524
9525pub(super) fn gutter_bounds(
9526 editor_bounds: Bounds<Pixels>,
9527 gutter_dimensions: GutterDimensions,
9528) -> Bounds<Pixels> {
9529 Bounds {
9530 origin: editor_bounds.origin,
9531 size: size(gutter_dimensions.width, editor_bounds.size.height),
9532 }
9533}
9534
9535#[derive(Clone, Copy)]
9536struct ContextMenuLayout {
9537 y_flipped: bool,
9538 bounds: Bounds<Pixels>,
9539}
9540
9541/// Holds information required for layouting the editor scrollbars.
9542struct ScrollbarLayoutInformation {
9543 /// The bounds of the editor area (excluding the content offset).
9544 editor_bounds: Bounds<Pixels>,
9545 /// The available range to scroll within the document.
9546 scroll_range: Size<Pixels>,
9547 /// The space available for one glyph in the editor.
9548 glyph_grid_cell: Size<Pixels>,
9549}
9550
9551impl ScrollbarLayoutInformation {
9552 pub fn new(
9553 editor_bounds: Bounds<Pixels>,
9554 glyph_grid_cell: Size<Pixels>,
9555 document_size: Size<Pixels>,
9556 longest_line_blame_width: Pixels,
9557 settings: &EditorSettings,
9558 ) -> Self {
9559 let vertical_overscroll = match settings.scroll_beyond_last_line {
9560 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
9561 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
9562 ScrollBeyondLastLine::VerticalScrollMargin => {
9563 (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
9564 }
9565 };
9566
9567 let overscroll = size(longest_line_blame_width, vertical_overscroll);
9568
9569 ScrollbarLayoutInformation {
9570 editor_bounds,
9571 scroll_range: document_size + overscroll,
9572 glyph_grid_cell,
9573 }
9574 }
9575}
9576
9577impl IntoElement for EditorElement {
9578 type Element = Self;
9579
9580 fn into_element(self) -> Self::Element {
9581 self
9582 }
9583}
9584
9585pub struct EditorLayout {
9586 position_map: Rc<PositionMap>,
9587 hitbox: Hitbox,
9588 gutter_hitbox: Hitbox,
9589 content_origin: gpui::Point<Pixels>,
9590 scrollbars_layout: Option<EditorScrollbars>,
9591 minimap: Option<MinimapLayout>,
9592 mode: EditorMode,
9593 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
9594 indent_guides: Option<Vec<IndentGuideLayout>>,
9595 visible_display_row_range: Range<DisplayRow>,
9596 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
9597 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
9598 line_elements: SmallVec<[AnyElement; 1]>,
9599 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
9600 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
9601 blamed_display_rows: Option<Vec<AnyElement>>,
9602 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
9603 inline_blame_layout: Option<InlineBlameLayout>,
9604 inline_code_actions: Option<AnyElement>,
9605 blocks: Vec<BlockLayout>,
9606 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
9607 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
9608 redacted_ranges: Vec<Range<DisplayPoint>>,
9609 cursors: Vec<(DisplayPoint, Hsla)>,
9610 visible_cursors: Vec<CursorLayout>,
9611 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
9612 test_indicators: Vec<AnyElement>,
9613 breakpoints: Vec<AnyElement>,
9614 crease_toggles: Vec<Option<AnyElement>>,
9615 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
9616 diff_hunk_controls: Vec<AnyElement>,
9617 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
9618 edit_prediction_popover: Option<AnyElement>,
9619 mouse_context_menu: Option<AnyElement>,
9620 tab_invisible: ShapedLine,
9621 space_invisible: ShapedLine,
9622 sticky_buffer_header: Option<AnyElement>,
9623 document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
9624}
9625
9626impl EditorLayout {
9627 fn line_end_overshoot(&self) -> Pixels {
9628 0.15 * self.position_map.line_height
9629 }
9630}
9631
9632struct LineNumberLayout {
9633 shaped_line: ShapedLine,
9634 hitbox: Option<Hitbox>,
9635}
9636
9637struct ColoredRange<T> {
9638 start: T,
9639 end: T,
9640 color: Hsla,
9641}
9642
9643impl Along for ScrollbarAxes {
9644 type Unit = bool;
9645
9646 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
9647 match axis {
9648 ScrollbarAxis::Horizontal => self.horizontal,
9649 ScrollbarAxis::Vertical => self.vertical,
9650 }
9651 }
9652
9653 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
9654 match axis {
9655 ScrollbarAxis::Horizontal => ScrollbarAxes {
9656 horizontal: f(self.horizontal),
9657 vertical: self.vertical,
9658 },
9659 ScrollbarAxis::Vertical => ScrollbarAxes {
9660 horizontal: self.horizontal,
9661 vertical: f(self.vertical),
9662 },
9663 }
9664 }
9665}
9666
9667#[derive(Clone)]
9668struct EditorScrollbars {
9669 pub vertical: Option<ScrollbarLayout>,
9670 pub horizontal: Option<ScrollbarLayout>,
9671 pub visible: bool,
9672}
9673
9674impl EditorScrollbars {
9675 pub fn from_scrollbar_axes(
9676 show_scrollbar: ScrollbarAxes,
9677 layout_information: &ScrollbarLayoutInformation,
9678 content_offset: gpui::Point<Pixels>,
9679 scroll_position: gpui::Point<f32>,
9680 scrollbar_width: Pixels,
9681 right_margin: Pixels,
9682 editor_width: Pixels,
9683 show_scrollbars: bool,
9684 scrollbar_state: Option<&ActiveScrollbarState>,
9685 window: &mut Window,
9686 ) -> Self {
9687 let ScrollbarLayoutInformation {
9688 editor_bounds,
9689 scroll_range,
9690 glyph_grid_cell,
9691 } = layout_information;
9692
9693 let viewport_size = size(editor_width, editor_bounds.size.height);
9694
9695 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
9696 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
9697 Corner::BottomLeft,
9698 editor_bounds.bottom_left(),
9699 size(
9700 // The horizontal viewport size differs from the space available for the
9701 // horizontal scrollbar, so we have to manually stitch it together here.
9702 editor_bounds.size.width - right_margin,
9703 scrollbar_width,
9704 ),
9705 ),
9706 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
9707 Corner::TopRight,
9708 editor_bounds.top_right(),
9709 size(scrollbar_width, viewport_size.height),
9710 ),
9711 };
9712
9713 let mut create_scrollbar_layout = |axis| {
9714 let viewport_size = viewport_size.along(axis);
9715 let scroll_range = scroll_range.along(axis);
9716
9717 // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
9718 (show_scrollbar.along(axis)
9719 && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
9720 .then(|| {
9721 ScrollbarLayout::new(
9722 window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
9723 viewport_size,
9724 scroll_range,
9725 glyph_grid_cell.along(axis),
9726 content_offset.along(axis),
9727 scroll_position.along(axis),
9728 show_scrollbars,
9729 axis,
9730 )
9731 .with_thumb_state(
9732 scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
9733 )
9734 })
9735 };
9736
9737 Self {
9738 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
9739 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
9740 visible: show_scrollbars,
9741 }
9742 }
9743
9744 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
9745 [
9746 (&self.vertical, ScrollbarAxis::Vertical),
9747 (&self.horizontal, ScrollbarAxis::Horizontal),
9748 ]
9749 .into_iter()
9750 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
9751 }
9752
9753 /// Returns the currently hovered scrollbar axis, if any.
9754 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
9755 self.iter_scrollbars()
9756 .find(|s| s.0.hitbox.is_hovered(window))
9757 }
9758}
9759
9760#[derive(Clone)]
9761struct ScrollbarLayout {
9762 hitbox: Hitbox,
9763 visible_range: Range<f32>,
9764 text_unit_size: Pixels,
9765 thumb_bounds: Option<Bounds<Pixels>>,
9766 thumb_state: ScrollbarThumbState,
9767}
9768
9769impl ScrollbarLayout {
9770 const BORDER_WIDTH: Pixels = px(1.0);
9771 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
9772 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
9773 const MIN_THUMB_SIZE: Pixels = px(25.0);
9774
9775 fn new(
9776 scrollbar_track_hitbox: Hitbox,
9777 viewport_size: Pixels,
9778 scroll_range: Pixels,
9779 glyph_space: Pixels,
9780 content_offset: Pixels,
9781 scroll_position: f32,
9782 show_thumb: bool,
9783 axis: ScrollbarAxis,
9784 ) -> Self {
9785 let track_bounds = scrollbar_track_hitbox.bounds;
9786 // The length of the track available to the scrollbar thumb. We deliberately
9787 // exclude the content size here so that the thumb aligns with the content.
9788 let track_length = track_bounds.size.along(axis) - content_offset;
9789
9790 Self::new_with_hitbox_and_track_length(
9791 scrollbar_track_hitbox,
9792 track_length,
9793 viewport_size,
9794 scroll_range,
9795 glyph_space,
9796 content_offset,
9797 scroll_position,
9798 show_thumb,
9799 axis,
9800 )
9801 }
9802
9803 fn for_minimap(
9804 minimap_track_hitbox: Hitbox,
9805 visible_lines: f32,
9806 total_editor_lines: f32,
9807 minimap_line_height: Pixels,
9808 scroll_position: f32,
9809 minimap_scroll_top: f32,
9810 show_thumb: bool,
9811 ) -> Self {
9812 // The scrollbar thumb size is calculated as
9813 // (visible_content/total_content) Γ scrollbar_track_length.
9814 //
9815 // For the minimap's thumb layout, we leverage this by setting the
9816 // scrollbar track length to the entire document size (using minimap line
9817 // height). This creates a thumb that exactly represents the editor
9818 // viewport scaled to minimap proportions.
9819 //
9820 // We adjust the thumb position relative to `minimap_scroll_top` to
9821 // accommodate for the deliberately oversized track.
9822 //
9823 // This approach ensures that the minimap thumb accurately reflects the
9824 // editor's current scroll position whilst nicely synchronizing the minimap
9825 // thumb and scrollbar thumb.
9826 let scroll_range = total_editor_lines * minimap_line_height;
9827 let viewport_size = visible_lines * minimap_line_height;
9828
9829 let track_top_offset = -minimap_scroll_top * minimap_line_height;
9830
9831 Self::new_with_hitbox_and_track_length(
9832 minimap_track_hitbox,
9833 scroll_range,
9834 viewport_size,
9835 scroll_range,
9836 minimap_line_height,
9837 track_top_offset,
9838 scroll_position,
9839 show_thumb,
9840 ScrollbarAxis::Vertical,
9841 )
9842 }
9843
9844 fn new_with_hitbox_and_track_length(
9845 scrollbar_track_hitbox: Hitbox,
9846 track_length: Pixels,
9847 viewport_size: Pixels,
9848 scroll_range: Pixels,
9849 glyph_space: Pixels,
9850 content_offset: Pixels,
9851 scroll_position: f32,
9852 show_thumb: bool,
9853 axis: ScrollbarAxis,
9854 ) -> Self {
9855 let text_units_per_page = viewport_size / glyph_space;
9856 let visible_range = scroll_position..scroll_position + text_units_per_page;
9857 let total_text_units = scroll_range / glyph_space;
9858
9859 let thumb_percentage = text_units_per_page / total_text_units;
9860 let thumb_size = (track_length * thumb_percentage)
9861 .max(ScrollbarLayout::MIN_THUMB_SIZE)
9862 .min(track_length);
9863
9864 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
9865
9866 let content_larger_than_viewport = text_unit_divisor > 0.;
9867
9868 let text_unit_size = if content_larger_than_viewport {
9869 (track_length - thumb_size) / text_unit_divisor
9870 } else {
9871 glyph_space
9872 };
9873
9874 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
9875 Self::thumb_bounds(
9876 &scrollbar_track_hitbox,
9877 content_offset,
9878 visible_range.start,
9879 text_unit_size,
9880 thumb_size,
9881 axis,
9882 )
9883 });
9884
9885 ScrollbarLayout {
9886 hitbox: scrollbar_track_hitbox,
9887 visible_range,
9888 text_unit_size,
9889 thumb_bounds,
9890 thumb_state: Default::default(),
9891 }
9892 }
9893
9894 fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
9895 if let Some(thumb_state) = thumb_state {
9896 Self {
9897 thumb_state,
9898 ..self
9899 }
9900 } else {
9901 self
9902 }
9903 }
9904
9905 fn thumb_bounds(
9906 scrollbar_track: &Hitbox,
9907 content_offset: Pixels,
9908 visible_range_start: f32,
9909 text_unit_size: Pixels,
9910 thumb_size: Pixels,
9911 axis: ScrollbarAxis,
9912 ) -> Bounds<Pixels> {
9913 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
9914 origin + content_offset + visible_range_start * text_unit_size
9915 });
9916 Bounds::new(
9917 thumb_origin,
9918 scrollbar_track.size.apply_along(axis, |_| thumb_size),
9919 )
9920 }
9921
9922 fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
9923 self.thumb_bounds
9924 .is_some_and(|bounds| bounds.contains(position))
9925 }
9926
9927 fn marker_quads_for_ranges(
9928 &self,
9929 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
9930 column: Option<usize>,
9931 ) -> Vec<PaintQuad> {
9932 struct MinMax {
9933 min: Pixels,
9934 max: Pixels,
9935 }
9936 let (x_range, height_limit) = if let Some(column) = column {
9937 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
9938 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
9939 let end = start + column_width;
9940 (
9941 Range { start, end },
9942 MinMax {
9943 min: Self::MIN_MARKER_HEIGHT,
9944 max: px(f32::MAX),
9945 },
9946 )
9947 } else {
9948 (
9949 Range {
9950 start: Self::BORDER_WIDTH,
9951 end: self.hitbox.size.width,
9952 },
9953 MinMax {
9954 min: Self::LINE_MARKER_HEIGHT,
9955 max: Self::LINE_MARKER_HEIGHT,
9956 },
9957 )
9958 };
9959
9960 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
9961 let mut pixel_ranges = row_ranges
9962 .into_iter()
9963 .map(|range| {
9964 let start_y = row_to_y(range.start);
9965 let end_y = row_to_y(range.end)
9966 + self
9967 .text_unit_size
9968 .max(height_limit.min)
9969 .min(height_limit.max);
9970 ColoredRange {
9971 start: start_y,
9972 end: end_y,
9973 color: range.color,
9974 }
9975 })
9976 .peekable();
9977
9978 let mut quads = Vec::new();
9979 while let Some(mut pixel_range) = pixel_ranges.next() {
9980 while let Some(next_pixel_range) = pixel_ranges.peek() {
9981 if pixel_range.end >= next_pixel_range.start - px(1.0)
9982 && pixel_range.color == next_pixel_range.color
9983 {
9984 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
9985 pixel_ranges.next();
9986 } else {
9987 break;
9988 }
9989 }
9990
9991 let bounds = Bounds::from_corners(
9992 point(x_range.start, pixel_range.start),
9993 point(x_range.end, pixel_range.end),
9994 );
9995 quads.push(quad(
9996 bounds,
9997 Corners::default(),
9998 pixel_range.color,
9999 Edges::default(),
10000 Hsla::transparent_black(),
10001 BorderStyle::default(),
10002 ));
10003 }
10004
10005 quads
10006 }
10007}
10008
10009struct MinimapLayout {
10010 pub minimap: AnyElement,
10011 pub thumb_layout: ScrollbarLayout,
10012 pub minimap_scroll_top: f32,
10013 pub minimap_line_height: Pixels,
10014 pub thumb_border_style: MinimapThumbBorder,
10015 pub max_scroll_top: f32,
10016}
10017
10018impl MinimapLayout {
10019 /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
10020 const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
10021 /// The minimap width as a percentage of the editor width.
10022 const MINIMAP_WIDTH_PCT: f32 = 0.15;
10023 /// Calculates the scroll top offset the minimap editor has to have based on the
10024 /// current scroll progress.
10025 fn calculate_minimap_top_offset(
10026 document_lines: f32,
10027 visible_editor_lines: f32,
10028 visible_minimap_lines: f32,
10029 scroll_position: f32,
10030 ) -> f32 {
10031 let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
10032 if non_visible_document_lines == 0. {
10033 0.
10034 } else {
10035 let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
10036 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
10037 }
10038 }
10039}
10040
10041struct CreaseTrailerLayout {
10042 element: AnyElement,
10043 bounds: Bounds<Pixels>,
10044}
10045
10046pub(crate) struct PositionMap {
10047 pub size: Size<Pixels>,
10048 pub line_height: Pixels,
10049 pub scroll_pixel_position: gpui::Point<Pixels>,
10050 pub scroll_max: gpui::Point<f32>,
10051 pub em_width: Pixels,
10052 pub em_advance: Pixels,
10053 pub visible_row_range: Range<DisplayRow>,
10054 pub line_layouts: Vec<LineWithInvisibles>,
10055 pub snapshot: EditorSnapshot,
10056 pub text_hitbox: Hitbox,
10057 pub gutter_hitbox: Hitbox,
10058 pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
10059 pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
10060 pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
10061}
10062
10063#[derive(Debug, Copy, Clone)]
10064pub struct PointForPosition {
10065 pub previous_valid: DisplayPoint,
10066 pub next_valid: DisplayPoint,
10067 pub exact_unclipped: DisplayPoint,
10068 pub column_overshoot_after_line_end: u32,
10069}
10070
10071impl PointForPosition {
10072 pub fn as_valid(&self) -> Option<DisplayPoint> {
10073 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
10074 Some(self.previous_valid)
10075 } else {
10076 None
10077 }
10078 }
10079
10080 pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
10081 let Some(valid_point) = self.as_valid() else {
10082 return false;
10083 };
10084 let range = selection.range();
10085
10086 let candidate_row = valid_point.row();
10087 let candidate_col = valid_point.column();
10088
10089 let start_row = range.start.row();
10090 let start_col = range.start.column();
10091 let end_row = range.end.row();
10092 let end_col = range.end.column();
10093
10094 if candidate_row < start_row || candidate_row > end_row {
10095 false
10096 } else if start_row == end_row {
10097 candidate_col >= start_col && candidate_col < end_col
10098 } else if candidate_row == start_row {
10099 candidate_col >= start_col
10100 } else if candidate_row == end_row {
10101 candidate_col < end_col
10102 } else {
10103 true
10104 }
10105 }
10106}
10107
10108impl PositionMap {
10109 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
10110 let text_bounds = self.text_hitbox.bounds;
10111 let scroll_position = self.snapshot.scroll_position();
10112 let position = position - text_bounds.origin;
10113 let y = position.y.max(px(0.)).min(self.size.height);
10114 let x = position.x + (scroll_position.x * self.em_advance);
10115 let row = ((y / self.line_height) + scroll_position.y) as u32;
10116
10117 let (column, x_overshoot_after_line_end) = if let Some(line) = self
10118 .line_layouts
10119 .get(row as usize - scroll_position.y as usize)
10120 {
10121 if let Some(ix) = line.index_for_x(x) {
10122 (ix as u32, px(0.))
10123 } else {
10124 (line.len as u32, px(0.).max(x - line.width))
10125 }
10126 } else {
10127 (0, x)
10128 };
10129
10130 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
10131 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
10132 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
10133
10134 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
10135 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
10136 PointForPosition {
10137 previous_valid,
10138 next_valid,
10139 exact_unclipped,
10140 column_overshoot_after_line_end,
10141 }
10142 }
10143}
10144
10145struct BlockLayout {
10146 id: BlockId,
10147 x_offset: Pixels,
10148 row: Option<DisplayRow>,
10149 element: AnyElement,
10150 available_space: Size<AvailableSpace>,
10151 style: BlockStyle,
10152 overlaps_gutter: bool,
10153 is_buffer_header: bool,
10154}
10155
10156pub fn layout_line(
10157 row: DisplayRow,
10158 snapshot: &EditorSnapshot,
10159 style: &EditorStyle,
10160 text_width: Pixels,
10161 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
10162 window: &mut Window,
10163 cx: &mut App,
10164) -> LineWithInvisibles {
10165 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
10166 LineWithInvisibles::from_chunks(
10167 chunks,
10168 style,
10169 MAX_LINE_LEN,
10170 1,
10171 &snapshot.mode,
10172 text_width,
10173 is_row_soft_wrapped,
10174 &[],
10175 window,
10176 cx,
10177 )
10178 .pop()
10179 .unwrap()
10180}
10181
10182#[derive(Debug)]
10183pub struct IndentGuideLayout {
10184 origin: gpui::Point<Pixels>,
10185 length: Pixels,
10186 single_indent_width: Pixels,
10187 depth: u32,
10188 active: bool,
10189 settings: IndentGuideSettings,
10190}
10191
10192pub struct CursorLayout {
10193 origin: gpui::Point<Pixels>,
10194 block_width: Pixels,
10195 line_height: Pixels,
10196 color: Hsla,
10197 shape: CursorShape,
10198 block_text: Option<ShapedLine>,
10199 cursor_name: Option<AnyElement>,
10200}
10201
10202#[derive(Debug)]
10203pub struct CursorName {
10204 string: SharedString,
10205 color: Hsla,
10206 is_top_row: bool,
10207}
10208
10209impl CursorLayout {
10210 pub fn new(
10211 origin: gpui::Point<Pixels>,
10212 block_width: Pixels,
10213 line_height: Pixels,
10214 color: Hsla,
10215 shape: CursorShape,
10216 block_text: Option<ShapedLine>,
10217 ) -> CursorLayout {
10218 CursorLayout {
10219 origin,
10220 block_width,
10221 line_height,
10222 color,
10223 shape,
10224 block_text,
10225 cursor_name: None,
10226 }
10227 }
10228
10229 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
10230 Bounds {
10231 origin: self.origin + origin,
10232 size: size(self.block_width, self.line_height),
10233 }
10234 }
10235
10236 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
10237 match self.shape {
10238 CursorShape::Bar => Bounds {
10239 origin: self.origin + origin,
10240 size: size(px(2.0), self.line_height),
10241 },
10242 CursorShape::Block | CursorShape::Hollow => Bounds {
10243 origin: self.origin + origin,
10244 size: size(self.block_width, self.line_height),
10245 },
10246 CursorShape::Underline => Bounds {
10247 origin: self.origin
10248 + origin
10249 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
10250 size: size(self.block_width, px(2.0)),
10251 },
10252 }
10253 }
10254
10255 pub fn layout(
10256 &mut self,
10257 origin: gpui::Point<Pixels>,
10258 cursor_name: Option<CursorName>,
10259 window: &mut Window,
10260 cx: &mut App,
10261 ) {
10262 if let Some(cursor_name) = cursor_name {
10263 let bounds = self.bounds(origin);
10264 let text_size = self.line_height / 1.5;
10265
10266 let name_origin = if cursor_name.is_top_row {
10267 point(bounds.right() - px(1.), bounds.top())
10268 } else {
10269 match self.shape {
10270 CursorShape::Bar => point(
10271 bounds.right() - px(2.),
10272 bounds.top() - text_size / 2. - px(1.),
10273 ),
10274 _ => point(
10275 bounds.right() - px(1.),
10276 bounds.top() - text_size / 2. - px(1.),
10277 ),
10278 }
10279 };
10280 let mut name_element = div()
10281 .bg(self.color)
10282 .text_size(text_size)
10283 .px_0p5()
10284 .line_height(text_size + px(2.))
10285 .text_color(cursor_name.color)
10286 .child(cursor_name.string)
10287 .into_any_element();
10288
10289 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
10290
10291 self.cursor_name = Some(name_element);
10292 }
10293 }
10294
10295 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
10296 let bounds = self.bounds(origin);
10297
10298 //Draw background or border quad
10299 let cursor = if matches!(self.shape, CursorShape::Hollow) {
10300 outline(bounds, self.color, BorderStyle::Solid)
10301 } else {
10302 fill(bounds, self.color)
10303 };
10304
10305 if let Some(name) = &mut self.cursor_name {
10306 name.paint(window, cx);
10307 }
10308
10309 window.paint_quad(cursor);
10310
10311 if let Some(block_text) = &self.block_text {
10312 block_text
10313 .paint(self.origin + origin, self.line_height, window, cx)
10314 .log_err();
10315 }
10316 }
10317
10318 pub fn shape(&self) -> CursorShape {
10319 self.shape
10320 }
10321}
10322
10323#[derive(Debug)]
10324pub struct HighlightedRange {
10325 pub start_y: Pixels,
10326 pub line_height: Pixels,
10327 pub lines: Vec<HighlightedRangeLine>,
10328 pub color: Hsla,
10329 pub corner_radius: Pixels,
10330}
10331
10332#[derive(Debug)]
10333pub struct HighlightedRangeLine {
10334 pub start_x: Pixels,
10335 pub end_x: Pixels,
10336}
10337
10338impl HighlightedRange {
10339 pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
10340 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
10341 self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
10342 self.paint_lines(
10343 self.start_y + self.line_height,
10344 &self.lines[1..],
10345 fill,
10346 bounds,
10347 window,
10348 );
10349 } else {
10350 self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
10351 }
10352 }
10353
10354 fn paint_lines(
10355 &self,
10356 start_y: Pixels,
10357 lines: &[HighlightedRangeLine],
10358 fill: bool,
10359 _bounds: Bounds<Pixels>,
10360 window: &mut Window,
10361 ) {
10362 if lines.is_empty() {
10363 return;
10364 }
10365
10366 let first_line = lines.first().unwrap();
10367 let last_line = lines.last().unwrap();
10368
10369 let first_top_left = point(first_line.start_x, start_y);
10370 let first_top_right = point(first_line.end_x, start_y);
10371
10372 let curve_height = point(Pixels::ZERO, self.corner_radius);
10373 let curve_width = |start_x: Pixels, end_x: Pixels| {
10374 let max = (end_x - start_x) / 2.;
10375 let width = if max < self.corner_radius {
10376 max
10377 } else {
10378 self.corner_radius
10379 };
10380
10381 point(width, Pixels::ZERO)
10382 };
10383
10384 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
10385 let mut builder = if fill {
10386 gpui::PathBuilder::fill()
10387 } else {
10388 gpui::PathBuilder::stroke(px(1.))
10389 };
10390 builder.move_to(first_top_right - top_curve_width);
10391 builder.curve_to(first_top_right + curve_height, first_top_right);
10392
10393 let mut iter = lines.iter().enumerate().peekable();
10394 while let Some((ix, line)) = iter.next() {
10395 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
10396
10397 if let Some((_, next_line)) = iter.peek() {
10398 let next_top_right = point(next_line.end_x, bottom_right.y);
10399
10400 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
10401 Ordering::Equal => {
10402 builder.line_to(bottom_right);
10403 }
10404 Ordering::Less => {
10405 let curve_width = curve_width(next_top_right.x, bottom_right.x);
10406 builder.line_to(bottom_right - curve_height);
10407 if self.corner_radius > Pixels::ZERO {
10408 builder.curve_to(bottom_right - curve_width, bottom_right);
10409 }
10410 builder.line_to(next_top_right + curve_width);
10411 if self.corner_radius > Pixels::ZERO {
10412 builder.curve_to(next_top_right + curve_height, next_top_right);
10413 }
10414 }
10415 Ordering::Greater => {
10416 let curve_width = curve_width(bottom_right.x, next_top_right.x);
10417 builder.line_to(bottom_right - curve_height);
10418 if self.corner_radius > Pixels::ZERO {
10419 builder.curve_to(bottom_right + curve_width, bottom_right);
10420 }
10421 builder.line_to(next_top_right - curve_width);
10422 if self.corner_radius > Pixels::ZERO {
10423 builder.curve_to(next_top_right + curve_height, next_top_right);
10424 }
10425 }
10426 }
10427 } else {
10428 let curve_width = curve_width(line.start_x, line.end_x);
10429 builder.line_to(bottom_right - curve_height);
10430 if self.corner_radius > Pixels::ZERO {
10431 builder.curve_to(bottom_right - curve_width, bottom_right);
10432 }
10433
10434 let bottom_left = point(line.start_x, bottom_right.y);
10435 builder.line_to(bottom_left + curve_width);
10436 if self.corner_radius > Pixels::ZERO {
10437 builder.curve_to(bottom_left - curve_height, bottom_left);
10438 }
10439 }
10440 }
10441
10442 if first_line.start_x > last_line.start_x {
10443 let curve_width = curve_width(last_line.start_x, first_line.start_x);
10444 let second_top_left = point(last_line.start_x, start_y + self.line_height);
10445 builder.line_to(second_top_left + curve_height);
10446 if self.corner_radius > Pixels::ZERO {
10447 builder.curve_to(second_top_left + curve_width, second_top_left);
10448 }
10449 let first_bottom_left = point(first_line.start_x, second_top_left.y);
10450 builder.line_to(first_bottom_left - curve_width);
10451 if self.corner_radius > Pixels::ZERO {
10452 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
10453 }
10454 }
10455
10456 builder.line_to(first_top_left + curve_height);
10457 if self.corner_radius > Pixels::ZERO {
10458 builder.curve_to(first_top_left + top_curve_width, first_top_left);
10459 }
10460 builder.line_to(first_top_right - top_curve_width);
10461
10462 if let Ok(path) = builder.build() {
10463 window.paint_path(path, self.color);
10464 }
10465 }
10466}
10467
10468enum CursorPopoverType {
10469 CodeContextMenu,
10470 EditPrediction,
10471}
10472
10473pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10474 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
10475}
10476
10477fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10478 (delta.pow(1.2) / 300.0).into()
10479}
10480
10481pub fn register_action<T: Action>(
10482 editor: &Entity<Editor>,
10483 window: &mut Window,
10484 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
10485) {
10486 let editor = editor.clone();
10487 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
10488 let action = action.downcast_ref().unwrap();
10489 if phase == DispatchPhase::Bubble {
10490 editor.update(cx, |editor, cx| {
10491 listener(editor, action, window, cx);
10492 })
10493 }
10494 })
10495}
10496
10497fn compute_auto_height_layout(
10498 editor: &mut Editor,
10499 min_lines: usize,
10500 max_lines: Option<usize>,
10501 max_line_number_width: Pixels,
10502 known_dimensions: Size<Option<Pixels>>,
10503 available_width: AvailableSpace,
10504 window: &mut Window,
10505 cx: &mut Context<Editor>,
10506) -> Option<Size<Pixels>> {
10507 let width = known_dimensions.width.or({
10508 if let AvailableSpace::Definite(available_width) = available_width {
10509 Some(available_width)
10510 } else {
10511 None
10512 }
10513 })?;
10514 if let Some(height) = known_dimensions.height {
10515 return Some(size(width, height));
10516 }
10517
10518 let style = editor.style.as_ref().unwrap();
10519 let font_id = window.text_system().resolve_font(&style.text.font());
10520 let font_size = style.text.font_size.to_pixels(window.rem_size());
10521 let line_height = style.text.line_height_in_pixels(window.rem_size());
10522 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
10523
10524 let mut snapshot = editor.snapshot(window, cx);
10525 let gutter_dimensions = snapshot
10526 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
10527 .or_else(|| {
10528 editor
10529 .offset_content
10530 .then(|| GutterDimensions::default_with_margin(font_id, font_size, cx))
10531 })
10532 .unwrap_or_default();
10533
10534 editor.gutter_dimensions = gutter_dimensions;
10535 let text_width = width - gutter_dimensions.width;
10536 let overscroll = size(em_width, px(0.));
10537
10538 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
10539 if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None)
10540 && editor.set_wrap_width(Some(editor_width), cx)
10541 {
10542 snapshot = editor.snapshot(window, cx);
10543 }
10544
10545 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
10546
10547 let min_height = line_height * min_lines as f32;
10548 let content_height = scroll_height.max(min_height);
10549
10550 let final_height = if let Some(max_lines) = max_lines {
10551 let max_height = line_height * max_lines as f32;
10552 content_height.min(max_height)
10553 } else {
10554 content_height
10555 };
10556
10557 Some(size(width, final_height))
10558}
10559
10560#[cfg(test)]
10561mod tests {
10562 use super::*;
10563 use crate::{
10564 Editor, MultiBuffer, SelectionEffects,
10565 display_map::{BlockPlacement, BlockProperties},
10566 editor_tests::{init_test, update_test_language_settings},
10567 };
10568 use gpui::{TestAppContext, VisualTestContext};
10569 use language::language_settings;
10570 use log::info;
10571 use std::num::NonZeroU32;
10572 use util::test::sample_text;
10573
10574 #[gpui::test]
10575 async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
10576 init_test(cx, |_| {});
10577
10578 let window = cx.add_window(|window, cx| {
10579 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
10580 let mut editor = Editor::new(
10581 EditorMode::AutoHeight {
10582 min_lines: 1,
10583 max_lines: None,
10584 },
10585 buffer,
10586 None,
10587 window,
10588 cx,
10589 );
10590 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10591 editor
10592 });
10593 let cx = &mut VisualTestContext::from_window(*window, cx);
10594 let editor = window.root(cx).unwrap();
10595 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10596
10597 for x in 1..=100 {
10598 let (_, state) = cx.draw(
10599 Default::default(),
10600 size(px(200. + 0.13 * x as f32), px(500.)),
10601 |_, _| EditorElement::new(&editor, style.clone()),
10602 );
10603
10604 assert!(
10605 state.position_map.scroll_max.x == 0.,
10606 "Soft wrapped editor should have no horizontal scrolling!"
10607 );
10608 }
10609 }
10610
10611 #[gpui::test]
10612 async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
10613 init_test(cx, |_| {});
10614
10615 let window = cx.add_window(|window, cx| {
10616 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
10617 let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
10618 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10619 editor
10620 });
10621 let cx = &mut VisualTestContext::from_window(*window, cx);
10622 let editor = window.root(cx).unwrap();
10623 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10624
10625 for x in 1..=100 {
10626 let (_, state) = cx.draw(
10627 Default::default(),
10628 size(px(200. + 0.13 * x as f32), px(500.)),
10629 |_, _| EditorElement::new(&editor, style.clone()),
10630 );
10631
10632 assert!(
10633 state.position_map.scroll_max.x == 0.,
10634 "Soft wrapped editor should have no horizontal scrolling!"
10635 );
10636 }
10637 }
10638
10639 #[gpui::test]
10640 fn test_shape_line_numbers(cx: &mut TestAppContext) {
10641 init_test(cx, |_| {});
10642 let window = cx.add_window(|window, cx| {
10643 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
10644 Editor::new(EditorMode::full(), buffer, None, window, cx)
10645 });
10646
10647 let editor = window.root(cx).unwrap();
10648 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
10649 let line_height = window
10650 .update(cx, |_, window, _| {
10651 style.text.line_height_in_pixels(window.rem_size())
10652 })
10653 .unwrap();
10654 let element = EditorElement::new(&editor, style);
10655 let snapshot = window
10656 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
10657 .unwrap();
10658
10659 let layouts = cx
10660 .update_window(*window, |_, window, cx| {
10661 element.layout_line_numbers(
10662 None,
10663 GutterDimensions {
10664 left_padding: Pixels::ZERO,
10665 right_padding: Pixels::ZERO,
10666 width: px(30.0),
10667 margin: Pixels::ZERO,
10668 git_blame_entries_width: None,
10669 },
10670 line_height,
10671 gpui::Point::default(),
10672 DisplayRow(0)..DisplayRow(6),
10673 &(0..6)
10674 .map(|row| RowInfo {
10675 buffer_row: Some(row),
10676 ..Default::default()
10677 })
10678 .collect::<Vec<_>>(),
10679 &BTreeMap::default(),
10680 Some(DisplayPoint::new(DisplayRow(0), 0)),
10681 &snapshot,
10682 window,
10683 cx,
10684 )
10685 })
10686 .unwrap();
10687 assert_eq!(layouts.len(), 6);
10688
10689 let relative_rows = window
10690 .update(cx, |editor, window, cx| {
10691 let snapshot = editor.snapshot(window, cx);
10692 element.calculate_relative_line_numbers(
10693 &snapshot,
10694 &(DisplayRow(0)..DisplayRow(6)),
10695 Some(DisplayRow(3)),
10696 )
10697 })
10698 .unwrap();
10699 assert_eq!(relative_rows[&DisplayRow(0)], 3);
10700 assert_eq!(relative_rows[&DisplayRow(1)], 2);
10701 assert_eq!(relative_rows[&DisplayRow(2)], 1);
10702 // current line has no relative number
10703 assert_eq!(relative_rows[&DisplayRow(4)], 1);
10704 assert_eq!(relative_rows[&DisplayRow(5)], 2);
10705
10706 // works if cursor is before screen
10707 let relative_rows = window
10708 .update(cx, |editor, window, cx| {
10709 let snapshot = editor.snapshot(window, cx);
10710 element.calculate_relative_line_numbers(
10711 &snapshot,
10712 &(DisplayRow(3)..DisplayRow(6)),
10713 Some(DisplayRow(1)),
10714 )
10715 })
10716 .unwrap();
10717 assert_eq!(relative_rows.len(), 3);
10718 assert_eq!(relative_rows[&DisplayRow(3)], 2);
10719 assert_eq!(relative_rows[&DisplayRow(4)], 3);
10720 assert_eq!(relative_rows[&DisplayRow(5)], 4);
10721
10722 // works if cursor is after screen
10723 let relative_rows = window
10724 .update(cx, |editor, window, cx| {
10725 let snapshot = editor.snapshot(window, cx);
10726 element.calculate_relative_line_numbers(
10727 &snapshot,
10728 &(DisplayRow(0)..DisplayRow(3)),
10729 Some(DisplayRow(6)),
10730 )
10731 })
10732 .unwrap();
10733 assert_eq!(relative_rows.len(), 3);
10734 assert_eq!(relative_rows[&DisplayRow(0)], 5);
10735 assert_eq!(relative_rows[&DisplayRow(1)], 4);
10736 assert_eq!(relative_rows[&DisplayRow(2)], 3);
10737 }
10738
10739 #[gpui::test]
10740 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
10741 init_test(cx, |_| {});
10742
10743 let window = cx.add_window(|window, cx| {
10744 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
10745 Editor::new(EditorMode::full(), buffer, None, window, cx)
10746 });
10747 let cx = &mut VisualTestContext::from_window(*window, cx);
10748 let editor = window.root(cx).unwrap();
10749 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10750
10751 window
10752 .update(cx, |editor, window, cx| {
10753 editor.cursor_shape = CursorShape::Block;
10754 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
10755 s.select_ranges([
10756 Point::new(0, 0)..Point::new(1, 0),
10757 Point::new(3, 2)..Point::new(3, 3),
10758 Point::new(5, 6)..Point::new(6, 0),
10759 ]);
10760 });
10761 })
10762 .unwrap();
10763
10764 let (_, state) = cx.draw(
10765 point(px(500.), px(500.)),
10766 size(px(500.), px(500.)),
10767 |_, _| EditorElement::new(&editor, style),
10768 );
10769
10770 assert_eq!(state.selections.len(), 1);
10771 let local_selections = &state.selections[0].1;
10772 assert_eq!(local_selections.len(), 3);
10773 // moves cursor back one line
10774 assert_eq!(
10775 local_selections[0].head,
10776 DisplayPoint::new(DisplayRow(0), 6)
10777 );
10778 assert_eq!(
10779 local_selections[0].range,
10780 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
10781 );
10782
10783 // moves cursor back one column
10784 assert_eq!(
10785 local_selections[1].range,
10786 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
10787 );
10788 assert_eq!(
10789 local_selections[1].head,
10790 DisplayPoint::new(DisplayRow(3), 2)
10791 );
10792
10793 // leaves cursor on the max point
10794 assert_eq!(
10795 local_selections[2].range,
10796 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
10797 );
10798 assert_eq!(
10799 local_selections[2].head,
10800 DisplayPoint::new(DisplayRow(6), 0)
10801 );
10802
10803 // active lines does not include 1 (even though the range of the selection does)
10804 assert_eq!(
10805 state.active_rows.keys().cloned().collect::<Vec<_>>(),
10806 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
10807 );
10808 }
10809
10810 #[gpui::test]
10811 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
10812 init_test(cx, |_| {});
10813
10814 let window = cx.add_window(|window, cx| {
10815 let buffer = MultiBuffer::build_simple("", cx);
10816 Editor::new(EditorMode::full(), buffer, None, window, cx)
10817 });
10818 let cx = &mut VisualTestContext::from_window(*window, cx);
10819 let editor = window.root(cx).unwrap();
10820 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10821 window
10822 .update(cx, |editor, window, cx| {
10823 editor.set_placeholder_text("hello", window, cx);
10824 editor.insert_blocks(
10825 [BlockProperties {
10826 style: BlockStyle::Fixed,
10827 placement: BlockPlacement::Above(Anchor::min()),
10828 height: Some(3),
10829 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
10830 priority: 0,
10831 }],
10832 None,
10833 cx,
10834 );
10835
10836 // Blur the editor so that it displays placeholder text.
10837 window.blur();
10838 })
10839 .unwrap();
10840
10841 let (_, state) = cx.draw(
10842 point(px(500.), px(500.)),
10843 size(px(500.), px(500.)),
10844 |_, _| EditorElement::new(&editor, style),
10845 );
10846 assert_eq!(state.position_map.line_layouts.len(), 4);
10847 assert_eq!(state.line_numbers.len(), 1);
10848 assert_eq!(
10849 state
10850 .line_numbers
10851 .get(&MultiBufferRow(0))
10852 .map(|line_number| line_number.shaped_line.text.as_ref()),
10853 Some("1")
10854 );
10855 }
10856
10857 #[gpui::test]
10858 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
10859 const TAB_SIZE: u32 = 4;
10860
10861 let input_text = "\t \t|\t| a b";
10862 let expected_invisibles = vec![
10863 Invisible::Tab {
10864 line_start_offset: 0,
10865 line_end_offset: TAB_SIZE as usize,
10866 },
10867 Invisible::Whitespace {
10868 line_offset: TAB_SIZE as usize,
10869 },
10870 Invisible::Tab {
10871 line_start_offset: TAB_SIZE as usize + 1,
10872 line_end_offset: TAB_SIZE as usize * 2,
10873 },
10874 Invisible::Tab {
10875 line_start_offset: TAB_SIZE as usize * 2 + 1,
10876 line_end_offset: TAB_SIZE as usize * 3,
10877 },
10878 Invisible::Whitespace {
10879 line_offset: TAB_SIZE as usize * 3 + 1,
10880 },
10881 Invisible::Whitespace {
10882 line_offset: TAB_SIZE as usize * 3 + 3,
10883 },
10884 ];
10885 assert_eq!(
10886 expected_invisibles.len(),
10887 input_text
10888 .chars()
10889 .filter(|initial_char| initial_char.is_whitespace())
10890 .count(),
10891 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10892 );
10893
10894 for show_line_numbers in [true, false] {
10895 init_test(cx, |s| {
10896 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10897 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
10898 });
10899
10900 let actual_invisibles = collect_invisibles_from_new_editor(
10901 cx,
10902 EditorMode::full(),
10903 input_text,
10904 px(500.0),
10905 show_line_numbers,
10906 );
10907
10908 assert_eq!(expected_invisibles, actual_invisibles);
10909 }
10910 }
10911
10912 #[gpui::test]
10913 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
10914 init_test(cx, |s| {
10915 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10916 s.defaults.tab_size = NonZeroU32::new(4);
10917 });
10918
10919 for editor_mode_without_invisibles in [
10920 EditorMode::SingleLine,
10921 EditorMode::AutoHeight {
10922 min_lines: 1,
10923 max_lines: Some(100),
10924 },
10925 ] {
10926 for show_line_numbers in [true, false] {
10927 let invisibles = collect_invisibles_from_new_editor(
10928 cx,
10929 editor_mode_without_invisibles.clone(),
10930 "\t\t\t| | a b",
10931 px(500.0),
10932 show_line_numbers,
10933 );
10934 assert!(
10935 invisibles.is_empty(),
10936 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
10937 );
10938 }
10939 }
10940 }
10941
10942 #[gpui::test]
10943 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
10944 let tab_size = 4;
10945 let input_text = "a\tbcd ".repeat(9);
10946 let repeated_invisibles = [
10947 Invisible::Tab {
10948 line_start_offset: 1,
10949 line_end_offset: tab_size as usize,
10950 },
10951 Invisible::Whitespace {
10952 line_offset: tab_size as usize + 3,
10953 },
10954 Invisible::Whitespace {
10955 line_offset: tab_size as usize + 4,
10956 },
10957 Invisible::Whitespace {
10958 line_offset: tab_size as usize + 5,
10959 },
10960 Invisible::Whitespace {
10961 line_offset: tab_size as usize + 6,
10962 },
10963 Invisible::Whitespace {
10964 line_offset: tab_size as usize + 7,
10965 },
10966 ];
10967 let expected_invisibles = std::iter::once(repeated_invisibles)
10968 .cycle()
10969 .take(9)
10970 .flatten()
10971 .collect::<Vec<_>>();
10972 assert_eq!(
10973 expected_invisibles.len(),
10974 input_text
10975 .chars()
10976 .filter(|initial_char| initial_char.is_whitespace())
10977 .count(),
10978 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10979 );
10980 info!("Expected invisibles: {expected_invisibles:?}");
10981
10982 init_test(cx, |_| {});
10983
10984 // Put the same string with repeating whitespace pattern into editors of various size,
10985 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
10986 let resize_step = 10.0;
10987 let mut editor_width = 200.0;
10988 while editor_width <= 1000.0 {
10989 for show_line_numbers in [true, false] {
10990 update_test_language_settings(cx, |s| {
10991 s.defaults.tab_size = NonZeroU32::new(tab_size);
10992 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10993 s.defaults.preferred_line_length = Some(editor_width as u32);
10994 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
10995 });
10996
10997 let actual_invisibles = collect_invisibles_from_new_editor(
10998 cx,
10999 EditorMode::full(),
11000 &input_text,
11001 px(editor_width),
11002 show_line_numbers,
11003 );
11004
11005 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
11006 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
11007 let mut i = 0;
11008 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
11009 i = actual_index;
11010 match expected_invisibles.get(i) {
11011 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
11012 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
11013 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
11014 _ => {
11015 panic!(
11016 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
11017 )
11018 }
11019 },
11020 None => {
11021 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
11022 }
11023 }
11024 }
11025 let missing_expected_invisibles = &expected_invisibles[i + 1..];
11026 assert!(
11027 missing_expected_invisibles.is_empty(),
11028 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
11029 );
11030
11031 editor_width += resize_step;
11032 }
11033 }
11034 }
11035
11036 fn collect_invisibles_from_new_editor(
11037 cx: &mut TestAppContext,
11038 editor_mode: EditorMode,
11039 input_text: &str,
11040 editor_width: Pixels,
11041 show_line_numbers: bool,
11042 ) -> Vec<Invisible> {
11043 info!(
11044 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
11045 editor_width.0
11046 );
11047 let window = cx.add_window(|window, cx| {
11048 let buffer = MultiBuffer::build_simple(input_text, cx);
11049 Editor::new(editor_mode, buffer, None, window, cx)
11050 });
11051 let cx = &mut VisualTestContext::from_window(*window, cx);
11052 let editor = window.root(cx).unwrap();
11053
11054 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
11055 window
11056 .update(cx, |editor, _, cx| {
11057 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
11058 editor.set_wrap_width(Some(editor_width), cx);
11059 editor.set_show_line_numbers(show_line_numbers, cx);
11060 })
11061 .unwrap();
11062 let (_, state) = cx.draw(
11063 point(px(500.), px(500.)),
11064 size(px(500.), px(500.)),
11065 |_, _| EditorElement::new(&editor, style),
11066 );
11067 state
11068 .position_map
11069 .line_layouts
11070 .iter()
11071 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
11072 .cloned()
11073 .collect()
11074 }
11075
11076 #[gpui::test]
11077 fn test_merge_overlapping_ranges() {
11078 let base_bg = Hsla::white();
11079 let color1 = Hsla {
11080 h: 0.0,
11081 s: 0.5,
11082 l: 0.5,
11083 a: 0.5,
11084 };
11085 let color2 = Hsla {
11086 h: 120.0,
11087 s: 0.5,
11088 l: 0.5,
11089 a: 0.5,
11090 };
11091
11092 let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
11093 let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
11094 v.iter()
11095 .map(|(r, _)| (r.start.column(), r.end.column()))
11096 .collect()
11097 };
11098
11099 // Test overlapping ranges blend colors
11100 let overlapping = vec![
11101 (display_point(5)..display_point(15), color1),
11102 (display_point(10)..display_point(20), color2),
11103 ];
11104 let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
11105 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
11106
11107 // Test middle segment should have blended color
11108 let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
11109 assert_eq!(result[1].1, blended);
11110
11111 // Test adjacent same-color ranges merge
11112 let adjacent_same = vec![
11113 (display_point(5)..display_point(10), color1),
11114 (display_point(10)..display_point(15), color1),
11115 ];
11116 let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
11117 assert_eq!(cols(&result), vec![(5, 15)]);
11118
11119 // Test contained range splits
11120 let contained = vec![
11121 (display_point(5)..display_point(20), color1),
11122 (display_point(10)..display_point(15), color2),
11123 ];
11124 let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
11125 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
11126
11127 // Test multiple overlaps split at every boundary
11128 let color3 = Hsla {
11129 h: 240.0,
11130 s: 0.5,
11131 l: 0.5,
11132 a: 0.5,
11133 };
11134 let complex = vec![
11135 (display_point(5)..display_point(12), color1),
11136 (display_point(8)..display_point(16), color2),
11137 (display_point(10)..display_point(14), color3),
11138 ];
11139 let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
11140 assert_eq!(
11141 cols(&result),
11142 vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
11143 );
11144 }
11145
11146 #[gpui::test]
11147 fn test_bg_segments_per_row() {
11148 let base_bg = Hsla::white();
11149
11150 // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
11151 {
11152 let selection_color = Hsla {
11153 h: 200.0,
11154 s: 0.5,
11155 l: 0.5,
11156 a: 0.5,
11157 };
11158 let player_color = PlayerColor {
11159 cursor: selection_color,
11160 background: selection_color,
11161 selection: selection_color,
11162 };
11163
11164 let spanning_selection = SelectionLayout {
11165 head: DisplayPoint::new(DisplayRow(3), 7),
11166 cursor_shape: CursorShape::Bar,
11167 is_newest: true,
11168 is_local: true,
11169 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
11170 active_rows: DisplayRow(1)..DisplayRow(4),
11171 user_name: None,
11172 };
11173
11174 let selections = vec![(player_color, vec![spanning_selection])];
11175 let result = EditorElement::bg_segments_per_row(
11176 DisplayRow(0)..DisplayRow(5),
11177 &selections,
11178 &[],
11179 base_bg,
11180 );
11181
11182 assert_eq!(result.len(), 5);
11183 assert!(result[0].is_empty());
11184 assert_eq!(result[1].len(), 1);
11185 assert_eq!(result[2].len(), 1);
11186 assert_eq!(result[3].len(), 1);
11187 assert!(result[4].is_empty());
11188
11189 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
11190 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
11191 assert_eq!(result[1][0].0.end.column(), u32::MAX);
11192 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
11193 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
11194 assert_eq!(result[2][0].0.end.column(), u32::MAX);
11195 assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
11196 assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
11197 }
11198
11199 // Case B: selection ends exactly at the start of row 3, excluding row 3
11200 {
11201 let selection_color = Hsla {
11202 h: 120.0,
11203 s: 0.5,
11204 l: 0.5,
11205 a: 0.5,
11206 };
11207 let player_color = PlayerColor {
11208 cursor: selection_color,
11209 background: selection_color,
11210 selection: selection_color,
11211 };
11212
11213 let selection = SelectionLayout {
11214 head: DisplayPoint::new(DisplayRow(2), 0),
11215 cursor_shape: CursorShape::Bar,
11216 is_newest: true,
11217 is_local: true,
11218 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
11219 active_rows: DisplayRow(1)..DisplayRow(3),
11220 user_name: None,
11221 };
11222
11223 let selections = vec![(player_color, vec![selection])];
11224 let result = EditorElement::bg_segments_per_row(
11225 DisplayRow(0)..DisplayRow(4),
11226 &selections,
11227 &[],
11228 base_bg,
11229 );
11230
11231 assert_eq!(result.len(), 4);
11232 assert!(result[0].is_empty());
11233 assert_eq!(result[1].len(), 1);
11234 assert_eq!(result[2].len(), 1);
11235 assert!(result[3].is_empty());
11236
11237 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
11238 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
11239 assert_eq!(result[1][0].0.end.column(), u32::MAX);
11240 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
11241 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
11242 assert_eq!(result[2][0].0.end.column(), u32::MAX);
11243 }
11244 }
11245
11246 #[cfg(test)]
11247 fn generate_test_run(len: usize, color: Hsla) -> TextRun {
11248 TextRun {
11249 len,
11250 font: gpui::font(".SystemUIFont"),
11251 color,
11252 background_color: None,
11253 underline: None,
11254 strikethrough: None,
11255 }
11256 }
11257
11258 #[gpui::test]
11259 fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
11260 init_test(cx, |_| {});
11261
11262 let text_color = Hsla {
11263 h: 210.0,
11264 s: 0.1,
11265 l: 0.4,
11266 a: 1.0,
11267 };
11268 let bg1 = Hsla {
11269 h: 30.0,
11270 s: 0.6,
11271 l: 0.8,
11272 a: 1.0,
11273 };
11274 let bg2 = Hsla {
11275 h: 200.0,
11276 s: 0.6,
11277 l: 0.2,
11278 a: 1.0,
11279 };
11280 let min_contrast = 45.0;
11281
11282 // Case A: single run; disjoint segments inside the run
11283 let runs = vec![generate_test_run(20, text_color)];
11284 let segs = vec![
11285 (
11286 DisplayPoint::new(DisplayRow(0), 5)..DisplayPoint::new(DisplayRow(0), 10),
11287 bg1,
11288 ),
11289 (
11290 DisplayPoint::new(DisplayRow(0), 12)..DisplayPoint::new(DisplayRow(0), 16),
11291 bg2,
11292 ),
11293 ];
11294 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast);
11295 // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
11296 assert_eq!(
11297 out.iter().map(|r| r.len).collect::<Vec<_>>(),
11298 vec![5, 5, 2, 4, 4]
11299 );
11300 assert_eq!(out[0].color, text_color);
11301 assert_eq!(
11302 out[1].color,
11303 ensure_minimum_contrast(text_color, bg1, min_contrast)
11304 );
11305 assert_eq!(out[2].color, text_color);
11306 assert_eq!(
11307 out[3].color,
11308 ensure_minimum_contrast(text_color, bg2, min_contrast)
11309 );
11310 assert_eq!(out[4].color, text_color);
11311
11312 // Case B: multiple runs; segment extends to end of line (u32::MAX)
11313 let runs = vec![
11314 generate_test_run(8, text_color),
11315 generate_test_run(7, text_color),
11316 ];
11317 let segs = vec![(
11318 DisplayPoint::new(DisplayRow(0), 6)..DisplayPoint::new(DisplayRow(0), u32::MAX),
11319 bg1,
11320 )];
11321 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast);
11322 // Expected slices across runs: [0,6) [6,8) | [0,7)
11323 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
11324 let adjusted = ensure_minimum_contrast(text_color, bg1, min_contrast);
11325 assert_eq!(out[0].color, text_color);
11326 assert_eq!(out[1].color, adjusted);
11327 assert_eq!(out[2].color, adjusted);
11328
11329 // Case C: multi-byte characters
11330 // for text: "Hello π δΈη!"
11331 let runs = vec![
11332 generate_test_run(5, text_color), // "Hello"
11333 generate_test_run(6, text_color), // " π "
11334 generate_test_run(6, text_color), // "δΈη"
11335 generate_test_run(1, text_color), // "!"
11336 ];
11337 // selecting "π δΈ"
11338 let segs = vec![(
11339 DisplayPoint::new(DisplayRow(0), 6)..DisplayPoint::new(DisplayRow(0), 14),
11340 bg1,
11341 )];
11342 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast);
11343 // "Hello" | " " | "π " | "δΈ" | "η" | "!"
11344 assert_eq!(
11345 out.iter().map(|r| r.len).collect::<Vec<_>>(),
11346 vec![5, 1, 5, 3, 3, 1]
11347 );
11348 assert_eq!(out[0].color, text_color); // "Hello"
11349 assert_eq!(
11350 out[2].color,
11351 ensure_minimum_contrast(text_color, bg1, min_contrast)
11352 ); // "π "
11353 assert_eq!(
11354 out[3].color,
11355 ensure_minimum_contrast(text_color, bg1, min_contrast)
11356 ); // "δΈ"
11357 assert_eq!(out[4].color, text_color); // "η"
11358 assert_eq!(out[5].color, text_color); // "!"
11359 }
11360}