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