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