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