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, Modifiers, 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, text_for_keystroke,
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<(Hsla, 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,
2639 window,
2640 cx,
2641 )?;
2642
2643 let start_y = ix as f32 * line_height - (scroll_top % line_height);
2644 let absolute_offset = gutter_hitbox.origin + point(start_x, start_y);
2645
2646 element.prepaint_as_root(
2647 absolute_offset,
2648 size(width, AvailableSpace::MinContent),
2649 window,
2650 cx,
2651 );
2652
2653 Some(element)
2654 })
2655 .collect();
2656
2657 Some(shaped_lines)
2658 }
2659
2660 fn layout_indent_guides(
2661 &self,
2662 content_origin: gpui::Point<Pixels>,
2663 text_origin: gpui::Point<Pixels>,
2664 visible_buffer_range: Range<MultiBufferRow>,
2665 scroll_pixel_position: gpui::Point<Pixels>,
2666 line_height: Pixels,
2667 snapshot: &DisplaySnapshot,
2668 window: &mut Window,
2669 cx: &mut App,
2670 ) -> Option<Vec<IndentGuideLayout>> {
2671 let indent_guides = self.editor.update(cx, |editor, cx| {
2672 editor.indent_guides(visible_buffer_range, snapshot, cx)
2673 })?;
2674
2675 let active_indent_guide_indices = self.editor.update(cx, |editor, cx| {
2676 editor
2677 .find_active_indent_guide_indices(&indent_guides, snapshot, window, cx)
2678 .unwrap_or_default()
2679 });
2680
2681 Some(
2682 indent_guides
2683 .into_iter()
2684 .enumerate()
2685 .filter_map(|(i, indent_guide)| {
2686 let single_indent_width =
2687 self.column_pixels(indent_guide.tab_size as usize, window);
2688 let total_width = single_indent_width * indent_guide.depth as f32;
2689 let start_x = content_origin.x + total_width - scroll_pixel_position.x;
2690 if start_x >= text_origin.x {
2691 let (offset_y, length) = Self::calculate_indent_guide_bounds(
2692 indent_guide.start_row..indent_guide.end_row,
2693 line_height,
2694 snapshot,
2695 );
2696
2697 let start_y = content_origin.y + offset_y - scroll_pixel_position.y;
2698
2699 Some(IndentGuideLayout {
2700 origin: point(start_x, start_y),
2701 length,
2702 single_indent_width,
2703 depth: indent_guide.depth,
2704 active: active_indent_guide_indices.contains(&i),
2705 settings: indent_guide.settings,
2706 })
2707 } else {
2708 None
2709 }
2710 })
2711 .collect(),
2712 )
2713 }
2714
2715 fn layout_wrap_guides(
2716 &self,
2717 em_advance: Pixels,
2718 scroll_position: gpui::Point<f32>,
2719 content_origin: gpui::Point<Pixels>,
2720 scrollbar_layout: Option<&EditorScrollbars>,
2721 vertical_scrollbar_width: Pixels,
2722 hitbox: &Hitbox,
2723 window: &Window,
2724 cx: &App,
2725 ) -> SmallVec<[(Pixels, bool); 2]> {
2726 let scroll_left = scroll_position.x * em_advance;
2727 let content_origin = content_origin.x;
2728 let horizontal_offset = content_origin - scroll_left;
2729 let vertical_scrollbar_width = scrollbar_layout
2730 .and_then(|layout| layout.visible.then_some(vertical_scrollbar_width))
2731 .unwrap_or_default();
2732
2733 self.editor
2734 .read(cx)
2735 .wrap_guides(cx)
2736 .into_iter()
2737 .flat_map(|(guide, active)| {
2738 let wrap_position = self.column_pixels(guide, window);
2739 let wrap_guide_x = wrap_position + horizontal_offset;
2740 let display_wrap_guide = wrap_guide_x >= content_origin
2741 && wrap_guide_x <= hitbox.bounds.right() - vertical_scrollbar_width;
2742
2743 display_wrap_guide.then_some((wrap_guide_x, active))
2744 })
2745 .collect()
2746 }
2747
2748 fn calculate_indent_guide_bounds(
2749 row_range: Range<MultiBufferRow>,
2750 line_height: Pixels,
2751 snapshot: &DisplaySnapshot,
2752 ) -> (gpui::Pixels, gpui::Pixels) {
2753 let start_point = Point::new(row_range.start.0, 0);
2754 let end_point = Point::new(row_range.end.0, 0);
2755
2756 let row_range = start_point.to_display_point(snapshot).row()
2757 ..end_point.to_display_point(snapshot).row();
2758
2759 let mut prev_line = start_point;
2760 prev_line.row = prev_line.row.saturating_sub(1);
2761 let prev_line = prev_line.to_display_point(snapshot).row();
2762
2763 let mut cons_line = end_point;
2764 cons_line.row += 1;
2765 let cons_line = cons_line.to_display_point(snapshot).row();
2766
2767 let mut offset_y = row_range.start.0 as f32 * line_height;
2768 let mut length = (cons_line.0.saturating_sub(row_range.start.0)) as f32 * line_height;
2769
2770 // If we are at the end of the buffer, ensure that the indent guide extends to the end of the line.
2771 if row_range.end == cons_line {
2772 length += line_height;
2773 }
2774
2775 // If there is a block (e.g. diagnostic) in between the start of the indent guide and the line above,
2776 // we want to extend the indent guide to the start of the block.
2777 let mut block_height = 0;
2778 let mut block_offset = 0;
2779 let mut found_excerpt_header = false;
2780 for (_, block) in snapshot.blocks_in_range(prev_line..row_range.start) {
2781 if matches!(
2782 block,
2783 Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
2784 ) {
2785 found_excerpt_header = true;
2786 break;
2787 }
2788 block_offset += block.height();
2789 block_height += block.height();
2790 }
2791 if !found_excerpt_header {
2792 offset_y -= block_offset as f32 * line_height;
2793 length += block_height as f32 * line_height;
2794 }
2795
2796 // If there is a block (e.g. diagnostic) at the end of an multibuffer excerpt,
2797 // we want to ensure that the indent guide stops before the excerpt header.
2798 let mut block_height = 0;
2799 let mut found_excerpt_header = false;
2800 for (_, block) in snapshot.blocks_in_range(row_range.end..cons_line) {
2801 if matches!(
2802 block,
2803 Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
2804 ) {
2805 found_excerpt_header = true;
2806 }
2807 block_height += block.height();
2808 }
2809 if found_excerpt_header {
2810 length -= block_height as f32 * line_height;
2811 }
2812
2813 (offset_y, length)
2814 }
2815
2816 fn layout_breakpoints(
2817 &self,
2818 line_height: Pixels,
2819 range: Range<DisplayRow>,
2820 scroll_pixel_position: gpui::Point<Pixels>,
2821 gutter_dimensions: &GutterDimensions,
2822 gutter_hitbox: &Hitbox,
2823 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
2824 snapshot: &EditorSnapshot,
2825 breakpoints: HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
2826 row_infos: &[RowInfo],
2827 window: &mut Window,
2828 cx: &mut App,
2829 ) -> Vec<AnyElement> {
2830 self.editor.update(cx, |editor, cx| {
2831 breakpoints
2832 .into_iter()
2833 .filter_map(|(display_row, (text_anchor, bp, state))| {
2834 if row_infos
2835 .get((display_row.0.saturating_sub(range.start.0)) as usize)
2836 .is_some_and(|row_info| {
2837 row_info.expand_info.is_some()
2838 || row_info
2839 .diff_status
2840 .is_some_and(|status| status.is_deleted())
2841 })
2842 {
2843 return None;
2844 }
2845
2846 if range.start > display_row || range.end < display_row {
2847 return None;
2848 }
2849
2850 let row =
2851 MultiBufferRow(DisplayPoint::new(display_row, 0).to_point(snapshot).row);
2852 if snapshot.is_line_folded(row) {
2853 return None;
2854 }
2855
2856 let button = editor.render_breakpoint(text_anchor, display_row, &bp, state, cx);
2857
2858 let button = prepaint_gutter_button(
2859 button,
2860 display_row,
2861 line_height,
2862 gutter_dimensions,
2863 scroll_pixel_position,
2864 gutter_hitbox,
2865 display_hunks,
2866 window,
2867 cx,
2868 );
2869 Some(button)
2870 })
2871 .collect_vec()
2872 })
2873 }
2874
2875 #[allow(clippy::too_many_arguments)]
2876 fn layout_run_indicators(
2877 &self,
2878 line_height: Pixels,
2879 range: Range<DisplayRow>,
2880 row_infos: &[RowInfo],
2881 scroll_pixel_position: gpui::Point<Pixels>,
2882 gutter_dimensions: &GutterDimensions,
2883 gutter_hitbox: &Hitbox,
2884 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
2885 snapshot: &EditorSnapshot,
2886 breakpoints: &mut HashMap<DisplayRow, (Anchor, Breakpoint, Option<BreakpointSessionState>)>,
2887 window: &mut Window,
2888 cx: &mut App,
2889 ) -> Vec<AnyElement> {
2890 self.editor.update(cx, |editor, cx| {
2891 let active_task_indicator_row =
2892 // TODO: add edit button on the right side of each row in the context menu
2893 if let Some(crate::CodeContextMenu::CodeActions(CodeActionsMenu {
2894 deployed_from,
2895 actions,
2896 ..
2897 })) = editor.context_menu.borrow().as_ref()
2898 {
2899 actions
2900 .tasks()
2901 .map(|tasks| tasks.position.to_display_point(snapshot).row())
2902 .or_else(|| match deployed_from {
2903 Some(CodeActionSource::Indicator(row)) => Some(*row),
2904 _ => None,
2905 })
2906 } else {
2907 None
2908 };
2909
2910 let offset_range_start =
2911 snapshot.display_point_to_point(DisplayPoint::new(range.start, 0), Bias::Left);
2912
2913 let offset_range_end =
2914 snapshot.display_point_to_point(DisplayPoint::new(range.end, 0), Bias::Right);
2915
2916 editor
2917 .tasks
2918 .iter()
2919 .filter_map(|(_, tasks)| {
2920 let multibuffer_point = tasks.offset.to_point(&snapshot.buffer_snapshot);
2921 if multibuffer_point < offset_range_start
2922 || multibuffer_point > offset_range_end
2923 {
2924 return None;
2925 }
2926 let multibuffer_row = MultiBufferRow(multibuffer_point.row);
2927 let buffer_folded = snapshot
2928 .buffer_snapshot
2929 .buffer_line_for_row(multibuffer_row)
2930 .map(|(buffer_snapshot, _)| buffer_snapshot.remote_id())
2931 .map(|buffer_id| editor.is_buffer_folded(buffer_id, cx))
2932 .unwrap_or(false);
2933 if buffer_folded {
2934 return None;
2935 }
2936
2937 if snapshot.is_line_folded(multibuffer_row) {
2938 // Skip folded indicators, unless it's the starting line of a fold.
2939 if multibuffer_row
2940 .0
2941 .checked_sub(1)
2942 .is_some_and(|previous_row| {
2943 snapshot.is_line_folded(MultiBufferRow(previous_row))
2944 })
2945 {
2946 return None;
2947 }
2948 }
2949
2950 let display_row = multibuffer_point.to_display_point(snapshot).row();
2951 if !range.contains(&display_row) {
2952 return None;
2953 }
2954 if row_infos
2955 .get((display_row - range.start).0 as usize)
2956 .is_some_and(|row_info| row_info.expand_info.is_some())
2957 {
2958 return None;
2959 }
2960
2961 let button = editor.render_run_indicator(
2962 &self.style,
2963 Some(display_row) == active_task_indicator_row,
2964 display_row,
2965 breakpoints.remove(&display_row),
2966 cx,
2967 );
2968
2969 let button = prepaint_gutter_button(
2970 button,
2971 display_row,
2972 line_height,
2973 gutter_dimensions,
2974 scroll_pixel_position,
2975 gutter_hitbox,
2976 display_hunks,
2977 window,
2978 cx,
2979 );
2980 Some(button)
2981 })
2982 .collect_vec()
2983 })
2984 }
2985
2986 fn layout_expand_toggles(
2987 &self,
2988 gutter_hitbox: &Hitbox,
2989 gutter_dimensions: GutterDimensions,
2990 em_width: Pixels,
2991 line_height: Pixels,
2992 scroll_position: gpui::Point<f32>,
2993 buffer_rows: &[RowInfo],
2994 window: &mut Window,
2995 cx: &mut App,
2996 ) -> Vec<Option<(AnyElement, gpui::Point<Pixels>)>> {
2997 if self.editor.read(cx).disable_expand_excerpt_buttons {
2998 return vec![];
2999 }
3000
3001 let editor_font_size = self.style.text.font_size.to_pixels(window.rem_size()) * 1.2;
3002
3003 let scroll_top = scroll_position.y * line_height;
3004
3005 let max_line_number_length = self
3006 .editor
3007 .read(cx)
3008 .buffer()
3009 .read(cx)
3010 .snapshot(cx)
3011 .widest_line_number()
3012 .ilog10()
3013 + 1;
3014
3015 let git_gutter_width = Self::gutter_strip_width(line_height)
3016 + gutter_dimensions
3017 .git_blame_entries_width
3018 .unwrap_or_default();
3019 let available_width = gutter_dimensions.left_padding - git_gutter_width;
3020
3021 buffer_rows
3022 .iter()
3023 .enumerate()
3024 .map(|(ix, row_info)| {
3025 let ExpandInfo {
3026 excerpt_id,
3027 direction,
3028 } = row_info.expand_info?;
3029
3030 let icon_name = match direction {
3031 ExpandExcerptDirection::Up => IconName::ExpandUp,
3032 ExpandExcerptDirection::Down => IconName::ExpandDown,
3033 ExpandExcerptDirection::UpAndDown => IconName::ExpandVertical,
3034 };
3035
3036 let editor = self.editor.clone();
3037 let is_wide = max_line_number_length
3038 >= EditorSettings::get_global(cx).gutter.min_line_number_digits as u32
3039 && row_info
3040 .buffer_row
3041 .is_some_and(|row| (row + 1).ilog10() + 1 == max_line_number_length)
3042 || gutter_dimensions.right_padding == px(0.);
3043
3044 let width = if is_wide {
3045 available_width - px(2.)
3046 } else {
3047 available_width + em_width - px(2.)
3048 };
3049
3050 let toggle = IconButton::new(("expand", ix), icon_name)
3051 .icon_color(Color::Custom(cx.theme().colors().editor_line_number))
3052 .selected_icon_color(Color::Custom(cx.theme().colors().editor_foreground))
3053 .icon_size(IconSize::Custom(rems(editor_font_size / window.rem_size())))
3054 .width(width)
3055 .on_click(move |_, window, cx| {
3056 editor.update(cx, |editor, cx| {
3057 editor.expand_excerpt(excerpt_id, direction, window, cx);
3058 });
3059 })
3060 .tooltip(Tooltip::for_action_title(
3061 "Expand Excerpt",
3062 &crate::actions::ExpandExcerpts::default(),
3063 ))
3064 .into_any_element();
3065
3066 let position = point(
3067 git_gutter_width + px(1.),
3068 ix as f32 * line_height - (scroll_top % line_height) + px(1.),
3069 );
3070 let origin = gutter_hitbox.origin + position;
3071
3072 Some((toggle, origin))
3073 })
3074 .collect()
3075 }
3076
3077 fn calculate_relative_line_numbers(
3078 &self,
3079 snapshot: &EditorSnapshot,
3080 rows: &Range<DisplayRow>,
3081 relative_to: Option<DisplayRow>,
3082 ) -> HashMap<DisplayRow, DisplayRowDelta> {
3083 let mut relative_rows: HashMap<DisplayRow, DisplayRowDelta> = Default::default();
3084 let Some(relative_to) = relative_to else {
3085 return relative_rows;
3086 };
3087
3088 let start = rows.start.min(relative_to);
3089 let end = rows.end.max(relative_to);
3090
3091 let buffer_rows = snapshot
3092 .row_infos(start)
3093 .take(1 + end.minus(start) as usize)
3094 .collect::<Vec<_>>();
3095
3096 let head_idx = relative_to.minus(start);
3097 let mut delta = 1;
3098 let mut i = head_idx + 1;
3099 while i < buffer_rows.len() as u32 {
3100 if buffer_rows[i as usize].buffer_row.is_some() {
3101 if rows.contains(&DisplayRow(i + start.0)) {
3102 relative_rows.insert(DisplayRow(i + start.0), delta);
3103 }
3104 delta += 1;
3105 }
3106 i += 1;
3107 }
3108 delta = 1;
3109 i = head_idx.min(buffer_rows.len() as u32 - 1);
3110 while i > 0 && buffer_rows[i as usize].buffer_row.is_none() {
3111 i -= 1;
3112 }
3113
3114 while i > 0 {
3115 i -= 1;
3116 if buffer_rows[i as usize].buffer_row.is_some() {
3117 if rows.contains(&DisplayRow(i + start.0)) {
3118 relative_rows.insert(DisplayRow(i + start.0), delta);
3119 }
3120 delta += 1;
3121 }
3122 }
3123
3124 relative_rows
3125 }
3126
3127 fn layout_line_numbers(
3128 &self,
3129 gutter_hitbox: Option<&Hitbox>,
3130 gutter_dimensions: GutterDimensions,
3131 line_height: Pixels,
3132 scroll_position: gpui::Point<f32>,
3133 rows: Range<DisplayRow>,
3134 buffer_rows: &[RowInfo],
3135 active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
3136 newest_selection_head: Option<DisplayPoint>,
3137 snapshot: &EditorSnapshot,
3138 window: &mut Window,
3139 cx: &mut App,
3140 ) -> Arc<HashMap<MultiBufferRow, LineNumberLayout>> {
3141 let include_line_numbers = snapshot
3142 .show_line_numbers
3143 .unwrap_or_else(|| EditorSettings::get_global(cx).gutter.line_numbers);
3144 if !include_line_numbers {
3145 return Arc::default();
3146 }
3147
3148 let (newest_selection_head, is_relative) = self.editor.update(cx, |editor, cx| {
3149 let newest_selection_head = newest_selection_head.unwrap_or_else(|| {
3150 let newest = editor.selections.newest::<Point>(cx);
3151 SelectionLayout::new(
3152 newest,
3153 editor.selections.line_mode(),
3154 editor.cursor_shape,
3155 &snapshot.display_snapshot,
3156 true,
3157 true,
3158 None,
3159 )
3160 .head
3161 });
3162 let is_relative = editor.should_use_relative_line_numbers(cx);
3163 (newest_selection_head, is_relative)
3164 });
3165
3166 let relative_to = if is_relative {
3167 Some(newest_selection_head.row())
3168 } else {
3169 None
3170 };
3171 let relative_rows = self.calculate_relative_line_numbers(snapshot, &rows, relative_to);
3172 let mut line_number = String::new();
3173 let line_numbers = buffer_rows
3174 .iter()
3175 .enumerate()
3176 .flat_map(|(ix, row_info)| {
3177 let display_row = DisplayRow(rows.start.0 + ix as u32);
3178 line_number.clear();
3179 let non_relative_number = row_info.buffer_row? + 1;
3180 let number = relative_rows
3181 .get(&display_row)
3182 .unwrap_or(&non_relative_number);
3183 write!(&mut line_number, "{number}").unwrap();
3184 if row_info
3185 .diff_status
3186 .is_some_and(|status| status.is_deleted())
3187 {
3188 return None;
3189 }
3190
3191 let color = active_rows
3192 .get(&display_row)
3193 .map(|spec| {
3194 if spec.breakpoint {
3195 cx.theme().colors().debugger_accent
3196 } else {
3197 cx.theme().colors().editor_active_line_number
3198 }
3199 })
3200 .unwrap_or_else(|| cx.theme().colors().editor_line_number);
3201 let shaped_line =
3202 self.shape_line_number(SharedString::from(&line_number), color, window);
3203 let scroll_top = scroll_position.y * line_height;
3204 let line_origin = gutter_hitbox.map(|hitbox| {
3205 hitbox.origin
3206 + point(
3207 hitbox.size.width - shaped_line.width - gutter_dimensions.right_padding,
3208 ix as f32 * line_height - (scroll_top % line_height),
3209 )
3210 });
3211
3212 #[cfg(not(test))]
3213 let hitbox = line_origin.map(|line_origin| {
3214 window.insert_hitbox(
3215 Bounds::new(line_origin, size(shaped_line.width, line_height)),
3216 HitboxBehavior::Normal,
3217 )
3218 });
3219 #[cfg(test)]
3220 let hitbox = {
3221 let _ = line_origin;
3222 None
3223 };
3224
3225 let multi_buffer_row = DisplayPoint::new(display_row, 0).to_point(snapshot).row;
3226 let multi_buffer_row = MultiBufferRow(multi_buffer_row);
3227 let line_number = LineNumberLayout {
3228 shaped_line,
3229 hitbox,
3230 };
3231 Some((multi_buffer_row, line_number))
3232 })
3233 .collect();
3234 Arc::new(line_numbers)
3235 }
3236
3237 fn layout_crease_toggles(
3238 &self,
3239 rows: Range<DisplayRow>,
3240 row_infos: &[RowInfo],
3241 active_rows: &BTreeMap<DisplayRow, LineHighlightSpec>,
3242 snapshot: &EditorSnapshot,
3243 window: &mut Window,
3244 cx: &mut App,
3245 ) -> Vec<Option<AnyElement>> {
3246 let include_fold_statuses = EditorSettings::get_global(cx).gutter.folds
3247 && snapshot.mode.is_full()
3248 && self.editor.read(cx).is_singleton(cx);
3249 if include_fold_statuses {
3250 row_infos
3251 .iter()
3252 .enumerate()
3253 .map(|(ix, info)| {
3254 if info.expand_info.is_some() {
3255 return None;
3256 }
3257 let row = info.multibuffer_row?;
3258 let display_row = DisplayRow(rows.start.0 + ix as u32);
3259 let active = active_rows.contains_key(&display_row);
3260
3261 snapshot.render_crease_toggle(row, active, self.editor.clone(), window, cx)
3262 })
3263 .collect()
3264 } else {
3265 Vec::new()
3266 }
3267 }
3268
3269 fn layout_crease_trailers(
3270 &self,
3271 buffer_rows: impl IntoIterator<Item = RowInfo>,
3272 snapshot: &EditorSnapshot,
3273 window: &mut Window,
3274 cx: &mut App,
3275 ) -> Vec<Option<AnyElement>> {
3276 buffer_rows
3277 .into_iter()
3278 .map(|row_info| {
3279 if row_info.expand_info.is_some() {
3280 return None;
3281 }
3282 if let Some(row) = row_info.multibuffer_row {
3283 snapshot.render_crease_trailer(row, window, cx)
3284 } else {
3285 None
3286 }
3287 })
3288 .collect()
3289 }
3290
3291 fn bg_segments_per_row(
3292 rows: Range<DisplayRow>,
3293 selections: &[(PlayerColor, Vec<SelectionLayout>)],
3294 highlight_ranges: &[(Range<DisplayPoint>, Hsla)],
3295 base_background: Hsla,
3296 ) -> Vec<Vec<(Range<DisplayPoint>, Hsla)>> {
3297 if rows.start >= rows.end {
3298 return Vec::new();
3299 }
3300 if !base_background.is_opaque() {
3301 // We don't actually know what color is behind this editor.
3302 return Vec::new();
3303 }
3304 let highlight_iter = highlight_ranges.iter().cloned();
3305 let selection_iter = selections.iter().flat_map(|(player_color, layouts)| {
3306 let color = player_color.selection;
3307 layouts.iter().filter_map(move |selection_layout| {
3308 if selection_layout.range.start != selection_layout.range.end {
3309 Some((selection_layout.range.clone(), color))
3310 } else {
3311 None
3312 }
3313 })
3314 });
3315 let mut per_row_map = vec![Vec::new(); rows.len()];
3316 for (range, color) in highlight_iter.chain(selection_iter) {
3317 let covered_rows = if range.end.column() == 0 {
3318 cmp::max(range.start.row(), rows.start)..cmp::min(range.end.row(), rows.end)
3319 } else {
3320 cmp::max(range.start.row(), rows.start)
3321 ..cmp::min(range.end.row().next_row(), rows.end)
3322 };
3323 for row in covered_rows.iter_rows() {
3324 let seg_start = if row == range.start.row() {
3325 range.start
3326 } else {
3327 DisplayPoint::new(row, 0)
3328 };
3329 let seg_end = if row == range.end.row() && range.end.column() != 0 {
3330 range.end
3331 } else {
3332 DisplayPoint::new(row, u32::MAX)
3333 };
3334 let ix = row.minus(rows.start) as usize;
3335 debug_assert!(row >= rows.start && row < rows.end);
3336 debug_assert!(ix < per_row_map.len());
3337 per_row_map[ix].push((seg_start..seg_end, color));
3338 }
3339 }
3340 for row_segments in per_row_map.iter_mut() {
3341 if row_segments.is_empty() {
3342 continue;
3343 }
3344 let segments = mem::take(row_segments);
3345 let merged = Self::merge_overlapping_ranges(segments, base_background);
3346 *row_segments = merged;
3347 }
3348 per_row_map
3349 }
3350
3351 /// Merge overlapping ranges by splitting at all range boundaries and blending colors where
3352 /// multiple ranges overlap. The result contains non-overlapping ranges ordered from left to right.
3353 ///
3354 /// Expects `start.row() == end.row()` for each range.
3355 fn merge_overlapping_ranges(
3356 ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3357 base_background: Hsla,
3358 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
3359 struct Boundary {
3360 pos: DisplayPoint,
3361 is_start: bool,
3362 index: usize,
3363 color: Hsla,
3364 }
3365
3366 let mut boundaries: SmallVec<[Boundary; 16]> = SmallVec::with_capacity(ranges.len() * 2);
3367 for (index, (range, color)) in ranges.iter().enumerate() {
3368 debug_assert!(
3369 range.start.row() == range.end.row(),
3370 "expects single-row ranges"
3371 );
3372 if range.start < range.end {
3373 boundaries.push(Boundary {
3374 pos: range.start,
3375 is_start: true,
3376 index,
3377 color: *color,
3378 });
3379 boundaries.push(Boundary {
3380 pos: range.end,
3381 is_start: false,
3382 index,
3383 color: *color,
3384 });
3385 }
3386 }
3387
3388 if boundaries.is_empty() {
3389 return Vec::new();
3390 }
3391
3392 boundaries
3393 .sort_unstable_by(|a, b| a.pos.cmp(&b.pos).then_with(|| a.is_start.cmp(&b.is_start)));
3394
3395 let mut processed_ranges: Vec<(Range<DisplayPoint>, Hsla)> = Vec::new();
3396 let mut active_ranges: SmallVec<[(usize, Hsla); 8]> = SmallVec::new();
3397
3398 let mut i = 0;
3399 let mut start_pos = boundaries[0].pos;
3400
3401 let boundaries_len = boundaries.len();
3402 while i < boundaries_len {
3403 let current_boundary_pos = boundaries[i].pos;
3404 if start_pos < current_boundary_pos {
3405 if !active_ranges.is_empty() {
3406 let mut color = base_background;
3407 for &(_, c) in &active_ranges {
3408 color = Hsla::blend(color, c);
3409 }
3410 if let Some((last_range, last_color)) = processed_ranges.last_mut() {
3411 if *last_color == color && last_range.end == start_pos {
3412 last_range.end = current_boundary_pos;
3413 } else {
3414 processed_ranges.push((start_pos..current_boundary_pos, color));
3415 }
3416 } else {
3417 processed_ranges.push((start_pos..current_boundary_pos, color));
3418 }
3419 }
3420 }
3421 while i < boundaries_len && boundaries[i].pos == current_boundary_pos {
3422 let active_range = &boundaries[i];
3423 if active_range.is_start {
3424 let idx = active_range.index;
3425 let pos = active_ranges
3426 .binary_search_by_key(&idx, |(i, _)| *i)
3427 .unwrap_or_else(|p| p);
3428 active_ranges.insert(pos, (idx, active_range.color));
3429 } else {
3430 let idx = active_range.index;
3431 if let Ok(pos) = active_ranges.binary_search_by_key(&idx, |(i, _)| *i) {
3432 active_ranges.remove(pos);
3433 }
3434 }
3435 i += 1;
3436 }
3437 start_pos = current_boundary_pos;
3438 }
3439
3440 processed_ranges
3441 }
3442
3443 fn layout_lines(
3444 rows: Range<DisplayRow>,
3445 snapshot: &EditorSnapshot,
3446 style: &EditorStyle,
3447 editor_width: Pixels,
3448 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3449 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
3450 window: &mut Window,
3451 cx: &mut App,
3452 ) -> Vec<LineWithInvisibles> {
3453 if rows.start >= rows.end {
3454 return Vec::new();
3455 }
3456
3457 // Show the placeholder when the editor is empty
3458 if snapshot.is_empty() {
3459 let font_size = style.text.font_size.to_pixels(window.rem_size());
3460 let placeholder_color = cx.theme().colors().text_placeholder;
3461 let placeholder_text = snapshot.placeholder_text();
3462
3463 let placeholder_lines = placeholder_text
3464 .as_ref()
3465 .map_or(Vec::new(), |text| text.split('\n').collect::<Vec<_>>());
3466
3467 let placeholder_line_count = placeholder_lines.len();
3468
3469 placeholder_lines
3470 .into_iter()
3471 .skip(rows.start.0 as usize)
3472 .chain(iter::repeat(""))
3473 .take(cmp::max(rows.len(), placeholder_line_count))
3474 .map(move |line| {
3475 let run = TextRun {
3476 len: line.len(),
3477 font: style.text.font(),
3478 color: placeholder_color,
3479 background_color: None,
3480 underline: None,
3481 strikethrough: None,
3482 };
3483 let line = window.text_system().shape_line(
3484 line.to_string().into(),
3485 font_size,
3486 &[run],
3487 None,
3488 );
3489 LineWithInvisibles {
3490 width: line.width,
3491 len: line.len,
3492 fragments: smallvec![LineFragment::Text(line)],
3493 invisibles: Vec::new(),
3494 font_size,
3495 }
3496 })
3497 .collect()
3498 } else {
3499 let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
3500 LineWithInvisibles::from_chunks(
3501 chunks,
3502 style,
3503 MAX_LINE_LEN,
3504 rows.len(),
3505 &snapshot.mode,
3506 editor_width,
3507 is_row_soft_wrapped,
3508 bg_segments_per_row,
3509 window,
3510 cx,
3511 )
3512 }
3513 }
3514
3515 fn prepaint_lines(
3516 &self,
3517 start_row: DisplayRow,
3518 line_layouts: &mut [LineWithInvisibles],
3519 line_height: Pixels,
3520 scroll_pixel_position: gpui::Point<Pixels>,
3521 content_origin: gpui::Point<Pixels>,
3522 window: &mut Window,
3523 cx: &mut App,
3524 ) -> SmallVec<[AnyElement; 1]> {
3525 let mut line_elements = SmallVec::new();
3526 for (ix, line) in line_layouts.iter_mut().enumerate() {
3527 let row = start_row + DisplayRow(ix as u32);
3528 line.prepaint(
3529 line_height,
3530 scroll_pixel_position,
3531 row,
3532 content_origin,
3533 &mut line_elements,
3534 window,
3535 cx,
3536 );
3537 }
3538 line_elements
3539 }
3540
3541 fn render_block(
3542 &self,
3543 block: &Block,
3544 available_width: AvailableSpace,
3545 block_id: BlockId,
3546 block_row_start: DisplayRow,
3547 snapshot: &EditorSnapshot,
3548 text_x: Pixels,
3549 rows: &Range<DisplayRow>,
3550 line_layouts: &[LineWithInvisibles],
3551 editor_margins: &EditorMargins,
3552 line_height: Pixels,
3553 em_width: Pixels,
3554 text_hitbox: &Hitbox,
3555 editor_width: Pixels,
3556 scroll_width: &mut Pixels,
3557 resized_blocks: &mut HashMap<CustomBlockId, u32>,
3558 row_block_types: &mut HashMap<DisplayRow, bool>,
3559 selections: &[Selection<Point>],
3560 selected_buffer_ids: &Vec<BufferId>,
3561 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3562 sticky_header_excerpt_id: Option<ExcerptId>,
3563 window: &mut Window,
3564 cx: &mut App,
3565 ) -> Option<(AnyElement, Size<Pixels>, DisplayRow, Pixels)> {
3566 let mut x_position = None;
3567 let mut element = match block {
3568 Block::Custom(custom) => {
3569 let block_start = custom.start().to_point(&snapshot.buffer_snapshot);
3570 let block_end = custom.end().to_point(&snapshot.buffer_snapshot);
3571 if block.place_near() && snapshot.is_line_folded(MultiBufferRow(block_start.row)) {
3572 return None;
3573 }
3574 let align_to = block_start.to_display_point(snapshot);
3575 let x_and_width = |layout: &LineWithInvisibles| {
3576 Some((
3577 text_x + layout.x_for_index(align_to.column() as usize),
3578 text_x + layout.width,
3579 ))
3580 };
3581 let line_ix = align_to.row().0.checked_sub(rows.start.0);
3582 x_position =
3583 if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
3584 x_and_width(layout)
3585 } else {
3586 x_and_width(&layout_line(
3587 align_to.row(),
3588 snapshot,
3589 &self.style,
3590 editor_width,
3591 is_row_soft_wrapped,
3592 window,
3593 cx,
3594 ))
3595 };
3596
3597 let anchor_x = x_position.unwrap().0;
3598
3599 let selected = selections
3600 .binary_search_by(|selection| {
3601 if selection.end <= block_start {
3602 Ordering::Less
3603 } else if selection.start >= block_end {
3604 Ordering::Greater
3605 } else {
3606 Ordering::Equal
3607 }
3608 })
3609 .is_ok();
3610
3611 div()
3612 .size_full()
3613 .child(custom.render(&mut BlockContext {
3614 window,
3615 app: cx,
3616 anchor_x,
3617 margins: editor_margins,
3618 line_height,
3619 em_width,
3620 block_id,
3621 selected,
3622 max_width: text_hitbox.size.width.max(*scroll_width),
3623 editor_style: &self.style,
3624 }))
3625 .into_any()
3626 }
3627
3628 Block::FoldedBuffer {
3629 first_excerpt,
3630 height,
3631 ..
3632 } => {
3633 let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
3634 let result = v_flex().id(block_id).w_full().pr(editor_margins.right);
3635
3636 let jump_data = header_jump_data(snapshot, block_row_start, *height, first_excerpt);
3637 result
3638 .child(self.render_buffer_header(
3639 first_excerpt,
3640 true,
3641 selected,
3642 false,
3643 jump_data,
3644 window,
3645 cx,
3646 ))
3647 .into_any_element()
3648 }
3649
3650 Block::ExcerptBoundary { .. } => {
3651 let color = cx.theme().colors().clone();
3652 let mut result = v_flex().id(block_id).w_full();
3653
3654 result = result.child(
3655 h_flex().relative().child(
3656 div()
3657 .top(line_height / 2.)
3658 .absolute()
3659 .w_full()
3660 .h_px()
3661 .bg(color.border_variant),
3662 ),
3663 );
3664
3665 result.into_any()
3666 }
3667
3668 Block::BufferHeader { excerpt, height } => {
3669 let mut result = v_flex().id(block_id).w_full();
3670
3671 let jump_data = header_jump_data(snapshot, block_row_start, *height, excerpt);
3672
3673 if sticky_header_excerpt_id != Some(excerpt.id) {
3674 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3675
3676 result = result.child(div().pr(editor_margins.right).child(
3677 self.render_buffer_header(
3678 excerpt, false, selected, false, jump_data, window, cx,
3679 ),
3680 ));
3681 } else {
3682 result =
3683 result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
3684 }
3685
3686 result.into_any()
3687 }
3688 };
3689
3690 // Discover the element's content height, then round up to the nearest multiple of line height.
3691 let preliminary_size = element.layout_as_root(
3692 size(available_width, AvailableSpace::MinContent),
3693 window,
3694 cx,
3695 );
3696 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
3697 let final_size = if preliminary_size.height == quantized_height {
3698 preliminary_size
3699 } else {
3700 element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
3701 };
3702 let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
3703
3704 let mut row = block_row_start;
3705 let mut x_offset = px(0.);
3706 let mut is_block = true;
3707
3708 if let BlockId::Custom(custom_block_id) = block_id
3709 && block.has_height()
3710 {
3711 if block.place_near()
3712 && let Some((x_target, line_width)) = x_position
3713 {
3714 let margin = em_width * 2;
3715 if line_width + final_size.width + margin
3716 < editor_width + editor_margins.gutter.full_width()
3717 && !row_block_types.contains_key(&(row - 1))
3718 && element_height_in_lines == 1
3719 {
3720 x_offset = line_width + margin;
3721 row = row - 1;
3722 is_block = false;
3723 element_height_in_lines = 0;
3724 row_block_types.insert(row, is_block);
3725 } else {
3726 let max_offset =
3727 editor_width + editor_margins.gutter.full_width() - final_size.width;
3728 let min_offset = (x_target + em_width - final_size.width)
3729 .max(editor_margins.gutter.full_width());
3730 x_offset = x_target.min(max_offset).max(min_offset);
3731 }
3732 };
3733 if element_height_in_lines != block.height() {
3734 resized_blocks.insert(custom_block_id, element_height_in_lines);
3735 }
3736 }
3737 for i in 0..element_height_in_lines {
3738 row_block_types.insert(row + i, is_block);
3739 }
3740
3741 Some((element, final_size, row, x_offset))
3742 }
3743
3744 fn render_buffer_header(
3745 &self,
3746 for_excerpt: &ExcerptInfo,
3747 is_folded: bool,
3748 is_selected: bool,
3749 is_sticky: bool,
3750 jump_data: JumpData,
3751 window: &mut Window,
3752 cx: &mut App,
3753 ) -> impl IntoElement {
3754 let editor = self.editor.read(cx);
3755 let multi_buffer = editor.buffer.read(cx);
3756 let file_status = multi_buffer
3757 .all_diff_hunks_expanded()
3758 .then(|| {
3759 editor
3760 .project
3761 .as_ref()?
3762 .read(cx)
3763 .status_for_buffer_id(for_excerpt.buffer_id, cx)
3764 })
3765 .flatten();
3766 let indicator = multi_buffer
3767 .buffer(for_excerpt.buffer_id)
3768 .and_then(|buffer| {
3769 let buffer = buffer.read(cx);
3770 let indicator_color = match (buffer.has_conflict(), buffer.is_dirty()) {
3771 (true, _) => Some(Color::Warning),
3772 (_, true) => Some(Color::Accent),
3773 (false, false) => None,
3774 };
3775 indicator_color.map(|indicator_color| Indicator::dot().color(indicator_color))
3776 });
3777
3778 let include_root = editor
3779 .project
3780 .as_ref()
3781 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
3782 .unwrap_or_default();
3783 let file = for_excerpt.buffer.file();
3784 let can_open_excerpts = Editor::can_open_excerpts_in_file(file);
3785 let path_style = file.map(|file| file.path_style(cx));
3786 let relative_path = for_excerpt.buffer.resolve_file_path(include_root, cx);
3787 let (parent_path, filename) = if let Some(path) = &relative_path {
3788 if let Some(path_style) = path_style {
3789 let (dir, file_name) = path_style.split(path);
3790 (dir.map(|dir| dir.to_owned()), Some(file_name.to_owned()))
3791 } else {
3792 (None, Some(path.clone()))
3793 }
3794 } else {
3795 (None, None)
3796 };
3797 let focus_handle = editor.focus_handle(cx);
3798 let colors = cx.theme().colors();
3799
3800 let header = div()
3801 .p_1()
3802 .w_full()
3803 .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
3804 .child(
3805 h_flex()
3806 .size_full()
3807 .gap_2()
3808 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
3809 .pl_0p5()
3810 .pr_5()
3811 .rounded_sm()
3812 .when(is_sticky, |el| el.shadow_md())
3813 .border_1()
3814 .map(|div| {
3815 let border_color = if is_selected
3816 && is_folded
3817 && focus_handle.contains_focused(window, cx)
3818 {
3819 colors.border_focused
3820 } else {
3821 colors.border
3822 };
3823 div.border_color(border_color)
3824 })
3825 .bg(colors.editor_subheader_background)
3826 .hover(|style| style.bg(colors.element_hover))
3827 .map(|header| {
3828 let editor = self.editor.clone();
3829 let buffer_id = for_excerpt.buffer_id;
3830 let toggle_chevron_icon =
3831 FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
3832 header.child(
3833 div()
3834 .hover(|style| style.bg(colors.element_selected))
3835 .rounded_xs()
3836 .child(
3837 ButtonLike::new("toggle-buffer-fold")
3838 .style(ui::ButtonStyle::Transparent)
3839 .height(px(28.).into())
3840 .width(px(28.))
3841 .children(toggle_chevron_icon)
3842 .tooltip({
3843 let focus_handle = focus_handle.clone();
3844 move |window, cx| {
3845 Tooltip::with_meta_in(
3846 "Toggle Excerpt Fold",
3847 Some(&ToggleFold),
3848 format!(
3849 "{} to toggle all",
3850 text_for_keystroke(
3851 &Modifiers::alt(),
3852 "click",
3853 cx
3854 )
3855 ),
3856 &focus_handle,
3857 window,
3858 cx,
3859 )
3860 }
3861 })
3862 .on_click(move |event, window, cx| {
3863 if event.modifiers().alt {
3864 // Alt+click toggles all buffers
3865 editor.update(cx, |editor, cx| {
3866 editor.toggle_fold_all(
3867 &ToggleFoldAll,
3868 window,
3869 cx,
3870 );
3871 });
3872 } else {
3873 // Regular click toggles single buffer
3874 if is_folded {
3875 editor.update(cx, |editor, cx| {
3876 editor.unfold_buffer(buffer_id, cx);
3877 });
3878 } else {
3879 editor.update(cx, |editor, cx| {
3880 editor.fold_buffer(buffer_id, cx);
3881 });
3882 }
3883 }
3884 }),
3885 ),
3886 )
3887 })
3888 .children(
3889 editor
3890 .addons
3891 .values()
3892 .filter_map(|addon| {
3893 addon.render_buffer_header_controls(for_excerpt, window, cx)
3894 })
3895 .take(1),
3896 )
3897 .child(
3898 h_flex()
3899 .size(Pixels(12.0))
3900 .justify_center()
3901 .children(indicator),
3902 )
3903 .child(
3904 h_flex()
3905 .cursor_pointer()
3906 .id("path header block")
3907 .size_full()
3908 .justify_between()
3909 .overflow_hidden()
3910 .child(
3911 h_flex()
3912 .gap_2()
3913 .map(|path_header| {
3914 let filename = filename
3915 .map(SharedString::from)
3916 .unwrap_or_else(|| "untitled".into());
3917
3918 path_header
3919 .when(ItemSettings::get_global(cx).file_icons, |el| {
3920 let path = path::Path::new(filename.as_str());
3921 let icon = FileIcons::get_icon(path, cx)
3922 .unwrap_or_default();
3923 let icon =
3924 Icon::from_path(icon).color(Color::Muted);
3925 el.child(icon)
3926 })
3927 .child(Label::new(filename).single_line().when_some(
3928 file_status,
3929 |el, status| {
3930 el.color(if status.is_conflicted() {
3931 Color::Conflict
3932 } else if status.is_modified() {
3933 Color::Modified
3934 } else if status.is_deleted() {
3935 Color::Disabled
3936 } else {
3937 Color::Created
3938 })
3939 .when(status.is_deleted(), |el| {
3940 el.strikethrough()
3941 })
3942 },
3943 ))
3944 })
3945 .when_some(parent_path, |then, path| {
3946 then.child(div().child(path).text_color(
3947 if file_status.is_some_and(FileStatus::is_deleted) {
3948 colors.text_disabled
3949 } else {
3950 colors.text_muted
3951 },
3952 ))
3953 }),
3954 )
3955 .when(
3956 can_open_excerpts && is_selected && relative_path.is_some(),
3957 |el| {
3958 el.child(
3959 h_flex()
3960 .id("jump-to-file-button")
3961 .gap_2p5()
3962 .child(Label::new("Jump To File"))
3963 .children(
3964 KeyBinding::for_action_in(
3965 &OpenExcerpts,
3966 &focus_handle,
3967 window,
3968 cx,
3969 )
3970 .map(|binding| binding.into_any_element()),
3971 ),
3972 )
3973 },
3974 )
3975 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
3976 .on_click(window.listener_for(&self.editor, {
3977 move |editor, e: &ClickEvent, window, cx| {
3978 editor.open_excerpts_common(
3979 Some(jump_data.clone()),
3980 e.modifiers().secondary(),
3981 window,
3982 cx,
3983 );
3984 }
3985 })),
3986 ),
3987 );
3988
3989 let file = for_excerpt.buffer.file().cloned();
3990 let editor = self.editor.clone();
3991 right_click_menu("buffer-header-context-menu")
3992 .trigger(move |_, _, _| header)
3993 .menu(move |window, cx| {
3994 let menu_context = focus_handle.clone();
3995 let editor = editor.clone();
3996 let file = file.clone();
3997 ContextMenu::build(window, cx, move |mut menu, window, cx| {
3998 if let Some(file) = file
3999 && let Some(project) = editor.read(cx).project()
4000 && let Some(worktree) =
4001 project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
4002 {
4003 let path_style = file.path_style(cx);
4004 let worktree = worktree.read(cx);
4005 let relative_path = file.path();
4006 let entry_for_path = worktree.entry_for_path(relative_path);
4007 let abs_path = entry_for_path.map(|e| {
4008 e.canonical_path.as_deref().map_or_else(
4009 || worktree.absolutize(relative_path),
4010 Path::to_path_buf,
4011 )
4012 });
4013 let has_relative_path = worktree.root_entry().is_some_and(Entry::is_dir);
4014
4015 let parent_abs_path = abs_path
4016 .as_ref()
4017 .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
4018 let relative_path = has_relative_path
4019 .then_some(relative_path)
4020 .map(ToOwned::to_owned);
4021
4022 let visible_in_project_panel =
4023 relative_path.is_some() && worktree.is_visible();
4024 let reveal_in_project_panel = entry_for_path
4025 .filter(|_| visible_in_project_panel)
4026 .map(|entry| entry.id);
4027 menu = menu
4028 .when_some(abs_path, |menu, abs_path| {
4029 menu.entry(
4030 "Copy Path",
4031 Some(Box::new(zed_actions::workspace::CopyPath)),
4032 window.handler_for(&editor, move |_, _, cx| {
4033 cx.write_to_clipboard(ClipboardItem::new_string(
4034 abs_path.to_string_lossy().into_owned(),
4035 ));
4036 }),
4037 )
4038 })
4039 .when_some(relative_path, |menu, relative_path| {
4040 menu.entry(
4041 "Copy Relative Path",
4042 Some(Box::new(zed_actions::workspace::CopyRelativePath)),
4043 window.handler_for(&editor, move |_, _, cx| {
4044 cx.write_to_clipboard(ClipboardItem::new_string(
4045 relative_path.display(path_style).to_string(),
4046 ));
4047 }),
4048 )
4049 })
4050 .when(
4051 reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
4052 |menu| menu.separator(),
4053 )
4054 .when_some(reveal_in_project_panel, |menu, entry_id| {
4055 menu.entry(
4056 "Reveal In Project Panel",
4057 Some(Box::new(RevealInProjectPanel::default())),
4058 window.handler_for(&editor, move |editor, _, cx| {
4059 if let Some(project) = &mut editor.project {
4060 project.update(cx, |_, cx| {
4061 cx.emit(project::Event::RevealInProjectPanel(
4062 entry_id,
4063 ))
4064 });
4065 }
4066 }),
4067 )
4068 })
4069 .when_some(parent_abs_path, |menu, parent_abs_path| {
4070 menu.entry(
4071 "Open in Terminal",
4072 Some(Box::new(OpenInTerminal)),
4073 window.handler_for(&editor, move |_, window, cx| {
4074 window.dispatch_action(
4075 OpenTerminal {
4076 working_directory: parent_abs_path.clone(),
4077 }
4078 .boxed_clone(),
4079 cx,
4080 );
4081 }),
4082 )
4083 });
4084 }
4085
4086 menu.context(menu_context)
4087 })
4088 })
4089 }
4090
4091 fn render_blocks(
4092 &self,
4093 rows: Range<DisplayRow>,
4094 snapshot: &EditorSnapshot,
4095 hitbox: &Hitbox,
4096 text_hitbox: &Hitbox,
4097 editor_width: Pixels,
4098 scroll_width: &mut Pixels,
4099 editor_margins: &EditorMargins,
4100 em_width: Pixels,
4101 text_x: Pixels,
4102 line_height: Pixels,
4103 line_layouts: &mut [LineWithInvisibles],
4104 selections: &[Selection<Point>],
4105 selected_buffer_ids: &Vec<BufferId>,
4106 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4107 sticky_header_excerpt_id: Option<ExcerptId>,
4108 window: &mut Window,
4109 cx: &mut App,
4110 ) -> Result<(Vec<BlockLayout>, HashMap<DisplayRow, bool>), HashMap<CustomBlockId, u32>> {
4111 let (fixed_blocks, non_fixed_blocks) = snapshot
4112 .blocks_in_range(rows.clone())
4113 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
4114
4115 let mut focused_block = self
4116 .editor
4117 .update(cx, |editor, _| editor.take_focused_block());
4118 let mut fixed_block_max_width = Pixels::ZERO;
4119 let mut blocks = Vec::new();
4120 let mut resized_blocks = HashMap::default();
4121 let mut row_block_types = HashMap::default();
4122
4123 for (row, block) in fixed_blocks {
4124 let block_id = block.id();
4125
4126 if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
4127 focused_block = None;
4128 }
4129
4130 if let Some((element, element_size, row, x_offset)) = self.render_block(
4131 block,
4132 AvailableSpace::MinContent,
4133 block_id,
4134 row,
4135 snapshot,
4136 text_x,
4137 &rows,
4138 line_layouts,
4139 editor_margins,
4140 line_height,
4141 em_width,
4142 text_hitbox,
4143 editor_width,
4144 scroll_width,
4145 &mut resized_blocks,
4146 &mut row_block_types,
4147 selections,
4148 selected_buffer_ids,
4149 is_row_soft_wrapped,
4150 sticky_header_excerpt_id,
4151 window,
4152 cx,
4153 ) {
4154 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
4155 blocks.push(BlockLayout {
4156 id: block_id,
4157 x_offset,
4158 row: Some(row),
4159 element,
4160 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
4161 style: BlockStyle::Fixed,
4162 overlaps_gutter: true,
4163 is_buffer_header: block.is_buffer_header(),
4164 });
4165 }
4166 }
4167
4168 for (row, block) in non_fixed_blocks {
4169 let style = block.style();
4170 let width = match (style, block.place_near()) {
4171 (_, true) => AvailableSpace::MinContent,
4172 (BlockStyle::Sticky, _) => hitbox.size.width.into(),
4173 (BlockStyle::Flex, _) => hitbox
4174 .size
4175 .width
4176 .max(fixed_block_max_width)
4177 .max(editor_margins.gutter.width + *scroll_width)
4178 .into(),
4179 (BlockStyle::Fixed, _) => unreachable!(),
4180 };
4181 let block_id = block.id();
4182
4183 if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
4184 focused_block = None;
4185 }
4186
4187 if let Some((element, element_size, row, x_offset)) = self.render_block(
4188 block,
4189 width,
4190 block_id,
4191 row,
4192 snapshot,
4193 text_x,
4194 &rows,
4195 line_layouts,
4196 editor_margins,
4197 line_height,
4198 em_width,
4199 text_hitbox,
4200 editor_width,
4201 scroll_width,
4202 &mut resized_blocks,
4203 &mut row_block_types,
4204 selections,
4205 selected_buffer_ids,
4206 is_row_soft_wrapped,
4207 sticky_header_excerpt_id,
4208 window,
4209 cx,
4210 ) {
4211 blocks.push(BlockLayout {
4212 id: block_id,
4213 x_offset,
4214 row: Some(row),
4215 element,
4216 available_space: size(width, element_size.height.into()),
4217 style,
4218 overlaps_gutter: !block.place_near(),
4219 is_buffer_header: block.is_buffer_header(),
4220 });
4221 }
4222 }
4223
4224 if let Some(focused_block) = focused_block
4225 && let Some(focus_handle) = focused_block.focus_handle.upgrade()
4226 && focus_handle.is_focused(window)
4227 && let Some(block) = snapshot.block_for_id(focused_block.id)
4228 {
4229 let style = block.style();
4230 let width = match style {
4231 BlockStyle::Fixed => AvailableSpace::MinContent,
4232 BlockStyle::Flex => AvailableSpace::Definite(
4233 hitbox
4234 .size
4235 .width
4236 .max(fixed_block_max_width)
4237 .max(editor_margins.gutter.width + *scroll_width),
4238 ),
4239 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
4240 };
4241
4242 if let Some((element, element_size, _, x_offset)) = self.render_block(
4243 &block,
4244 width,
4245 focused_block.id,
4246 rows.end,
4247 snapshot,
4248 text_x,
4249 &rows,
4250 line_layouts,
4251 editor_margins,
4252 line_height,
4253 em_width,
4254 text_hitbox,
4255 editor_width,
4256 scroll_width,
4257 &mut resized_blocks,
4258 &mut row_block_types,
4259 selections,
4260 selected_buffer_ids,
4261 is_row_soft_wrapped,
4262 sticky_header_excerpt_id,
4263 window,
4264 cx,
4265 ) {
4266 blocks.push(BlockLayout {
4267 id: block.id(),
4268 x_offset,
4269 row: None,
4270 element,
4271 available_space: size(width, element_size.height.into()),
4272 style,
4273 overlaps_gutter: true,
4274 is_buffer_header: block.is_buffer_header(),
4275 });
4276 }
4277 }
4278
4279 if resized_blocks.is_empty() {
4280 *scroll_width =
4281 (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
4282 Ok((blocks, row_block_types))
4283 } else {
4284 Err(resized_blocks)
4285 }
4286 }
4287
4288 fn layout_blocks(
4289 &self,
4290 blocks: &mut Vec<BlockLayout>,
4291 hitbox: &Hitbox,
4292 line_height: Pixels,
4293 scroll_pixel_position: gpui::Point<Pixels>,
4294 window: &mut Window,
4295 cx: &mut App,
4296 ) {
4297 for block in blocks {
4298 let mut origin = if let Some(row) = block.row {
4299 hitbox.origin
4300 + point(
4301 block.x_offset,
4302 row.as_f32() * line_height - scroll_pixel_position.y,
4303 )
4304 } else {
4305 // Position the block outside the visible area
4306 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
4307 };
4308
4309 if !matches!(block.style, BlockStyle::Sticky) {
4310 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
4311 }
4312
4313 let focus_handle =
4314 block
4315 .element
4316 .prepaint_as_root(origin, block.available_space, window, cx);
4317
4318 if let Some(focus_handle) = focus_handle {
4319 self.editor.update(cx, |editor, _cx| {
4320 editor.set_focused_block(FocusedBlock {
4321 id: block.id,
4322 focus_handle: focus_handle.downgrade(),
4323 });
4324 });
4325 }
4326 }
4327 }
4328
4329 fn layout_sticky_buffer_header(
4330 &self,
4331 StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
4332 scroll_position: f32,
4333 line_height: Pixels,
4334 right_margin: Pixels,
4335 snapshot: &EditorSnapshot,
4336 hitbox: &Hitbox,
4337 selected_buffer_ids: &Vec<BufferId>,
4338 blocks: &[BlockLayout],
4339 window: &mut Window,
4340 cx: &mut App,
4341 ) -> AnyElement {
4342 let jump_data = header_jump_data(
4343 snapshot,
4344 DisplayRow(scroll_position as u32),
4345 FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
4346 excerpt,
4347 );
4348
4349 let editor_bg_color = cx.theme().colors().editor_background;
4350
4351 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
4352
4353 let available_width = hitbox.bounds.size.width - right_margin;
4354
4355 let mut header = v_flex()
4356 .w_full()
4357 .relative()
4358 .child(
4359 div()
4360 .w(available_width)
4361 .h(FILE_HEADER_HEIGHT as f32 * line_height)
4362 .bg(linear_gradient(
4363 0.,
4364 linear_color_stop(editor_bg_color.opacity(0.), 0.),
4365 linear_color_stop(editor_bg_color, 0.6),
4366 ))
4367 .absolute()
4368 .top_0(),
4369 )
4370 .child(
4371 self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
4372 .into_any_element(),
4373 )
4374 .into_any_element();
4375
4376 let mut origin = hitbox.origin;
4377 // Move floating header up to avoid colliding with the next buffer header.
4378 for block in blocks.iter() {
4379 if !block.is_buffer_header {
4380 continue;
4381 }
4382
4383 let Some(display_row) = block.row.filter(|row| row.0 > scroll_position as u32) else {
4384 continue;
4385 };
4386
4387 let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
4388 let offset = scroll_position - max_row as f32;
4389
4390 if offset > 0.0 {
4391 origin.y -= offset * line_height;
4392 }
4393 break;
4394 }
4395
4396 let size = size(
4397 AvailableSpace::Definite(available_width),
4398 AvailableSpace::MinContent,
4399 );
4400
4401 header.prepaint_as_root(origin, size, window, cx);
4402
4403 header
4404 }
4405
4406 fn layout_cursor_popovers(
4407 &self,
4408 line_height: Pixels,
4409 text_hitbox: &Hitbox,
4410 content_origin: gpui::Point<Pixels>,
4411 right_margin: Pixels,
4412 start_row: DisplayRow,
4413 scroll_pixel_position: gpui::Point<Pixels>,
4414 line_layouts: &[LineWithInvisibles],
4415 cursor: DisplayPoint,
4416 cursor_point: Point,
4417 style: &EditorStyle,
4418 window: &mut Window,
4419 cx: &mut App,
4420 ) -> Option<ContextMenuLayout> {
4421 let mut min_menu_height = Pixels::ZERO;
4422 let mut max_menu_height = Pixels::ZERO;
4423 let mut height_above_menu = Pixels::ZERO;
4424 let height_below_menu = Pixels::ZERO;
4425 let mut edit_prediction_popover_visible = false;
4426 let mut context_menu_visible = false;
4427 let context_menu_placement;
4428
4429 {
4430 let editor = self.editor.read(cx);
4431 if editor.edit_prediction_visible_in_cursor_popover(editor.has_active_edit_prediction())
4432 {
4433 height_above_menu +=
4434 editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
4435 edit_prediction_popover_visible = true;
4436 }
4437
4438 if editor.context_menu_visible()
4439 && let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin()
4440 {
4441 let (min_height_in_lines, max_height_in_lines) = editor
4442 .context_menu_options
4443 .as_ref()
4444 .map_or((3, 12), |options| {
4445 (options.min_entries_visible, options.max_entries_visible)
4446 });
4447
4448 min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4449 max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4450 context_menu_visible = true;
4451 }
4452 context_menu_placement = editor
4453 .context_menu_options
4454 .as_ref()
4455 .and_then(|options| options.placement.clone());
4456 }
4457
4458 let visible = edit_prediction_popover_visible || context_menu_visible;
4459 if !visible {
4460 return None;
4461 }
4462
4463 let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
4464 let target_position = content_origin
4465 + gpui::Point {
4466 x: cmp::max(
4467 px(0.),
4468 cursor_row_layout.x_for_index(cursor.column() as usize)
4469 - scroll_pixel_position.x,
4470 ),
4471 y: cmp::max(
4472 px(0.),
4473 cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
4474 ),
4475 };
4476
4477 let viewport_bounds =
4478 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4479 right: -right_margin - MENU_GAP,
4480 ..Default::default()
4481 });
4482
4483 let min_height = height_above_menu + min_menu_height + height_below_menu;
4484 let max_height = height_above_menu + max_menu_height + height_below_menu;
4485 let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
4486 target_position,
4487 line_height,
4488 min_height,
4489 max_height,
4490 context_menu_placement,
4491 text_hitbox,
4492 viewport_bounds,
4493 window,
4494 cx,
4495 |height, max_width_for_stable_x, y_flipped, window, cx| {
4496 // First layout the menu to get its size - others can be at least this wide.
4497 let context_menu = if context_menu_visible {
4498 let menu_height = if y_flipped {
4499 height - height_below_menu
4500 } else {
4501 height - height_above_menu
4502 };
4503 let mut element = self
4504 .render_context_menu(line_height, menu_height, window, cx)
4505 .expect("Visible context menu should always render.");
4506 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4507 Some((CursorPopoverType::CodeContextMenu, element, size))
4508 } else {
4509 None
4510 };
4511 let min_width = context_menu
4512 .as_ref()
4513 .map_or(px(0.), |(_, _, size)| size.width);
4514 let max_width = max_width_for_stable_x.max(
4515 context_menu
4516 .as_ref()
4517 .map_or(px(0.), |(_, _, size)| size.width),
4518 );
4519
4520 let edit_prediction = if edit_prediction_popover_visible {
4521 self.editor.update(cx, move |editor, cx| {
4522 let accept_binding =
4523 editor.accept_edit_prediction_keybind(false, window, cx);
4524 let mut element = editor.render_edit_prediction_cursor_popover(
4525 min_width,
4526 max_width,
4527 cursor_point,
4528 style,
4529 accept_binding.keystroke(),
4530 window,
4531 cx,
4532 )?;
4533 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4534 Some((CursorPopoverType::EditPrediction, element, size))
4535 })
4536 } else {
4537 None
4538 };
4539 vec![edit_prediction, context_menu]
4540 .into_iter()
4541 .flatten()
4542 .collect::<Vec<_>>()
4543 },
4544 )?;
4545
4546 let (menu_ix, (_, menu_bounds)) = laid_out_popovers
4547 .iter()
4548 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
4549 let last_ix = laid_out_popovers.len() - 1;
4550 let menu_is_last = menu_ix == last_ix;
4551 let first_popover_bounds = laid_out_popovers[0].1;
4552 let last_popover_bounds = laid_out_popovers[last_ix].1;
4553
4554 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
4555 // right, and otherwise it goes below or to the right.
4556 let mut target_bounds = Bounds::from_corners(
4557 first_popover_bounds.origin,
4558 last_popover_bounds.bottom_right(),
4559 );
4560 target_bounds.size.width = menu_bounds.size.width;
4561
4562 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
4563 // based on this is preferred for layout stability.
4564 let mut max_target_bounds = target_bounds;
4565 max_target_bounds.size.height = max_height;
4566 if y_flipped {
4567 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
4568 }
4569
4570 // Add spacing around `target_bounds` and `max_target_bounds`.
4571 let mut extend_amount = Edges::all(MENU_GAP);
4572 if y_flipped {
4573 extend_amount.bottom = line_height;
4574 } else {
4575 extend_amount.top = line_height;
4576 }
4577 let target_bounds = target_bounds.extend(extend_amount);
4578 let max_target_bounds = max_target_bounds.extend(extend_amount);
4579
4580 let must_place_above_or_below =
4581 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
4582 laid_out_popovers[menu_ix + 1..]
4583 .iter()
4584 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
4585 } else {
4586 false
4587 };
4588
4589 let aside_bounds = self.layout_context_menu_aside(
4590 y_flipped,
4591 *menu_bounds,
4592 target_bounds,
4593 max_target_bounds,
4594 max_menu_height,
4595 must_place_above_or_below,
4596 text_hitbox,
4597 viewport_bounds,
4598 window,
4599 cx,
4600 );
4601
4602 if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
4603 if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
4604 Some(*bounds)
4605 } else {
4606 None
4607 }
4608 }) {
4609 let bounds = if let Some(aside_bounds) = aside_bounds {
4610 menu_bounds.union(&aside_bounds)
4611 } else {
4612 menu_bounds
4613 };
4614 return Some(ContextMenuLayout { y_flipped, bounds });
4615 }
4616
4617 None
4618 }
4619
4620 fn layout_gutter_menu(
4621 &self,
4622 line_height: Pixels,
4623 text_hitbox: &Hitbox,
4624 content_origin: gpui::Point<Pixels>,
4625 right_margin: Pixels,
4626 scroll_pixel_position: gpui::Point<Pixels>,
4627 gutter_overshoot: Pixels,
4628 window: &mut Window,
4629 cx: &mut App,
4630 ) {
4631 let editor = self.editor.read(cx);
4632 if !editor.context_menu_visible() {
4633 return;
4634 }
4635 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
4636 editor.context_menu_origin()
4637 else {
4638 return;
4639 };
4640 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
4641 // indicator than just a plain first column of the text field.
4642 let target_position = content_origin
4643 + gpui::Point {
4644 x: -gutter_overshoot,
4645 y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
4646 };
4647
4648 let (min_height_in_lines, max_height_in_lines) = editor
4649 .context_menu_options
4650 .as_ref()
4651 .map_or((3, 12), |options| {
4652 (options.min_entries_visible, options.max_entries_visible)
4653 });
4654
4655 let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4656 let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4657 let viewport_bounds =
4658 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4659 right: -right_margin - MENU_GAP,
4660 ..Default::default()
4661 });
4662 self.layout_popovers_above_or_below_line(
4663 target_position,
4664 line_height,
4665 min_height,
4666 max_height,
4667 editor
4668 .context_menu_options
4669 .as_ref()
4670 .and_then(|options| options.placement.clone()),
4671 text_hitbox,
4672 viewport_bounds,
4673 window,
4674 cx,
4675 move |height, _max_width_for_stable_x, _, window, cx| {
4676 let mut element = self
4677 .render_context_menu(line_height, height, window, cx)
4678 .expect("Visible context menu should always render.");
4679 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4680 vec![(CursorPopoverType::CodeContextMenu, element, size)]
4681 },
4682 );
4683 }
4684
4685 fn layout_popovers_above_or_below_line(
4686 &self,
4687 target_position: gpui::Point<Pixels>,
4688 line_height: Pixels,
4689 min_height: Pixels,
4690 max_height: Pixels,
4691 placement: Option<ContextMenuPlacement>,
4692 text_hitbox: &Hitbox,
4693 viewport_bounds: Bounds<Pixels>,
4694 window: &mut Window,
4695 cx: &mut App,
4696 make_sized_popovers: impl FnOnce(
4697 Pixels,
4698 Pixels,
4699 bool,
4700 &mut Window,
4701 &mut App,
4702 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
4703 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
4704 let text_style = TextStyleRefinement {
4705 line_height: Some(DefiniteLength::Fraction(
4706 BufferLineHeight::Comfortable.value(),
4707 )),
4708 ..Default::default()
4709 };
4710 window.with_text_style(Some(text_style), |window| {
4711 // If the max height won't fit below and there is more space above, put it above the line.
4712 let bottom_y_when_flipped = target_position.y - line_height;
4713 let available_above = bottom_y_when_flipped - text_hitbox.top();
4714 let available_below = text_hitbox.bottom() - target_position.y;
4715 let y_overflows_below = max_height > available_below;
4716 let mut y_flipped = match placement {
4717 Some(ContextMenuPlacement::Above) => true,
4718 Some(ContextMenuPlacement::Below) => false,
4719 None => y_overflows_below && available_above > available_below,
4720 };
4721 let mut height = cmp::min(
4722 max_height,
4723 if y_flipped {
4724 available_above
4725 } else {
4726 available_below
4727 },
4728 );
4729
4730 // If the min height doesn't fit within text bounds, instead fit within the window.
4731 if height < min_height {
4732 let available_above = bottom_y_when_flipped;
4733 let available_below = viewport_bounds.bottom() - target_position.y;
4734 let (y_flipped_override, height_override) = match placement {
4735 Some(ContextMenuPlacement::Above) => {
4736 (true, cmp::min(available_above, min_height))
4737 }
4738 Some(ContextMenuPlacement::Below) => {
4739 (false, cmp::min(available_below, min_height))
4740 }
4741 None => {
4742 if available_below > min_height {
4743 (false, min_height)
4744 } else if available_above > min_height {
4745 (true, min_height)
4746 } else if available_above > available_below {
4747 (true, available_above)
4748 } else {
4749 (false, available_below)
4750 }
4751 }
4752 };
4753 y_flipped = y_flipped_override;
4754 height = height_override;
4755 }
4756
4757 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
4758
4759 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
4760 // for very narrow windows.
4761 let popovers =
4762 make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
4763 if popovers.is_empty() {
4764 return None;
4765 }
4766
4767 let max_width = popovers
4768 .iter()
4769 .map(|(_, _, size)| size.width)
4770 .max()
4771 .unwrap_or_default();
4772
4773 let mut current_position = gpui::Point {
4774 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
4775 // overflow. Include space for the scrollbar.
4776 x: target_position
4777 .x
4778 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
4779 y: if y_flipped {
4780 bottom_y_when_flipped
4781 } else {
4782 target_position.y
4783 },
4784 };
4785
4786 let mut laid_out_popovers = popovers
4787 .into_iter()
4788 .map(|(popover_type, element, size)| {
4789 if y_flipped {
4790 current_position.y -= size.height;
4791 }
4792 let position = current_position;
4793 window.defer_draw(element, current_position, 1);
4794 if !y_flipped {
4795 current_position.y += size.height + MENU_GAP;
4796 } else {
4797 current_position.y -= MENU_GAP;
4798 }
4799 (popover_type, Bounds::new(position, size))
4800 })
4801 .collect::<Vec<_>>();
4802
4803 if y_flipped {
4804 laid_out_popovers.reverse();
4805 }
4806
4807 Some((laid_out_popovers, y_flipped))
4808 })
4809 }
4810
4811 fn layout_context_menu_aside(
4812 &self,
4813 y_flipped: bool,
4814 menu_bounds: Bounds<Pixels>,
4815 target_bounds: Bounds<Pixels>,
4816 max_target_bounds: Bounds<Pixels>,
4817 max_height: Pixels,
4818 must_place_above_or_below: bool,
4819 text_hitbox: &Hitbox,
4820 viewport_bounds: Bounds<Pixels>,
4821 window: &mut Window,
4822 cx: &mut App,
4823 ) -> Option<Bounds<Pixels>> {
4824 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
4825 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
4826 && !must_place_above_or_below
4827 {
4828 let max_width = cmp::min(
4829 available_within_viewport.right - px(1.),
4830 MENU_ASIDE_MAX_WIDTH,
4831 );
4832 let mut aside = self.render_context_menu_aside(
4833 size(max_width, max_height - POPOVER_Y_PADDING),
4834 window,
4835 cx,
4836 )?;
4837 let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
4838 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
4839 Some((aside, right_position, size))
4840 } else {
4841 let max_size = size(
4842 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
4843 // won't be needed here.
4844 cmp::min(
4845 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
4846 viewport_bounds.right(),
4847 ),
4848 cmp::min(
4849 max_height,
4850 cmp::max(
4851 available_within_viewport.top,
4852 available_within_viewport.bottom,
4853 ),
4854 ) - POPOVER_Y_PADDING,
4855 );
4856 let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
4857 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
4858
4859 let top_position = point(
4860 menu_bounds.origin.x,
4861 target_bounds.top() - actual_size.height,
4862 );
4863 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
4864
4865 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
4866 // Prefer to fit on the same side of the line as the menu, then on the other side of
4867 // the line.
4868 if !y_flipped && wanted.height < available.bottom {
4869 Some(bottom_position)
4870 } else if !y_flipped && wanted.height < available.top {
4871 Some(top_position)
4872 } else if y_flipped && wanted.height < available.top {
4873 Some(top_position)
4874 } else if y_flipped && wanted.height < available.bottom {
4875 Some(bottom_position)
4876 } else {
4877 None
4878 }
4879 };
4880
4881 // Prefer choosing a direction using max sizes rather than actual size for stability.
4882 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
4883 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
4884 let aside_position = fit_within(available_within_text, wanted)
4885 // Fallback: fit max size in window.
4886 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
4887 // Fallback: fit actual size in window.
4888 .or_else(|| fit_within(available_within_viewport, actual_size));
4889
4890 aside_position.map(|position| (aside, position, actual_size))
4891 };
4892
4893 // Skip drawing if it doesn't fit anywhere.
4894 if let Some((aside, position, size)) = positioned_aside {
4895 let aside_bounds = Bounds::new(position, size);
4896 window.defer_draw(aside, position, 2);
4897 return Some(aside_bounds);
4898 }
4899
4900 None
4901 }
4902
4903 fn render_context_menu(
4904 &self,
4905 line_height: Pixels,
4906 height: Pixels,
4907 window: &mut Window,
4908 cx: &mut App,
4909 ) -> Option<AnyElement> {
4910 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
4911 self.editor.update(cx, |editor, cx| {
4912 editor.render_context_menu(&self.style, max_height_in_lines, window, cx)
4913 })
4914 }
4915
4916 fn render_context_menu_aside(
4917 &self,
4918 max_size: Size<Pixels>,
4919 window: &mut Window,
4920 cx: &mut App,
4921 ) -> Option<AnyElement> {
4922 if max_size.width < px(100.) || max_size.height < px(12.) {
4923 None
4924 } else {
4925 self.editor.update(cx, |editor, cx| {
4926 editor.render_context_menu_aside(max_size, window, cx)
4927 })
4928 }
4929 }
4930
4931 fn layout_mouse_context_menu(
4932 &self,
4933 editor_snapshot: &EditorSnapshot,
4934 visible_range: Range<DisplayRow>,
4935 content_origin: gpui::Point<Pixels>,
4936 window: &mut Window,
4937 cx: &mut App,
4938 ) -> Option<AnyElement> {
4939 let position = self.editor.update(cx, |editor, _cx| {
4940 let visible_start_point = editor.display_to_pixel_point(
4941 DisplayPoint::new(visible_range.start, 0),
4942 editor_snapshot,
4943 window,
4944 )?;
4945 let visible_end_point = editor.display_to_pixel_point(
4946 DisplayPoint::new(visible_range.end, 0),
4947 editor_snapshot,
4948 window,
4949 )?;
4950
4951 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4952 let (source_display_point, position) = match mouse_context_menu.position {
4953 MenuPosition::PinnedToScreen(point) => (None, point),
4954 MenuPosition::PinnedToEditor { source, offset } => {
4955 let source_display_point = source.to_display_point(editor_snapshot);
4956 let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
4957 let position = content_origin + source_point + offset;
4958 (Some(source_display_point), position)
4959 }
4960 };
4961
4962 let source_included = source_display_point.is_none_or(|source_display_point| {
4963 visible_range
4964 .to_inclusive()
4965 .contains(&source_display_point.row())
4966 });
4967 let position_included =
4968 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
4969 if !source_included && !position_included {
4970 None
4971 } else {
4972 Some(position)
4973 }
4974 })?;
4975
4976 let text_style = TextStyleRefinement {
4977 line_height: Some(DefiniteLength::Fraction(
4978 BufferLineHeight::Comfortable.value(),
4979 )),
4980 ..Default::default()
4981 };
4982 window.with_text_style(Some(text_style), |window| {
4983 let mut element = self.editor.read_with(cx, |editor, _| {
4984 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4985 let context_menu = mouse_context_menu.context_menu.clone();
4986
4987 Some(
4988 deferred(
4989 anchored()
4990 .position(position)
4991 .child(context_menu)
4992 .anchor(Corner::TopLeft)
4993 .snap_to_window_with_margin(px(8.)),
4994 )
4995 .with_priority(1)
4996 .into_any(),
4997 )
4998 })?;
4999
5000 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
5001 Some(element)
5002 })
5003 }
5004
5005 fn layout_hover_popovers(
5006 &self,
5007 snapshot: &EditorSnapshot,
5008 hitbox: &Hitbox,
5009 visible_display_row_range: Range<DisplayRow>,
5010 content_origin: gpui::Point<Pixels>,
5011 scroll_pixel_position: gpui::Point<Pixels>,
5012 line_layouts: &[LineWithInvisibles],
5013 line_height: Pixels,
5014 em_width: Pixels,
5015 context_menu_layout: Option<ContextMenuLayout>,
5016 window: &mut Window,
5017 cx: &mut App,
5018 ) {
5019 struct MeasuredHoverPopover {
5020 element: AnyElement,
5021 size: Size<Pixels>,
5022 horizontal_offset: Pixels,
5023 }
5024
5025 let max_size = size(
5026 (120. * em_width) // Default size
5027 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5028 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5029 (16. * line_height) // Default size
5030 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5031 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5032 );
5033
5034 let hover_popovers = self.editor.update(cx, |editor, cx| {
5035 editor.hover_state.render(
5036 snapshot,
5037 visible_display_row_range.clone(),
5038 max_size,
5039 window,
5040 cx,
5041 )
5042 });
5043 let Some((position, hover_popovers)) = hover_popovers else {
5044 return;
5045 };
5046
5047 // This is safe because we check on layout whether the required row is available
5048 let hovered_row_layout =
5049 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
5050
5051 // Compute Hovered Point
5052 let x =
5053 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
5054 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
5055 let hovered_point = content_origin + point(x, y);
5056
5057 let mut overall_height = Pixels::ZERO;
5058 let mut measured_hover_popovers = Vec::new();
5059 for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
5060 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
5061 let horizontal_offset =
5062 (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
5063 .min(Pixels::ZERO);
5064 match position {
5065 itertools::Position::Middle | itertools::Position::Last => {
5066 overall_height += HOVER_POPOVER_GAP
5067 }
5068 _ => {}
5069 }
5070 overall_height += size.height;
5071 measured_hover_popovers.push(MeasuredHoverPopover {
5072 element: hover_popover,
5073 size,
5074 horizontal_offset,
5075 });
5076 }
5077
5078 fn draw_occluder(
5079 width: Pixels,
5080 origin: gpui::Point<Pixels>,
5081 window: &mut Window,
5082 cx: &mut App,
5083 ) {
5084 let mut occlusion = div()
5085 .size_full()
5086 .occlude()
5087 .on_mouse_move(|_, _, cx| cx.stop_propagation())
5088 .into_any_element();
5089 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
5090 window.defer_draw(occlusion, origin, 2);
5091 }
5092
5093 fn place_popovers_above(
5094 hovered_point: gpui::Point<Pixels>,
5095 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5096 window: &mut Window,
5097 cx: &mut App,
5098 ) {
5099 let mut current_y = hovered_point.y;
5100 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5101 let size = popover.size;
5102 let popover_origin = point(
5103 hovered_point.x + popover.horizontal_offset,
5104 current_y - size.height,
5105 );
5106
5107 window.defer_draw(popover.element, popover_origin, 2);
5108 if position != itertools::Position::Last {
5109 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
5110 draw_occluder(size.width, origin, window, cx);
5111 }
5112
5113 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5114 }
5115 }
5116
5117 fn place_popovers_below(
5118 hovered_point: gpui::Point<Pixels>,
5119 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5120 line_height: Pixels,
5121 window: &mut Window,
5122 cx: &mut App,
5123 ) {
5124 let mut current_y = hovered_point.y + line_height;
5125 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5126 let size = popover.size;
5127 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5128
5129 window.defer_draw(popover.element, popover_origin, 2);
5130 if position != itertools::Position::Last {
5131 let origin = point(popover_origin.x, popover_origin.y + size.height);
5132 draw_occluder(size.width, origin, window, cx);
5133 }
5134
5135 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5136 }
5137 }
5138
5139 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5140 context_menu_layout
5141 .as_ref()
5142 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5143 };
5144
5145 let can_place_above = {
5146 let mut bounds_above = Vec::new();
5147 let mut current_y = hovered_point.y;
5148 for popover in &measured_hover_popovers {
5149 let size = popover.size;
5150 let popover_origin = point(
5151 hovered_point.x + popover.horizontal_offset,
5152 current_y - size.height,
5153 );
5154 bounds_above.push(Bounds::new(popover_origin, size));
5155 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5156 }
5157 bounds_above
5158 .iter()
5159 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5160 };
5161
5162 let can_place_below = || {
5163 let mut bounds_below = Vec::new();
5164 let mut current_y = hovered_point.y + line_height;
5165 for popover in &measured_hover_popovers {
5166 let size = popover.size;
5167 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5168 bounds_below.push(Bounds::new(popover_origin, size));
5169 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5170 }
5171 bounds_below
5172 .iter()
5173 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5174 };
5175
5176 if can_place_above {
5177 // try placing above hovered point
5178 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5179 } else if can_place_below() {
5180 // try placing below hovered point
5181 place_popovers_below(
5182 hovered_point,
5183 measured_hover_popovers,
5184 line_height,
5185 window,
5186 cx,
5187 );
5188 } else {
5189 // try to place popovers around the context menu
5190 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5191 let total_width = measured_hover_popovers
5192 .iter()
5193 .map(|p| p.size.width)
5194 .max()
5195 .unwrap_or(Pixels::ZERO);
5196 let y_for_horizontal_positioning = if menu.y_flipped {
5197 menu.bounds.bottom() - overall_height
5198 } else {
5199 menu.bounds.top()
5200 };
5201 let possible_origins = vec![
5202 // left of context menu
5203 point(
5204 menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
5205 y_for_horizontal_positioning,
5206 ),
5207 // right of context menu
5208 point(
5209 menu.bounds.right() + HOVER_POPOVER_GAP,
5210 y_for_horizontal_positioning,
5211 ),
5212 // top of context menu
5213 point(
5214 menu.bounds.left(),
5215 menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
5216 ),
5217 // bottom of context menu
5218 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5219 ];
5220 possible_origins.into_iter().find(|&origin| {
5221 Bounds::new(origin, size(total_width, overall_height))
5222 .is_contained_within(hitbox)
5223 })
5224 });
5225 if let Some(origin) = origin_surrounding_menu {
5226 let mut current_y = origin.y;
5227 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5228 let size = popover.size;
5229 let popover_origin = point(origin.x, current_y);
5230
5231 window.defer_draw(popover.element, popover_origin, 2);
5232 if position != itertools::Position::Last {
5233 let origin = point(popover_origin.x, popover_origin.y + size.height);
5234 draw_occluder(size.width, origin, window, cx);
5235 }
5236
5237 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5238 }
5239 } else {
5240 // fallback to existing above/below cursor logic
5241 // this might overlap menu or overflow in rare case
5242 if can_place_above {
5243 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5244 } else {
5245 place_popovers_below(
5246 hovered_point,
5247 measured_hover_popovers,
5248 line_height,
5249 window,
5250 cx,
5251 );
5252 }
5253 }
5254 }
5255 }
5256
5257 fn layout_diff_hunk_controls(
5258 &self,
5259 row_range: Range<DisplayRow>,
5260 row_infos: &[RowInfo],
5261 text_hitbox: &Hitbox,
5262 newest_cursor_position: Option<DisplayPoint>,
5263 line_height: Pixels,
5264 right_margin: Pixels,
5265 scroll_pixel_position: gpui::Point<Pixels>,
5266 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5267 highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
5268 editor: Entity<Editor>,
5269 window: &mut Window,
5270 cx: &mut App,
5271 ) -> (Vec<AnyElement>, Vec<(DisplayRow, Bounds<Pixels>)>) {
5272 let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
5273 let hovered_diff_hunk_row = editor.read(cx).hovered_diff_hunk_row;
5274
5275 let mut controls = vec![];
5276 let mut control_bounds = vec![];
5277
5278 let active_positions = [
5279 hovered_diff_hunk_row.map(|row| DisplayPoint::new(row, 0)),
5280 newest_cursor_position,
5281 ];
5282
5283 for (hunk, _) in display_hunks {
5284 if let DisplayDiffHunk::Unfolded {
5285 display_row_range,
5286 multi_buffer_range,
5287 status,
5288 is_created_file,
5289 ..
5290 } = &hunk
5291 {
5292 if display_row_range.start < row_range.start
5293 || display_row_range.start >= row_range.end
5294 {
5295 continue;
5296 }
5297 if highlighted_rows
5298 .get(&display_row_range.start)
5299 .and_then(|highlight| highlight.type_id)
5300 .is_some_and(|type_id| {
5301 [
5302 TypeId::of::<ConflictsOuter>(),
5303 TypeId::of::<ConflictsOursMarker>(),
5304 TypeId::of::<ConflictsOurs>(),
5305 TypeId::of::<ConflictsTheirs>(),
5306 TypeId::of::<ConflictsTheirsMarker>(),
5307 ]
5308 .contains(&type_id)
5309 })
5310 {
5311 continue;
5312 }
5313 let row_ix = (display_row_range.start - row_range.start).0 as usize;
5314 if row_infos[row_ix].diff_status.is_none() {
5315 continue;
5316 }
5317 if row_infos[row_ix]
5318 .diff_status
5319 .is_some_and(|status| status.is_added())
5320 && !status.is_added()
5321 {
5322 continue;
5323 }
5324
5325 if active_positions
5326 .iter()
5327 .any(|p| p.is_some_and(|p| display_row_range.contains(&p.row())))
5328 {
5329 let y = display_row_range.start.as_f32() * line_height
5330 + text_hitbox.bounds.top()
5331 - scroll_pixel_position.y;
5332
5333 let mut element = render_diff_hunk_controls(
5334 display_row_range.start.0,
5335 status,
5336 multi_buffer_range.clone(),
5337 *is_created_file,
5338 line_height,
5339 &editor,
5340 window,
5341 cx,
5342 );
5343 let size =
5344 element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
5345
5346 let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
5347
5348 let bounds = Bounds::new(gpui::Point::new(x, y), size);
5349 control_bounds.push((display_row_range.start, bounds));
5350
5351 window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
5352 element.prepaint(window, cx)
5353 });
5354 controls.push(element);
5355 }
5356 }
5357 }
5358
5359 (controls, control_bounds)
5360 }
5361
5362 fn layout_signature_help(
5363 &self,
5364 hitbox: &Hitbox,
5365 content_origin: gpui::Point<Pixels>,
5366 scroll_pixel_position: gpui::Point<Pixels>,
5367 newest_selection_head: Option<DisplayPoint>,
5368 start_row: DisplayRow,
5369 line_layouts: &[LineWithInvisibles],
5370 line_height: Pixels,
5371 em_width: Pixels,
5372 context_menu_layout: Option<ContextMenuLayout>,
5373 window: &mut Window,
5374 cx: &mut App,
5375 ) {
5376 if !self.editor.focus_handle(cx).is_focused(window) {
5377 return;
5378 }
5379 let Some(newest_selection_head) = newest_selection_head else {
5380 return;
5381 };
5382
5383 let max_size = size(
5384 (120. * em_width) // Default size
5385 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5386 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5387 (16. * line_height) // Default size
5388 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5389 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5390 );
5391
5392 let maybe_element = self.editor.update(cx, |editor, cx| {
5393 if let Some(popover) = editor.signature_help_state.popover_mut() {
5394 let element = popover.render(max_size, window, cx);
5395 Some(element)
5396 } else {
5397 None
5398 }
5399 });
5400 let Some(mut element) = maybe_element else {
5401 return;
5402 };
5403
5404 let selection_row = newest_selection_head.row();
5405 let Some(cursor_row_layout) = (selection_row >= start_row)
5406 .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
5407 .flatten()
5408 else {
5409 return;
5410 };
5411
5412 let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
5413 - scroll_pixel_position.x;
5414 let target_y = selection_row.as_f32() * line_height - scroll_pixel_position.y;
5415 let target_point = content_origin + point(target_x, target_y);
5416
5417 let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
5418
5419 let (popover_bounds_above, popover_bounds_below) = {
5420 let horizontal_offset = (hitbox.top_right().x
5421 - POPOVER_RIGHT_OFFSET
5422 - (target_point.x + actual_size.width))
5423 .min(Pixels::ZERO);
5424 let initial_x = target_point.x + horizontal_offset;
5425 (
5426 Bounds::new(
5427 point(initial_x, target_point.y - actual_size.height),
5428 actual_size,
5429 ),
5430 Bounds::new(
5431 point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
5432 actual_size,
5433 ),
5434 )
5435 };
5436
5437 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5438 context_menu_layout
5439 .as_ref()
5440 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5441 };
5442
5443 let final_origin = if popover_bounds_above.is_contained_within(hitbox)
5444 && !intersects_menu(popover_bounds_above)
5445 {
5446 // try placing above cursor
5447 popover_bounds_above.origin
5448 } else if popover_bounds_below.is_contained_within(hitbox)
5449 && !intersects_menu(popover_bounds_below)
5450 {
5451 // try placing below cursor
5452 popover_bounds_below.origin
5453 } else {
5454 // try surrounding context menu if exists
5455 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5456 let y_for_horizontal_positioning = if menu.y_flipped {
5457 menu.bounds.bottom() - actual_size.height
5458 } else {
5459 menu.bounds.top()
5460 };
5461 let possible_origins = vec![
5462 // left of context menu
5463 point(
5464 menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
5465 y_for_horizontal_positioning,
5466 ),
5467 // right of context menu
5468 point(
5469 menu.bounds.right() + HOVER_POPOVER_GAP,
5470 y_for_horizontal_positioning,
5471 ),
5472 // top of context menu
5473 point(
5474 menu.bounds.left(),
5475 menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
5476 ),
5477 // bottom of context menu
5478 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5479 ];
5480 possible_origins
5481 .into_iter()
5482 .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
5483 });
5484 origin_surrounding_menu.unwrap_or_else(|| {
5485 // fallback to existing above/below cursor logic
5486 // this might overlap menu or overflow in rare case
5487 if popover_bounds_above.is_contained_within(hitbox) {
5488 popover_bounds_above.origin
5489 } else {
5490 popover_bounds_below.origin
5491 }
5492 })
5493 };
5494
5495 window.defer_draw(element, final_origin, 2);
5496 }
5497
5498 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5499 window.paint_layer(layout.hitbox.bounds, |window| {
5500 let scroll_top = layout.position_map.snapshot.scroll_position().y;
5501 let gutter_bg = cx.theme().colors().editor_gutter_background;
5502 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
5503 window.paint_quad(fill(
5504 layout.position_map.text_hitbox.bounds,
5505 self.style.background,
5506 ));
5507
5508 if matches!(
5509 layout.mode,
5510 EditorMode::Full { .. } | EditorMode::Minimap { .. }
5511 ) {
5512 let show_active_line_background = match layout.mode {
5513 EditorMode::Full {
5514 show_active_line_background,
5515 ..
5516 } => show_active_line_background,
5517 EditorMode::Minimap { .. } => true,
5518 _ => false,
5519 };
5520 let mut active_rows = layout.active_rows.iter().peekable();
5521 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
5522 let mut end_row = start_row.0;
5523 while active_rows
5524 .peek()
5525 .is_some_and(|(active_row, has_selection)| {
5526 active_row.0 == end_row + 1
5527 && has_selection.selection == contains_non_empty_selection.selection
5528 })
5529 {
5530 active_rows.next().unwrap();
5531 end_row += 1;
5532 }
5533
5534 if show_active_line_background && !contains_non_empty_selection.selection {
5535 let highlight_h_range =
5536 match layout.position_map.snapshot.current_line_highlight {
5537 CurrentLineHighlight::Gutter => Some(Range {
5538 start: layout.hitbox.left(),
5539 end: layout.gutter_hitbox.right(),
5540 }),
5541 CurrentLineHighlight::Line => Some(Range {
5542 start: layout.position_map.text_hitbox.bounds.left(),
5543 end: layout.position_map.text_hitbox.bounds.right(),
5544 }),
5545 CurrentLineHighlight::All => Some(Range {
5546 start: layout.hitbox.left(),
5547 end: layout.hitbox.right(),
5548 }),
5549 CurrentLineHighlight::None => None,
5550 };
5551 if let Some(range) = highlight_h_range {
5552 let active_line_bg = cx.theme().colors().editor_active_line_background;
5553 let bounds = Bounds {
5554 origin: point(
5555 range.start,
5556 layout.hitbox.origin.y
5557 + (start_row.as_f32() - scroll_top)
5558 * layout.position_map.line_height,
5559 ),
5560 size: size(
5561 range.end - range.start,
5562 layout.position_map.line_height
5563 * (end_row - start_row.0 + 1) as f32,
5564 ),
5565 };
5566 window.paint_quad(fill(bounds, active_line_bg));
5567 }
5568 }
5569 }
5570
5571 let mut paint_highlight = |highlight_row_start: DisplayRow,
5572 highlight_row_end: DisplayRow,
5573 highlight: crate::LineHighlight,
5574 edges| {
5575 let mut origin_x = layout.hitbox.left();
5576 let mut width = layout.hitbox.size.width;
5577 if !highlight.include_gutter {
5578 origin_x += layout.gutter_hitbox.size.width;
5579 width -= layout.gutter_hitbox.size.width;
5580 }
5581
5582 let origin = point(
5583 origin_x,
5584 layout.hitbox.origin.y
5585 + (highlight_row_start.as_f32() - scroll_top)
5586 * layout.position_map.line_height,
5587 );
5588 let size = size(
5589 width,
5590 layout.position_map.line_height
5591 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
5592 );
5593 let mut quad = fill(Bounds { origin, size }, highlight.background);
5594 if let Some(border_color) = highlight.border {
5595 quad.border_color = border_color;
5596 quad.border_widths = edges
5597 }
5598 window.paint_quad(quad);
5599 };
5600
5601 let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
5602 None;
5603 for (&new_row, &new_background) in &layout.highlighted_rows {
5604 match &mut current_paint {
5605 &mut Some((current_background, ref mut current_range, mut edges)) => {
5606 let new_range_started = current_background != new_background
5607 || current_range.end.next_row() != new_row;
5608 if new_range_started {
5609 if current_range.end.next_row() == new_row {
5610 edges.bottom = px(0.);
5611 };
5612 paint_highlight(
5613 current_range.start,
5614 current_range.end,
5615 current_background,
5616 edges,
5617 );
5618 let edges = Edges {
5619 top: if current_range.end.next_row() != new_row {
5620 px(1.)
5621 } else {
5622 px(0.)
5623 },
5624 bottom: px(1.),
5625 ..Default::default()
5626 };
5627 current_paint = Some((new_background, new_row..new_row, edges));
5628 continue;
5629 } else {
5630 current_range.end = current_range.end.next_row();
5631 }
5632 }
5633 None => {
5634 let edges = Edges {
5635 top: px(1.),
5636 bottom: px(1.),
5637 ..Default::default()
5638 };
5639 current_paint = Some((new_background, new_row..new_row, edges))
5640 }
5641 };
5642 }
5643 if let Some((color, range, edges)) = current_paint {
5644 paint_highlight(range.start, range.end, color, edges);
5645 }
5646
5647 for (guide_x, active) in layout.wrap_guides.iter() {
5648 let color = if *active {
5649 cx.theme().colors().editor_active_wrap_guide
5650 } else {
5651 cx.theme().colors().editor_wrap_guide
5652 };
5653 window.paint_quad(fill(
5654 Bounds {
5655 origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
5656 size: size(px(1.), layout.position_map.text_hitbox.size.height),
5657 },
5658 color,
5659 ));
5660 }
5661 }
5662 })
5663 }
5664
5665 fn paint_indent_guides(
5666 &mut self,
5667 layout: &mut EditorLayout,
5668 window: &mut Window,
5669 cx: &mut App,
5670 ) {
5671 let Some(indent_guides) = &layout.indent_guides else {
5672 return;
5673 };
5674
5675 let faded_color = |color: Hsla, alpha: f32| {
5676 let mut faded = color;
5677 faded.a = alpha;
5678 faded
5679 };
5680
5681 for indent_guide in indent_guides {
5682 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
5683 let settings = &indent_guide.settings;
5684
5685 // TODO fixed for now, expose them through themes later
5686 const INDENT_AWARE_ALPHA: f32 = 0.2;
5687 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
5688 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
5689 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
5690
5691 let line_color = match (settings.coloring, indent_guide.active) {
5692 (IndentGuideColoring::Disabled, _) => None,
5693 (IndentGuideColoring::Fixed, false) => {
5694 Some(cx.theme().colors().editor_indent_guide)
5695 }
5696 (IndentGuideColoring::Fixed, true) => {
5697 Some(cx.theme().colors().editor_indent_guide_active)
5698 }
5699 (IndentGuideColoring::IndentAware, false) => {
5700 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
5701 }
5702 (IndentGuideColoring::IndentAware, true) => {
5703 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
5704 }
5705 };
5706
5707 let background_color = match (settings.background_coloring, indent_guide.active) {
5708 (IndentGuideBackgroundColoring::Disabled, _) => None,
5709 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
5710 indent_accent_colors,
5711 INDENT_AWARE_BACKGROUND_ALPHA,
5712 )),
5713 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
5714 indent_accent_colors,
5715 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
5716 )),
5717 };
5718
5719 let requested_line_width = if indent_guide.active {
5720 settings.active_line_width
5721 } else {
5722 settings.line_width
5723 }
5724 .clamp(1, 10);
5725 let mut line_indicator_width = 0.;
5726 if let Some(color) = line_color {
5727 window.paint_quad(fill(
5728 Bounds {
5729 origin: indent_guide.origin,
5730 size: size(px(requested_line_width as f32), indent_guide.length),
5731 },
5732 color,
5733 ));
5734 line_indicator_width = requested_line_width as f32;
5735 }
5736
5737 if let Some(color) = background_color {
5738 let width = indent_guide.single_indent_width - px(line_indicator_width);
5739 window.paint_quad(fill(
5740 Bounds {
5741 origin: point(
5742 indent_guide.origin.x + px(line_indicator_width),
5743 indent_guide.origin.y,
5744 ),
5745 size: size(width, indent_guide.length),
5746 },
5747 color,
5748 ));
5749 }
5750 }
5751 }
5752
5753 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5754 let is_singleton = self.editor.read(cx).is_singleton(cx);
5755
5756 let line_height = layout.position_map.line_height;
5757 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
5758
5759 for LineNumberLayout {
5760 shaped_line,
5761 hitbox,
5762 } in layout.line_numbers.values()
5763 {
5764 let Some(hitbox) = hitbox else {
5765 continue;
5766 };
5767
5768 let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
5769 let color = cx.theme().colors().editor_hover_line_number;
5770
5771 let line = self.shape_line_number(shaped_line.text.clone(), color, window);
5772 line.paint(hitbox.origin, line_height, window, cx).log_err()
5773 } else {
5774 shaped_line
5775 .paint(hitbox.origin, line_height, window, cx)
5776 .log_err()
5777 }) else {
5778 continue;
5779 };
5780
5781 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
5782 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
5783 if is_singleton {
5784 window.set_cursor_style(CursorStyle::IBeam, hitbox);
5785 } else {
5786 window.set_cursor_style(CursorStyle::PointingHand, hitbox);
5787 }
5788 }
5789 }
5790
5791 fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5792 if layout.display_hunks.is_empty() {
5793 return;
5794 }
5795
5796 let line_height = layout.position_map.line_height;
5797 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5798 for (hunk, hitbox) in &layout.display_hunks {
5799 let hunk_to_paint = match hunk {
5800 DisplayDiffHunk::Folded { .. } => {
5801 let hunk_bounds = Self::diff_hunk_bounds(
5802 &layout.position_map.snapshot,
5803 line_height,
5804 layout.gutter_hitbox.bounds,
5805 hunk,
5806 );
5807 Some((
5808 hunk_bounds,
5809 cx.theme().colors().version_control_modified,
5810 Corners::all(px(0.)),
5811 DiffHunkStatus::modified_none(),
5812 ))
5813 }
5814 DisplayDiffHunk::Unfolded {
5815 status,
5816 display_row_range,
5817 ..
5818 } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
5819 DiffHunkStatusKind::Added => (
5820 hunk_hitbox.bounds,
5821 cx.theme().colors().version_control_added,
5822 Corners::all(px(0.)),
5823 *status,
5824 ),
5825 DiffHunkStatusKind::Modified => (
5826 hunk_hitbox.bounds,
5827 cx.theme().colors().version_control_modified,
5828 Corners::all(px(0.)),
5829 *status,
5830 ),
5831 DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
5832 hunk_hitbox.bounds,
5833 cx.theme().colors().version_control_deleted,
5834 Corners::all(px(0.)),
5835 *status,
5836 ),
5837 DiffHunkStatusKind::Deleted => (
5838 Bounds::new(
5839 point(
5840 hunk_hitbox.origin.x - hunk_hitbox.size.width,
5841 hunk_hitbox.origin.y,
5842 ),
5843 size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
5844 ),
5845 cx.theme().colors().version_control_deleted,
5846 Corners::all(1. * line_height),
5847 *status,
5848 ),
5849 }),
5850 };
5851
5852 if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
5853 // Flatten the background color with the editor color to prevent
5854 // elements below transparent hunks from showing through
5855 let flattened_background_color = cx
5856 .theme()
5857 .colors()
5858 .editor_background
5859 .blend(background_color);
5860
5861 if !Self::diff_hunk_hollow(status, cx) {
5862 window.paint_quad(quad(
5863 hunk_bounds,
5864 corner_radii,
5865 flattened_background_color,
5866 Edges::default(),
5867 transparent_black(),
5868 BorderStyle::default(),
5869 ));
5870 } else {
5871 let flattened_unstaged_background_color = cx
5872 .theme()
5873 .colors()
5874 .editor_background
5875 .blend(background_color.opacity(0.3));
5876
5877 window.paint_quad(quad(
5878 hunk_bounds,
5879 corner_radii,
5880 flattened_unstaged_background_color,
5881 Edges::all(Pixels(1.0)),
5882 flattened_background_color,
5883 BorderStyle::Solid,
5884 ));
5885 }
5886 }
5887 }
5888 });
5889 }
5890
5891 fn gutter_strip_width(line_height: Pixels) -> Pixels {
5892 (0.275 * line_height).floor()
5893 }
5894
5895 fn diff_hunk_bounds(
5896 snapshot: &EditorSnapshot,
5897 line_height: Pixels,
5898 gutter_bounds: Bounds<Pixels>,
5899 hunk: &DisplayDiffHunk,
5900 ) -> Bounds<Pixels> {
5901 let scroll_position = snapshot.scroll_position();
5902 let scroll_top = scroll_position.y * line_height;
5903 let gutter_strip_width = Self::gutter_strip_width(line_height);
5904
5905 match hunk {
5906 DisplayDiffHunk::Folded { display_row, .. } => {
5907 let start_y = display_row.as_f32() * line_height - scroll_top;
5908 let end_y = start_y + line_height;
5909 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5910 let highlight_size = size(gutter_strip_width, end_y - start_y);
5911 Bounds::new(highlight_origin, highlight_size)
5912 }
5913 DisplayDiffHunk::Unfolded {
5914 display_row_range,
5915 status,
5916 ..
5917 } => {
5918 if status.is_deleted() && display_row_range.is_empty() {
5919 let row = display_row_range.start;
5920
5921 let offset = line_height / 2.;
5922 let start_y = row.as_f32() * line_height - offset - scroll_top;
5923 let end_y = start_y + line_height;
5924
5925 let width = (0.35 * line_height).floor();
5926 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5927 let highlight_size = size(width, end_y - start_y);
5928 Bounds::new(highlight_origin, highlight_size)
5929 } else {
5930 let start_row = display_row_range.start;
5931 let end_row = display_row_range.end;
5932 // If we're in a multibuffer, row range span might include an
5933 // excerpt header, so if we were to draw the marker straight away,
5934 // the hunk might include the rows of that header.
5935 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
5936 // Instead, we simply check whether the range we're dealing with includes
5937 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
5938 let end_row_in_current_excerpt = snapshot
5939 .blocks_in_range(start_row..end_row)
5940 .find_map(|(start_row, block)| {
5941 if matches!(
5942 block,
5943 Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
5944 ) {
5945 Some(start_row)
5946 } else {
5947 None
5948 }
5949 })
5950 .unwrap_or(end_row);
5951
5952 let start_y = start_row.as_f32() * line_height - scroll_top;
5953 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
5954
5955 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5956 let highlight_size = size(gutter_strip_width, end_y - start_y);
5957 Bounds::new(highlight_origin, highlight_size)
5958 }
5959 }
5960 }
5961 }
5962
5963 fn paint_gutter_indicators(
5964 &self,
5965 layout: &mut EditorLayout,
5966 window: &mut Window,
5967 cx: &mut App,
5968 ) {
5969 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5970 window.with_element_namespace("crease_toggles", |window| {
5971 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
5972 crease_toggle.paint(window, cx);
5973 }
5974 });
5975
5976 window.with_element_namespace("expand_toggles", |window| {
5977 for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
5978 expand_toggle.paint(window, cx);
5979 }
5980 });
5981
5982 for breakpoint in layout.breakpoints.iter_mut() {
5983 breakpoint.paint(window, cx);
5984 }
5985
5986 for test_indicator in layout.test_indicators.iter_mut() {
5987 test_indicator.paint(window, cx);
5988 }
5989 });
5990 }
5991
5992 fn paint_gutter_highlights(
5993 &self,
5994 layout: &mut EditorLayout,
5995 window: &mut Window,
5996 cx: &mut App,
5997 ) {
5998 for (_, hunk_hitbox) in &layout.display_hunks {
5999 if let Some(hunk_hitbox) = hunk_hitbox
6000 && !self
6001 .editor
6002 .read(cx)
6003 .buffer()
6004 .read(cx)
6005 .all_diff_hunks_expanded()
6006 {
6007 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
6008 }
6009 }
6010
6011 let show_git_gutter = layout
6012 .position_map
6013 .snapshot
6014 .show_git_diff_gutter
6015 .unwrap_or_else(|| {
6016 matches!(
6017 ProjectSettings::get_global(cx).git.git_gutter,
6018 GitGutterSetting::TrackedFiles
6019 )
6020 });
6021 if show_git_gutter {
6022 Self::paint_gutter_diff_hunks(layout, window, cx)
6023 }
6024
6025 let highlight_width = 0.275 * layout.position_map.line_height;
6026 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
6027 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6028 for (range, color) in &layout.highlighted_gutter_ranges {
6029 let start_row = if range.start.row() < layout.visible_display_row_range.start {
6030 layout.visible_display_row_range.start - DisplayRow(1)
6031 } else {
6032 range.start.row()
6033 };
6034 let end_row = if range.end.row() > layout.visible_display_row_range.end {
6035 layout.visible_display_row_range.end + DisplayRow(1)
6036 } else {
6037 range.end.row()
6038 };
6039
6040 let start_y = layout.gutter_hitbox.top()
6041 + start_row.0 as f32 * layout.position_map.line_height
6042 - layout.position_map.scroll_pixel_position.y;
6043 let end_y = layout.gutter_hitbox.top()
6044 + (end_row.0 + 1) as f32 * layout.position_map.line_height
6045 - layout.position_map.scroll_pixel_position.y;
6046 let bounds = Bounds::from_corners(
6047 point(layout.gutter_hitbox.left(), start_y),
6048 point(layout.gutter_hitbox.left() + highlight_width, end_y),
6049 );
6050 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
6051 }
6052 });
6053 }
6054
6055 fn paint_blamed_display_rows(
6056 &self,
6057 layout: &mut EditorLayout,
6058 window: &mut Window,
6059 cx: &mut App,
6060 ) {
6061 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
6062 return;
6063 };
6064
6065 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6066 for mut blame_element in blamed_display_rows.into_iter() {
6067 blame_element.paint(window, cx);
6068 }
6069 })
6070 }
6071
6072 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6073 window.with_content_mask(
6074 Some(ContentMask {
6075 bounds: layout.position_map.text_hitbox.bounds,
6076 }),
6077 |window| {
6078 let editor = self.editor.read(cx);
6079 if editor.mouse_cursor_hidden {
6080 window.set_window_cursor_style(CursorStyle::None);
6081 } else if let SelectionDragState::ReadyToDrag {
6082 mouse_down_time, ..
6083 } = &editor.selection_drag_state
6084 {
6085 let drag_and_drop_delay = Duration::from_millis(
6086 EditorSettings::get_global(cx).drag_and_drop_selection.delay,
6087 );
6088 if mouse_down_time.elapsed() >= drag_and_drop_delay {
6089 window.set_cursor_style(
6090 CursorStyle::DragCopy,
6091 &layout.position_map.text_hitbox,
6092 );
6093 }
6094 } else if matches!(
6095 editor.selection_drag_state,
6096 SelectionDragState::Dragging { .. }
6097 ) {
6098 window
6099 .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
6100 } else if editor
6101 .hovered_link_state
6102 .as_ref()
6103 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
6104 {
6105 window.set_cursor_style(
6106 CursorStyle::PointingHand,
6107 &layout.position_map.text_hitbox,
6108 );
6109 } else {
6110 window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
6111 };
6112
6113 self.paint_lines_background(layout, window, cx);
6114 let invisible_display_ranges = self.paint_highlights(layout, window, cx);
6115 self.paint_document_colors(layout, window);
6116 self.paint_lines(&invisible_display_ranges, layout, window, cx);
6117 self.paint_redactions(layout, window);
6118 self.paint_cursors(layout, window, cx);
6119 self.paint_inline_diagnostics(layout, window, cx);
6120 self.paint_inline_blame(layout, window, cx);
6121 self.paint_inline_code_actions(layout, window, cx);
6122 self.paint_diff_hunk_controls(layout, window, cx);
6123 window.with_element_namespace("crease_trailers", |window| {
6124 for trailer in layout.crease_trailers.iter_mut().flatten() {
6125 trailer.element.paint(window, cx);
6126 }
6127 });
6128 },
6129 )
6130 }
6131
6132 fn paint_highlights(
6133 &mut self,
6134 layout: &mut EditorLayout,
6135 window: &mut Window,
6136 cx: &mut App,
6137 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
6138 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6139 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
6140 let line_end_overshoot = 0.15 * layout.position_map.line_height;
6141 for (range, color) in &layout.highlighted_ranges {
6142 self.paint_highlighted_range(
6143 range.clone(),
6144 true,
6145 *color,
6146 Pixels::ZERO,
6147 line_end_overshoot,
6148 layout,
6149 window,
6150 );
6151 }
6152
6153 let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
6154 0.15 * layout.position_map.line_height
6155 } else {
6156 Pixels::ZERO
6157 };
6158
6159 for (player_color, selections) in &layout.selections {
6160 for selection in selections.iter() {
6161 self.paint_highlighted_range(
6162 selection.range.clone(),
6163 true,
6164 player_color.selection,
6165 corner_radius,
6166 corner_radius * 2.,
6167 layout,
6168 window,
6169 );
6170
6171 if selection.is_local && !selection.range.is_empty() {
6172 invisible_display_ranges.push(selection.range.clone());
6173 }
6174 }
6175 }
6176 invisible_display_ranges
6177 })
6178 }
6179
6180 fn paint_lines(
6181 &mut self,
6182 invisible_display_ranges: &[Range<DisplayPoint>],
6183 layout: &mut EditorLayout,
6184 window: &mut Window,
6185 cx: &mut App,
6186 ) {
6187 let whitespace_setting = self
6188 .editor
6189 .read(cx)
6190 .buffer
6191 .read(cx)
6192 .language_settings(cx)
6193 .show_whitespaces;
6194
6195 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6196 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6197 line_with_invisibles.draw(
6198 layout,
6199 row,
6200 layout.content_origin,
6201 whitespace_setting,
6202 invisible_display_ranges,
6203 window,
6204 cx,
6205 )
6206 }
6207
6208 for line_element in &mut layout.line_elements {
6209 line_element.paint(window, cx);
6210 }
6211 }
6212
6213 fn paint_lines_background(
6214 &mut self,
6215 layout: &mut EditorLayout,
6216 window: &mut Window,
6217 cx: &mut App,
6218 ) {
6219 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6220 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6221 line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
6222 }
6223 }
6224
6225 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
6226 if layout.redacted_ranges.is_empty() {
6227 return;
6228 }
6229
6230 let line_end_overshoot = layout.line_end_overshoot();
6231
6232 // A softer than perfect black
6233 let redaction_color = gpui::rgb(0x0e1111);
6234
6235 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6236 for range in layout.redacted_ranges.iter() {
6237 self.paint_highlighted_range(
6238 range.clone(),
6239 true,
6240 redaction_color.into(),
6241 Pixels::ZERO,
6242 line_end_overshoot,
6243 layout,
6244 window,
6245 );
6246 }
6247 });
6248 }
6249
6250 fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
6251 let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
6252 return;
6253 };
6254 if image_colors.is_empty()
6255 || colors_render_mode == &DocumentColorsRenderMode::None
6256 || colors_render_mode == &DocumentColorsRenderMode::Inlay
6257 {
6258 return;
6259 }
6260
6261 let line_end_overshoot = layout.line_end_overshoot();
6262
6263 for (range, color) in image_colors {
6264 match colors_render_mode {
6265 DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
6266 DocumentColorsRenderMode::Background => {
6267 self.paint_highlighted_range(
6268 range.clone(),
6269 true,
6270 *color,
6271 Pixels::ZERO,
6272 line_end_overshoot,
6273 layout,
6274 window,
6275 );
6276 }
6277 DocumentColorsRenderMode::Border => {
6278 self.paint_highlighted_range(
6279 range.clone(),
6280 false,
6281 *color,
6282 Pixels::ZERO,
6283 line_end_overshoot,
6284 layout,
6285 window,
6286 );
6287 }
6288 }
6289 }
6290 }
6291
6292 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6293 for cursor in &mut layout.visible_cursors {
6294 cursor.paint(layout.content_origin, window, cx);
6295 }
6296 }
6297
6298 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6299 let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
6300 return;
6301 };
6302 let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
6303
6304 for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
6305 let hitbox = &scrollbar_layout.hitbox;
6306 if scrollbars_layout.visible {
6307 let scrollbar_edges = match axis {
6308 ScrollbarAxis::Horizontal => Edges {
6309 top: Pixels::ZERO,
6310 right: Pixels::ZERO,
6311 bottom: Pixels::ZERO,
6312 left: Pixels::ZERO,
6313 },
6314 ScrollbarAxis::Vertical => Edges {
6315 top: Pixels::ZERO,
6316 right: Pixels::ZERO,
6317 bottom: Pixels::ZERO,
6318 left: ScrollbarLayout::BORDER_WIDTH,
6319 },
6320 };
6321
6322 window.paint_layer(hitbox.bounds, |window| {
6323 window.paint_quad(quad(
6324 hitbox.bounds,
6325 Corners::default(),
6326 cx.theme().colors().scrollbar_track_background,
6327 scrollbar_edges,
6328 cx.theme().colors().scrollbar_track_border,
6329 BorderStyle::Solid,
6330 ));
6331
6332 if axis == ScrollbarAxis::Vertical {
6333 let fast_markers =
6334 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
6335 // Refresh slow scrollbar markers in the background. Below, we
6336 // paint whatever markers have already been computed.
6337 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
6338
6339 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
6340 for marker in markers.iter().chain(&fast_markers) {
6341 let mut marker = marker.clone();
6342 marker.bounds.origin += hitbox.origin;
6343 window.paint_quad(marker);
6344 }
6345 }
6346
6347 if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
6348 let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
6349 ScrollbarThumbState::Dragging => {
6350 cx.theme().colors().scrollbar_thumb_active_background
6351 }
6352 ScrollbarThumbState::Hovered => {
6353 cx.theme().colors().scrollbar_thumb_hover_background
6354 }
6355 ScrollbarThumbState::Idle => {
6356 cx.theme().colors().scrollbar_thumb_background
6357 }
6358 };
6359 window.paint_quad(quad(
6360 thumb_bounds,
6361 Corners::default(),
6362 scrollbar_thumb_color,
6363 scrollbar_edges,
6364 cx.theme().colors().scrollbar_thumb_border,
6365 BorderStyle::Solid,
6366 ));
6367
6368 if any_scrollbar_dragged {
6369 window.set_window_cursor_style(CursorStyle::Arrow);
6370 } else {
6371 window.set_cursor_style(CursorStyle::Arrow, hitbox);
6372 }
6373 }
6374 })
6375 }
6376 }
6377
6378 window.on_mouse_event({
6379 let editor = self.editor.clone();
6380 let scrollbars_layout = scrollbars_layout.clone();
6381
6382 let mut mouse_position = window.mouse_position();
6383 move |event: &MouseMoveEvent, phase, window, cx| {
6384 if phase == DispatchPhase::Capture {
6385 return;
6386 }
6387
6388 editor.update(cx, |editor, cx| {
6389 if let Some((scrollbar_layout, axis)) = event
6390 .pressed_button
6391 .filter(|button| *button == MouseButton::Left)
6392 .and(editor.scroll_manager.dragging_scrollbar_axis())
6393 .and_then(|axis| {
6394 scrollbars_layout
6395 .iter_scrollbars()
6396 .find(|(_, a)| *a == axis)
6397 })
6398 {
6399 let ScrollbarLayout {
6400 hitbox,
6401 text_unit_size,
6402 ..
6403 } = scrollbar_layout;
6404
6405 let old_position = mouse_position.along(axis);
6406 let new_position = event.position.along(axis);
6407 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
6408 .contains(&old_position)
6409 {
6410 let position = editor.scroll_position(cx).apply_along(axis, |p| {
6411 (p + (new_position - old_position) / *text_unit_size).max(0.)
6412 });
6413 editor.set_scroll_position(position, window, cx);
6414 }
6415
6416 editor.scroll_manager.show_scrollbars(window, cx);
6417 cx.stop_propagation();
6418 } else if let Some((layout, axis)) = scrollbars_layout
6419 .get_hovered_axis(window)
6420 .filter(|_| !event.dragging())
6421 {
6422 if layout.thumb_hovered(&event.position) {
6423 editor
6424 .scroll_manager
6425 .set_hovered_scroll_thumb_axis(axis, cx);
6426 } else {
6427 editor.scroll_manager.reset_scrollbar_state(cx);
6428 }
6429
6430 editor.scroll_manager.show_scrollbars(window, cx);
6431 } else {
6432 editor.scroll_manager.reset_scrollbar_state(cx);
6433 }
6434
6435 mouse_position = event.position;
6436 })
6437 }
6438 });
6439
6440 if any_scrollbar_dragged {
6441 window.on_mouse_event({
6442 let editor = self.editor.clone();
6443 move |_: &MouseUpEvent, phase, window, cx| {
6444 if phase == DispatchPhase::Capture {
6445 return;
6446 }
6447
6448 editor.update(cx, |editor, cx| {
6449 if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
6450 editor
6451 .scroll_manager
6452 .set_hovered_scroll_thumb_axis(axis, cx);
6453 } else {
6454 editor.scroll_manager.reset_scrollbar_state(cx);
6455 }
6456 cx.stop_propagation();
6457 });
6458 }
6459 });
6460 } else {
6461 window.on_mouse_event({
6462 let editor = self.editor.clone();
6463
6464 move |event: &MouseDownEvent, phase, window, cx| {
6465 if phase == DispatchPhase::Capture {
6466 return;
6467 }
6468 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
6469 else {
6470 return;
6471 };
6472
6473 let ScrollbarLayout {
6474 hitbox,
6475 visible_range,
6476 text_unit_size,
6477 thumb_bounds,
6478 ..
6479 } = scrollbar_layout;
6480
6481 let Some(thumb_bounds) = thumb_bounds else {
6482 return;
6483 };
6484
6485 editor.update(cx, |editor, cx| {
6486 editor
6487 .scroll_manager
6488 .set_dragged_scroll_thumb_axis(axis, cx);
6489
6490 let event_position = event.position.along(axis);
6491
6492 if event_position < thumb_bounds.origin.along(axis)
6493 || thumb_bounds.bottom_right().along(axis) < event_position
6494 {
6495 let center_position = ((event_position - hitbox.origin.along(axis))
6496 / *text_unit_size)
6497 .round() as u32;
6498 let start_position = center_position.saturating_sub(
6499 (visible_range.end - visible_range.start) as u32 / 2,
6500 );
6501
6502 let position = editor
6503 .scroll_position(cx)
6504 .apply_along(axis, |_| start_position as f32);
6505
6506 editor.set_scroll_position(position, window, cx);
6507 } else {
6508 editor.scroll_manager.show_scrollbars(window, cx);
6509 }
6510
6511 cx.stop_propagation();
6512 });
6513 }
6514 });
6515 }
6516 }
6517
6518 fn collect_fast_scrollbar_markers(
6519 &self,
6520 layout: &EditorLayout,
6521 scrollbar_layout: &ScrollbarLayout,
6522 cx: &mut App,
6523 ) -> Vec<PaintQuad> {
6524 const LIMIT: usize = 100;
6525 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
6526 return vec![];
6527 }
6528 let cursor_ranges = layout
6529 .cursors
6530 .iter()
6531 .map(|(point, color)| ColoredRange {
6532 start: point.row(),
6533 end: point.row(),
6534 color: *color,
6535 })
6536 .collect_vec();
6537 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
6538 }
6539
6540 fn refresh_slow_scrollbar_markers(
6541 &self,
6542 layout: &EditorLayout,
6543 scrollbar_layout: &ScrollbarLayout,
6544 window: &mut Window,
6545 cx: &mut App,
6546 ) {
6547 self.editor.update(cx, |editor, cx| {
6548 if !editor.is_singleton(cx)
6549 || !editor
6550 .scrollbar_marker_state
6551 .should_refresh(scrollbar_layout.hitbox.size)
6552 {
6553 return;
6554 }
6555
6556 let scrollbar_layout = scrollbar_layout.clone();
6557 let background_highlights = editor.background_highlights.clone();
6558 let snapshot = layout.position_map.snapshot.clone();
6559 let theme = cx.theme().clone();
6560 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
6561
6562 editor.scrollbar_marker_state.dirty = false;
6563 editor.scrollbar_marker_state.pending_refresh =
6564 Some(cx.spawn_in(window, async move |editor, cx| {
6565 let scrollbar_size = scrollbar_layout.hitbox.size;
6566 let scrollbar_markers = cx
6567 .background_spawn(async move {
6568 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
6569 let mut marker_quads = Vec::new();
6570 if scrollbar_settings.git_diff {
6571 let marker_row_ranges =
6572 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
6573 let start_display_row =
6574 MultiBufferPoint::new(hunk.row_range.start.0, 0)
6575 .to_display_point(&snapshot.display_snapshot)
6576 .row();
6577 let mut end_display_row =
6578 MultiBufferPoint::new(hunk.row_range.end.0, 0)
6579 .to_display_point(&snapshot.display_snapshot)
6580 .row();
6581 if end_display_row != start_display_row {
6582 end_display_row.0 -= 1;
6583 }
6584 let color = match &hunk.status().kind {
6585 DiffHunkStatusKind::Added => {
6586 theme.colors().version_control_added
6587 }
6588 DiffHunkStatusKind::Modified => {
6589 theme.colors().version_control_modified
6590 }
6591 DiffHunkStatusKind::Deleted => {
6592 theme.colors().version_control_deleted
6593 }
6594 };
6595 ColoredRange {
6596 start: start_display_row,
6597 end: end_display_row,
6598 color,
6599 }
6600 });
6601
6602 marker_quads.extend(
6603 scrollbar_layout
6604 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
6605 );
6606 }
6607
6608 for (background_highlight_id, (_, background_ranges)) in
6609 background_highlights.iter()
6610 {
6611 let is_search_highlights = *background_highlight_id
6612 == HighlightKey::Type(TypeId::of::<BufferSearchHighlights>());
6613 let is_text_highlights = *background_highlight_id
6614 == HighlightKey::Type(TypeId::of::<SelectedTextHighlight>());
6615 let is_symbol_occurrences = *background_highlight_id
6616 == HighlightKey::Type(TypeId::of::<DocumentHighlightRead>())
6617 || *background_highlight_id
6618 == HighlightKey::Type(
6619 TypeId::of::<DocumentHighlightWrite>(),
6620 );
6621 if (is_search_highlights && scrollbar_settings.search_results)
6622 || (is_text_highlights && scrollbar_settings.selected_text)
6623 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
6624 {
6625 let mut color = theme.status().info;
6626 if is_symbol_occurrences {
6627 color.fade_out(0.5);
6628 }
6629 let marker_row_ranges = background_ranges.iter().map(|range| {
6630 let display_start = range
6631 .start
6632 .to_display_point(&snapshot.display_snapshot);
6633 let display_end =
6634 range.end.to_display_point(&snapshot.display_snapshot);
6635 ColoredRange {
6636 start: display_start.row(),
6637 end: display_end.row(),
6638 color,
6639 }
6640 });
6641 marker_quads.extend(
6642 scrollbar_layout
6643 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
6644 );
6645 }
6646 }
6647
6648 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
6649 let diagnostics = snapshot
6650 .buffer_snapshot
6651 .diagnostics_in_range::<Point>(Point::zero()..max_point)
6652 // Don't show diagnostics the user doesn't care about
6653 .filter(|diagnostic| {
6654 match (
6655 scrollbar_settings.diagnostics,
6656 diagnostic.diagnostic.severity,
6657 ) {
6658 (ScrollbarDiagnostics::All, _) => true,
6659 (
6660 ScrollbarDiagnostics::Error,
6661 lsp::DiagnosticSeverity::ERROR,
6662 ) => true,
6663 (
6664 ScrollbarDiagnostics::Warning,
6665 lsp::DiagnosticSeverity::ERROR
6666 | lsp::DiagnosticSeverity::WARNING,
6667 ) => true,
6668 (
6669 ScrollbarDiagnostics::Information,
6670 lsp::DiagnosticSeverity::ERROR
6671 | lsp::DiagnosticSeverity::WARNING
6672 | lsp::DiagnosticSeverity::INFORMATION,
6673 ) => true,
6674 (_, _) => false,
6675 }
6676 })
6677 // We want to sort by severity, in order to paint the most severe diagnostics last.
6678 .sorted_by_key(|diagnostic| {
6679 std::cmp::Reverse(diagnostic.diagnostic.severity)
6680 });
6681
6682 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
6683 let start_display = diagnostic
6684 .range
6685 .start
6686 .to_display_point(&snapshot.display_snapshot);
6687 let end_display = diagnostic
6688 .range
6689 .end
6690 .to_display_point(&snapshot.display_snapshot);
6691 let color = match diagnostic.diagnostic.severity {
6692 lsp::DiagnosticSeverity::ERROR => theme.status().error,
6693 lsp::DiagnosticSeverity::WARNING => theme.status().warning,
6694 lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
6695 _ => theme.status().hint,
6696 };
6697 ColoredRange {
6698 start: start_display.row(),
6699 end: end_display.row(),
6700 color,
6701 }
6702 });
6703 marker_quads.extend(
6704 scrollbar_layout
6705 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
6706 );
6707 }
6708
6709 Arc::from(marker_quads)
6710 })
6711 .await;
6712
6713 editor.update(cx, |editor, cx| {
6714 editor.scrollbar_marker_state.markers = scrollbar_markers;
6715 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
6716 editor.scrollbar_marker_state.pending_refresh = None;
6717 cx.notify();
6718 })?;
6719
6720 Ok(())
6721 }));
6722 });
6723 }
6724
6725 fn paint_highlighted_range(
6726 &self,
6727 range: Range<DisplayPoint>,
6728 fill: bool,
6729 color: Hsla,
6730 corner_radius: Pixels,
6731 line_end_overshoot: Pixels,
6732 layout: &EditorLayout,
6733 window: &mut Window,
6734 ) {
6735 let start_row = layout.visible_display_row_range.start;
6736 let end_row = layout.visible_display_row_range.end;
6737 if range.start != range.end {
6738 let row_range = if range.end.column() == 0 {
6739 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
6740 } else {
6741 cmp::max(range.start.row(), start_row)
6742 ..cmp::min(range.end.row().next_row(), end_row)
6743 };
6744
6745 let highlighted_range = HighlightedRange {
6746 color,
6747 line_height: layout.position_map.line_height,
6748 corner_radius,
6749 start_y: layout.content_origin.y
6750 + row_range.start.as_f32() * layout.position_map.line_height
6751 - layout.position_map.scroll_pixel_position.y,
6752 lines: row_range
6753 .iter_rows()
6754 .map(|row| {
6755 let line_layout =
6756 &layout.position_map.line_layouts[row.minus(start_row) as usize];
6757 HighlightedRangeLine {
6758 start_x: if row == range.start.row() {
6759 layout.content_origin.x
6760 + line_layout.x_for_index(range.start.column() as usize)
6761 - layout.position_map.scroll_pixel_position.x
6762 } else {
6763 layout.content_origin.x
6764 - layout.position_map.scroll_pixel_position.x
6765 },
6766 end_x: if row == range.end.row() {
6767 layout.content_origin.x
6768 + line_layout.x_for_index(range.end.column() as usize)
6769 - layout.position_map.scroll_pixel_position.x
6770 } else {
6771 layout.content_origin.x + line_layout.width + line_end_overshoot
6772 - layout.position_map.scroll_pixel_position.x
6773 },
6774 }
6775 })
6776 .collect(),
6777 };
6778
6779 highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
6780 }
6781 }
6782
6783 fn paint_inline_diagnostics(
6784 &mut self,
6785 layout: &mut EditorLayout,
6786 window: &mut Window,
6787 cx: &mut App,
6788 ) {
6789 for mut inline_diagnostic in layout.inline_diagnostics.drain() {
6790 inline_diagnostic.1.paint(window, cx);
6791 }
6792 }
6793
6794 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6795 if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
6796 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6797 blame_layout.element.paint(window, cx);
6798 })
6799 }
6800 }
6801
6802 fn paint_inline_code_actions(
6803 &mut self,
6804 layout: &mut EditorLayout,
6805 window: &mut Window,
6806 cx: &mut App,
6807 ) {
6808 if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
6809 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6810 inline_code_actions.paint(window, cx);
6811 })
6812 }
6813 }
6814
6815 fn paint_diff_hunk_controls(
6816 &mut self,
6817 layout: &mut EditorLayout,
6818 window: &mut Window,
6819 cx: &mut App,
6820 ) {
6821 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
6822 diff_hunk_control.paint(window, cx);
6823 }
6824 }
6825
6826 fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6827 if let Some(mut layout) = layout.minimap.take() {
6828 let minimap_hitbox = layout.thumb_layout.hitbox.clone();
6829 let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
6830
6831 window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
6832 window.with_element_namespace("minimap", |window| {
6833 layout.minimap.paint(window, cx);
6834 if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
6835 let minimap_thumb_color = match layout.thumb_layout.thumb_state {
6836 ScrollbarThumbState::Idle => {
6837 cx.theme().colors().minimap_thumb_background
6838 }
6839 ScrollbarThumbState::Hovered => {
6840 cx.theme().colors().minimap_thumb_hover_background
6841 }
6842 ScrollbarThumbState::Dragging => {
6843 cx.theme().colors().minimap_thumb_active_background
6844 }
6845 };
6846 let minimap_thumb_border = match layout.thumb_border_style {
6847 MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
6848 MinimapThumbBorder::LeftOnly => Edges {
6849 left: ScrollbarLayout::BORDER_WIDTH,
6850 ..Default::default()
6851 },
6852 MinimapThumbBorder::LeftOpen => Edges {
6853 right: ScrollbarLayout::BORDER_WIDTH,
6854 top: ScrollbarLayout::BORDER_WIDTH,
6855 bottom: ScrollbarLayout::BORDER_WIDTH,
6856 ..Default::default()
6857 },
6858 MinimapThumbBorder::RightOpen => Edges {
6859 left: ScrollbarLayout::BORDER_WIDTH,
6860 top: ScrollbarLayout::BORDER_WIDTH,
6861 bottom: ScrollbarLayout::BORDER_WIDTH,
6862 ..Default::default()
6863 },
6864 MinimapThumbBorder::None => Default::default(),
6865 };
6866
6867 window.paint_layer(minimap_hitbox.bounds, |window| {
6868 window.paint_quad(quad(
6869 thumb_bounds,
6870 Corners::default(),
6871 minimap_thumb_color,
6872 minimap_thumb_border,
6873 cx.theme().colors().minimap_thumb_border,
6874 BorderStyle::Solid,
6875 ));
6876 });
6877 }
6878 });
6879 });
6880
6881 if dragging_minimap {
6882 window.set_window_cursor_style(CursorStyle::Arrow);
6883 } else {
6884 window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
6885 }
6886
6887 let minimap_axis = ScrollbarAxis::Vertical;
6888 let pixels_per_line = (minimap_hitbox.size.height / layout.max_scroll_top)
6889 .min(layout.minimap_line_height);
6890
6891 let mut mouse_position = window.mouse_position();
6892
6893 window.on_mouse_event({
6894 let editor = self.editor.clone();
6895
6896 let minimap_hitbox = minimap_hitbox.clone();
6897
6898 move |event: &MouseMoveEvent, phase, window, cx| {
6899 if phase == DispatchPhase::Capture {
6900 return;
6901 }
6902
6903 editor.update(cx, |editor, cx| {
6904 if event.pressed_button == Some(MouseButton::Left)
6905 && editor.scroll_manager.is_dragging_minimap()
6906 {
6907 let old_position = mouse_position.along(minimap_axis);
6908 let new_position = event.position.along(minimap_axis);
6909 if (minimap_hitbox.origin.along(minimap_axis)
6910 ..minimap_hitbox.bottom_right().along(minimap_axis))
6911 .contains(&old_position)
6912 {
6913 let position =
6914 editor.scroll_position(cx).apply_along(minimap_axis, |p| {
6915 (p + (new_position - old_position) / pixels_per_line)
6916 .max(0.)
6917 });
6918 editor.set_scroll_position(position, window, cx);
6919 }
6920 cx.stop_propagation();
6921 } else if minimap_hitbox.is_hovered(window) {
6922 editor.scroll_manager.set_is_hovering_minimap_thumb(
6923 !event.dragging()
6924 && layout
6925 .thumb_layout
6926 .thumb_bounds
6927 .is_some_and(|bounds| bounds.contains(&event.position)),
6928 cx,
6929 );
6930
6931 // Stop hover events from propagating to the
6932 // underlying editor if the minimap hitbox is hovered
6933 if !event.dragging() {
6934 cx.stop_propagation();
6935 }
6936 } else {
6937 editor.scroll_manager.hide_minimap_thumb(cx);
6938 }
6939 mouse_position = event.position;
6940 });
6941 }
6942 });
6943
6944 if dragging_minimap {
6945 window.on_mouse_event({
6946 let editor = self.editor.clone();
6947 move |event: &MouseUpEvent, phase, window, cx| {
6948 if phase == DispatchPhase::Capture {
6949 return;
6950 }
6951
6952 editor.update(cx, |editor, cx| {
6953 if minimap_hitbox.is_hovered(window) {
6954 editor.scroll_manager.set_is_hovering_minimap_thumb(
6955 layout
6956 .thumb_layout
6957 .thumb_bounds
6958 .is_some_and(|bounds| bounds.contains(&event.position)),
6959 cx,
6960 );
6961 } else {
6962 editor.scroll_manager.hide_minimap_thumb(cx);
6963 }
6964 cx.stop_propagation();
6965 });
6966 }
6967 });
6968 } else {
6969 window.on_mouse_event({
6970 let editor = self.editor.clone();
6971
6972 move |event: &MouseDownEvent, phase, window, cx| {
6973 if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
6974 return;
6975 }
6976
6977 let event_position = event.position;
6978
6979 let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
6980 return;
6981 };
6982
6983 editor.update(cx, |editor, cx| {
6984 if !thumb_bounds.contains(&event_position) {
6985 let click_position =
6986 event_position.relative_to(&minimap_hitbox.origin).y;
6987
6988 let top_position = (click_position
6989 - thumb_bounds.size.along(minimap_axis) / 2.0)
6990 .max(Pixels::ZERO);
6991
6992 let scroll_offset = (layout.minimap_scroll_top
6993 + top_position / layout.minimap_line_height)
6994 .min(layout.max_scroll_top);
6995
6996 let scroll_position = editor
6997 .scroll_position(cx)
6998 .apply_along(minimap_axis, |_| scroll_offset);
6999 editor.set_scroll_position(scroll_position, window, cx);
7000 }
7001
7002 editor.scroll_manager.set_is_dragging_minimap(cx);
7003 cx.stop_propagation();
7004 });
7005 }
7006 });
7007 }
7008 }
7009 }
7010
7011 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
7012 for mut block in layout.blocks.drain(..) {
7013 if block.overlaps_gutter {
7014 block.element.paint(window, cx);
7015 } else {
7016 let mut bounds = layout.hitbox.bounds;
7017 bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
7018 window.with_content_mask(Some(ContentMask { bounds }), |window| {
7019 block.element.paint(window, cx);
7020 })
7021 }
7022 }
7023 }
7024
7025 fn paint_edit_prediction_popover(
7026 &mut self,
7027 layout: &mut EditorLayout,
7028 window: &mut Window,
7029 cx: &mut App,
7030 ) {
7031 if let Some(edit_prediction_popover) = layout.edit_prediction_popover.as_mut() {
7032 edit_prediction_popover.paint(window, cx);
7033 }
7034 }
7035
7036 fn paint_mouse_context_menu(
7037 &mut self,
7038 layout: &mut EditorLayout,
7039 window: &mut Window,
7040 cx: &mut App,
7041 ) {
7042 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
7043 mouse_context_menu.paint(window, cx);
7044 }
7045 }
7046
7047 fn paint_scroll_wheel_listener(
7048 &mut self,
7049 layout: &EditorLayout,
7050 window: &mut Window,
7051 cx: &mut App,
7052 ) {
7053 window.on_mouse_event({
7054 let position_map = layout.position_map.clone();
7055 let editor = self.editor.clone();
7056 let hitbox = layout.hitbox.clone();
7057 let mut delta = ScrollDelta::default();
7058
7059 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
7060 // accidentally turn off their scrolling.
7061 let base_scroll_sensitivity =
7062 EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
7063
7064 // Use a minimum fast_scroll_sensitivity for same reason above
7065 let fast_scroll_sensitivity = EditorSettings::get_global(cx)
7066 .fast_scroll_sensitivity
7067 .max(0.01);
7068
7069 move |event: &ScrollWheelEvent, phase, window, cx| {
7070 let scroll_sensitivity = {
7071 if event.modifiers.alt {
7072 fast_scroll_sensitivity
7073 } else {
7074 base_scroll_sensitivity
7075 }
7076 };
7077
7078 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
7079 delta = delta.coalesce(event.delta);
7080 editor.update(cx, |editor, cx| {
7081 let position_map: &PositionMap = &position_map;
7082
7083 let line_height = position_map.line_height;
7084 let max_glyph_advance = position_map.em_advance;
7085 let (delta, axis) = match delta {
7086 gpui::ScrollDelta::Pixels(mut pixels) => {
7087 //Trackpad
7088 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
7089 (pixels, axis)
7090 }
7091
7092 gpui::ScrollDelta::Lines(lines) => {
7093 //Not trackpad
7094 let pixels =
7095 point(lines.x * max_glyph_advance, lines.y * line_height);
7096 (pixels, None)
7097 }
7098 };
7099
7100 let current_scroll_position = position_map.snapshot.scroll_position();
7101 let x = (current_scroll_position.x * max_glyph_advance
7102 - (delta.x * scroll_sensitivity))
7103 / max_glyph_advance;
7104 let y = (current_scroll_position.y * line_height
7105 - (delta.y * scroll_sensitivity))
7106 / line_height;
7107 let mut scroll_position =
7108 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
7109 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
7110 if forbid_vertical_scroll {
7111 scroll_position.y = current_scroll_position.y;
7112 }
7113
7114 if scroll_position != current_scroll_position {
7115 editor.scroll(scroll_position, axis, window, cx);
7116 cx.stop_propagation();
7117 } else if y < 0. {
7118 // Due to clamping, we may fail to detect cases of overscroll to the top;
7119 // We want the scroll manager to get an update in such cases and detect the change of direction
7120 // on the next frame.
7121 cx.notify();
7122 }
7123 });
7124 }
7125 }
7126 });
7127 }
7128
7129 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
7130 if layout.mode.is_minimap() {
7131 return;
7132 }
7133
7134 self.paint_scroll_wheel_listener(layout, window, cx);
7135
7136 window.on_mouse_event({
7137 let position_map = layout.position_map.clone();
7138 let editor = self.editor.clone();
7139 let diff_hunk_range =
7140 layout
7141 .display_hunks
7142 .iter()
7143 .find_map(|(hunk, hunk_hitbox)| match hunk {
7144 DisplayDiffHunk::Folded { .. } => None,
7145 DisplayDiffHunk::Unfolded {
7146 multi_buffer_range, ..
7147 } => {
7148 if hunk_hitbox
7149 .as_ref()
7150 .map(|hitbox| hitbox.is_hovered(window))
7151 .unwrap_or(false)
7152 {
7153 Some(multi_buffer_range.clone())
7154 } else {
7155 None
7156 }
7157 }
7158 });
7159 let line_numbers = layout.line_numbers.clone();
7160
7161 move |event: &MouseDownEvent, phase, window, cx| {
7162 if phase == DispatchPhase::Bubble {
7163 match event.button {
7164 MouseButton::Left => editor.update(cx, |editor, cx| {
7165 let pending_mouse_down = editor
7166 .pending_mouse_down
7167 .get_or_insert_with(Default::default)
7168 .clone();
7169
7170 *pending_mouse_down.borrow_mut() = Some(event.clone());
7171
7172 Self::mouse_left_down(
7173 editor,
7174 event,
7175 diff_hunk_range.clone(),
7176 &position_map,
7177 line_numbers.as_ref(),
7178 window,
7179 cx,
7180 );
7181 }),
7182 MouseButton::Right => editor.update(cx, |editor, cx| {
7183 Self::mouse_right_down(editor, event, &position_map, window, cx);
7184 }),
7185 MouseButton::Middle => editor.update(cx, |editor, cx| {
7186 Self::mouse_middle_down(editor, event, &position_map, window, cx);
7187 }),
7188 _ => {}
7189 };
7190 }
7191 }
7192 });
7193
7194 window.on_mouse_event({
7195 let editor = self.editor.clone();
7196 let position_map = layout.position_map.clone();
7197
7198 move |event: &MouseUpEvent, phase, window, cx| {
7199 if phase == DispatchPhase::Bubble {
7200 editor.update(cx, |editor, cx| {
7201 Self::mouse_up(editor, event, &position_map, window, cx)
7202 });
7203 }
7204 }
7205 });
7206
7207 window.on_mouse_event({
7208 let editor = self.editor.clone();
7209 let position_map = layout.position_map.clone();
7210 let mut captured_mouse_down = None;
7211
7212 move |event: &MouseUpEvent, phase, window, cx| match phase {
7213 // Clear the pending mouse down during the capture phase,
7214 // so that it happens even if another event handler stops
7215 // propagation.
7216 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
7217 let pending_mouse_down = editor
7218 .pending_mouse_down
7219 .get_or_insert_with(Default::default)
7220 .clone();
7221
7222 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
7223 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
7224 captured_mouse_down = pending_mouse_down.take();
7225 window.refresh();
7226 }
7227 }),
7228 // Fire click handlers during the bubble phase.
7229 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
7230 if let Some(mouse_down) = captured_mouse_down.take() {
7231 let event = ClickEvent::Mouse(MouseClickEvent {
7232 down: mouse_down,
7233 up: event.clone(),
7234 });
7235 Self::click(editor, &event, &position_map, window, cx);
7236 }
7237 }),
7238 }
7239 });
7240
7241 window.on_mouse_event({
7242 let position_map = layout.position_map.clone();
7243 let editor = self.editor.clone();
7244
7245 move |event: &MouseMoveEvent, phase, window, cx| {
7246 if phase == DispatchPhase::Bubble {
7247 editor.update(cx, |editor, cx| {
7248 if editor.hover_state.focused(window, cx) {
7249 return;
7250 }
7251 if event.pressed_button == Some(MouseButton::Left)
7252 || event.pressed_button == Some(MouseButton::Middle)
7253 {
7254 Self::mouse_dragged(editor, event, &position_map, window, cx)
7255 }
7256
7257 Self::mouse_moved(editor, event, &position_map, window, cx)
7258 });
7259 }
7260 }
7261 });
7262 }
7263
7264 fn column_pixels(&self, column: usize, window: &Window) -> Pixels {
7265 let style = &self.style;
7266 let font_size = style.text.font_size.to_pixels(window.rem_size());
7267 let layout = window.text_system().shape_line(
7268 SharedString::from(" ".repeat(column)),
7269 font_size,
7270 &[TextRun {
7271 len: column,
7272 font: style.text.font(),
7273 color: Hsla::default(),
7274 background_color: None,
7275 underline: None,
7276 strikethrough: None,
7277 }],
7278 None,
7279 );
7280
7281 layout.width
7282 }
7283
7284 fn max_line_number_width(&self, snapshot: &EditorSnapshot, window: &mut Window) -> Pixels {
7285 let digit_count = snapshot.widest_line_number().ilog10() + 1;
7286 self.column_pixels(digit_count as usize, window)
7287 }
7288
7289 fn shape_line_number(
7290 &self,
7291 text: SharedString,
7292 color: Hsla,
7293 window: &mut Window,
7294 ) -> ShapedLine {
7295 let run = TextRun {
7296 len: text.len(),
7297 font: self.style.text.font(),
7298 color,
7299 background_color: None,
7300 underline: None,
7301 strikethrough: None,
7302 };
7303 window.text_system().shape_line(
7304 text,
7305 self.style.text.font_size.to_pixels(window.rem_size()),
7306 &[run],
7307 None,
7308 )
7309 }
7310
7311 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
7312 let unstaged = status.has_secondary_hunk();
7313 let unstaged_hollow = matches!(
7314 ProjectSettings::get_global(cx).git.hunk_style,
7315 GitHunkStyleSetting::UnstagedHollow
7316 );
7317
7318 unstaged == unstaged_hollow
7319 }
7320
7321 #[cfg(debug_assertions)]
7322 fn layout_debug_ranges(
7323 selections: &mut Vec<(PlayerColor, Vec<SelectionLayout>)>,
7324 anchor_range: Range<Anchor>,
7325 display_snapshot: &DisplaySnapshot,
7326 cx: &App,
7327 ) {
7328 let theme = cx.theme();
7329 text::debug::GlobalDebugRanges::with_locked(|debug_ranges| {
7330 if debug_ranges.ranges.is_empty() {
7331 return;
7332 }
7333 let buffer_snapshot = &display_snapshot.buffer_snapshot;
7334 for (buffer, buffer_range, excerpt_id) in
7335 buffer_snapshot.range_to_buffer_ranges(anchor_range)
7336 {
7337 let buffer_range =
7338 buffer.anchor_after(buffer_range.start)..buffer.anchor_before(buffer_range.end);
7339 selections.extend(debug_ranges.ranges.iter().flat_map(|debug_range| {
7340 let player_color = theme
7341 .players()
7342 .color_for_participant(debug_range.occurrence_index as u32 + 1);
7343 debug_range.ranges.iter().filter_map(move |range| {
7344 if range.start.buffer_id != Some(buffer.remote_id()) {
7345 return None;
7346 }
7347 let clipped_start = range.start.max(&buffer_range.start, buffer);
7348 let clipped_end = range.end.min(&buffer_range.end, buffer);
7349 let range = buffer_snapshot.anchor_in_excerpt(excerpt_id, clipped_start)?
7350 ..buffer_snapshot.anchor_in_excerpt(excerpt_id, clipped_end)?;
7351 let start = range.start.to_display_point(display_snapshot);
7352 let end = range.end.to_display_point(display_snapshot);
7353 let selection_layout = SelectionLayout {
7354 head: start,
7355 range: start..end,
7356 cursor_shape: CursorShape::Bar,
7357 is_newest: false,
7358 is_local: false,
7359 active_rows: start.row()..end.row(),
7360 user_name: Some(SharedString::new(debug_range.value.clone())),
7361 };
7362 Some((player_color, vec![selection_layout]))
7363 })
7364 }));
7365 }
7366 });
7367 }
7368}
7369
7370fn header_jump_data(
7371 snapshot: &EditorSnapshot,
7372 block_row_start: DisplayRow,
7373 height: u32,
7374 for_excerpt: &ExcerptInfo,
7375) -> JumpData {
7376 let range = &for_excerpt.range;
7377 let buffer = &for_excerpt.buffer;
7378 let jump_anchor = range.primary.start;
7379
7380 let excerpt_start = range.context.start;
7381 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
7382 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
7383 0
7384 } else {
7385 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
7386 jump_position.row.saturating_sub(excerpt_start_point.row)
7387 };
7388
7389 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
7390 .saturating_sub(
7391 snapshot
7392 .scroll_anchor
7393 .scroll_position(&snapshot.display_snapshot)
7394 .y as u32,
7395 );
7396
7397 JumpData::MultiBufferPoint {
7398 excerpt_id: for_excerpt.id,
7399 anchor: jump_anchor,
7400 position: jump_position,
7401 line_offset_from_top,
7402 }
7403}
7404
7405pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
7406
7407impl AcceptEditPredictionBinding {
7408 pub fn keystroke(&self) -> Option<&KeybindingKeystroke> {
7409 if let Some(binding) = self.0.as_ref() {
7410 match &binding.keystrokes() {
7411 [keystroke, ..] => Some(keystroke),
7412 _ => None,
7413 }
7414 } else {
7415 None
7416 }
7417 }
7418}
7419
7420fn prepaint_gutter_button(
7421 button: IconButton,
7422 row: DisplayRow,
7423 line_height: Pixels,
7424 gutter_dimensions: &GutterDimensions,
7425 scroll_pixel_position: gpui::Point<Pixels>,
7426 gutter_hitbox: &Hitbox,
7427 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
7428 window: &mut Window,
7429 cx: &mut App,
7430) -> AnyElement {
7431 let mut button = button.into_any_element();
7432
7433 let available_space = size(
7434 AvailableSpace::MinContent,
7435 AvailableSpace::Definite(line_height),
7436 );
7437 let indicator_size = button.layout_as_root(available_space, window, cx);
7438
7439 let blame_width = gutter_dimensions.git_blame_entries_width;
7440 let gutter_width = display_hunks
7441 .binary_search_by(|(hunk, _)| match hunk {
7442 DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
7443 DisplayDiffHunk::Unfolded {
7444 display_row_range, ..
7445 } => {
7446 if display_row_range.end <= row {
7447 Ordering::Less
7448 } else if display_row_range.start > row {
7449 Ordering::Greater
7450 } else {
7451 Ordering::Equal
7452 }
7453 }
7454 })
7455 .ok()
7456 .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
7457 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
7458
7459 let mut x = left_offset;
7460 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
7461 - indicator_size.width
7462 - left_offset;
7463 x += available_width / 2.;
7464
7465 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
7466 y += (line_height - indicator_size.height) / 2.;
7467
7468 button.prepaint_as_root(
7469 gutter_hitbox.origin + point(x, y),
7470 available_space,
7471 window,
7472 cx,
7473 );
7474 button
7475}
7476
7477fn render_inline_blame_entry(
7478 blame_entry: BlameEntry,
7479 style: &EditorStyle,
7480 cx: &mut App,
7481) -> Option<AnyElement> {
7482 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7483 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
7484}
7485
7486fn render_blame_entry_popover(
7487 blame_entry: BlameEntry,
7488 scroll_handle: ScrollHandle,
7489 commit_message: Option<ParsedCommitMessage>,
7490 markdown: Entity<Markdown>,
7491 workspace: WeakEntity<Workspace>,
7492 blame: &Entity<GitBlame>,
7493 buffer: BufferId,
7494 window: &mut Window,
7495 cx: &mut App,
7496) -> Option<AnyElement> {
7497 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7498 let blame = blame.read(cx);
7499 let repository = blame.repository(cx, buffer)?;
7500 renderer.render_blame_entry_popover(
7501 blame_entry,
7502 scroll_handle,
7503 commit_message,
7504 markdown,
7505 repository,
7506 workspace,
7507 window,
7508 cx,
7509 )
7510}
7511
7512fn render_blame_entry(
7513 ix: usize,
7514 blame: &Entity<GitBlame>,
7515 blame_entry: BlameEntry,
7516 style: &EditorStyle,
7517 last_used_color: &mut Option<(Hsla, Oid)>,
7518 editor: Entity<Editor>,
7519 workspace: Entity<Workspace>,
7520 buffer: BufferId,
7521 renderer: &dyn BlameRenderer,
7522 window: &mut Window,
7523 cx: &mut App,
7524) -> Option<AnyElement> {
7525 let index: u32 = blame_entry.sha.into();
7526 let mut sha_color = cx.theme().players().color_for_participant(index).cursor;
7527
7528 // If the last color we used is the same as the one we get for this line, but
7529 // the commit SHAs are different, then we try again to get a different color.
7530 if let Some((color, sha)) = *last_used_color
7531 && sha != blame_entry.sha
7532 && color == sha_color
7533 {
7534 sha_color = cx.theme().players().color_for_participant(index + 1).cursor;
7535 }
7536 last_used_color.replace((sha_color, blame_entry.sha));
7537
7538 let blame = blame.read(cx);
7539 let details = blame.details_for_entry(buffer, &blame_entry);
7540 let repository = blame.repository(cx, buffer)?;
7541 renderer.render_blame_entry(
7542 &style.text,
7543 blame_entry,
7544 details,
7545 repository,
7546 workspace.downgrade(),
7547 editor,
7548 ix,
7549 sha_color,
7550 window,
7551 cx,
7552 )
7553}
7554
7555#[derive(Debug)]
7556pub(crate) struct LineWithInvisibles {
7557 fragments: SmallVec<[LineFragment; 1]>,
7558 invisibles: Vec<Invisible>,
7559 len: usize,
7560 pub(crate) width: Pixels,
7561 font_size: Pixels,
7562}
7563
7564enum LineFragment {
7565 Text(ShapedLine),
7566 Element {
7567 id: ChunkRendererId,
7568 element: Option<AnyElement>,
7569 size: Size<Pixels>,
7570 len: usize,
7571 },
7572}
7573
7574impl fmt::Debug for LineFragment {
7575 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7576 match self {
7577 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
7578 LineFragment::Element { size, len, .. } => f
7579 .debug_struct("Element")
7580 .field("size", size)
7581 .field("len", len)
7582 .finish(),
7583 }
7584 }
7585}
7586
7587impl LineWithInvisibles {
7588 fn from_chunks<'a>(
7589 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
7590 editor_style: &EditorStyle,
7591 max_line_len: usize,
7592 max_line_count: usize,
7593 editor_mode: &EditorMode,
7594 text_width: Pixels,
7595 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
7596 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
7597 window: &mut Window,
7598 cx: &mut App,
7599 ) -> Vec<Self> {
7600 let text_style = &editor_style.text;
7601 let mut layouts = Vec::with_capacity(max_line_count);
7602 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
7603 let mut line = String::new();
7604 let mut invisibles = Vec::new();
7605 let mut width = Pixels::ZERO;
7606 let mut len = 0;
7607 let mut styles = Vec::new();
7608 let mut non_whitespace_added = false;
7609 let mut row = 0;
7610 let mut line_exceeded_max_len = false;
7611 let font_size = text_style.font_size.to_pixels(window.rem_size());
7612 let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
7613
7614 let ellipsis = SharedString::from("β―");
7615
7616 for highlighted_chunk in chunks.chain([HighlightedChunk {
7617 text: "\n",
7618 style: None,
7619 is_tab: false,
7620 is_inlay: false,
7621 replacement: None,
7622 }]) {
7623 if let Some(replacement) = highlighted_chunk.replacement {
7624 if !line.is_empty() {
7625 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
7626 let text_runs: &[TextRun] = if segments.is_empty() {
7627 &styles
7628 } else {
7629 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
7630 };
7631 let shaped_line = window.text_system().shape_line(
7632 line.clone().into(),
7633 font_size,
7634 text_runs,
7635 None,
7636 );
7637 width += shaped_line.width;
7638 len += shaped_line.len;
7639 fragments.push(LineFragment::Text(shaped_line));
7640 line.clear();
7641 styles.clear();
7642 }
7643
7644 match replacement {
7645 ChunkReplacement::Renderer(renderer) => {
7646 let available_width = if renderer.constrain_width {
7647 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
7648 ellipsis.clone()
7649 } else {
7650 SharedString::from(Arc::from(highlighted_chunk.text))
7651 };
7652 let shaped_line = window.text_system().shape_line(
7653 chunk,
7654 font_size,
7655 &[text_style.to_run(highlighted_chunk.text.len())],
7656 None,
7657 );
7658 AvailableSpace::Definite(shaped_line.width)
7659 } else {
7660 AvailableSpace::MinContent
7661 };
7662
7663 let mut element = (renderer.render)(&mut ChunkRendererContext {
7664 context: cx,
7665 window,
7666 max_width: text_width,
7667 });
7668 let line_height = text_style.line_height_in_pixels(window.rem_size());
7669 let size = element.layout_as_root(
7670 size(available_width, AvailableSpace::Definite(line_height)),
7671 window,
7672 cx,
7673 );
7674
7675 width += size.width;
7676 len += highlighted_chunk.text.len();
7677 fragments.push(LineFragment::Element {
7678 id: renderer.id,
7679 element: Some(element),
7680 size,
7681 len: highlighted_chunk.text.len(),
7682 });
7683 }
7684 ChunkReplacement::Str(x) => {
7685 let text_style = if let Some(style) = highlighted_chunk.style {
7686 Cow::Owned(text_style.clone().highlight(style))
7687 } else {
7688 Cow::Borrowed(text_style)
7689 };
7690
7691 let run = TextRun {
7692 len: x.len(),
7693 font: text_style.font(),
7694 color: text_style.color,
7695 background_color: text_style.background_color,
7696 underline: text_style.underline,
7697 strikethrough: text_style.strikethrough,
7698 };
7699 let line_layout = window
7700 .text_system()
7701 .shape_line(x, font_size, &[run], None)
7702 .with_len(highlighted_chunk.text.len());
7703
7704 width += line_layout.width;
7705 len += highlighted_chunk.text.len();
7706 fragments.push(LineFragment::Text(line_layout))
7707 }
7708 }
7709 } else {
7710 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
7711 if ix > 0 {
7712 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
7713 let text_runs = if segments.is_empty() {
7714 &styles
7715 } else {
7716 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast, len)
7717 };
7718 let shaped_line = window.text_system().shape_line(
7719 line.clone().into(),
7720 font_size,
7721 text_runs,
7722 None,
7723 );
7724 width += shaped_line.width;
7725 len += shaped_line.len;
7726 fragments.push(LineFragment::Text(shaped_line));
7727 layouts.push(Self {
7728 width: mem::take(&mut width),
7729 len: mem::take(&mut len),
7730 fragments: mem::take(&mut fragments),
7731 invisibles: std::mem::take(&mut invisibles),
7732 font_size,
7733 });
7734
7735 line.clear();
7736 styles.clear();
7737 row += 1;
7738 line_exceeded_max_len = false;
7739 non_whitespace_added = false;
7740 if row == max_line_count {
7741 return layouts;
7742 }
7743 }
7744
7745 if !line_chunk.is_empty() && !line_exceeded_max_len {
7746 let text_style = if let Some(style) = highlighted_chunk.style {
7747 Cow::Owned(text_style.clone().highlight(style))
7748 } else {
7749 Cow::Borrowed(text_style)
7750 };
7751
7752 if line.len() + line_chunk.len() > max_line_len {
7753 let mut chunk_len = max_line_len - line.len();
7754 while !line_chunk.is_char_boundary(chunk_len) {
7755 chunk_len -= 1;
7756 }
7757 line_chunk = &line_chunk[..chunk_len];
7758 line_exceeded_max_len = true;
7759 }
7760
7761 styles.push(TextRun {
7762 len: line_chunk.len(),
7763 font: text_style.font(),
7764 color: text_style.color,
7765 background_color: text_style.background_color,
7766 underline: text_style.underline,
7767 strikethrough: text_style.strikethrough,
7768 });
7769
7770 if editor_mode.is_full() && !highlighted_chunk.is_inlay {
7771 // Line wrap pads its contents with fake whitespaces,
7772 // avoid printing them
7773 let is_soft_wrapped = is_row_soft_wrapped(row);
7774 if highlighted_chunk.is_tab {
7775 if non_whitespace_added || !is_soft_wrapped {
7776 invisibles.push(Invisible::Tab {
7777 line_start_offset: line.len(),
7778 line_end_offset: line.len() + line_chunk.len(),
7779 });
7780 }
7781 } else {
7782 invisibles.extend(line_chunk.char_indices().filter_map(
7783 |(index, c)| {
7784 let is_whitespace = c.is_whitespace();
7785 non_whitespace_added |= !is_whitespace;
7786 if is_whitespace
7787 && (non_whitespace_added || !is_soft_wrapped)
7788 {
7789 Some(Invisible::Whitespace {
7790 line_offset: line.len() + index,
7791 })
7792 } else {
7793 None
7794 }
7795 },
7796 ))
7797 }
7798 }
7799
7800 line.push_str(line_chunk);
7801 }
7802 }
7803 }
7804 }
7805
7806 layouts
7807 }
7808
7809 /// Takes text runs and non-overlapping left-to-right background ranges with color.
7810 /// Returns new text runs with adjusted contrast as per background ranges.
7811 fn split_runs_by_bg_segments(
7812 text_runs: &[TextRun],
7813 bg_segments: &[(Range<DisplayPoint>, Hsla)],
7814 min_contrast: f32,
7815 start_col_offset: usize,
7816 ) -> Vec<TextRun> {
7817 let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
7818 let mut line_col = start_col_offset;
7819 let mut segment_ix = 0usize;
7820
7821 for text_run in text_runs.iter() {
7822 let run_start_col = line_col;
7823 let run_end_col = run_start_col + text_run.len;
7824 while segment_ix < bg_segments.len()
7825 && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
7826 {
7827 segment_ix += 1;
7828 }
7829 let mut cursor_col = run_start_col;
7830 let mut local_segment_ix = segment_ix;
7831 while local_segment_ix < bg_segments.len() {
7832 let (range, segment_color) = &bg_segments[local_segment_ix];
7833 let segment_start_col = range.start.column() as usize;
7834 let segment_end_col = range.end.column() as usize;
7835 if segment_start_col >= run_end_col {
7836 break;
7837 }
7838 if segment_start_col > cursor_col {
7839 let span_len = segment_start_col - cursor_col;
7840 output_runs.push(TextRun {
7841 len: span_len,
7842 font: text_run.font.clone(),
7843 color: text_run.color,
7844 background_color: text_run.background_color,
7845 underline: text_run.underline,
7846 strikethrough: text_run.strikethrough,
7847 });
7848 cursor_col = segment_start_col;
7849 }
7850 let segment_slice_end_col = segment_end_col.min(run_end_col);
7851 if segment_slice_end_col > cursor_col {
7852 let new_text_color =
7853 ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
7854 output_runs.push(TextRun {
7855 len: segment_slice_end_col - cursor_col,
7856 font: text_run.font.clone(),
7857 color: new_text_color,
7858 background_color: text_run.background_color,
7859 underline: text_run.underline,
7860 strikethrough: text_run.strikethrough,
7861 });
7862 cursor_col = segment_slice_end_col;
7863 }
7864 if segment_end_col >= run_end_col {
7865 break;
7866 }
7867 local_segment_ix += 1;
7868 }
7869 if cursor_col < run_end_col {
7870 output_runs.push(TextRun {
7871 len: run_end_col - cursor_col,
7872 font: text_run.font.clone(),
7873 color: text_run.color,
7874 background_color: text_run.background_color,
7875 underline: text_run.underline,
7876 strikethrough: text_run.strikethrough,
7877 });
7878 }
7879 line_col = run_end_col;
7880 segment_ix = local_segment_ix;
7881 }
7882 output_runs
7883 }
7884
7885 fn prepaint(
7886 &mut self,
7887 line_height: Pixels,
7888 scroll_pixel_position: gpui::Point<Pixels>,
7889 row: DisplayRow,
7890 content_origin: gpui::Point<Pixels>,
7891 line_elements: &mut SmallVec<[AnyElement; 1]>,
7892 window: &mut Window,
7893 cx: &mut App,
7894 ) {
7895 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
7896 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
7897 for fragment in &mut self.fragments {
7898 match fragment {
7899 LineFragment::Text(line) => {
7900 fragment_origin.x += line.width;
7901 }
7902 LineFragment::Element { element, size, .. } => {
7903 let mut element = element
7904 .take()
7905 .expect("you can't prepaint LineWithInvisibles twice");
7906
7907 // Center the element vertically within the line.
7908 let mut element_origin = fragment_origin;
7909 element_origin.y += (line_height - size.height) / 2.;
7910 element.prepaint_at(element_origin, window, cx);
7911 line_elements.push(element);
7912
7913 fragment_origin.x += size.width;
7914 }
7915 }
7916 }
7917 }
7918
7919 fn draw(
7920 &self,
7921 layout: &EditorLayout,
7922 row: DisplayRow,
7923 content_origin: gpui::Point<Pixels>,
7924 whitespace_setting: ShowWhitespaceSetting,
7925 selection_ranges: &[Range<DisplayPoint>],
7926 window: &mut Window,
7927 cx: &mut App,
7928 ) {
7929 let line_height = layout.position_map.line_height;
7930 let line_y = line_height
7931 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7932
7933 let mut fragment_origin =
7934 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7935
7936 for fragment in &self.fragments {
7937 match fragment {
7938 LineFragment::Text(line) => {
7939 line.paint(fragment_origin, line_height, window, cx)
7940 .log_err();
7941 fragment_origin.x += line.width;
7942 }
7943 LineFragment::Element { size, .. } => {
7944 fragment_origin.x += size.width;
7945 }
7946 }
7947 }
7948
7949 self.draw_invisibles(
7950 selection_ranges,
7951 layout,
7952 content_origin,
7953 line_y,
7954 row,
7955 line_height,
7956 whitespace_setting,
7957 window,
7958 cx,
7959 );
7960 }
7961
7962 fn draw_background(
7963 &self,
7964 layout: &EditorLayout,
7965 row: DisplayRow,
7966 content_origin: gpui::Point<Pixels>,
7967 window: &mut Window,
7968 cx: &mut App,
7969 ) {
7970 let line_height = layout.position_map.line_height;
7971 let line_y = line_height
7972 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7973
7974 let mut fragment_origin =
7975 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7976
7977 for fragment in &self.fragments {
7978 match fragment {
7979 LineFragment::Text(line) => {
7980 line.paint_background(fragment_origin, line_height, window, cx)
7981 .log_err();
7982 fragment_origin.x += line.width;
7983 }
7984 LineFragment::Element { size, .. } => {
7985 fragment_origin.x += size.width;
7986 }
7987 }
7988 }
7989 }
7990
7991 fn draw_invisibles(
7992 &self,
7993 selection_ranges: &[Range<DisplayPoint>],
7994 layout: &EditorLayout,
7995 content_origin: gpui::Point<Pixels>,
7996 line_y: Pixels,
7997 row: DisplayRow,
7998 line_height: Pixels,
7999 whitespace_setting: ShowWhitespaceSetting,
8000 window: &mut Window,
8001 cx: &mut App,
8002 ) {
8003 let extract_whitespace_info = |invisible: &Invisible| {
8004 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
8005 Invisible::Tab {
8006 line_start_offset,
8007 line_end_offset,
8008 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
8009 Invisible::Whitespace { line_offset } => {
8010 (*line_offset, line_offset + 1, &layout.space_invisible)
8011 }
8012 };
8013
8014 let x_offset = self.x_for_index(token_offset);
8015 let invisible_offset =
8016 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
8017 let origin = content_origin
8018 + gpui::point(
8019 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
8020 line_y,
8021 );
8022
8023 (
8024 [token_offset, token_end_offset],
8025 Box::new(move |window: &mut Window, cx: &mut App| {
8026 invisible_symbol
8027 .paint(origin, line_height, window, cx)
8028 .log_err();
8029 }),
8030 )
8031 };
8032
8033 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
8034 match whitespace_setting {
8035 ShowWhitespaceSetting::None => (),
8036 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
8037 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
8038 let invisible_point = DisplayPoint::new(row, start as u32);
8039 if !selection_ranges
8040 .iter()
8041 .any(|region| region.start <= invisible_point && invisible_point < region.end)
8042 {
8043 return;
8044 }
8045
8046 paint(window, cx);
8047 }),
8048
8049 ShowWhitespaceSetting::Trailing => {
8050 let mut previous_start = self.len;
8051 for ([start, end], paint) in invisible_iter.rev() {
8052 if previous_start != end {
8053 break;
8054 }
8055 previous_start = start;
8056 paint(window, cx);
8057 }
8058 }
8059
8060 // For a whitespace to be on a boundary, any of the following conditions need to be met:
8061 // - It is a tab
8062 // - It is adjacent to an edge (start or end)
8063 // - It is adjacent to a whitespace (left or right)
8064 ShowWhitespaceSetting::Boundary => {
8065 // 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
8066 // the above cases.
8067 // Note: We zip in the original `invisibles` to check for tab equality
8068 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
8069 for (([start, end], paint), invisible) in
8070 invisible_iter.zip_eq(self.invisibles.iter())
8071 {
8072 let should_render = match (&last_seen, invisible) {
8073 (_, Invisible::Tab { .. }) => true,
8074 (Some((_, last_end, _)), _) => *last_end == start,
8075 _ => false,
8076 };
8077
8078 if should_render || start == 0 || end == self.len {
8079 paint(window, cx);
8080
8081 // Since we are scanning from the left, we will skip over the first available whitespace that is part
8082 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
8083 if let Some((should_render_last, last_end, paint_last)) = last_seen {
8084 // Note that we need to make sure that the last one is actually adjacent
8085 if !should_render_last && last_end == start {
8086 paint_last(window, cx);
8087 }
8088 }
8089 }
8090
8091 // Manually render anything within a selection
8092 let invisible_point = DisplayPoint::new(row, start as u32);
8093 if selection_ranges.iter().any(|region| {
8094 region.start <= invisible_point && invisible_point < region.end
8095 }) {
8096 paint(window, cx);
8097 }
8098
8099 last_seen = Some((should_render, end, paint));
8100 }
8101 }
8102 }
8103 }
8104
8105 pub fn x_for_index(&self, index: usize) -> Pixels {
8106 let mut fragment_start_x = Pixels::ZERO;
8107 let mut fragment_start_index = 0;
8108
8109 for fragment in &self.fragments {
8110 match fragment {
8111 LineFragment::Text(shaped_line) => {
8112 let fragment_end_index = fragment_start_index + shaped_line.len;
8113 if index < fragment_end_index {
8114 return fragment_start_x
8115 + shaped_line.x_for_index(index - fragment_start_index);
8116 }
8117 fragment_start_x += shaped_line.width;
8118 fragment_start_index = fragment_end_index;
8119 }
8120 LineFragment::Element { len, size, .. } => {
8121 let fragment_end_index = fragment_start_index + len;
8122 if index < fragment_end_index {
8123 return fragment_start_x;
8124 }
8125 fragment_start_x += size.width;
8126 fragment_start_index = fragment_end_index;
8127 }
8128 }
8129 }
8130
8131 fragment_start_x
8132 }
8133
8134 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
8135 let mut fragment_start_x = Pixels::ZERO;
8136 let mut fragment_start_index = 0;
8137
8138 for fragment in &self.fragments {
8139 match fragment {
8140 LineFragment::Text(shaped_line) => {
8141 let fragment_end_x = fragment_start_x + shaped_line.width;
8142 if x < fragment_end_x {
8143 return Some(
8144 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
8145 );
8146 }
8147 fragment_start_x = fragment_end_x;
8148 fragment_start_index += shaped_line.len;
8149 }
8150 LineFragment::Element { len, size, .. } => {
8151 let fragment_end_x = fragment_start_x + size.width;
8152 if x < fragment_end_x {
8153 return Some(fragment_start_index);
8154 }
8155 fragment_start_index += len;
8156 fragment_start_x = fragment_end_x;
8157 }
8158 }
8159 }
8160
8161 None
8162 }
8163
8164 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
8165 let mut fragment_start_index = 0;
8166
8167 for fragment in &self.fragments {
8168 match fragment {
8169 LineFragment::Text(shaped_line) => {
8170 let fragment_end_index = fragment_start_index + shaped_line.len;
8171 if index < fragment_end_index {
8172 return shaped_line.font_id_for_index(index - fragment_start_index);
8173 }
8174 fragment_start_index = fragment_end_index;
8175 }
8176 LineFragment::Element { len, .. } => {
8177 let fragment_end_index = fragment_start_index + len;
8178 if index < fragment_end_index {
8179 return None;
8180 }
8181 fragment_start_index = fragment_end_index;
8182 }
8183 }
8184 }
8185
8186 None
8187 }
8188}
8189
8190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8191enum Invisible {
8192 /// A tab character
8193 ///
8194 /// A tab character is internally represented by spaces (configured by the user's tab width)
8195 /// aligned to the nearest column, so it's necessary to store the start and end offset for
8196 /// adjacency checks.
8197 Tab {
8198 line_start_offset: usize,
8199 line_end_offset: usize,
8200 },
8201 Whitespace {
8202 line_offset: usize,
8203 },
8204}
8205
8206impl EditorElement {
8207 /// Returns the rem size to use when rendering the [`EditorElement`].
8208 ///
8209 /// This allows UI elements to scale based on the `buffer_font_size`.
8210 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
8211 match self.editor.read(cx).mode {
8212 EditorMode::Full {
8213 scale_ui_elements_with_buffer_font_size: true,
8214 ..
8215 }
8216 | EditorMode::Minimap { .. } => {
8217 let buffer_font_size = self.style.text.font_size;
8218 match buffer_font_size {
8219 AbsoluteLength::Pixels(pixels) => {
8220 let rem_size_scale = {
8221 // Our default UI font size is 14px on a 16px base scale.
8222 // This means the default UI font size is 0.875rems.
8223 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
8224
8225 // We then determine the delta between a single rem and the default font
8226 // size scale.
8227 let default_font_size_delta = 1. - default_font_size_scale;
8228
8229 // Finally, we add this delta to 1rem to get the scale factor that
8230 // should be used to scale up the UI.
8231 1. + default_font_size_delta
8232 };
8233
8234 Some(pixels * rem_size_scale)
8235 }
8236 AbsoluteLength::Rems(rems) => {
8237 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
8238 }
8239 }
8240 }
8241 // We currently use single-line and auto-height editors in UI contexts,
8242 // so we don't want to scale everything with the buffer font size, as it
8243 // ends up looking off.
8244 _ => None,
8245 }
8246 }
8247
8248 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
8249 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
8250 parent.upgrade()
8251 } else {
8252 Some(self.editor.clone())
8253 }
8254 }
8255}
8256
8257impl Element for EditorElement {
8258 type RequestLayoutState = ();
8259 type PrepaintState = EditorLayout;
8260
8261 fn id(&self) -> Option<ElementId> {
8262 None
8263 }
8264
8265 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
8266 None
8267 }
8268
8269 fn request_layout(
8270 &mut self,
8271 _: Option<&GlobalElementId>,
8272 _inspector_id: Option<&gpui::InspectorElementId>,
8273 window: &mut Window,
8274 cx: &mut App,
8275 ) -> (gpui::LayoutId, ()) {
8276 let rem_size = self.rem_size(cx);
8277 window.with_rem_size(rem_size, |window| {
8278 self.editor.update(cx, |editor, cx| {
8279 editor.set_style(self.style.clone(), window, cx);
8280
8281 let layout_id = match editor.mode {
8282 EditorMode::SingleLine => {
8283 let rem_size = window.rem_size();
8284 let height = self.style.text.line_height_in_pixels(rem_size);
8285 let mut style = Style::default();
8286 style.size.height = height.into();
8287 style.size.width = relative(1.).into();
8288 window.request_layout(style, None, cx)
8289 }
8290 EditorMode::AutoHeight {
8291 min_lines,
8292 max_lines,
8293 } => {
8294 let editor_handle = cx.entity();
8295 let max_line_number_width =
8296 self.max_line_number_width(&editor.snapshot(window, cx), window);
8297 window.request_measured_layout(
8298 Style::default(),
8299 move |known_dimensions, available_space, window, cx| {
8300 editor_handle
8301 .update(cx, |editor, cx| {
8302 compute_auto_height_layout(
8303 editor,
8304 min_lines,
8305 max_lines,
8306 max_line_number_width,
8307 known_dimensions,
8308 available_space.width,
8309 window,
8310 cx,
8311 )
8312 })
8313 .unwrap_or_default()
8314 },
8315 )
8316 }
8317 EditorMode::Minimap { .. } => {
8318 let mut style = Style::default();
8319 style.size.width = relative(1.).into();
8320 style.size.height = relative(1.).into();
8321 window.request_layout(style, None, cx)
8322 }
8323 EditorMode::Full {
8324 sized_by_content, ..
8325 } => {
8326 let mut style = Style::default();
8327 style.size.width = relative(1.).into();
8328 if sized_by_content {
8329 let snapshot = editor.snapshot(window, cx);
8330 let line_height =
8331 self.style.text.line_height_in_pixels(window.rem_size());
8332 let scroll_height =
8333 (snapshot.max_point().row().next_row().0 as f32) * line_height;
8334 style.size.height = scroll_height.into();
8335 } else {
8336 style.size.height = relative(1.).into();
8337 }
8338 window.request_layout(style, None, cx)
8339 }
8340 };
8341
8342 (layout_id, ())
8343 })
8344 })
8345 }
8346
8347 fn prepaint(
8348 &mut self,
8349 _: Option<&GlobalElementId>,
8350 _inspector_id: Option<&gpui::InspectorElementId>,
8351 bounds: Bounds<Pixels>,
8352 _: &mut Self::RequestLayoutState,
8353 window: &mut Window,
8354 cx: &mut App,
8355 ) -> Self::PrepaintState {
8356 let text_style = TextStyleRefinement {
8357 font_size: Some(self.style.text.font_size),
8358 line_height: Some(self.style.text.line_height),
8359 ..Default::default()
8360 };
8361
8362 let is_minimap = self.editor.read(cx).mode.is_minimap();
8363
8364 if !is_minimap {
8365 let focus_handle = self.editor.focus_handle(cx);
8366 window.set_view_id(self.editor.entity_id());
8367 window.set_focus_handle(&focus_handle, cx);
8368 }
8369
8370 let rem_size = self.rem_size(cx);
8371 window.with_rem_size(rem_size, |window| {
8372 window.with_text_style(Some(text_style), |window| {
8373 window.with_content_mask(Some(ContentMask { bounds }), |window| {
8374 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
8375 (editor.snapshot(window, cx), editor.read_only(cx))
8376 });
8377 let style = &self.style;
8378
8379 let rem_size = window.rem_size();
8380 let font_id = window.text_system().resolve_font(&style.text.font());
8381 let font_size = style.text.font_size.to_pixels(rem_size);
8382 let line_height = style.text.line_height_in_pixels(rem_size);
8383 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8384 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
8385 let glyph_grid_cell = size(em_advance, line_height);
8386
8387 let gutter_dimensions = snapshot
8388 .gutter_dimensions(
8389 font_id,
8390 font_size,
8391 self.max_line_number_width(&snapshot, window),
8392 cx,
8393 )
8394 .or_else(|| {
8395 self.editor.read(cx).offset_content.then(|| {
8396 GutterDimensions::default_with_margin(font_id, font_size, cx)
8397 })
8398 })
8399 .unwrap_or_default();
8400 let text_width = bounds.size.width - gutter_dimensions.width;
8401
8402 let settings = EditorSettings::get_global(cx);
8403 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
8404 let vertical_scrollbar_width = (scrollbars_shown
8405 && settings.scrollbar.axes.vertical
8406 && self.editor.read(cx).show_scrollbars.vertical)
8407 .then_some(style.scrollbar_width)
8408 .unwrap_or_default();
8409 let minimap_width = self
8410 .get_minimap_width(
8411 &settings.minimap,
8412 scrollbars_shown,
8413 text_width,
8414 em_width,
8415 font_size,
8416 rem_size,
8417 cx,
8418 )
8419 .unwrap_or_default();
8420
8421 let right_margin = minimap_width + vertical_scrollbar_width;
8422
8423 let editor_width =
8424 text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
8425 let editor_margins = EditorMargins {
8426 gutter: gutter_dimensions,
8427 right: right_margin,
8428 };
8429
8430 snapshot = self.editor.update(cx, |editor, cx| {
8431 editor.last_bounds = Some(bounds);
8432 editor.gutter_dimensions = gutter_dimensions;
8433 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
8434 editor.set_visible_column_count(editor_width / em_advance);
8435
8436 if matches!(
8437 editor.mode,
8438 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
8439 ) {
8440 snapshot
8441 } else {
8442 let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
8443 let wrap_width = match editor.soft_wrap_mode(cx) {
8444 SoftWrap::GitDiff => None,
8445 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
8446 SoftWrap::EditorWidth => Some(editor_width),
8447 SoftWrap::Column(column) => Some(wrap_width_for(column)),
8448 SoftWrap::Bounded(column) => {
8449 Some(editor_width.min(wrap_width_for(column)))
8450 }
8451 };
8452
8453 if editor.set_wrap_width(wrap_width, cx) {
8454 editor.snapshot(window, cx)
8455 } else {
8456 snapshot
8457 }
8458 }
8459 });
8460
8461 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
8462 let gutter_hitbox = window.insert_hitbox(
8463 gutter_bounds(bounds, gutter_dimensions),
8464 HitboxBehavior::Normal,
8465 );
8466 let text_hitbox = window.insert_hitbox(
8467 Bounds {
8468 origin: gutter_hitbox.top_right(),
8469 size: size(text_width, bounds.size.height),
8470 },
8471 HitboxBehavior::Normal,
8472 );
8473
8474 // Offset the content_bounds from the text_bounds by the gutter margin (which
8475 // is roughly half a character wide) to make hit testing work more like how we want.
8476 let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
8477 let content_origin = text_hitbox.origin + content_offset;
8478
8479 let height_in_lines = bounds.size.height / line_height;
8480 let max_row = snapshot.max_point().row().as_f32();
8481
8482 // The max scroll position for the top of the window
8483 let max_scroll_top = if matches!(
8484 snapshot.mode,
8485 EditorMode::SingleLine
8486 | EditorMode::AutoHeight { .. }
8487 | EditorMode::Full {
8488 sized_by_content: true,
8489 ..
8490 }
8491 ) {
8492 (max_row - height_in_lines + 1.).max(0.)
8493 } else {
8494 let settings = EditorSettings::get_global(cx);
8495 match settings.scroll_beyond_last_line {
8496 ScrollBeyondLastLine::OnePage => max_row,
8497 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
8498 ScrollBeyondLastLine::VerticalScrollMargin => {
8499 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
8500 .max(0.)
8501 }
8502 }
8503 };
8504
8505 let (
8506 autoscroll_request,
8507 autoscroll_containing_element,
8508 needs_horizontal_autoscroll,
8509 ) = self.editor.update(cx, |editor, cx| {
8510 let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
8511
8512 let autoscroll_containing_element =
8513 autoscroll_request.is_some() || editor.has_pending_selection();
8514
8515 let (needs_horizontal_autoscroll, was_scrolled) = editor
8516 .autoscroll_vertically(
8517 bounds,
8518 line_height,
8519 max_scroll_top,
8520 autoscroll_request,
8521 window,
8522 cx,
8523 );
8524 if was_scrolled.0 {
8525 snapshot = editor.snapshot(window, cx);
8526 }
8527 (
8528 autoscroll_request,
8529 autoscroll_containing_element,
8530 needs_horizontal_autoscroll,
8531 )
8532 });
8533
8534 let mut scroll_position = snapshot.scroll_position();
8535 // The scroll position is a fractional point, the whole number of which represents
8536 // the top of the window in terms of display rows.
8537 let start_row = DisplayRow(scroll_position.y as u32);
8538 let max_row = snapshot.max_point().row();
8539 let end_row = cmp::min(
8540 (scroll_position.y + height_in_lines).ceil() as u32,
8541 max_row.next_row().0,
8542 );
8543 let end_row = DisplayRow(end_row);
8544
8545 let row_infos = snapshot
8546 .row_infos(start_row)
8547 .take((start_row..end_row).len())
8548 .collect::<Vec<RowInfo>>();
8549 let is_row_soft_wrapped = |row: usize| {
8550 row_infos
8551 .get(row)
8552 .is_none_or(|info| info.buffer_row.is_none())
8553 };
8554
8555 let start_anchor = if start_row == Default::default() {
8556 Anchor::min()
8557 } else {
8558 snapshot.buffer_snapshot.anchor_before(
8559 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
8560 )
8561 };
8562 let end_anchor = if end_row > max_row {
8563 Anchor::max()
8564 } else {
8565 snapshot.buffer_snapshot.anchor_before(
8566 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
8567 )
8568 };
8569
8570 let mut highlighted_rows = self
8571 .editor
8572 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
8573
8574 let is_light = cx.theme().appearance().is_light();
8575
8576 for (ix, row_info) in row_infos.iter().enumerate() {
8577 let Some(diff_status) = row_info.diff_status else {
8578 continue;
8579 };
8580
8581 let background_color = match diff_status.kind {
8582 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
8583 DiffHunkStatusKind::Deleted => {
8584 cx.theme().colors().version_control_deleted
8585 }
8586 DiffHunkStatusKind::Modified => {
8587 debug_panic!("modified diff status for row info");
8588 continue;
8589 }
8590 };
8591
8592 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
8593
8594 let hollow_highlight = LineHighlight {
8595 background: (background_color.opacity(if is_light {
8596 0.08
8597 } else {
8598 0.06
8599 }))
8600 .into(),
8601 border: Some(if is_light {
8602 background_color.opacity(0.48)
8603 } else {
8604 background_color.opacity(0.36)
8605 }),
8606 include_gutter: true,
8607 type_id: None,
8608 };
8609
8610 let filled_highlight = LineHighlight {
8611 background: solid_background(background_color.opacity(hunk_opacity)),
8612 border: None,
8613 include_gutter: true,
8614 type_id: None,
8615 };
8616
8617 let background = if Self::diff_hunk_hollow(diff_status, cx) {
8618 hollow_highlight
8619 } else {
8620 filled_highlight
8621 };
8622
8623 highlighted_rows
8624 .entry(start_row + DisplayRow(ix as u32))
8625 .or_insert(background);
8626 }
8627
8628 let highlighted_ranges = self
8629 .editor_with_selections(cx)
8630 .map(|editor| {
8631 editor.read(cx).background_highlights_in_range(
8632 start_anchor..end_anchor,
8633 &snapshot.display_snapshot,
8634 cx.theme(),
8635 )
8636 })
8637 .unwrap_or_default();
8638 let highlighted_gutter_ranges =
8639 self.editor.read(cx).gutter_highlights_in_range(
8640 start_anchor..end_anchor,
8641 &snapshot.display_snapshot,
8642 cx,
8643 );
8644
8645 let document_colors = self
8646 .editor
8647 .read(cx)
8648 .colors
8649 .as_ref()
8650 .map(|colors| colors.editor_display_highlights(&snapshot));
8651 let redacted_ranges = self.editor.read(cx).redacted_ranges(
8652 start_anchor..end_anchor,
8653 &snapshot.display_snapshot,
8654 cx,
8655 );
8656
8657 let (local_selections, selected_buffer_ids): (
8658 Vec<Selection<Point>>,
8659 Vec<BufferId>,
8660 ) = self
8661 .editor_with_selections(cx)
8662 .map(|editor| {
8663 editor.update(cx, |editor, cx| {
8664 let all_selections = editor.selections.all::<Point>(cx);
8665 let selected_buffer_ids = if editor.is_singleton(cx) {
8666 Vec::new()
8667 } else {
8668 let mut selected_buffer_ids =
8669 Vec::with_capacity(all_selections.len());
8670
8671 for selection in all_selections {
8672 for buffer_id in snapshot
8673 .buffer_snapshot
8674 .buffer_ids_for_range(selection.range())
8675 {
8676 if selected_buffer_ids.last() != Some(&buffer_id) {
8677 selected_buffer_ids.push(buffer_id);
8678 }
8679 }
8680 }
8681
8682 selected_buffer_ids
8683 };
8684
8685 let mut selections = editor
8686 .selections
8687 .disjoint_in_range(start_anchor..end_anchor, cx);
8688 selections.extend(editor.selections.pending(cx));
8689
8690 (selections, selected_buffer_ids)
8691 })
8692 })
8693 .unwrap_or_default();
8694
8695 let (selections, mut active_rows, newest_selection_head) = self
8696 .layout_selections(
8697 start_anchor,
8698 end_anchor,
8699 &local_selections,
8700 &snapshot,
8701 start_row,
8702 end_row,
8703 window,
8704 cx,
8705 );
8706 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
8707 editor.active_breakpoints(start_row..end_row, window, cx)
8708 });
8709 for (display_row, (_, bp, state)) in &breakpoint_rows {
8710 if bp.is_enabled() && state.is_none_or(|s| s.verified) {
8711 active_rows.entry(*display_row).or_default().breakpoint = true;
8712 }
8713 }
8714
8715 let line_numbers = self.layout_line_numbers(
8716 Some(&gutter_hitbox),
8717 gutter_dimensions,
8718 line_height,
8719 scroll_position,
8720 start_row..end_row,
8721 &row_infos,
8722 &active_rows,
8723 newest_selection_head,
8724 &snapshot,
8725 window,
8726 cx,
8727 );
8728
8729 // We add the gutter breakpoint indicator to breakpoint_rows after painting
8730 // line numbers so we don't paint a line number debug accent color if a user
8731 // has their mouse over that line when a breakpoint isn't there
8732 self.editor.update(cx, |editor, _| {
8733 if let Some(phantom_breakpoint) = &mut editor
8734 .gutter_breakpoint_indicator
8735 .0
8736 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
8737 {
8738 // Is there a non-phantom breakpoint on this line?
8739 phantom_breakpoint.collides_with_existing_breakpoint = true;
8740 breakpoint_rows
8741 .entry(phantom_breakpoint.display_row)
8742 .or_insert_with(|| {
8743 let position = snapshot.display_point_to_anchor(
8744 DisplayPoint::new(phantom_breakpoint.display_row, 0),
8745 Bias::Right,
8746 );
8747 let breakpoint = Breakpoint::new_standard();
8748 phantom_breakpoint.collides_with_existing_breakpoint = false;
8749 (position, breakpoint, None)
8750 });
8751 }
8752 });
8753
8754 let mut expand_toggles =
8755 window.with_element_namespace("expand_toggles", |window| {
8756 self.layout_expand_toggles(
8757 &gutter_hitbox,
8758 gutter_dimensions,
8759 em_width,
8760 line_height,
8761 scroll_position,
8762 &row_infos,
8763 window,
8764 cx,
8765 )
8766 });
8767
8768 let mut crease_toggles =
8769 window.with_element_namespace("crease_toggles", |window| {
8770 self.layout_crease_toggles(
8771 start_row..end_row,
8772 &row_infos,
8773 &active_rows,
8774 &snapshot,
8775 window,
8776 cx,
8777 )
8778 });
8779 let crease_trailers =
8780 window.with_element_namespace("crease_trailers", |window| {
8781 self.layout_crease_trailers(
8782 row_infos.iter().copied(),
8783 &snapshot,
8784 window,
8785 cx,
8786 )
8787 });
8788
8789 let display_hunks = self.layout_gutter_diff_hunks(
8790 line_height,
8791 &gutter_hitbox,
8792 start_row..end_row,
8793 &snapshot,
8794 window,
8795 cx,
8796 );
8797
8798 let bg_segments_per_row = Self::bg_segments_per_row(
8799 start_row..end_row,
8800 &selections,
8801 &highlighted_ranges,
8802 self.style.background,
8803 );
8804
8805 let mut line_layouts = Self::layout_lines(
8806 start_row..end_row,
8807 &snapshot,
8808 &self.style,
8809 editor_width,
8810 is_row_soft_wrapped,
8811 &bg_segments_per_row,
8812 window,
8813 cx,
8814 );
8815 let new_renderer_widths = (!is_minimap).then(|| {
8816 line_layouts
8817 .iter()
8818 .flat_map(|layout| &layout.fragments)
8819 .filter_map(|fragment| {
8820 if let LineFragment::Element { id, size, .. } = fragment {
8821 Some((*id, size.width))
8822 } else {
8823 None
8824 }
8825 })
8826 });
8827 if new_renderer_widths.is_some_and(|new_renderer_widths| {
8828 self.editor.update(cx, |editor, cx| {
8829 editor.update_renderer_widths(new_renderer_widths, cx)
8830 })
8831 }) {
8832 // If the fold widths have changed, we need to prepaint
8833 // the element again to account for any changes in
8834 // wrapping.
8835 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8836 }
8837
8838 let longest_line_blame_width = self
8839 .editor
8840 .update(cx, |editor, cx| {
8841 if !editor.show_git_blame_inline {
8842 return None;
8843 }
8844 let blame = editor.blame.as_ref()?;
8845 let (_, blame_entry) = blame
8846 .update(cx, |blame, cx| {
8847 let row_infos =
8848 snapshot.row_infos(snapshot.longest_row()).next()?;
8849 blame.blame_for_rows(&[row_infos], cx).next()
8850 })
8851 .flatten()?;
8852 let mut element = render_inline_blame_entry(blame_entry, style, cx)?;
8853 let inline_blame_padding =
8854 ProjectSettings::get_global(cx).git.inline_blame.padding as f32
8855 * em_advance;
8856 Some(
8857 element
8858 .layout_as_root(AvailableSpace::min_size(), window, cx)
8859 .width
8860 + inline_blame_padding,
8861 )
8862 })
8863 .unwrap_or(Pixels::ZERO);
8864
8865 let longest_line_width = layout_line(
8866 snapshot.longest_row(),
8867 &snapshot,
8868 style,
8869 editor_width,
8870 is_row_soft_wrapped,
8871 window,
8872 cx,
8873 )
8874 .width;
8875
8876 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
8877 text_hitbox.bounds,
8878 glyph_grid_cell,
8879 size(longest_line_width, max_row.as_f32() * line_height),
8880 longest_line_blame_width,
8881 EditorSettings::get_global(cx),
8882 );
8883
8884 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
8885
8886 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
8887 snapshot.sticky_header_excerpt(scroll_position.y)
8888 } else {
8889 None
8890 };
8891 let sticky_header_excerpt_id =
8892 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
8893
8894 let blocks = (!is_minimap)
8895 .then(|| {
8896 window.with_element_namespace("blocks", |window| {
8897 self.render_blocks(
8898 start_row..end_row,
8899 &snapshot,
8900 &hitbox,
8901 &text_hitbox,
8902 editor_width,
8903 &mut scroll_width,
8904 &editor_margins,
8905 em_width,
8906 gutter_dimensions.full_width(),
8907 line_height,
8908 &mut line_layouts,
8909 &local_selections,
8910 &selected_buffer_ids,
8911 is_row_soft_wrapped,
8912 sticky_header_excerpt_id,
8913 window,
8914 cx,
8915 )
8916 })
8917 })
8918 .unwrap_or_else(|| Ok((Vec::default(), HashMap::default())));
8919 let (mut blocks, row_block_types) = match blocks {
8920 Ok(blocks) => blocks,
8921 Err(resized_blocks) => {
8922 self.editor.update(cx, |editor, cx| {
8923 editor.resize_blocks(
8924 resized_blocks,
8925 autoscroll_request.map(|(autoscroll, _)| autoscroll),
8926 cx,
8927 )
8928 });
8929 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8930 }
8931 };
8932
8933 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
8934 window.with_element_namespace("blocks", |window| {
8935 self.layout_sticky_buffer_header(
8936 sticky_header_excerpt,
8937 scroll_position.y,
8938 line_height,
8939 right_margin,
8940 &snapshot,
8941 &hitbox,
8942 &selected_buffer_ids,
8943 &blocks,
8944 window,
8945 cx,
8946 )
8947 })
8948 });
8949
8950 let start_buffer_row =
8951 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
8952 let end_buffer_row =
8953 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
8954
8955 let scroll_max = point(
8956 ((scroll_width - editor_width) / em_advance).max(0.0),
8957 max_scroll_top,
8958 );
8959
8960 self.editor.update(cx, |editor, cx| {
8961 if editor.scroll_manager.clamp_scroll_left(scroll_max.x) {
8962 scroll_position.x = scroll_position.x.min(scroll_max.x);
8963 }
8964
8965 if needs_horizontal_autoscroll.0
8966 && let Some(new_scroll_position) = editor.autoscroll_horizontally(
8967 start_row,
8968 editor_width,
8969 scroll_width,
8970 em_advance,
8971 &line_layouts,
8972 autoscroll_request,
8973 window,
8974 cx,
8975 )
8976 {
8977 scroll_position = new_scroll_position;
8978 }
8979 });
8980
8981 let scroll_pixel_position = point(
8982 scroll_position.x * em_advance,
8983 scroll_position.y * line_height,
8984 );
8985 let indent_guides = self.layout_indent_guides(
8986 content_origin,
8987 text_hitbox.origin,
8988 start_buffer_row..end_buffer_row,
8989 scroll_pixel_position,
8990 line_height,
8991 &snapshot,
8992 window,
8993 cx,
8994 );
8995
8996 let crease_trailers =
8997 window.with_element_namespace("crease_trailers", |window| {
8998 self.prepaint_crease_trailers(
8999 crease_trailers,
9000 &line_layouts,
9001 line_height,
9002 content_origin,
9003 scroll_pixel_position,
9004 em_width,
9005 window,
9006 cx,
9007 )
9008 });
9009
9010 let (edit_prediction_popover, edit_prediction_popover_origin) = self
9011 .editor
9012 .update(cx, |editor, cx| {
9013 editor.render_edit_prediction_popover(
9014 &text_hitbox.bounds,
9015 content_origin,
9016 right_margin,
9017 &snapshot,
9018 start_row..end_row,
9019 scroll_position.y,
9020 scroll_position.y + height_in_lines,
9021 &line_layouts,
9022 line_height,
9023 scroll_pixel_position,
9024 newest_selection_head,
9025 editor_width,
9026 style,
9027 window,
9028 cx,
9029 )
9030 })
9031 .unzip();
9032
9033 let mut inline_diagnostics = self.layout_inline_diagnostics(
9034 &line_layouts,
9035 &crease_trailers,
9036 &row_block_types,
9037 content_origin,
9038 scroll_pixel_position,
9039 edit_prediction_popover_origin,
9040 start_row,
9041 end_row,
9042 line_height,
9043 em_width,
9044 style,
9045 window,
9046 cx,
9047 );
9048
9049 let mut inline_blame_layout = None;
9050 let mut inline_code_actions = None;
9051 if let Some(newest_selection_head) = newest_selection_head {
9052 let display_row = newest_selection_head.row();
9053 if (start_row..end_row).contains(&display_row)
9054 && !row_block_types.contains_key(&display_row)
9055 {
9056 inline_code_actions = self.layout_inline_code_actions(
9057 newest_selection_head,
9058 content_origin,
9059 scroll_pixel_position,
9060 line_height,
9061 &snapshot,
9062 window,
9063 cx,
9064 );
9065
9066 let line_ix = display_row.minus(start_row) as usize;
9067 if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
9068 row_infos.get(line_ix),
9069 line_layouts.get(line_ix),
9070 crease_trailers.get(line_ix),
9071 ) {
9072 let crease_trailer_layout = crease_trailer.as_ref();
9073 if let Some(layout) = self.layout_inline_blame(
9074 display_row,
9075 row_info,
9076 line_layout,
9077 crease_trailer_layout,
9078 em_width,
9079 content_origin,
9080 scroll_pixel_position,
9081 line_height,
9082 &text_hitbox,
9083 window,
9084 cx,
9085 ) {
9086 inline_blame_layout = Some(layout);
9087 // Blame overrides inline diagnostics
9088 inline_diagnostics.remove(&display_row);
9089 }
9090 } else {
9091 log::error!(
9092 "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
9093 line_layouts.len(): {}, \
9094 crease_trailers.len(): {}",
9095 line_ix,
9096 row_infos.len(),
9097 line_layouts.len(),
9098 crease_trailers.len(),
9099 );
9100 }
9101 }
9102 }
9103
9104 let blamed_display_rows = self.layout_blame_entries(
9105 &row_infos,
9106 em_width,
9107 scroll_position,
9108 line_height,
9109 &gutter_hitbox,
9110 gutter_dimensions.git_blame_entries_width,
9111 window,
9112 cx,
9113 );
9114
9115 let line_elements = self.prepaint_lines(
9116 start_row,
9117 &mut line_layouts,
9118 line_height,
9119 scroll_pixel_position,
9120 content_origin,
9121 window,
9122 cx,
9123 );
9124
9125 window.with_element_namespace("blocks", |window| {
9126 self.layout_blocks(
9127 &mut blocks,
9128 &hitbox,
9129 line_height,
9130 scroll_pixel_position,
9131 window,
9132 cx,
9133 );
9134 });
9135
9136 let cursors = self.collect_cursors(&snapshot, cx);
9137 let visible_row_range = start_row..end_row;
9138 let non_visible_cursors = cursors
9139 .iter()
9140 .any(|c| !visible_row_range.contains(&c.0.row()));
9141
9142 let visible_cursors = self.layout_visible_cursors(
9143 &snapshot,
9144 &selections,
9145 &row_block_types,
9146 start_row..end_row,
9147 &line_layouts,
9148 &text_hitbox,
9149 content_origin,
9150 scroll_position,
9151 scroll_pixel_position,
9152 line_height,
9153 em_width,
9154 em_advance,
9155 autoscroll_containing_element,
9156 window,
9157 cx,
9158 );
9159
9160 let scrollbars_layout = self.layout_scrollbars(
9161 &snapshot,
9162 &scrollbar_layout_information,
9163 content_offset,
9164 scroll_position,
9165 non_visible_cursors,
9166 right_margin,
9167 editor_width,
9168 window,
9169 cx,
9170 );
9171
9172 let gutter_settings = EditorSettings::get_global(cx).gutter;
9173
9174 let context_menu_layout =
9175 if let Some(newest_selection_head) = newest_selection_head {
9176 let newest_selection_point =
9177 newest_selection_head.to_point(&snapshot.display_snapshot);
9178 if (start_row..end_row).contains(&newest_selection_head.row()) {
9179 self.layout_cursor_popovers(
9180 line_height,
9181 &text_hitbox,
9182 content_origin,
9183 right_margin,
9184 start_row,
9185 scroll_pixel_position,
9186 &line_layouts,
9187 newest_selection_head,
9188 newest_selection_point,
9189 style,
9190 window,
9191 cx,
9192 )
9193 } else {
9194 None
9195 }
9196 } else {
9197 None
9198 };
9199
9200 self.layout_gutter_menu(
9201 line_height,
9202 &text_hitbox,
9203 content_origin,
9204 right_margin,
9205 scroll_pixel_position,
9206 gutter_dimensions.width - gutter_dimensions.left_padding,
9207 window,
9208 cx,
9209 );
9210
9211 let test_indicators = if gutter_settings.runnables {
9212 self.layout_run_indicators(
9213 line_height,
9214 start_row..end_row,
9215 &row_infos,
9216 scroll_pixel_position,
9217 &gutter_dimensions,
9218 &gutter_hitbox,
9219 &display_hunks,
9220 &snapshot,
9221 &mut breakpoint_rows,
9222 window,
9223 cx,
9224 )
9225 } else {
9226 Vec::new()
9227 };
9228
9229 let show_breakpoints = snapshot
9230 .show_breakpoints
9231 .unwrap_or(gutter_settings.breakpoints);
9232 let breakpoints = if show_breakpoints {
9233 self.layout_breakpoints(
9234 line_height,
9235 start_row..end_row,
9236 scroll_pixel_position,
9237 &gutter_dimensions,
9238 &gutter_hitbox,
9239 &display_hunks,
9240 &snapshot,
9241 breakpoint_rows,
9242 &row_infos,
9243 window,
9244 cx,
9245 )
9246 } else {
9247 Vec::new()
9248 };
9249
9250 self.layout_signature_help(
9251 &hitbox,
9252 content_origin,
9253 scroll_pixel_position,
9254 newest_selection_head,
9255 start_row,
9256 &line_layouts,
9257 line_height,
9258 em_width,
9259 context_menu_layout,
9260 window,
9261 cx,
9262 );
9263
9264 if !cx.has_active_drag() {
9265 self.layout_hover_popovers(
9266 &snapshot,
9267 &hitbox,
9268 start_row..end_row,
9269 content_origin,
9270 scroll_pixel_position,
9271 &line_layouts,
9272 line_height,
9273 em_width,
9274 context_menu_layout,
9275 window,
9276 cx,
9277 );
9278 }
9279
9280 let mouse_context_menu = self.layout_mouse_context_menu(
9281 &snapshot,
9282 start_row..end_row,
9283 content_origin,
9284 window,
9285 cx,
9286 );
9287
9288 window.with_element_namespace("crease_toggles", |window| {
9289 self.prepaint_crease_toggles(
9290 &mut crease_toggles,
9291 line_height,
9292 &gutter_dimensions,
9293 gutter_settings,
9294 scroll_pixel_position,
9295 &gutter_hitbox,
9296 window,
9297 cx,
9298 )
9299 });
9300
9301 window.with_element_namespace("expand_toggles", |window| {
9302 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
9303 });
9304
9305 let wrap_guides = self.layout_wrap_guides(
9306 em_advance,
9307 scroll_position,
9308 content_origin,
9309 scrollbars_layout.as_ref(),
9310 vertical_scrollbar_width,
9311 &hitbox,
9312 window,
9313 cx,
9314 );
9315
9316 let minimap = window.with_element_namespace("minimap", |window| {
9317 self.layout_minimap(
9318 &snapshot,
9319 minimap_width,
9320 scroll_position,
9321 &scrollbar_layout_information,
9322 scrollbars_layout.as_ref(),
9323 window,
9324 cx,
9325 )
9326 });
9327
9328 let invisible_symbol_font_size = font_size / 2.;
9329 let whitespace_map = &self
9330 .editor
9331 .read(cx)
9332 .buffer
9333 .read(cx)
9334 .language_settings(cx)
9335 .whitespace_map;
9336
9337 let tab_char = whitespace_map.tab.clone();
9338 let tab_len = tab_char.len();
9339 let tab_invisible = window.text_system().shape_line(
9340 tab_char,
9341 invisible_symbol_font_size,
9342 &[TextRun {
9343 len: tab_len,
9344 font: self.style.text.font(),
9345 color: cx.theme().colors().editor_invisible,
9346 background_color: None,
9347 underline: None,
9348 strikethrough: None,
9349 }],
9350 None,
9351 );
9352
9353 let space_char = whitespace_map.space.clone();
9354 let space_len = space_char.len();
9355 let space_invisible = window.text_system().shape_line(
9356 space_char,
9357 invisible_symbol_font_size,
9358 &[TextRun {
9359 len: space_len,
9360 font: self.style.text.font(),
9361 color: cx.theme().colors().editor_invisible,
9362 background_color: None,
9363 underline: None,
9364 strikethrough: None,
9365 }],
9366 None,
9367 );
9368
9369 let mode = snapshot.mode.clone();
9370
9371 let (diff_hunk_controls, diff_hunk_control_bounds) = if is_read_only {
9372 (vec![], vec![])
9373 } else {
9374 self.layout_diff_hunk_controls(
9375 start_row..end_row,
9376 &row_infos,
9377 &text_hitbox,
9378 newest_selection_head,
9379 line_height,
9380 right_margin,
9381 scroll_pixel_position,
9382 &display_hunks,
9383 &highlighted_rows,
9384 self.editor.clone(),
9385 window,
9386 cx,
9387 )
9388 };
9389
9390 let position_map = Rc::new(PositionMap {
9391 size: bounds.size,
9392 visible_row_range,
9393 scroll_pixel_position,
9394 scroll_max,
9395 line_layouts,
9396 line_height,
9397 em_width,
9398 em_advance,
9399 snapshot,
9400 gutter_hitbox: gutter_hitbox.clone(),
9401 text_hitbox: text_hitbox.clone(),
9402 inline_blame_bounds: inline_blame_layout
9403 .as_ref()
9404 .map(|layout| (layout.bounds, layout.buffer_id, layout.entry.clone())),
9405 display_hunks: display_hunks.clone(),
9406 diff_hunk_control_bounds,
9407 });
9408
9409 self.editor.update(cx, |editor, _| {
9410 editor.last_position_map = Some(position_map.clone())
9411 });
9412
9413 EditorLayout {
9414 mode,
9415 position_map,
9416 visible_display_row_range: start_row..end_row,
9417 wrap_guides,
9418 indent_guides,
9419 hitbox,
9420 gutter_hitbox,
9421 display_hunks,
9422 content_origin,
9423 scrollbars_layout,
9424 minimap,
9425 active_rows,
9426 highlighted_rows,
9427 highlighted_ranges,
9428 highlighted_gutter_ranges,
9429 redacted_ranges,
9430 document_colors,
9431 line_elements,
9432 line_numbers,
9433 blamed_display_rows,
9434 inline_diagnostics,
9435 inline_blame_layout,
9436 inline_code_actions,
9437 blocks,
9438 cursors,
9439 visible_cursors,
9440 selections,
9441 edit_prediction_popover,
9442 diff_hunk_controls,
9443 mouse_context_menu,
9444 test_indicators,
9445 breakpoints,
9446 crease_toggles,
9447 crease_trailers,
9448 tab_invisible,
9449 space_invisible,
9450 sticky_buffer_header,
9451 expand_toggles,
9452 }
9453 })
9454 })
9455 })
9456 }
9457
9458 fn paint(
9459 &mut self,
9460 _: Option<&GlobalElementId>,
9461 _inspector_id: Option<&gpui::InspectorElementId>,
9462 bounds: Bounds<gpui::Pixels>,
9463 _: &mut Self::RequestLayoutState,
9464 layout: &mut Self::PrepaintState,
9465 window: &mut Window,
9466 cx: &mut App,
9467 ) {
9468 if !layout.mode.is_minimap() {
9469 let focus_handle = self.editor.focus_handle(cx);
9470 let key_context = self
9471 .editor
9472 .update(cx, |editor, cx| editor.key_context(window, cx));
9473
9474 window.set_key_context(key_context);
9475 window.handle_input(
9476 &focus_handle,
9477 ElementInputHandler::new(bounds, self.editor.clone()),
9478 cx,
9479 );
9480 self.register_actions(window, cx);
9481 self.register_key_listeners(window, cx, layout);
9482 }
9483
9484 let text_style = TextStyleRefinement {
9485 font_size: Some(self.style.text.font_size),
9486 line_height: Some(self.style.text.line_height),
9487 ..Default::default()
9488 };
9489 let rem_size = self.rem_size(cx);
9490 window.with_rem_size(rem_size, |window| {
9491 window.with_text_style(Some(text_style), |window| {
9492 window.with_content_mask(Some(ContentMask { bounds }), |window| {
9493 self.paint_mouse_listeners(layout, window, cx);
9494 self.paint_background(layout, window, cx);
9495 self.paint_indent_guides(layout, window, cx);
9496
9497 if layout.gutter_hitbox.size.width > Pixels::ZERO {
9498 self.paint_blamed_display_rows(layout, window, cx);
9499 self.paint_line_numbers(layout, window, cx);
9500 }
9501
9502 self.paint_text(layout, window, cx);
9503
9504 if layout.gutter_hitbox.size.width > Pixels::ZERO {
9505 self.paint_gutter_highlights(layout, window, cx);
9506 self.paint_gutter_indicators(layout, window, cx);
9507 }
9508
9509 if !layout.blocks.is_empty() {
9510 window.with_element_namespace("blocks", |window| {
9511 self.paint_blocks(layout, window, cx);
9512 });
9513 }
9514
9515 window.with_element_namespace("blocks", |window| {
9516 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
9517 sticky_header.paint(window, cx)
9518 }
9519 });
9520
9521 self.paint_minimap(layout, window, cx);
9522 self.paint_scrollbars(layout, window, cx);
9523 self.paint_edit_prediction_popover(layout, window, cx);
9524 self.paint_mouse_context_menu(layout, window, cx);
9525 });
9526 })
9527 })
9528 }
9529}
9530
9531pub(super) fn gutter_bounds(
9532 editor_bounds: Bounds<Pixels>,
9533 gutter_dimensions: GutterDimensions,
9534) -> Bounds<Pixels> {
9535 Bounds {
9536 origin: editor_bounds.origin,
9537 size: size(gutter_dimensions.width, editor_bounds.size.height),
9538 }
9539}
9540
9541#[derive(Clone, Copy)]
9542struct ContextMenuLayout {
9543 y_flipped: bool,
9544 bounds: Bounds<Pixels>,
9545}
9546
9547/// Holds information required for layouting the editor scrollbars.
9548struct ScrollbarLayoutInformation {
9549 /// The bounds of the editor area (excluding the content offset).
9550 editor_bounds: Bounds<Pixels>,
9551 /// The available range to scroll within the document.
9552 scroll_range: Size<Pixels>,
9553 /// The space available for one glyph in the editor.
9554 glyph_grid_cell: Size<Pixels>,
9555}
9556
9557impl ScrollbarLayoutInformation {
9558 pub fn new(
9559 editor_bounds: Bounds<Pixels>,
9560 glyph_grid_cell: Size<Pixels>,
9561 document_size: Size<Pixels>,
9562 longest_line_blame_width: Pixels,
9563 settings: &EditorSettings,
9564 ) -> Self {
9565 let vertical_overscroll = match settings.scroll_beyond_last_line {
9566 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
9567 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
9568 ScrollBeyondLastLine::VerticalScrollMargin => {
9569 (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
9570 }
9571 };
9572
9573 let overscroll = size(longest_line_blame_width, vertical_overscroll);
9574
9575 ScrollbarLayoutInformation {
9576 editor_bounds,
9577 scroll_range: document_size + overscroll,
9578 glyph_grid_cell,
9579 }
9580 }
9581}
9582
9583impl IntoElement for EditorElement {
9584 type Element = Self;
9585
9586 fn into_element(self) -> Self::Element {
9587 self
9588 }
9589}
9590
9591pub struct EditorLayout {
9592 position_map: Rc<PositionMap>,
9593 hitbox: Hitbox,
9594 gutter_hitbox: Hitbox,
9595 content_origin: gpui::Point<Pixels>,
9596 scrollbars_layout: Option<EditorScrollbars>,
9597 minimap: Option<MinimapLayout>,
9598 mode: EditorMode,
9599 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
9600 indent_guides: Option<Vec<IndentGuideLayout>>,
9601 visible_display_row_range: Range<DisplayRow>,
9602 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
9603 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
9604 line_elements: SmallVec<[AnyElement; 1]>,
9605 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
9606 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
9607 blamed_display_rows: Option<Vec<AnyElement>>,
9608 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
9609 inline_blame_layout: Option<InlineBlameLayout>,
9610 inline_code_actions: Option<AnyElement>,
9611 blocks: Vec<BlockLayout>,
9612 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
9613 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
9614 redacted_ranges: Vec<Range<DisplayPoint>>,
9615 cursors: Vec<(DisplayPoint, Hsla)>,
9616 visible_cursors: Vec<CursorLayout>,
9617 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
9618 test_indicators: Vec<AnyElement>,
9619 breakpoints: Vec<AnyElement>,
9620 crease_toggles: Vec<Option<AnyElement>>,
9621 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
9622 diff_hunk_controls: Vec<AnyElement>,
9623 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
9624 edit_prediction_popover: Option<AnyElement>,
9625 mouse_context_menu: Option<AnyElement>,
9626 tab_invisible: ShapedLine,
9627 space_invisible: ShapedLine,
9628 sticky_buffer_header: Option<AnyElement>,
9629 document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
9630}
9631
9632impl EditorLayout {
9633 fn line_end_overshoot(&self) -> Pixels {
9634 0.15 * self.position_map.line_height
9635 }
9636}
9637
9638struct LineNumberLayout {
9639 shaped_line: ShapedLine,
9640 hitbox: Option<Hitbox>,
9641}
9642
9643struct ColoredRange<T> {
9644 start: T,
9645 end: T,
9646 color: Hsla,
9647}
9648
9649impl Along for ScrollbarAxes {
9650 type Unit = bool;
9651
9652 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
9653 match axis {
9654 ScrollbarAxis::Horizontal => self.horizontal,
9655 ScrollbarAxis::Vertical => self.vertical,
9656 }
9657 }
9658
9659 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
9660 match axis {
9661 ScrollbarAxis::Horizontal => ScrollbarAxes {
9662 horizontal: f(self.horizontal),
9663 vertical: self.vertical,
9664 },
9665 ScrollbarAxis::Vertical => ScrollbarAxes {
9666 horizontal: self.horizontal,
9667 vertical: f(self.vertical),
9668 },
9669 }
9670 }
9671}
9672
9673#[derive(Clone)]
9674struct EditorScrollbars {
9675 pub vertical: Option<ScrollbarLayout>,
9676 pub horizontal: Option<ScrollbarLayout>,
9677 pub visible: bool,
9678}
9679
9680impl EditorScrollbars {
9681 pub fn from_scrollbar_axes(
9682 show_scrollbar: ScrollbarAxes,
9683 layout_information: &ScrollbarLayoutInformation,
9684 content_offset: gpui::Point<Pixels>,
9685 scroll_position: gpui::Point<f32>,
9686 scrollbar_width: Pixels,
9687 right_margin: Pixels,
9688 editor_width: Pixels,
9689 show_scrollbars: bool,
9690 scrollbar_state: Option<&ActiveScrollbarState>,
9691 window: &mut Window,
9692 ) -> Self {
9693 let ScrollbarLayoutInformation {
9694 editor_bounds,
9695 scroll_range,
9696 glyph_grid_cell,
9697 } = layout_information;
9698
9699 let viewport_size = size(editor_width, editor_bounds.size.height);
9700
9701 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
9702 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
9703 Corner::BottomLeft,
9704 editor_bounds.bottom_left(),
9705 size(
9706 // The horizontal viewport size differs from the space available for the
9707 // horizontal scrollbar, so we have to manually stitch it together here.
9708 editor_bounds.size.width - right_margin,
9709 scrollbar_width,
9710 ),
9711 ),
9712 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
9713 Corner::TopRight,
9714 editor_bounds.top_right(),
9715 size(scrollbar_width, viewport_size.height),
9716 ),
9717 };
9718
9719 let mut create_scrollbar_layout = |axis| {
9720 let viewport_size = viewport_size.along(axis);
9721 let scroll_range = scroll_range.along(axis);
9722
9723 // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
9724 (show_scrollbar.along(axis)
9725 && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
9726 .then(|| {
9727 ScrollbarLayout::new(
9728 window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
9729 viewport_size,
9730 scroll_range,
9731 glyph_grid_cell.along(axis),
9732 content_offset.along(axis),
9733 scroll_position.along(axis),
9734 show_scrollbars,
9735 axis,
9736 )
9737 .with_thumb_state(
9738 scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
9739 )
9740 })
9741 };
9742
9743 Self {
9744 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
9745 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
9746 visible: show_scrollbars,
9747 }
9748 }
9749
9750 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
9751 [
9752 (&self.vertical, ScrollbarAxis::Vertical),
9753 (&self.horizontal, ScrollbarAxis::Horizontal),
9754 ]
9755 .into_iter()
9756 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
9757 }
9758
9759 /// Returns the currently hovered scrollbar axis, if any.
9760 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
9761 self.iter_scrollbars()
9762 .find(|s| s.0.hitbox.is_hovered(window))
9763 }
9764}
9765
9766#[derive(Clone)]
9767struct ScrollbarLayout {
9768 hitbox: Hitbox,
9769 visible_range: Range<f32>,
9770 text_unit_size: Pixels,
9771 thumb_bounds: Option<Bounds<Pixels>>,
9772 thumb_state: ScrollbarThumbState,
9773}
9774
9775impl ScrollbarLayout {
9776 const BORDER_WIDTH: Pixels = px(1.0);
9777 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
9778 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
9779 const MIN_THUMB_SIZE: Pixels = px(25.0);
9780
9781 fn new(
9782 scrollbar_track_hitbox: Hitbox,
9783 viewport_size: Pixels,
9784 scroll_range: Pixels,
9785 glyph_space: Pixels,
9786 content_offset: Pixels,
9787 scroll_position: f32,
9788 show_thumb: bool,
9789 axis: ScrollbarAxis,
9790 ) -> Self {
9791 let track_bounds = scrollbar_track_hitbox.bounds;
9792 // The length of the track available to the scrollbar thumb. We deliberately
9793 // exclude the content size here so that the thumb aligns with the content.
9794 let track_length = track_bounds.size.along(axis) - content_offset;
9795
9796 Self::new_with_hitbox_and_track_length(
9797 scrollbar_track_hitbox,
9798 track_length,
9799 viewport_size,
9800 scroll_range,
9801 glyph_space,
9802 content_offset,
9803 scroll_position,
9804 show_thumb,
9805 axis,
9806 )
9807 }
9808
9809 fn for_minimap(
9810 minimap_track_hitbox: Hitbox,
9811 visible_lines: f32,
9812 total_editor_lines: f32,
9813 minimap_line_height: Pixels,
9814 scroll_position: f32,
9815 minimap_scroll_top: f32,
9816 show_thumb: bool,
9817 ) -> Self {
9818 // The scrollbar thumb size is calculated as
9819 // (visible_content/total_content) Γ scrollbar_track_length.
9820 //
9821 // For the minimap's thumb layout, we leverage this by setting the
9822 // scrollbar track length to the entire document size (using minimap line
9823 // height). This creates a thumb that exactly represents the editor
9824 // viewport scaled to minimap proportions.
9825 //
9826 // We adjust the thumb position relative to `minimap_scroll_top` to
9827 // accommodate for the deliberately oversized track.
9828 //
9829 // This approach ensures that the minimap thumb accurately reflects the
9830 // editor's current scroll position whilst nicely synchronizing the minimap
9831 // thumb and scrollbar thumb.
9832 let scroll_range = total_editor_lines * minimap_line_height;
9833 let viewport_size = visible_lines * minimap_line_height;
9834
9835 let track_top_offset = -minimap_scroll_top * minimap_line_height;
9836
9837 Self::new_with_hitbox_and_track_length(
9838 minimap_track_hitbox,
9839 scroll_range,
9840 viewport_size,
9841 scroll_range,
9842 minimap_line_height,
9843 track_top_offset,
9844 scroll_position,
9845 show_thumb,
9846 ScrollbarAxis::Vertical,
9847 )
9848 }
9849
9850 fn new_with_hitbox_and_track_length(
9851 scrollbar_track_hitbox: Hitbox,
9852 track_length: Pixels,
9853 viewport_size: Pixels,
9854 scroll_range: Pixels,
9855 glyph_space: Pixels,
9856 content_offset: Pixels,
9857 scroll_position: f32,
9858 show_thumb: bool,
9859 axis: ScrollbarAxis,
9860 ) -> Self {
9861 let text_units_per_page = viewport_size / glyph_space;
9862 let visible_range = scroll_position..scroll_position + text_units_per_page;
9863 let total_text_units = scroll_range / glyph_space;
9864
9865 let thumb_percentage = text_units_per_page / total_text_units;
9866 let thumb_size = (track_length * thumb_percentage)
9867 .max(ScrollbarLayout::MIN_THUMB_SIZE)
9868 .min(track_length);
9869
9870 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
9871
9872 let content_larger_than_viewport = text_unit_divisor > 0.;
9873
9874 let text_unit_size = if content_larger_than_viewport {
9875 (track_length - thumb_size) / text_unit_divisor
9876 } else {
9877 glyph_space
9878 };
9879
9880 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
9881 Self::thumb_bounds(
9882 &scrollbar_track_hitbox,
9883 content_offset,
9884 visible_range.start,
9885 text_unit_size,
9886 thumb_size,
9887 axis,
9888 )
9889 });
9890
9891 ScrollbarLayout {
9892 hitbox: scrollbar_track_hitbox,
9893 visible_range,
9894 text_unit_size,
9895 thumb_bounds,
9896 thumb_state: Default::default(),
9897 }
9898 }
9899
9900 fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
9901 if let Some(thumb_state) = thumb_state {
9902 Self {
9903 thumb_state,
9904 ..self
9905 }
9906 } else {
9907 self
9908 }
9909 }
9910
9911 fn thumb_bounds(
9912 scrollbar_track: &Hitbox,
9913 content_offset: Pixels,
9914 visible_range_start: f32,
9915 text_unit_size: Pixels,
9916 thumb_size: Pixels,
9917 axis: ScrollbarAxis,
9918 ) -> Bounds<Pixels> {
9919 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
9920 origin + content_offset + visible_range_start * text_unit_size
9921 });
9922 Bounds::new(
9923 thumb_origin,
9924 scrollbar_track.size.apply_along(axis, |_| thumb_size),
9925 )
9926 }
9927
9928 fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
9929 self.thumb_bounds
9930 .is_some_and(|bounds| bounds.contains(position))
9931 }
9932
9933 fn marker_quads_for_ranges(
9934 &self,
9935 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
9936 column: Option<usize>,
9937 ) -> Vec<PaintQuad> {
9938 struct MinMax {
9939 min: Pixels,
9940 max: Pixels,
9941 }
9942 let (x_range, height_limit) = if let Some(column) = column {
9943 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
9944 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
9945 let end = start + column_width;
9946 (
9947 Range { start, end },
9948 MinMax {
9949 min: Self::MIN_MARKER_HEIGHT,
9950 max: px(f32::MAX),
9951 },
9952 )
9953 } else {
9954 (
9955 Range {
9956 start: Self::BORDER_WIDTH,
9957 end: self.hitbox.size.width,
9958 },
9959 MinMax {
9960 min: Self::LINE_MARKER_HEIGHT,
9961 max: Self::LINE_MARKER_HEIGHT,
9962 },
9963 )
9964 };
9965
9966 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
9967 let mut pixel_ranges = row_ranges
9968 .into_iter()
9969 .map(|range| {
9970 let start_y = row_to_y(range.start);
9971 let end_y = row_to_y(range.end)
9972 + self
9973 .text_unit_size
9974 .max(height_limit.min)
9975 .min(height_limit.max);
9976 ColoredRange {
9977 start: start_y,
9978 end: end_y,
9979 color: range.color,
9980 }
9981 })
9982 .peekable();
9983
9984 let mut quads = Vec::new();
9985 while let Some(mut pixel_range) = pixel_ranges.next() {
9986 while let Some(next_pixel_range) = pixel_ranges.peek() {
9987 if pixel_range.end >= next_pixel_range.start - px(1.0)
9988 && pixel_range.color == next_pixel_range.color
9989 {
9990 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
9991 pixel_ranges.next();
9992 } else {
9993 break;
9994 }
9995 }
9996
9997 let bounds = Bounds::from_corners(
9998 point(x_range.start, pixel_range.start),
9999 point(x_range.end, pixel_range.end),
10000 );
10001 quads.push(quad(
10002 bounds,
10003 Corners::default(),
10004 pixel_range.color,
10005 Edges::default(),
10006 Hsla::transparent_black(),
10007 BorderStyle::default(),
10008 ));
10009 }
10010
10011 quads
10012 }
10013}
10014
10015struct MinimapLayout {
10016 pub minimap: AnyElement,
10017 pub thumb_layout: ScrollbarLayout,
10018 pub minimap_scroll_top: f32,
10019 pub minimap_line_height: Pixels,
10020 pub thumb_border_style: MinimapThumbBorder,
10021 pub max_scroll_top: f32,
10022}
10023
10024impl MinimapLayout {
10025 /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
10026 const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
10027 /// The minimap width as a percentage of the editor width.
10028 const MINIMAP_WIDTH_PCT: f32 = 0.15;
10029 /// Calculates the scroll top offset the minimap editor has to have based on the
10030 /// current scroll progress.
10031 fn calculate_minimap_top_offset(
10032 document_lines: f32,
10033 visible_editor_lines: f32,
10034 visible_minimap_lines: f32,
10035 scroll_position: f32,
10036 ) -> f32 {
10037 let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
10038 if non_visible_document_lines == 0. {
10039 0.
10040 } else {
10041 let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
10042 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
10043 }
10044 }
10045}
10046
10047struct CreaseTrailerLayout {
10048 element: AnyElement,
10049 bounds: Bounds<Pixels>,
10050}
10051
10052pub(crate) struct PositionMap {
10053 pub size: Size<Pixels>,
10054 pub line_height: Pixels,
10055 pub scroll_pixel_position: gpui::Point<Pixels>,
10056 pub scroll_max: gpui::Point<f32>,
10057 pub em_width: Pixels,
10058 pub em_advance: Pixels,
10059 pub visible_row_range: Range<DisplayRow>,
10060 pub line_layouts: Vec<LineWithInvisibles>,
10061 pub snapshot: EditorSnapshot,
10062 pub text_hitbox: Hitbox,
10063 pub gutter_hitbox: Hitbox,
10064 pub inline_blame_bounds: Option<(Bounds<Pixels>, BufferId, BlameEntry)>,
10065 pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
10066 pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
10067}
10068
10069#[derive(Debug, Copy, Clone)]
10070pub struct PointForPosition {
10071 pub previous_valid: DisplayPoint,
10072 pub next_valid: DisplayPoint,
10073 pub exact_unclipped: DisplayPoint,
10074 pub column_overshoot_after_line_end: u32,
10075}
10076
10077impl PointForPosition {
10078 pub fn as_valid(&self) -> Option<DisplayPoint> {
10079 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
10080 Some(self.previous_valid)
10081 } else {
10082 None
10083 }
10084 }
10085
10086 pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
10087 let Some(valid_point) = self.as_valid() else {
10088 return false;
10089 };
10090 let range = selection.range();
10091
10092 let candidate_row = valid_point.row();
10093 let candidate_col = valid_point.column();
10094
10095 let start_row = range.start.row();
10096 let start_col = range.start.column();
10097 let end_row = range.end.row();
10098 let end_col = range.end.column();
10099
10100 if candidate_row < start_row || candidate_row > end_row {
10101 false
10102 } else if start_row == end_row {
10103 candidate_col >= start_col && candidate_col < end_col
10104 } else if candidate_row == start_row {
10105 candidate_col >= start_col
10106 } else if candidate_row == end_row {
10107 candidate_col < end_col
10108 } else {
10109 true
10110 }
10111 }
10112}
10113
10114impl PositionMap {
10115 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
10116 let text_bounds = self.text_hitbox.bounds;
10117 let scroll_position = self.snapshot.scroll_position();
10118 let position = position - text_bounds.origin;
10119 let y = position.y.max(px(0.)).min(self.size.height);
10120 let x = position.x + (scroll_position.x * self.em_advance);
10121 let row = ((y / self.line_height) + scroll_position.y) as u32;
10122
10123 let (column, x_overshoot_after_line_end) = if let Some(line) = self
10124 .line_layouts
10125 .get(row as usize - scroll_position.y as usize)
10126 {
10127 if let Some(ix) = line.index_for_x(x) {
10128 (ix as u32, px(0.))
10129 } else {
10130 (line.len as u32, px(0.).max(x - line.width))
10131 }
10132 } else {
10133 (0, x)
10134 };
10135
10136 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
10137 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
10138 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
10139
10140 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
10141 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
10142 PointForPosition {
10143 previous_valid,
10144 next_valid,
10145 exact_unclipped,
10146 column_overshoot_after_line_end,
10147 }
10148 }
10149}
10150
10151struct BlockLayout {
10152 id: BlockId,
10153 x_offset: Pixels,
10154 row: Option<DisplayRow>,
10155 element: AnyElement,
10156 available_space: Size<AvailableSpace>,
10157 style: BlockStyle,
10158 overlaps_gutter: bool,
10159 is_buffer_header: bool,
10160}
10161
10162pub fn layout_line(
10163 row: DisplayRow,
10164 snapshot: &EditorSnapshot,
10165 style: &EditorStyle,
10166 text_width: Pixels,
10167 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
10168 window: &mut Window,
10169 cx: &mut App,
10170) -> LineWithInvisibles {
10171 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
10172 LineWithInvisibles::from_chunks(
10173 chunks,
10174 style,
10175 MAX_LINE_LEN,
10176 1,
10177 &snapshot.mode,
10178 text_width,
10179 is_row_soft_wrapped,
10180 &[],
10181 window,
10182 cx,
10183 )
10184 .pop()
10185 .unwrap()
10186}
10187
10188#[derive(Debug)]
10189pub struct IndentGuideLayout {
10190 origin: gpui::Point<Pixels>,
10191 length: Pixels,
10192 single_indent_width: Pixels,
10193 depth: u32,
10194 active: bool,
10195 settings: IndentGuideSettings,
10196}
10197
10198pub struct CursorLayout {
10199 origin: gpui::Point<Pixels>,
10200 block_width: Pixels,
10201 line_height: Pixels,
10202 color: Hsla,
10203 shape: CursorShape,
10204 block_text: Option<ShapedLine>,
10205 cursor_name: Option<AnyElement>,
10206}
10207
10208#[derive(Debug)]
10209pub struct CursorName {
10210 string: SharedString,
10211 color: Hsla,
10212 is_top_row: bool,
10213}
10214
10215impl CursorLayout {
10216 pub fn new(
10217 origin: gpui::Point<Pixels>,
10218 block_width: Pixels,
10219 line_height: Pixels,
10220 color: Hsla,
10221 shape: CursorShape,
10222 block_text: Option<ShapedLine>,
10223 ) -> CursorLayout {
10224 CursorLayout {
10225 origin,
10226 block_width,
10227 line_height,
10228 color,
10229 shape,
10230 block_text,
10231 cursor_name: None,
10232 }
10233 }
10234
10235 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
10236 Bounds {
10237 origin: self.origin + origin,
10238 size: size(self.block_width, self.line_height),
10239 }
10240 }
10241
10242 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
10243 match self.shape {
10244 CursorShape::Bar => Bounds {
10245 origin: self.origin + origin,
10246 size: size(px(2.0), self.line_height),
10247 },
10248 CursorShape::Block | CursorShape::Hollow => Bounds {
10249 origin: self.origin + origin,
10250 size: size(self.block_width, self.line_height),
10251 },
10252 CursorShape::Underline => Bounds {
10253 origin: self.origin
10254 + origin
10255 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
10256 size: size(self.block_width, px(2.0)),
10257 },
10258 }
10259 }
10260
10261 pub fn layout(
10262 &mut self,
10263 origin: gpui::Point<Pixels>,
10264 cursor_name: Option<CursorName>,
10265 window: &mut Window,
10266 cx: &mut App,
10267 ) {
10268 if let Some(cursor_name) = cursor_name {
10269 let bounds = self.bounds(origin);
10270 let text_size = self.line_height / 1.5;
10271
10272 let name_origin = if cursor_name.is_top_row {
10273 point(bounds.right() - px(1.), bounds.top())
10274 } else {
10275 match self.shape {
10276 CursorShape::Bar => point(
10277 bounds.right() - px(2.),
10278 bounds.top() - text_size / 2. - px(1.),
10279 ),
10280 _ => point(
10281 bounds.right() - px(1.),
10282 bounds.top() - text_size / 2. - px(1.),
10283 ),
10284 }
10285 };
10286 let mut name_element = div()
10287 .bg(self.color)
10288 .text_size(text_size)
10289 .px_0p5()
10290 .line_height(text_size + px(2.))
10291 .text_color(cursor_name.color)
10292 .child(cursor_name.string)
10293 .into_any_element();
10294
10295 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
10296
10297 self.cursor_name = Some(name_element);
10298 }
10299 }
10300
10301 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
10302 let bounds = self.bounds(origin);
10303
10304 //Draw background or border quad
10305 let cursor = if matches!(self.shape, CursorShape::Hollow) {
10306 outline(bounds, self.color, BorderStyle::Solid)
10307 } else {
10308 fill(bounds, self.color)
10309 };
10310
10311 if let Some(name) = &mut self.cursor_name {
10312 name.paint(window, cx);
10313 }
10314
10315 window.paint_quad(cursor);
10316
10317 if let Some(block_text) = &self.block_text {
10318 block_text
10319 .paint(self.origin + origin, self.line_height, window, cx)
10320 .log_err();
10321 }
10322 }
10323
10324 pub fn shape(&self) -> CursorShape {
10325 self.shape
10326 }
10327}
10328
10329#[derive(Debug)]
10330pub struct HighlightedRange {
10331 pub start_y: Pixels,
10332 pub line_height: Pixels,
10333 pub lines: Vec<HighlightedRangeLine>,
10334 pub color: Hsla,
10335 pub corner_radius: Pixels,
10336}
10337
10338#[derive(Debug)]
10339pub struct HighlightedRangeLine {
10340 pub start_x: Pixels,
10341 pub end_x: Pixels,
10342}
10343
10344impl HighlightedRange {
10345 pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
10346 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
10347 self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
10348 self.paint_lines(
10349 self.start_y + self.line_height,
10350 &self.lines[1..],
10351 fill,
10352 bounds,
10353 window,
10354 );
10355 } else {
10356 self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
10357 }
10358 }
10359
10360 fn paint_lines(
10361 &self,
10362 start_y: Pixels,
10363 lines: &[HighlightedRangeLine],
10364 fill: bool,
10365 _bounds: Bounds<Pixels>,
10366 window: &mut Window,
10367 ) {
10368 if lines.is_empty() {
10369 return;
10370 }
10371
10372 let first_line = lines.first().unwrap();
10373 let last_line = lines.last().unwrap();
10374
10375 let first_top_left = point(first_line.start_x, start_y);
10376 let first_top_right = point(first_line.end_x, start_y);
10377
10378 let curve_height = point(Pixels::ZERO, self.corner_radius);
10379 let curve_width = |start_x: Pixels, end_x: Pixels| {
10380 let max = (end_x - start_x) / 2.;
10381 let width = if max < self.corner_radius {
10382 max
10383 } else {
10384 self.corner_radius
10385 };
10386
10387 point(width, Pixels::ZERO)
10388 };
10389
10390 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
10391 let mut builder = if fill {
10392 gpui::PathBuilder::fill()
10393 } else {
10394 gpui::PathBuilder::stroke(px(1.))
10395 };
10396 builder.move_to(first_top_right - top_curve_width);
10397 builder.curve_to(first_top_right + curve_height, first_top_right);
10398
10399 let mut iter = lines.iter().enumerate().peekable();
10400 while let Some((ix, line)) = iter.next() {
10401 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
10402
10403 if let Some((_, next_line)) = iter.peek() {
10404 let next_top_right = point(next_line.end_x, bottom_right.y);
10405
10406 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
10407 Ordering::Equal => {
10408 builder.line_to(bottom_right);
10409 }
10410 Ordering::Less => {
10411 let curve_width = curve_width(next_top_right.x, bottom_right.x);
10412 builder.line_to(bottom_right - curve_height);
10413 if self.corner_radius > Pixels::ZERO {
10414 builder.curve_to(bottom_right - curve_width, bottom_right);
10415 }
10416 builder.line_to(next_top_right + curve_width);
10417 if self.corner_radius > Pixels::ZERO {
10418 builder.curve_to(next_top_right + curve_height, next_top_right);
10419 }
10420 }
10421 Ordering::Greater => {
10422 let curve_width = curve_width(bottom_right.x, next_top_right.x);
10423 builder.line_to(bottom_right - curve_height);
10424 if self.corner_radius > Pixels::ZERO {
10425 builder.curve_to(bottom_right + curve_width, bottom_right);
10426 }
10427 builder.line_to(next_top_right - curve_width);
10428 if self.corner_radius > Pixels::ZERO {
10429 builder.curve_to(next_top_right + curve_height, next_top_right);
10430 }
10431 }
10432 }
10433 } else {
10434 let curve_width = curve_width(line.start_x, line.end_x);
10435 builder.line_to(bottom_right - curve_height);
10436 if self.corner_radius > Pixels::ZERO {
10437 builder.curve_to(bottom_right - curve_width, bottom_right);
10438 }
10439
10440 let bottom_left = point(line.start_x, bottom_right.y);
10441 builder.line_to(bottom_left + curve_width);
10442 if self.corner_radius > Pixels::ZERO {
10443 builder.curve_to(bottom_left - curve_height, bottom_left);
10444 }
10445 }
10446 }
10447
10448 if first_line.start_x > last_line.start_x {
10449 let curve_width = curve_width(last_line.start_x, first_line.start_x);
10450 let second_top_left = point(last_line.start_x, start_y + self.line_height);
10451 builder.line_to(second_top_left + curve_height);
10452 if self.corner_radius > Pixels::ZERO {
10453 builder.curve_to(second_top_left + curve_width, second_top_left);
10454 }
10455 let first_bottom_left = point(first_line.start_x, second_top_left.y);
10456 builder.line_to(first_bottom_left - curve_width);
10457 if self.corner_radius > Pixels::ZERO {
10458 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
10459 }
10460 }
10461
10462 builder.line_to(first_top_left + curve_height);
10463 if self.corner_radius > Pixels::ZERO {
10464 builder.curve_to(first_top_left + top_curve_width, first_top_left);
10465 }
10466 builder.line_to(first_top_right - top_curve_width);
10467
10468 if let Ok(path) = builder.build() {
10469 window.paint_path(path, self.color);
10470 }
10471 }
10472}
10473
10474enum CursorPopoverType {
10475 CodeContextMenu,
10476 EditPrediction,
10477}
10478
10479pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10480 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
10481}
10482
10483fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10484 (delta.pow(1.2) / 300.0).into()
10485}
10486
10487pub fn register_action<T: Action>(
10488 editor: &Entity<Editor>,
10489 window: &mut Window,
10490 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
10491) {
10492 let editor = editor.clone();
10493 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
10494 let action = action.downcast_ref().unwrap();
10495 if phase == DispatchPhase::Bubble {
10496 editor.update(cx, |editor, cx| {
10497 listener(editor, action, window, cx);
10498 })
10499 }
10500 })
10501}
10502
10503fn compute_auto_height_layout(
10504 editor: &mut Editor,
10505 min_lines: usize,
10506 max_lines: Option<usize>,
10507 max_line_number_width: Pixels,
10508 known_dimensions: Size<Option<Pixels>>,
10509 available_width: AvailableSpace,
10510 window: &mut Window,
10511 cx: &mut Context<Editor>,
10512) -> Option<Size<Pixels>> {
10513 let width = known_dimensions.width.or({
10514 if let AvailableSpace::Definite(available_width) = available_width {
10515 Some(available_width)
10516 } else {
10517 None
10518 }
10519 })?;
10520 if let Some(height) = known_dimensions.height {
10521 return Some(size(width, height));
10522 }
10523
10524 let style = editor.style.as_ref().unwrap();
10525 let font_id = window.text_system().resolve_font(&style.text.font());
10526 let font_size = style.text.font_size.to_pixels(window.rem_size());
10527 let line_height = style.text.line_height_in_pixels(window.rem_size());
10528 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
10529
10530 let mut snapshot = editor.snapshot(window, cx);
10531 let gutter_dimensions = snapshot
10532 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
10533 .or_else(|| {
10534 editor
10535 .offset_content
10536 .then(|| GutterDimensions::default_with_margin(font_id, font_size, cx))
10537 })
10538 .unwrap_or_default();
10539
10540 editor.gutter_dimensions = gutter_dimensions;
10541 let text_width = width - gutter_dimensions.width;
10542 let overscroll = size(em_width, px(0.));
10543
10544 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
10545 if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None)
10546 && editor.set_wrap_width(Some(editor_width), cx)
10547 {
10548 snapshot = editor.snapshot(window, cx);
10549 }
10550
10551 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
10552
10553 let min_height = line_height * min_lines as f32;
10554 let content_height = scroll_height.max(min_height);
10555
10556 let final_height = if let Some(max_lines) = max_lines {
10557 let max_height = line_height * max_lines as f32;
10558 content_height.min(max_height)
10559 } else {
10560 content_height
10561 };
10562
10563 Some(size(width, final_height))
10564}
10565
10566#[cfg(test)]
10567mod tests {
10568 use super::*;
10569 use crate::{
10570 Editor, MultiBuffer, SelectionEffects,
10571 display_map::{BlockPlacement, BlockProperties},
10572 editor_tests::{init_test, update_test_language_settings},
10573 };
10574 use gpui::{TestAppContext, VisualTestContext};
10575 use language::language_settings;
10576 use log::info;
10577 use std::num::NonZeroU32;
10578 use util::test::sample_text;
10579
10580 #[gpui::test]
10581 async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
10582 init_test(cx, |_| {});
10583
10584 let window = cx.add_window(|window, cx| {
10585 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
10586 let mut editor = Editor::new(
10587 EditorMode::AutoHeight {
10588 min_lines: 1,
10589 max_lines: None,
10590 },
10591 buffer,
10592 None,
10593 window,
10594 cx,
10595 );
10596 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10597 editor
10598 });
10599 let cx = &mut VisualTestContext::from_window(*window, cx);
10600 let editor = window.root(cx).unwrap();
10601 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10602
10603 for x in 1..=100 {
10604 let (_, state) = cx.draw(
10605 Default::default(),
10606 size(px(200. + 0.13 * x as f32), px(500.)),
10607 |_, _| EditorElement::new(&editor, style.clone()),
10608 );
10609
10610 assert!(
10611 state.position_map.scroll_max.x == 0.,
10612 "Soft wrapped editor should have no horizontal scrolling!"
10613 );
10614 }
10615 }
10616
10617 #[gpui::test]
10618 async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
10619 init_test(cx, |_| {});
10620
10621 let window = cx.add_window(|window, cx| {
10622 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
10623 let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
10624 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10625 editor
10626 });
10627 let cx = &mut VisualTestContext::from_window(*window, cx);
10628 let editor = window.root(cx).unwrap();
10629 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10630
10631 for x in 1..=100 {
10632 let (_, state) = cx.draw(
10633 Default::default(),
10634 size(px(200. + 0.13 * x as f32), px(500.)),
10635 |_, _| EditorElement::new(&editor, style.clone()),
10636 );
10637
10638 assert!(
10639 state.position_map.scroll_max.x == 0.,
10640 "Soft wrapped editor should have no horizontal scrolling!"
10641 );
10642 }
10643 }
10644
10645 #[gpui::test]
10646 fn test_shape_line_numbers(cx: &mut TestAppContext) {
10647 init_test(cx, |_| {});
10648 let window = cx.add_window(|window, cx| {
10649 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
10650 Editor::new(EditorMode::full(), buffer, None, window, cx)
10651 });
10652
10653 let editor = window.root(cx).unwrap();
10654 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
10655 let line_height = window
10656 .update(cx, |_, window, _| {
10657 style.text.line_height_in_pixels(window.rem_size())
10658 })
10659 .unwrap();
10660 let element = EditorElement::new(&editor, style);
10661 let snapshot = window
10662 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
10663 .unwrap();
10664
10665 let layouts = cx
10666 .update_window(*window, |_, window, cx| {
10667 element.layout_line_numbers(
10668 None,
10669 GutterDimensions {
10670 left_padding: Pixels::ZERO,
10671 right_padding: Pixels::ZERO,
10672 width: px(30.0),
10673 margin: Pixels::ZERO,
10674 git_blame_entries_width: None,
10675 },
10676 line_height,
10677 gpui::Point::default(),
10678 DisplayRow(0)..DisplayRow(6),
10679 &(0..6)
10680 .map(|row| RowInfo {
10681 buffer_row: Some(row),
10682 ..Default::default()
10683 })
10684 .collect::<Vec<_>>(),
10685 &BTreeMap::default(),
10686 Some(DisplayPoint::new(DisplayRow(0), 0)),
10687 &snapshot,
10688 window,
10689 cx,
10690 )
10691 })
10692 .unwrap();
10693 assert_eq!(layouts.len(), 6);
10694
10695 let relative_rows = window
10696 .update(cx, |editor, window, cx| {
10697 let snapshot = editor.snapshot(window, cx);
10698 element.calculate_relative_line_numbers(
10699 &snapshot,
10700 &(DisplayRow(0)..DisplayRow(6)),
10701 Some(DisplayRow(3)),
10702 )
10703 })
10704 .unwrap();
10705 assert_eq!(relative_rows[&DisplayRow(0)], 3);
10706 assert_eq!(relative_rows[&DisplayRow(1)], 2);
10707 assert_eq!(relative_rows[&DisplayRow(2)], 1);
10708 // current line has no relative number
10709 assert_eq!(relative_rows[&DisplayRow(4)], 1);
10710 assert_eq!(relative_rows[&DisplayRow(5)], 2);
10711
10712 // works if cursor is before screen
10713 let relative_rows = window
10714 .update(cx, |editor, window, cx| {
10715 let snapshot = editor.snapshot(window, cx);
10716 element.calculate_relative_line_numbers(
10717 &snapshot,
10718 &(DisplayRow(3)..DisplayRow(6)),
10719 Some(DisplayRow(1)),
10720 )
10721 })
10722 .unwrap();
10723 assert_eq!(relative_rows.len(), 3);
10724 assert_eq!(relative_rows[&DisplayRow(3)], 2);
10725 assert_eq!(relative_rows[&DisplayRow(4)], 3);
10726 assert_eq!(relative_rows[&DisplayRow(5)], 4);
10727
10728 // works if cursor is after screen
10729 let relative_rows = window
10730 .update(cx, |editor, window, cx| {
10731 let snapshot = editor.snapshot(window, cx);
10732 element.calculate_relative_line_numbers(
10733 &snapshot,
10734 &(DisplayRow(0)..DisplayRow(3)),
10735 Some(DisplayRow(6)),
10736 )
10737 })
10738 .unwrap();
10739 assert_eq!(relative_rows.len(), 3);
10740 assert_eq!(relative_rows[&DisplayRow(0)], 5);
10741 assert_eq!(relative_rows[&DisplayRow(1)], 4);
10742 assert_eq!(relative_rows[&DisplayRow(2)], 3);
10743 }
10744
10745 #[gpui::test]
10746 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
10747 init_test(cx, |_| {});
10748
10749 let window = cx.add_window(|window, cx| {
10750 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
10751 Editor::new(EditorMode::full(), buffer, None, window, cx)
10752 });
10753 let cx = &mut VisualTestContext::from_window(*window, cx);
10754 let editor = window.root(cx).unwrap();
10755 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10756
10757 window
10758 .update(cx, |editor, window, cx| {
10759 editor.cursor_shape = CursorShape::Block;
10760 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
10761 s.select_ranges([
10762 Point::new(0, 0)..Point::new(1, 0),
10763 Point::new(3, 2)..Point::new(3, 3),
10764 Point::new(5, 6)..Point::new(6, 0),
10765 ]);
10766 });
10767 })
10768 .unwrap();
10769
10770 let (_, state) = cx.draw(
10771 point(px(500.), px(500.)),
10772 size(px(500.), px(500.)),
10773 |_, _| EditorElement::new(&editor, style),
10774 );
10775
10776 assert_eq!(state.selections.len(), 1);
10777 let local_selections = &state.selections[0].1;
10778 assert_eq!(local_selections.len(), 3);
10779 // moves cursor back one line
10780 assert_eq!(
10781 local_selections[0].head,
10782 DisplayPoint::new(DisplayRow(0), 6)
10783 );
10784 assert_eq!(
10785 local_selections[0].range,
10786 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
10787 );
10788
10789 // moves cursor back one column
10790 assert_eq!(
10791 local_selections[1].range,
10792 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
10793 );
10794 assert_eq!(
10795 local_selections[1].head,
10796 DisplayPoint::new(DisplayRow(3), 2)
10797 );
10798
10799 // leaves cursor on the max point
10800 assert_eq!(
10801 local_selections[2].range,
10802 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
10803 );
10804 assert_eq!(
10805 local_selections[2].head,
10806 DisplayPoint::new(DisplayRow(6), 0)
10807 );
10808
10809 // active lines does not include 1 (even though the range of the selection does)
10810 assert_eq!(
10811 state.active_rows.keys().cloned().collect::<Vec<_>>(),
10812 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
10813 );
10814 }
10815
10816 #[gpui::test]
10817 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
10818 init_test(cx, |_| {});
10819
10820 let window = cx.add_window(|window, cx| {
10821 let buffer = MultiBuffer::build_simple("", cx);
10822 Editor::new(EditorMode::full(), buffer, None, window, cx)
10823 });
10824 let cx = &mut VisualTestContext::from_window(*window, cx);
10825 let editor = window.root(cx).unwrap();
10826 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10827 window
10828 .update(cx, |editor, window, cx| {
10829 editor.set_placeholder_text("hello", window, cx);
10830 editor.insert_blocks(
10831 [BlockProperties {
10832 style: BlockStyle::Fixed,
10833 placement: BlockPlacement::Above(Anchor::min()),
10834 height: Some(3),
10835 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
10836 priority: 0,
10837 }],
10838 None,
10839 cx,
10840 );
10841
10842 // Blur the editor so that it displays placeholder text.
10843 window.blur();
10844 })
10845 .unwrap();
10846
10847 let (_, state) = cx.draw(
10848 point(px(500.), px(500.)),
10849 size(px(500.), px(500.)),
10850 |_, _| EditorElement::new(&editor, style),
10851 );
10852 assert_eq!(state.position_map.line_layouts.len(), 4);
10853 assert_eq!(state.line_numbers.len(), 1);
10854 assert_eq!(
10855 state
10856 .line_numbers
10857 .get(&MultiBufferRow(0))
10858 .map(|line_number| line_number.shaped_line.text.as_ref()),
10859 Some("1")
10860 );
10861 }
10862
10863 #[gpui::test]
10864 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
10865 const TAB_SIZE: u32 = 4;
10866
10867 let input_text = "\t \t|\t| a b";
10868 let expected_invisibles = vec![
10869 Invisible::Tab {
10870 line_start_offset: 0,
10871 line_end_offset: TAB_SIZE as usize,
10872 },
10873 Invisible::Whitespace {
10874 line_offset: TAB_SIZE as usize,
10875 },
10876 Invisible::Tab {
10877 line_start_offset: TAB_SIZE as usize + 1,
10878 line_end_offset: TAB_SIZE as usize * 2,
10879 },
10880 Invisible::Tab {
10881 line_start_offset: TAB_SIZE as usize * 2 + 1,
10882 line_end_offset: TAB_SIZE as usize * 3,
10883 },
10884 Invisible::Whitespace {
10885 line_offset: TAB_SIZE as usize * 3 + 1,
10886 },
10887 Invisible::Whitespace {
10888 line_offset: TAB_SIZE as usize * 3 + 3,
10889 },
10890 ];
10891 assert_eq!(
10892 expected_invisibles.len(),
10893 input_text
10894 .chars()
10895 .filter(|initial_char| initial_char.is_whitespace())
10896 .count(),
10897 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10898 );
10899
10900 for show_line_numbers in [true, false] {
10901 init_test(cx, |s| {
10902 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10903 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
10904 });
10905
10906 let actual_invisibles = collect_invisibles_from_new_editor(
10907 cx,
10908 EditorMode::full(),
10909 input_text,
10910 px(500.0),
10911 show_line_numbers,
10912 );
10913
10914 assert_eq!(expected_invisibles, actual_invisibles);
10915 }
10916 }
10917
10918 #[gpui::test]
10919 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
10920 init_test(cx, |s| {
10921 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10922 s.defaults.tab_size = NonZeroU32::new(4);
10923 });
10924
10925 for editor_mode_without_invisibles in [
10926 EditorMode::SingleLine,
10927 EditorMode::AutoHeight {
10928 min_lines: 1,
10929 max_lines: Some(100),
10930 },
10931 ] {
10932 for show_line_numbers in [true, false] {
10933 let invisibles = collect_invisibles_from_new_editor(
10934 cx,
10935 editor_mode_without_invisibles.clone(),
10936 "\t\t\t| | a b",
10937 px(500.0),
10938 show_line_numbers,
10939 );
10940 assert!(
10941 invisibles.is_empty(),
10942 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
10943 );
10944 }
10945 }
10946 }
10947
10948 #[gpui::test]
10949 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
10950 let tab_size = 4;
10951 let input_text = "a\tbcd ".repeat(9);
10952 let repeated_invisibles = [
10953 Invisible::Tab {
10954 line_start_offset: 1,
10955 line_end_offset: tab_size as usize,
10956 },
10957 Invisible::Whitespace {
10958 line_offset: tab_size as usize + 3,
10959 },
10960 Invisible::Whitespace {
10961 line_offset: tab_size as usize + 4,
10962 },
10963 Invisible::Whitespace {
10964 line_offset: tab_size as usize + 5,
10965 },
10966 Invisible::Whitespace {
10967 line_offset: tab_size as usize + 6,
10968 },
10969 Invisible::Whitespace {
10970 line_offset: tab_size as usize + 7,
10971 },
10972 ];
10973 let expected_invisibles = std::iter::once(repeated_invisibles)
10974 .cycle()
10975 .take(9)
10976 .flatten()
10977 .collect::<Vec<_>>();
10978 assert_eq!(
10979 expected_invisibles.len(),
10980 input_text
10981 .chars()
10982 .filter(|initial_char| initial_char.is_whitespace())
10983 .count(),
10984 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10985 );
10986 info!("Expected invisibles: {expected_invisibles:?}");
10987
10988 init_test(cx, |_| {});
10989
10990 // Put the same string with repeating whitespace pattern into editors of various size,
10991 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
10992 let resize_step = 10.0;
10993 let mut editor_width = 200.0;
10994 while editor_width <= 1000.0 {
10995 for show_line_numbers in [true, false] {
10996 update_test_language_settings(cx, |s| {
10997 s.defaults.tab_size = NonZeroU32::new(tab_size);
10998 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10999 s.defaults.preferred_line_length = Some(editor_width as u32);
11000 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
11001 });
11002
11003 let actual_invisibles = collect_invisibles_from_new_editor(
11004 cx,
11005 EditorMode::full(),
11006 &input_text,
11007 px(editor_width),
11008 show_line_numbers,
11009 );
11010
11011 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
11012 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
11013 let mut i = 0;
11014 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
11015 i = actual_index;
11016 match expected_invisibles.get(i) {
11017 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
11018 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
11019 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
11020 _ => {
11021 panic!(
11022 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
11023 )
11024 }
11025 },
11026 None => {
11027 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
11028 }
11029 }
11030 }
11031 let missing_expected_invisibles = &expected_invisibles[i + 1..];
11032 assert!(
11033 missing_expected_invisibles.is_empty(),
11034 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
11035 );
11036
11037 editor_width += resize_step;
11038 }
11039 }
11040 }
11041
11042 fn collect_invisibles_from_new_editor(
11043 cx: &mut TestAppContext,
11044 editor_mode: EditorMode,
11045 input_text: &str,
11046 editor_width: Pixels,
11047 show_line_numbers: bool,
11048 ) -> Vec<Invisible> {
11049 info!(
11050 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
11051 editor_width.0
11052 );
11053 let window = cx.add_window(|window, cx| {
11054 let buffer = MultiBuffer::build_simple(input_text, cx);
11055 Editor::new(editor_mode, buffer, None, window, cx)
11056 });
11057 let cx = &mut VisualTestContext::from_window(*window, cx);
11058 let editor = window.root(cx).unwrap();
11059
11060 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
11061 window
11062 .update(cx, |editor, _, cx| {
11063 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
11064 editor.set_wrap_width(Some(editor_width), cx);
11065 editor.set_show_line_numbers(show_line_numbers, cx);
11066 })
11067 .unwrap();
11068 let (_, state) = cx.draw(
11069 point(px(500.), px(500.)),
11070 size(px(500.), px(500.)),
11071 |_, _| EditorElement::new(&editor, style),
11072 );
11073 state
11074 .position_map
11075 .line_layouts
11076 .iter()
11077 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
11078 .cloned()
11079 .collect()
11080 }
11081
11082 #[gpui::test]
11083 fn test_merge_overlapping_ranges() {
11084 let base_bg = Hsla::white();
11085 let color1 = Hsla {
11086 h: 0.0,
11087 s: 0.5,
11088 l: 0.5,
11089 a: 0.5,
11090 };
11091 let color2 = Hsla {
11092 h: 120.0,
11093 s: 0.5,
11094 l: 0.5,
11095 a: 0.5,
11096 };
11097
11098 let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
11099 let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
11100 v.iter()
11101 .map(|(r, _)| (r.start.column(), r.end.column()))
11102 .collect()
11103 };
11104
11105 // Test overlapping ranges blend colors
11106 let overlapping = vec![
11107 (display_point(5)..display_point(15), color1),
11108 (display_point(10)..display_point(20), color2),
11109 ];
11110 let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
11111 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
11112
11113 // Test middle segment should have blended color
11114 let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
11115 assert_eq!(result[1].1, blended);
11116
11117 // Test adjacent same-color ranges merge
11118 let adjacent_same = vec![
11119 (display_point(5)..display_point(10), color1),
11120 (display_point(10)..display_point(15), color1),
11121 ];
11122 let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
11123 assert_eq!(cols(&result), vec![(5, 15)]);
11124
11125 // Test contained range splits
11126 let contained = vec![
11127 (display_point(5)..display_point(20), color1),
11128 (display_point(10)..display_point(15), color2),
11129 ];
11130 let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
11131 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
11132
11133 // Test multiple overlaps split at every boundary
11134 let color3 = Hsla {
11135 h: 240.0,
11136 s: 0.5,
11137 l: 0.5,
11138 a: 0.5,
11139 };
11140 let complex = vec![
11141 (display_point(5)..display_point(12), color1),
11142 (display_point(8)..display_point(16), color2),
11143 (display_point(10)..display_point(14), color3),
11144 ];
11145 let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
11146 assert_eq!(
11147 cols(&result),
11148 vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
11149 );
11150 }
11151
11152 #[gpui::test]
11153 fn test_bg_segments_per_row() {
11154 let base_bg = Hsla::white();
11155
11156 // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
11157 {
11158 let selection_color = Hsla {
11159 h: 200.0,
11160 s: 0.5,
11161 l: 0.5,
11162 a: 0.5,
11163 };
11164 let player_color = PlayerColor {
11165 cursor: selection_color,
11166 background: selection_color,
11167 selection: selection_color,
11168 };
11169
11170 let spanning_selection = SelectionLayout {
11171 head: DisplayPoint::new(DisplayRow(3), 7),
11172 cursor_shape: CursorShape::Bar,
11173 is_newest: true,
11174 is_local: true,
11175 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
11176 active_rows: DisplayRow(1)..DisplayRow(4),
11177 user_name: None,
11178 };
11179
11180 let selections = vec![(player_color, vec![spanning_selection])];
11181 let result = EditorElement::bg_segments_per_row(
11182 DisplayRow(0)..DisplayRow(5),
11183 &selections,
11184 &[],
11185 base_bg,
11186 );
11187
11188 assert_eq!(result.len(), 5);
11189 assert!(result[0].is_empty());
11190 assert_eq!(result[1].len(), 1);
11191 assert_eq!(result[2].len(), 1);
11192 assert_eq!(result[3].len(), 1);
11193 assert!(result[4].is_empty());
11194
11195 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
11196 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
11197 assert_eq!(result[1][0].0.end.column(), u32::MAX);
11198 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
11199 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
11200 assert_eq!(result[2][0].0.end.column(), u32::MAX);
11201 assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
11202 assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
11203 }
11204
11205 // Case B: selection ends exactly at the start of row 3, excluding row 3
11206 {
11207 let selection_color = Hsla {
11208 h: 120.0,
11209 s: 0.5,
11210 l: 0.5,
11211 a: 0.5,
11212 };
11213 let player_color = PlayerColor {
11214 cursor: selection_color,
11215 background: selection_color,
11216 selection: selection_color,
11217 };
11218
11219 let selection = SelectionLayout {
11220 head: DisplayPoint::new(DisplayRow(2), 0),
11221 cursor_shape: CursorShape::Bar,
11222 is_newest: true,
11223 is_local: true,
11224 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
11225 active_rows: DisplayRow(1)..DisplayRow(3),
11226 user_name: None,
11227 };
11228
11229 let selections = vec![(player_color, vec![selection])];
11230 let result = EditorElement::bg_segments_per_row(
11231 DisplayRow(0)..DisplayRow(4),
11232 &selections,
11233 &[],
11234 base_bg,
11235 );
11236
11237 assert_eq!(result.len(), 4);
11238 assert!(result[0].is_empty());
11239 assert_eq!(result[1].len(), 1);
11240 assert_eq!(result[2].len(), 1);
11241 assert!(result[3].is_empty());
11242
11243 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
11244 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
11245 assert_eq!(result[1][0].0.end.column(), u32::MAX);
11246 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
11247 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
11248 assert_eq!(result[2][0].0.end.column(), u32::MAX);
11249 }
11250 }
11251
11252 #[cfg(test)]
11253 fn generate_test_run(len: usize, color: Hsla) -> TextRun {
11254 TextRun {
11255 len,
11256 font: gpui::font(".SystemUIFont"),
11257 color,
11258 background_color: None,
11259 underline: None,
11260 strikethrough: None,
11261 }
11262 }
11263
11264 #[gpui::test]
11265 fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
11266 init_test(cx, |_| {});
11267
11268 let dx = |start: u32, end: u32| {
11269 DisplayPoint::new(DisplayRow(0), start)..DisplayPoint::new(DisplayRow(0), end)
11270 };
11271
11272 let text_color = Hsla {
11273 h: 210.0,
11274 s: 0.1,
11275 l: 0.4,
11276 a: 1.0,
11277 };
11278 let bg_1 = Hsla {
11279 h: 30.0,
11280 s: 0.6,
11281 l: 0.8,
11282 a: 1.0,
11283 };
11284 let bg_2 = Hsla {
11285 h: 200.0,
11286 s: 0.6,
11287 l: 0.2,
11288 a: 1.0,
11289 };
11290 let min_contrast = 45.0;
11291 let adjusted_bg1 = ensure_minimum_contrast(text_color, bg_1, min_contrast);
11292 let adjusted_bg2 = ensure_minimum_contrast(text_color, bg_2, min_contrast);
11293
11294 // Case A: single run; disjoint segments inside the run
11295 {
11296 let runs = vec![generate_test_run(20, text_color)];
11297 let segs = vec![(dx(5, 10), bg_1), (dx(12, 16), bg_2)];
11298 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
11299 // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
11300 assert_eq!(
11301 out.iter().map(|r| r.len).collect::<Vec<_>>(),
11302 vec![5, 5, 2, 4, 4]
11303 );
11304 assert_eq!(out[0].color, text_color);
11305 assert_eq!(out[1].color, adjusted_bg1);
11306 assert_eq!(out[2].color, text_color);
11307 assert_eq!(out[3].color, adjusted_bg2);
11308 assert_eq!(out[4].color, text_color);
11309 }
11310
11311 // Case B: multiple runs; segment extends to end of line (u32::MAX)
11312 {
11313 let runs = vec![
11314 generate_test_run(8, text_color),
11315 generate_test_run(7, text_color),
11316 ];
11317 let segs = vec![(dx(6, u32::MAX), bg_1)];
11318 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
11319 // Expected slices across runs: [0,6) [6,8) | [0,7)
11320 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
11321 assert_eq!(out[0].color, text_color);
11322 assert_eq!(out[1].color, adjusted_bg1);
11323 assert_eq!(out[2].color, adjusted_bg1);
11324 }
11325
11326 // Case C: multi-byte characters
11327 {
11328 // for text: "Hello π δΈη!"
11329 let runs = vec![
11330 generate_test_run(5, text_color), // "Hello"
11331 generate_test_run(6, text_color), // " π "
11332 generate_test_run(6, text_color), // "δΈη"
11333 generate_test_run(1, text_color), // "!"
11334 ];
11335 // selecting "π δΈ"
11336 let segs = vec![(dx(6, 14), bg_1)];
11337 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
11338 // "Hello" | " " | "π " | "δΈ" | "η" | "!"
11339 assert_eq!(
11340 out.iter().map(|r| r.len).collect::<Vec<_>>(),
11341 vec![5, 1, 5, 3, 3, 1]
11342 );
11343 assert_eq!(out[0].color, text_color); // "Hello"
11344 assert_eq!(out[2].color, adjusted_bg1); // "π "
11345 assert_eq!(out[3].color, adjusted_bg1); // "δΈ"
11346 assert_eq!(out[4].color, text_color); // "η"
11347 assert_eq!(out[5].color, text_color); // "!"
11348 }
11349
11350 // Case D: split multiple consecutive text runs with segments
11351 {
11352 let segs = vec![
11353 (dx(2, 4), bg_1), // selecting "cd"
11354 (dx(4, 8), bg_2), // selecting "efgh"
11355 (dx(9, 11), bg_1), // selecting "jk"
11356 (dx(12, 16), bg_2), // selecting "mnop"
11357 (dx(18, 19), bg_1), // selecting "s"
11358 ];
11359
11360 // for text: "abcdef"
11361 let runs = vec![
11362 generate_test_run(2, text_color), // ab
11363 generate_test_run(4, text_color), // cdef
11364 ];
11365 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 0);
11366 // new splits "ab", "cd", "ef"
11367 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![2, 2, 2]);
11368 assert_eq!(out[0].color, text_color);
11369 assert_eq!(out[1].color, adjusted_bg1);
11370 assert_eq!(out[2].color, adjusted_bg2);
11371
11372 // for text: "ghijklmn"
11373 let runs = vec![
11374 generate_test_run(3, text_color), // ghi
11375 generate_test_run(2, text_color), // jk
11376 generate_test_run(3, text_color), // lmn
11377 ];
11378 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 6); // 2 + 4 from first run
11379 // new splits "gh", "i", "jk", "l", "mn"
11380 assert_eq!(
11381 out.iter().map(|r| r.len).collect::<Vec<_>>(),
11382 vec![2, 1, 2, 1, 2]
11383 );
11384 assert_eq!(out[0].color, adjusted_bg2);
11385 assert_eq!(out[1].color, text_color);
11386 assert_eq!(out[2].color, adjusted_bg1);
11387 assert_eq!(out[3].color, text_color);
11388 assert_eq!(out[4].color, adjusted_bg2);
11389
11390 // for text: "opqrs"
11391 let runs = vec![
11392 generate_test_run(1, text_color), // o
11393 generate_test_run(4, text_color), // pqrs
11394 ];
11395 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast, 14); // 6 + 3 + 2 + 3 from first two runs
11396 // new splits "o", "p", "qr", "s"
11397 assert_eq!(
11398 out.iter().map(|r| r.len).collect::<Vec<_>>(),
11399 vec![1, 1, 2, 1]
11400 );
11401 assert_eq!(out[0].color, adjusted_bg2);
11402 assert_eq!(out[1].color, adjusted_bg2);
11403 assert_eq!(out[2].color, text_color);
11404 assert_eq!(out[3].color, adjusted_bg1);
11405 }
11406 }
11407}