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