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);
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 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
6089 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6090 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
6091 let line_end_overshoot = 0.15 * layout.position_map.line_height;
6092 for (range, color) in &layout.highlighted_ranges {
6093 self.paint_highlighted_range(
6094 range.clone(),
6095 true,
6096 *color,
6097 Pixels::ZERO,
6098 line_end_overshoot,
6099 layout,
6100 window,
6101 );
6102 }
6103
6104 let corner_radius = 0.15 * layout.position_map.line_height;
6105
6106 for (player_color, selections) in &layout.selections {
6107 for selection in selections.iter() {
6108 self.paint_highlighted_range(
6109 selection.range.clone(),
6110 true,
6111 player_color.selection,
6112 corner_radius,
6113 corner_radius * 2.,
6114 layout,
6115 window,
6116 );
6117
6118 if selection.is_local && !selection.range.is_empty() {
6119 invisible_display_ranges.push(selection.range.clone());
6120 }
6121 }
6122 }
6123 invisible_display_ranges
6124 })
6125 }
6126
6127 fn paint_lines(
6128 &mut self,
6129 invisible_display_ranges: &[Range<DisplayPoint>],
6130 layout: &mut EditorLayout,
6131 window: &mut Window,
6132 cx: &mut App,
6133 ) {
6134 let whitespace_setting = self
6135 .editor
6136 .read(cx)
6137 .buffer
6138 .read(cx)
6139 .language_settings(cx)
6140 .show_whitespaces;
6141
6142 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6143 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6144 line_with_invisibles.draw(
6145 layout,
6146 row,
6147 layout.content_origin,
6148 whitespace_setting,
6149 invisible_display_ranges,
6150 window,
6151 cx,
6152 )
6153 }
6154
6155 for line_element in &mut layout.line_elements {
6156 line_element.paint(window, cx);
6157 }
6158 }
6159
6160 fn paint_lines_background(
6161 &mut self,
6162 layout: &mut EditorLayout,
6163 window: &mut Window,
6164 cx: &mut App,
6165 ) {
6166 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6167 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6168 line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
6169 }
6170 }
6171
6172 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
6173 if layout.redacted_ranges.is_empty() {
6174 return;
6175 }
6176
6177 let line_end_overshoot = layout.line_end_overshoot();
6178
6179 // A softer than perfect black
6180 let redaction_color = gpui::rgb(0x0e1111);
6181
6182 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6183 for range in layout.redacted_ranges.iter() {
6184 self.paint_highlighted_range(
6185 range.clone(),
6186 true,
6187 redaction_color.into(),
6188 Pixels::ZERO,
6189 line_end_overshoot,
6190 layout,
6191 window,
6192 );
6193 }
6194 });
6195 }
6196
6197 fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
6198 let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
6199 return;
6200 };
6201 if image_colors.is_empty()
6202 || colors_render_mode == &DocumentColorsRenderMode::None
6203 || colors_render_mode == &DocumentColorsRenderMode::Inlay
6204 {
6205 return;
6206 }
6207
6208 let line_end_overshoot = layout.line_end_overshoot();
6209
6210 for (range, color) in image_colors {
6211 match colors_render_mode {
6212 DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
6213 DocumentColorsRenderMode::Background => {
6214 self.paint_highlighted_range(
6215 range.clone(),
6216 true,
6217 *color,
6218 Pixels::ZERO,
6219 line_end_overshoot,
6220 layout,
6221 window,
6222 );
6223 }
6224 DocumentColorsRenderMode::Border => {
6225 self.paint_highlighted_range(
6226 range.clone(),
6227 false,
6228 *color,
6229 Pixels::ZERO,
6230 line_end_overshoot,
6231 layout,
6232 window,
6233 );
6234 }
6235 }
6236 }
6237 }
6238
6239 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6240 for cursor in &mut layout.visible_cursors {
6241 cursor.paint(layout.content_origin, window, cx);
6242 }
6243 }
6244
6245 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6246 let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
6247 return;
6248 };
6249 let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
6250
6251 for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
6252 let hitbox = &scrollbar_layout.hitbox;
6253 if scrollbars_layout.visible {
6254 let scrollbar_edges = match axis {
6255 ScrollbarAxis::Horizontal => Edges {
6256 top: Pixels::ZERO,
6257 right: Pixels::ZERO,
6258 bottom: Pixels::ZERO,
6259 left: Pixels::ZERO,
6260 },
6261 ScrollbarAxis::Vertical => Edges {
6262 top: Pixels::ZERO,
6263 right: Pixels::ZERO,
6264 bottom: Pixels::ZERO,
6265 left: ScrollbarLayout::BORDER_WIDTH,
6266 },
6267 };
6268
6269 window.paint_layer(hitbox.bounds, |window| {
6270 window.paint_quad(quad(
6271 hitbox.bounds,
6272 Corners::default(),
6273 cx.theme().colors().scrollbar_track_background,
6274 scrollbar_edges,
6275 cx.theme().colors().scrollbar_track_border,
6276 BorderStyle::Solid,
6277 ));
6278
6279 if axis == ScrollbarAxis::Vertical {
6280 let fast_markers =
6281 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
6282 // Refresh slow scrollbar markers in the background. Below, we
6283 // paint whatever markers have already been computed.
6284 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
6285
6286 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
6287 for marker in markers.iter().chain(&fast_markers) {
6288 let mut marker = marker.clone();
6289 marker.bounds.origin += hitbox.origin;
6290 window.paint_quad(marker);
6291 }
6292 }
6293
6294 if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
6295 let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
6296 ScrollbarThumbState::Dragging => {
6297 cx.theme().colors().scrollbar_thumb_active_background
6298 }
6299 ScrollbarThumbState::Hovered => {
6300 cx.theme().colors().scrollbar_thumb_hover_background
6301 }
6302 ScrollbarThumbState::Idle => {
6303 cx.theme().colors().scrollbar_thumb_background
6304 }
6305 };
6306 window.paint_quad(quad(
6307 thumb_bounds,
6308 Corners::default(),
6309 scrollbar_thumb_color,
6310 scrollbar_edges,
6311 cx.theme().colors().scrollbar_thumb_border,
6312 BorderStyle::Solid,
6313 ));
6314
6315 if any_scrollbar_dragged {
6316 window.set_window_cursor_style(CursorStyle::Arrow);
6317 } else {
6318 window.set_cursor_style(CursorStyle::Arrow, hitbox);
6319 }
6320 }
6321 })
6322 }
6323 }
6324
6325 window.on_mouse_event({
6326 let editor = self.editor.clone();
6327 let scrollbars_layout = scrollbars_layout.clone();
6328
6329 let mut mouse_position = window.mouse_position();
6330 move |event: &MouseMoveEvent, phase, window, cx| {
6331 if phase == DispatchPhase::Capture {
6332 return;
6333 }
6334
6335 editor.update(cx, |editor, cx| {
6336 if let Some((scrollbar_layout, axis)) = event
6337 .pressed_button
6338 .filter(|button| *button == MouseButton::Left)
6339 .and(editor.scroll_manager.dragging_scrollbar_axis())
6340 .and_then(|axis| {
6341 scrollbars_layout
6342 .iter_scrollbars()
6343 .find(|(_, a)| *a == axis)
6344 })
6345 {
6346 let ScrollbarLayout {
6347 hitbox,
6348 text_unit_size,
6349 ..
6350 } = scrollbar_layout;
6351
6352 let old_position = mouse_position.along(axis);
6353 let new_position = event.position.along(axis);
6354 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
6355 .contains(&old_position)
6356 {
6357 let position = editor.scroll_position(cx).apply_along(axis, |p| {
6358 (p + (new_position - old_position) / *text_unit_size).max(0.)
6359 });
6360 editor.set_scroll_position(position, window, cx);
6361 }
6362
6363 editor.scroll_manager.show_scrollbars(window, cx);
6364 cx.stop_propagation();
6365 } else if let Some((layout, axis)) = scrollbars_layout
6366 .get_hovered_axis(window)
6367 .filter(|_| !event.dragging())
6368 {
6369 if layout.thumb_hovered(&event.position) {
6370 editor
6371 .scroll_manager
6372 .set_hovered_scroll_thumb_axis(axis, cx);
6373 } else {
6374 editor.scroll_manager.reset_scrollbar_state(cx);
6375 }
6376
6377 editor.scroll_manager.show_scrollbars(window, cx);
6378 } else {
6379 editor.scroll_manager.reset_scrollbar_state(cx);
6380 }
6381
6382 mouse_position = event.position;
6383 })
6384 }
6385 });
6386
6387 if any_scrollbar_dragged {
6388 window.on_mouse_event({
6389 let editor = self.editor.clone();
6390 move |_: &MouseUpEvent, phase, window, cx| {
6391 if phase == DispatchPhase::Capture {
6392 return;
6393 }
6394
6395 editor.update(cx, |editor, cx| {
6396 if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
6397 editor
6398 .scroll_manager
6399 .set_hovered_scroll_thumb_axis(axis, cx);
6400 } else {
6401 editor.scroll_manager.reset_scrollbar_state(cx);
6402 }
6403 cx.stop_propagation();
6404 });
6405 }
6406 });
6407 } else {
6408 window.on_mouse_event({
6409 let editor = self.editor.clone();
6410
6411 move |event: &MouseDownEvent, phase, window, cx| {
6412 if phase == DispatchPhase::Capture {
6413 return;
6414 }
6415 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
6416 else {
6417 return;
6418 };
6419
6420 let ScrollbarLayout {
6421 hitbox,
6422 visible_range,
6423 text_unit_size,
6424 thumb_bounds,
6425 ..
6426 } = scrollbar_layout;
6427
6428 let Some(thumb_bounds) = thumb_bounds else {
6429 return;
6430 };
6431
6432 editor.update(cx, |editor, cx| {
6433 editor
6434 .scroll_manager
6435 .set_dragged_scroll_thumb_axis(axis, cx);
6436
6437 let event_position = event.position.along(axis);
6438
6439 if event_position < thumb_bounds.origin.along(axis)
6440 || thumb_bounds.bottom_right().along(axis) < event_position
6441 {
6442 let center_position = ((event_position - hitbox.origin.along(axis))
6443 / *text_unit_size)
6444 .round() as u32;
6445 let start_position = center_position.saturating_sub(
6446 (visible_range.end - visible_range.start) as u32 / 2,
6447 );
6448
6449 let position = editor
6450 .scroll_position(cx)
6451 .apply_along(axis, |_| start_position as f32);
6452
6453 editor.set_scroll_position(position, window, cx);
6454 } else {
6455 editor.scroll_manager.show_scrollbars(window, cx);
6456 }
6457
6458 cx.stop_propagation();
6459 });
6460 }
6461 });
6462 }
6463 }
6464
6465 fn collect_fast_scrollbar_markers(
6466 &self,
6467 layout: &EditorLayout,
6468 scrollbar_layout: &ScrollbarLayout,
6469 cx: &mut App,
6470 ) -> Vec<PaintQuad> {
6471 const LIMIT: usize = 100;
6472 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
6473 return vec![];
6474 }
6475 let cursor_ranges = layout
6476 .cursors
6477 .iter()
6478 .map(|(point, color)| ColoredRange {
6479 start: point.row(),
6480 end: point.row(),
6481 color: *color,
6482 })
6483 .collect_vec();
6484 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
6485 }
6486
6487 fn refresh_slow_scrollbar_markers(
6488 &self,
6489 layout: &EditorLayout,
6490 scrollbar_layout: &ScrollbarLayout,
6491 window: &mut Window,
6492 cx: &mut App,
6493 ) {
6494 self.editor.update(cx, |editor, cx| {
6495 if !editor.is_singleton(cx)
6496 || !editor
6497 .scrollbar_marker_state
6498 .should_refresh(scrollbar_layout.hitbox.size)
6499 {
6500 return;
6501 }
6502
6503 let scrollbar_layout = scrollbar_layout.clone();
6504 let background_highlights = editor.background_highlights.clone();
6505 let snapshot = layout.position_map.snapshot.clone();
6506 let theme = cx.theme().clone();
6507 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
6508
6509 editor.scrollbar_marker_state.dirty = false;
6510 editor.scrollbar_marker_state.pending_refresh =
6511 Some(cx.spawn_in(window, async move |editor, cx| {
6512 let scrollbar_size = scrollbar_layout.hitbox.size;
6513 let scrollbar_markers = cx
6514 .background_spawn(async move {
6515 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
6516 let mut marker_quads = Vec::new();
6517 if scrollbar_settings.git_diff {
6518 let marker_row_ranges =
6519 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
6520 let start_display_row =
6521 MultiBufferPoint::new(hunk.row_range.start.0, 0)
6522 .to_display_point(&snapshot.display_snapshot)
6523 .row();
6524 let mut end_display_row =
6525 MultiBufferPoint::new(hunk.row_range.end.0, 0)
6526 .to_display_point(&snapshot.display_snapshot)
6527 .row();
6528 if end_display_row != start_display_row {
6529 end_display_row.0 -= 1;
6530 }
6531 let color = match &hunk.status().kind {
6532 DiffHunkStatusKind::Added => {
6533 theme.colors().version_control_added
6534 }
6535 DiffHunkStatusKind::Modified => {
6536 theme.colors().version_control_modified
6537 }
6538 DiffHunkStatusKind::Deleted => {
6539 theme.colors().version_control_deleted
6540 }
6541 };
6542 ColoredRange {
6543 start: start_display_row,
6544 end: end_display_row,
6545 color,
6546 }
6547 });
6548
6549 marker_quads.extend(
6550 scrollbar_layout
6551 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
6552 );
6553 }
6554
6555 for (background_highlight_id, (_, background_ranges)) in
6556 background_highlights.iter()
6557 {
6558 let is_search_highlights = *background_highlight_id
6559 == HighlightKey::Type(TypeId::of::<BufferSearchHighlights>());
6560 let is_text_highlights = *background_highlight_id
6561 == HighlightKey::Type(TypeId::of::<SelectedTextHighlight>());
6562 let is_symbol_occurrences = *background_highlight_id
6563 == HighlightKey::Type(TypeId::of::<DocumentHighlightRead>())
6564 || *background_highlight_id
6565 == HighlightKey::Type(
6566 TypeId::of::<DocumentHighlightWrite>(),
6567 );
6568 if (is_search_highlights && scrollbar_settings.search_results)
6569 || (is_text_highlights && scrollbar_settings.selected_text)
6570 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
6571 {
6572 let mut color = theme.status().info;
6573 if is_symbol_occurrences {
6574 color.fade_out(0.5);
6575 }
6576 let marker_row_ranges = background_ranges.iter().map(|range| {
6577 let display_start = range
6578 .start
6579 .to_display_point(&snapshot.display_snapshot);
6580 let display_end =
6581 range.end.to_display_point(&snapshot.display_snapshot);
6582 ColoredRange {
6583 start: display_start.row(),
6584 end: display_end.row(),
6585 color,
6586 }
6587 });
6588 marker_quads.extend(
6589 scrollbar_layout
6590 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
6591 );
6592 }
6593 }
6594
6595 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
6596 let diagnostics = snapshot
6597 .buffer_snapshot
6598 .diagnostics_in_range::<Point>(Point::zero()..max_point)
6599 // Don't show diagnostics the user doesn't care about
6600 .filter(|diagnostic| {
6601 match (
6602 scrollbar_settings.diagnostics,
6603 diagnostic.diagnostic.severity,
6604 ) {
6605 (ScrollbarDiagnostics::All, _) => true,
6606 (
6607 ScrollbarDiagnostics::Error,
6608 lsp::DiagnosticSeverity::ERROR,
6609 ) => true,
6610 (
6611 ScrollbarDiagnostics::Warning,
6612 lsp::DiagnosticSeverity::ERROR
6613 | lsp::DiagnosticSeverity::WARNING,
6614 ) => true,
6615 (
6616 ScrollbarDiagnostics::Information,
6617 lsp::DiagnosticSeverity::ERROR
6618 | lsp::DiagnosticSeverity::WARNING
6619 | lsp::DiagnosticSeverity::INFORMATION,
6620 ) => true,
6621 (_, _) => false,
6622 }
6623 })
6624 // We want to sort by severity, in order to paint the most severe diagnostics last.
6625 .sorted_by_key(|diagnostic| {
6626 std::cmp::Reverse(diagnostic.diagnostic.severity)
6627 });
6628
6629 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
6630 let start_display = diagnostic
6631 .range
6632 .start
6633 .to_display_point(&snapshot.display_snapshot);
6634 let end_display = diagnostic
6635 .range
6636 .end
6637 .to_display_point(&snapshot.display_snapshot);
6638 let color = match diagnostic.diagnostic.severity {
6639 lsp::DiagnosticSeverity::ERROR => theme.status().error,
6640 lsp::DiagnosticSeverity::WARNING => theme.status().warning,
6641 lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
6642 _ => theme.status().hint,
6643 };
6644 ColoredRange {
6645 start: start_display.row(),
6646 end: end_display.row(),
6647 color,
6648 }
6649 });
6650 marker_quads.extend(
6651 scrollbar_layout
6652 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
6653 );
6654 }
6655
6656 Arc::from(marker_quads)
6657 })
6658 .await;
6659
6660 editor.update(cx, |editor, cx| {
6661 editor.scrollbar_marker_state.markers = scrollbar_markers;
6662 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
6663 editor.scrollbar_marker_state.pending_refresh = None;
6664 cx.notify();
6665 })?;
6666
6667 Ok(())
6668 }));
6669 });
6670 }
6671
6672 fn paint_highlighted_range(
6673 &self,
6674 range: Range<DisplayPoint>,
6675 fill: bool,
6676 color: Hsla,
6677 corner_radius: Pixels,
6678 line_end_overshoot: Pixels,
6679 layout: &EditorLayout,
6680 window: &mut Window,
6681 ) {
6682 let start_row = layout.visible_display_row_range.start;
6683 let end_row = layout.visible_display_row_range.end;
6684 if range.start != range.end {
6685 let row_range = if range.end.column() == 0 {
6686 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
6687 } else {
6688 cmp::max(range.start.row(), start_row)
6689 ..cmp::min(range.end.row().next_row(), end_row)
6690 };
6691
6692 let highlighted_range = HighlightedRange {
6693 color,
6694 line_height: layout.position_map.line_height,
6695 corner_radius,
6696 start_y: layout.content_origin.y
6697 + row_range.start.as_f32() * layout.position_map.line_height
6698 - layout.position_map.scroll_pixel_position.y,
6699 lines: row_range
6700 .iter_rows()
6701 .map(|row| {
6702 let line_layout =
6703 &layout.position_map.line_layouts[row.minus(start_row) as usize];
6704 HighlightedRangeLine {
6705 start_x: if row == range.start.row() {
6706 layout.content_origin.x
6707 + line_layout.x_for_index(range.start.column() as usize)
6708 - layout.position_map.scroll_pixel_position.x
6709 } else {
6710 layout.content_origin.x
6711 - layout.position_map.scroll_pixel_position.x
6712 },
6713 end_x: if row == range.end.row() {
6714 layout.content_origin.x
6715 + line_layout.x_for_index(range.end.column() as usize)
6716 - layout.position_map.scroll_pixel_position.x
6717 } else {
6718 layout.content_origin.x + line_layout.width + line_end_overshoot
6719 - layout.position_map.scroll_pixel_position.x
6720 },
6721 }
6722 })
6723 .collect(),
6724 };
6725
6726 highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
6727 }
6728 }
6729
6730 fn paint_inline_diagnostics(
6731 &mut self,
6732 layout: &mut EditorLayout,
6733 window: &mut Window,
6734 cx: &mut App,
6735 ) {
6736 for mut inline_diagnostic in layout.inline_diagnostics.drain() {
6737 inline_diagnostic.1.paint(window, cx);
6738 }
6739 }
6740
6741 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6742 if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
6743 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6744 blame_layout.element.paint(window, cx);
6745 })
6746 }
6747 }
6748
6749 fn paint_inline_code_actions(
6750 &mut self,
6751 layout: &mut EditorLayout,
6752 window: &mut Window,
6753 cx: &mut App,
6754 ) {
6755 if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
6756 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6757 inline_code_actions.paint(window, cx);
6758 })
6759 }
6760 }
6761
6762 fn paint_diff_hunk_controls(
6763 &mut self,
6764 layout: &mut EditorLayout,
6765 window: &mut Window,
6766 cx: &mut App,
6767 ) {
6768 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
6769 diff_hunk_control.paint(window, cx);
6770 }
6771 }
6772
6773 fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6774 if let Some(mut layout) = layout.minimap.take() {
6775 let minimap_hitbox = layout.thumb_layout.hitbox.clone();
6776 let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
6777
6778 window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
6779 window.with_element_namespace("minimap", |window| {
6780 layout.minimap.paint(window, cx);
6781 if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
6782 let minimap_thumb_color = match layout.thumb_layout.thumb_state {
6783 ScrollbarThumbState::Idle => {
6784 cx.theme().colors().minimap_thumb_background
6785 }
6786 ScrollbarThumbState::Hovered => {
6787 cx.theme().colors().minimap_thumb_hover_background
6788 }
6789 ScrollbarThumbState::Dragging => {
6790 cx.theme().colors().minimap_thumb_active_background
6791 }
6792 };
6793 let minimap_thumb_border = match layout.thumb_border_style {
6794 MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
6795 MinimapThumbBorder::LeftOnly => Edges {
6796 left: ScrollbarLayout::BORDER_WIDTH,
6797 ..Default::default()
6798 },
6799 MinimapThumbBorder::LeftOpen => Edges {
6800 right: ScrollbarLayout::BORDER_WIDTH,
6801 top: ScrollbarLayout::BORDER_WIDTH,
6802 bottom: ScrollbarLayout::BORDER_WIDTH,
6803 ..Default::default()
6804 },
6805 MinimapThumbBorder::RightOpen => Edges {
6806 left: ScrollbarLayout::BORDER_WIDTH,
6807 top: ScrollbarLayout::BORDER_WIDTH,
6808 bottom: ScrollbarLayout::BORDER_WIDTH,
6809 ..Default::default()
6810 },
6811 MinimapThumbBorder::None => Default::default(),
6812 };
6813
6814 window.paint_layer(minimap_hitbox.bounds, |window| {
6815 window.paint_quad(quad(
6816 thumb_bounds,
6817 Corners::default(),
6818 minimap_thumb_color,
6819 minimap_thumb_border,
6820 cx.theme().colors().minimap_thumb_border,
6821 BorderStyle::Solid,
6822 ));
6823 });
6824 }
6825 });
6826 });
6827
6828 if dragging_minimap {
6829 window.set_window_cursor_style(CursorStyle::Arrow);
6830 } else {
6831 window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
6832 }
6833
6834 let minimap_axis = ScrollbarAxis::Vertical;
6835 let pixels_per_line = (minimap_hitbox.size.height / layout.max_scroll_top)
6836 .min(layout.minimap_line_height);
6837
6838 let mut mouse_position = window.mouse_position();
6839
6840 window.on_mouse_event({
6841 let editor = self.editor.clone();
6842
6843 let minimap_hitbox = minimap_hitbox.clone();
6844
6845 move |event: &MouseMoveEvent, phase, window, cx| {
6846 if phase == DispatchPhase::Capture {
6847 return;
6848 }
6849
6850 editor.update(cx, |editor, cx| {
6851 if event.pressed_button == Some(MouseButton::Left)
6852 && editor.scroll_manager.is_dragging_minimap()
6853 {
6854 let old_position = mouse_position.along(minimap_axis);
6855 let new_position = event.position.along(minimap_axis);
6856 if (minimap_hitbox.origin.along(minimap_axis)
6857 ..minimap_hitbox.bottom_right().along(minimap_axis))
6858 .contains(&old_position)
6859 {
6860 let position =
6861 editor.scroll_position(cx).apply_along(minimap_axis, |p| {
6862 (p + (new_position - old_position) / pixels_per_line)
6863 .max(0.)
6864 });
6865 editor.set_scroll_position(position, window, cx);
6866 }
6867 cx.stop_propagation();
6868 } else if minimap_hitbox.is_hovered(window) {
6869 editor.scroll_manager.set_is_hovering_minimap_thumb(
6870 !event.dragging()
6871 && layout
6872 .thumb_layout
6873 .thumb_bounds
6874 .is_some_and(|bounds| bounds.contains(&event.position)),
6875 cx,
6876 );
6877
6878 // Stop hover events from propagating to the
6879 // underlying editor if the minimap hitbox is hovered
6880 if !event.dragging() {
6881 cx.stop_propagation();
6882 }
6883 } else {
6884 editor.scroll_manager.hide_minimap_thumb(cx);
6885 }
6886 mouse_position = event.position;
6887 });
6888 }
6889 });
6890
6891 if dragging_minimap {
6892 window.on_mouse_event({
6893 let editor = self.editor.clone();
6894 move |event: &MouseUpEvent, phase, window, cx| {
6895 if phase == DispatchPhase::Capture {
6896 return;
6897 }
6898
6899 editor.update(cx, |editor, cx| {
6900 if minimap_hitbox.is_hovered(window) {
6901 editor.scroll_manager.set_is_hovering_minimap_thumb(
6902 layout
6903 .thumb_layout
6904 .thumb_bounds
6905 .is_some_and(|bounds| bounds.contains(&event.position)),
6906 cx,
6907 );
6908 } else {
6909 editor.scroll_manager.hide_minimap_thumb(cx);
6910 }
6911 cx.stop_propagation();
6912 });
6913 }
6914 });
6915 } else {
6916 window.on_mouse_event({
6917 let editor = self.editor.clone();
6918
6919 move |event: &MouseDownEvent, phase, window, cx| {
6920 if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
6921 return;
6922 }
6923
6924 let event_position = event.position;
6925
6926 let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
6927 return;
6928 };
6929
6930 editor.update(cx, |editor, cx| {
6931 if !thumb_bounds.contains(&event_position) {
6932 let click_position =
6933 event_position.relative_to(&minimap_hitbox.origin).y;
6934
6935 let top_position = (click_position
6936 - thumb_bounds.size.along(minimap_axis) / 2.0)
6937 .max(Pixels::ZERO);
6938
6939 let scroll_offset = (layout.minimap_scroll_top
6940 + top_position / layout.minimap_line_height)
6941 .min(layout.max_scroll_top);
6942
6943 let scroll_position = editor
6944 .scroll_position(cx)
6945 .apply_along(minimap_axis, |_| scroll_offset);
6946 editor.set_scroll_position(scroll_position, window, cx);
6947 }
6948
6949 editor.scroll_manager.set_is_dragging_minimap(cx);
6950 cx.stop_propagation();
6951 });
6952 }
6953 });
6954 }
6955 }
6956 }
6957
6958 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6959 for mut block in layout.blocks.drain(..) {
6960 if block.overlaps_gutter {
6961 block.element.paint(window, cx);
6962 } else {
6963 let mut bounds = layout.hitbox.bounds;
6964 bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
6965 window.with_content_mask(Some(ContentMask { bounds }), |window| {
6966 block.element.paint(window, cx);
6967 })
6968 }
6969 }
6970 }
6971
6972 fn paint_edit_prediction_popover(
6973 &mut self,
6974 layout: &mut EditorLayout,
6975 window: &mut Window,
6976 cx: &mut App,
6977 ) {
6978 if let Some(edit_prediction_popover) = layout.edit_prediction_popover.as_mut() {
6979 edit_prediction_popover.paint(window, cx);
6980 }
6981 }
6982
6983 fn paint_mouse_context_menu(
6984 &mut self,
6985 layout: &mut EditorLayout,
6986 window: &mut Window,
6987 cx: &mut App,
6988 ) {
6989 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
6990 mouse_context_menu.paint(window, cx);
6991 }
6992 }
6993
6994 fn paint_scroll_wheel_listener(
6995 &mut self,
6996 layout: &EditorLayout,
6997 window: &mut Window,
6998 cx: &mut App,
6999 ) {
7000 window.on_mouse_event({
7001 let position_map = layout.position_map.clone();
7002 let editor = self.editor.clone();
7003 let hitbox = layout.hitbox.clone();
7004 let mut delta = ScrollDelta::default();
7005
7006 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
7007 // accidentally turn off their scrolling.
7008 let base_scroll_sensitivity =
7009 EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
7010
7011 // Use a minimum fast_scroll_sensitivity for same reason above
7012 let fast_scroll_sensitivity = EditorSettings::get_global(cx)
7013 .fast_scroll_sensitivity
7014 .max(0.01);
7015
7016 move |event: &ScrollWheelEvent, phase, window, cx| {
7017 let scroll_sensitivity = {
7018 if event.modifiers.alt {
7019 fast_scroll_sensitivity
7020 } else {
7021 base_scroll_sensitivity
7022 }
7023 };
7024
7025 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
7026 delta = delta.coalesce(event.delta);
7027 editor.update(cx, |editor, cx| {
7028 let position_map: &PositionMap = &position_map;
7029
7030 let line_height = position_map.line_height;
7031 let max_glyph_advance = position_map.em_advance;
7032 let (delta, axis) = match delta {
7033 gpui::ScrollDelta::Pixels(mut pixels) => {
7034 //Trackpad
7035 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
7036 (pixels, axis)
7037 }
7038
7039 gpui::ScrollDelta::Lines(lines) => {
7040 //Not trackpad
7041 let pixels =
7042 point(lines.x * max_glyph_advance, lines.y * line_height);
7043 (pixels, None)
7044 }
7045 };
7046
7047 let current_scroll_position = position_map.snapshot.scroll_position();
7048 let x = (current_scroll_position.x * max_glyph_advance
7049 - (delta.x * scroll_sensitivity))
7050 / max_glyph_advance;
7051 let y = (current_scroll_position.y * line_height
7052 - (delta.y * scroll_sensitivity))
7053 / line_height;
7054 let mut scroll_position =
7055 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
7056 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
7057 if forbid_vertical_scroll {
7058 scroll_position.y = current_scroll_position.y;
7059 }
7060
7061 if scroll_position != current_scroll_position {
7062 editor.scroll(scroll_position, axis, window, cx);
7063 cx.stop_propagation();
7064 } else if y < 0. {
7065 // Due to clamping, we may fail to detect cases of overscroll to the top;
7066 // We want the scroll manager to get an update in such cases and detect the change of direction
7067 // on the next frame.
7068 cx.notify();
7069 }
7070 });
7071 }
7072 }
7073 });
7074 }
7075
7076 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
7077 if layout.mode.is_minimap() {
7078 return;
7079 }
7080
7081 self.paint_scroll_wheel_listener(layout, window, cx);
7082
7083 window.on_mouse_event({
7084 let position_map = layout.position_map.clone();
7085 let editor = self.editor.clone();
7086 let diff_hunk_range =
7087 layout
7088 .display_hunks
7089 .iter()
7090 .find_map(|(hunk, hunk_hitbox)| match hunk {
7091 DisplayDiffHunk::Folded { .. } => None,
7092 DisplayDiffHunk::Unfolded {
7093 multi_buffer_range, ..
7094 } => {
7095 if hunk_hitbox
7096 .as_ref()
7097 .map(|hitbox| hitbox.is_hovered(window))
7098 .unwrap_or(false)
7099 {
7100 Some(multi_buffer_range.clone())
7101 } else {
7102 None
7103 }
7104 }
7105 });
7106 let line_numbers = layout.line_numbers.clone();
7107
7108 move |event: &MouseDownEvent, phase, window, cx| {
7109 if phase == DispatchPhase::Bubble {
7110 match event.button {
7111 MouseButton::Left => editor.update(cx, |editor, cx| {
7112 let pending_mouse_down = editor
7113 .pending_mouse_down
7114 .get_or_insert_with(Default::default)
7115 .clone();
7116
7117 *pending_mouse_down.borrow_mut() = Some(event.clone());
7118
7119 Self::mouse_left_down(
7120 editor,
7121 event,
7122 diff_hunk_range.clone(),
7123 &position_map,
7124 line_numbers.as_ref(),
7125 window,
7126 cx,
7127 );
7128 }),
7129 MouseButton::Right => editor.update(cx, |editor, cx| {
7130 Self::mouse_right_down(editor, event, &position_map, window, cx);
7131 }),
7132 MouseButton::Middle => editor.update(cx, |editor, cx| {
7133 Self::mouse_middle_down(editor, event, &position_map, window, cx);
7134 }),
7135 _ => {}
7136 };
7137 }
7138 }
7139 });
7140
7141 window.on_mouse_event({
7142 let editor = self.editor.clone();
7143 let position_map = layout.position_map.clone();
7144
7145 move |event: &MouseUpEvent, phase, window, cx| {
7146 if phase == DispatchPhase::Bubble {
7147 editor.update(cx, |editor, cx| {
7148 Self::mouse_up(editor, event, &position_map, window, cx)
7149 });
7150 }
7151 }
7152 });
7153
7154 window.on_mouse_event({
7155 let editor = self.editor.clone();
7156 let position_map = layout.position_map.clone();
7157 let mut captured_mouse_down = None;
7158
7159 move |event: &MouseUpEvent, phase, window, cx| match phase {
7160 // Clear the pending mouse down during the capture phase,
7161 // so that it happens even if another event handler stops
7162 // propagation.
7163 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
7164 let pending_mouse_down = editor
7165 .pending_mouse_down
7166 .get_or_insert_with(Default::default)
7167 .clone();
7168
7169 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
7170 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
7171 captured_mouse_down = pending_mouse_down.take();
7172 window.refresh();
7173 }
7174 }),
7175 // Fire click handlers during the bubble phase.
7176 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
7177 if let Some(mouse_down) = captured_mouse_down.take() {
7178 let event = ClickEvent::Mouse(MouseClickEvent {
7179 down: mouse_down,
7180 up: event.clone(),
7181 });
7182 Self::click(editor, &event, &position_map, window, cx);
7183 }
7184 }),
7185 }
7186 });
7187
7188 window.on_mouse_event({
7189 let position_map = layout.position_map.clone();
7190 let editor = self.editor.clone();
7191
7192 move |event: &MouseMoveEvent, phase, window, cx| {
7193 if phase == DispatchPhase::Bubble {
7194 editor.update(cx, |editor, cx| {
7195 if editor.hover_state.focused(window, cx) {
7196 return;
7197 }
7198 if event.pressed_button == Some(MouseButton::Left)
7199 || event.pressed_button == Some(MouseButton::Middle)
7200 {
7201 Self::mouse_dragged(editor, event, &position_map, window, cx)
7202 }
7203
7204 Self::mouse_moved(editor, event, &position_map, window, cx)
7205 });
7206 }
7207 }
7208 });
7209 }
7210
7211 fn column_pixels(&self, column: usize, window: &Window) -> Pixels {
7212 let style = &self.style;
7213 let font_size = style.text.font_size.to_pixels(window.rem_size());
7214 let layout = window.text_system().shape_line(
7215 SharedString::from(" ".repeat(column)),
7216 font_size,
7217 &[TextRun {
7218 len: column,
7219 font: style.text.font(),
7220 color: Hsla::default(),
7221 background_color: None,
7222 underline: None,
7223 strikethrough: None,
7224 }],
7225 None,
7226 );
7227
7228 layout.width
7229 }
7230
7231 fn max_line_number_width(&self, snapshot: &EditorSnapshot, window: &mut Window) -> Pixels {
7232 let digit_count = snapshot.widest_line_number().ilog10() + 1;
7233 self.column_pixels(digit_count as usize, window)
7234 }
7235
7236 fn shape_line_number(
7237 &self,
7238 text: SharedString,
7239 color: Hsla,
7240 window: &mut Window,
7241 ) -> ShapedLine {
7242 let run = TextRun {
7243 len: text.len(),
7244 font: self.style.text.font(),
7245 color,
7246 background_color: None,
7247 underline: None,
7248 strikethrough: None,
7249 };
7250 window.text_system().shape_line(
7251 text,
7252 self.style.text.font_size.to_pixels(window.rem_size()),
7253 &[run],
7254 None,
7255 )
7256 }
7257
7258 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
7259 let unstaged = status.has_secondary_hunk();
7260 let unstaged_hollow = ProjectSettings::get_global(cx)
7261 .git
7262 .hunk_style
7263 .is_some_and(|style| matches!(style, GitHunkStyleSetting::UnstagedHollow));
7264
7265 unstaged == unstaged_hollow
7266 }
7267}
7268
7269fn header_jump_data(
7270 snapshot: &EditorSnapshot,
7271 block_row_start: DisplayRow,
7272 height: u32,
7273 for_excerpt: &ExcerptInfo,
7274) -> JumpData {
7275 let range = &for_excerpt.range;
7276 let buffer = &for_excerpt.buffer;
7277 let jump_anchor = range.primary.start;
7278
7279 let excerpt_start = range.context.start;
7280 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
7281 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
7282 0
7283 } else {
7284 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
7285 jump_position.row.saturating_sub(excerpt_start_point.row)
7286 };
7287
7288 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
7289 .saturating_sub(
7290 snapshot
7291 .scroll_anchor
7292 .scroll_position(&snapshot.display_snapshot)
7293 .y as u32,
7294 );
7295
7296 JumpData::MultiBufferPoint {
7297 excerpt_id: for_excerpt.id,
7298 anchor: jump_anchor,
7299 position: jump_position,
7300 line_offset_from_top,
7301 }
7302}
7303
7304pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
7305
7306impl AcceptEditPredictionBinding {
7307 pub fn keystroke(&self) -> Option<&KeybindingKeystroke> {
7308 if let Some(binding) = self.0.as_ref() {
7309 match &binding.keystrokes() {
7310 [keystroke, ..] => Some(keystroke),
7311 _ => None,
7312 }
7313 } else {
7314 None
7315 }
7316 }
7317}
7318
7319fn prepaint_gutter_button(
7320 button: IconButton,
7321 row: DisplayRow,
7322 line_height: Pixels,
7323 gutter_dimensions: &GutterDimensions,
7324 scroll_pixel_position: gpui::Point<Pixels>,
7325 gutter_hitbox: &Hitbox,
7326 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
7327 window: &mut Window,
7328 cx: &mut App,
7329) -> AnyElement {
7330 let mut button = button.into_any_element();
7331
7332 let available_space = size(
7333 AvailableSpace::MinContent,
7334 AvailableSpace::Definite(line_height),
7335 );
7336 let indicator_size = button.layout_as_root(available_space, window, cx);
7337
7338 let blame_width = gutter_dimensions.git_blame_entries_width;
7339 let gutter_width = display_hunks
7340 .binary_search_by(|(hunk, _)| match hunk {
7341 DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
7342 DisplayDiffHunk::Unfolded {
7343 display_row_range, ..
7344 } => {
7345 if display_row_range.end <= row {
7346 Ordering::Less
7347 } else if display_row_range.start > row {
7348 Ordering::Greater
7349 } else {
7350 Ordering::Equal
7351 }
7352 }
7353 })
7354 .ok()
7355 .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
7356 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
7357
7358 let mut x = left_offset;
7359 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
7360 - indicator_size.width
7361 - left_offset;
7362 x += available_width / 2.;
7363
7364 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
7365 y += (line_height - indicator_size.height) / 2.;
7366
7367 button.prepaint_as_root(
7368 gutter_hitbox.origin + point(x, y),
7369 available_space,
7370 window,
7371 cx,
7372 );
7373 button
7374}
7375
7376fn render_inline_blame_entry(
7377 blame_entry: BlameEntry,
7378 style: &EditorStyle,
7379 cx: &mut App,
7380) -> Option<AnyElement> {
7381 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7382 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
7383}
7384
7385fn render_blame_entry_popover(
7386 blame_entry: BlameEntry,
7387 scroll_handle: ScrollHandle,
7388 commit_message: Option<ParsedCommitMessage>,
7389 markdown: Entity<Markdown>,
7390 workspace: WeakEntity<Workspace>,
7391 blame: &Entity<GitBlame>,
7392 window: &mut Window,
7393 cx: &mut App,
7394) -> Option<AnyElement> {
7395 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7396 let blame = blame.read(cx);
7397 let repository = blame.repository(cx)?;
7398 renderer.render_blame_entry_popover(
7399 blame_entry,
7400 scroll_handle,
7401 commit_message,
7402 markdown,
7403 repository,
7404 workspace,
7405 window,
7406 cx,
7407 )
7408}
7409
7410fn render_blame_entry(
7411 ix: usize,
7412 blame: &Entity<GitBlame>,
7413 blame_entry: BlameEntry,
7414 style: &EditorStyle,
7415 last_used_color: &mut Option<(PlayerColor, Oid)>,
7416 editor: Entity<Editor>,
7417 workspace: Entity<Workspace>,
7418 renderer: Arc<dyn BlameRenderer>,
7419 cx: &mut App,
7420) -> Option<AnyElement> {
7421 let mut sha_color = cx
7422 .theme()
7423 .players()
7424 .color_for_participant(blame_entry.sha.into());
7425
7426 // If the last color we used is the same as the one we get for this line, but
7427 // the commit SHAs are different, then we try again to get a different color.
7428 match *last_used_color {
7429 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
7430 let index: u32 = blame_entry.sha.into();
7431 sha_color = cx.theme().players().color_for_participant(index + 1);
7432 }
7433 _ => {}
7434 };
7435 last_used_color.replace((sha_color, blame_entry.sha));
7436
7437 let blame = blame.read(cx);
7438 let details = blame.details_for_entry(&blame_entry);
7439 let repository = blame.repository(cx)?;
7440 renderer.render_blame_entry(
7441 &style.text,
7442 blame_entry,
7443 details,
7444 repository,
7445 workspace.downgrade(),
7446 editor,
7447 ix,
7448 sha_color.cursor,
7449 cx,
7450 )
7451}
7452
7453#[derive(Debug)]
7454pub(crate) struct LineWithInvisibles {
7455 fragments: SmallVec<[LineFragment; 1]>,
7456 invisibles: Vec<Invisible>,
7457 len: usize,
7458 pub(crate) width: Pixels,
7459 font_size: Pixels,
7460}
7461
7462enum LineFragment {
7463 Text(ShapedLine),
7464 Element {
7465 id: ChunkRendererId,
7466 element: Option<AnyElement>,
7467 size: Size<Pixels>,
7468 len: usize,
7469 },
7470}
7471
7472impl fmt::Debug for LineFragment {
7473 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7474 match self {
7475 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
7476 LineFragment::Element { size, len, .. } => f
7477 .debug_struct("Element")
7478 .field("size", size)
7479 .field("len", len)
7480 .finish(),
7481 }
7482 }
7483}
7484
7485impl LineWithInvisibles {
7486 fn from_chunks<'a>(
7487 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
7488 editor_style: &EditorStyle,
7489 max_line_len: usize,
7490 max_line_count: usize,
7491 editor_mode: &EditorMode,
7492 text_width: Pixels,
7493 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
7494 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
7495 window: &mut Window,
7496 cx: &mut App,
7497 ) -> Vec<Self> {
7498 let text_style = &editor_style.text;
7499 let mut layouts = Vec::with_capacity(max_line_count);
7500 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
7501 let mut line = String::new();
7502 let mut invisibles = Vec::new();
7503 let mut width = Pixels::ZERO;
7504 let mut len = 0;
7505 let mut styles = Vec::new();
7506 let mut non_whitespace_added = false;
7507 let mut row = 0;
7508 let mut line_exceeded_max_len = false;
7509 let font_size = text_style.font_size.to_pixels(window.rem_size());
7510 let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
7511
7512 let ellipsis = SharedString::from("β―");
7513
7514 for highlighted_chunk in chunks.chain([HighlightedChunk {
7515 text: "\n",
7516 style: None,
7517 is_tab: false,
7518 is_inlay: false,
7519 replacement: None,
7520 }]) {
7521 if let Some(replacement) = highlighted_chunk.replacement {
7522 if !line.is_empty() {
7523 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
7524 let text_runs: &[TextRun] = if segments.is_empty() {
7525 &styles
7526 } else {
7527 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast)
7528 };
7529 let shaped_line = window.text_system().shape_line(
7530 line.clone().into(),
7531 font_size,
7532 text_runs,
7533 None,
7534 );
7535 width += shaped_line.width;
7536 len += shaped_line.len;
7537 fragments.push(LineFragment::Text(shaped_line));
7538 line.clear();
7539 styles.clear();
7540 }
7541
7542 match replacement {
7543 ChunkReplacement::Renderer(renderer) => {
7544 let available_width = if renderer.constrain_width {
7545 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
7546 ellipsis.clone()
7547 } else {
7548 SharedString::from(Arc::from(highlighted_chunk.text))
7549 };
7550 let shaped_line = window.text_system().shape_line(
7551 chunk,
7552 font_size,
7553 &[text_style.to_run(highlighted_chunk.text.len())],
7554 None,
7555 );
7556 AvailableSpace::Definite(shaped_line.width)
7557 } else {
7558 AvailableSpace::MinContent
7559 };
7560
7561 let mut element = (renderer.render)(&mut ChunkRendererContext {
7562 context: cx,
7563 window,
7564 max_width: text_width,
7565 });
7566 let line_height = text_style.line_height_in_pixels(window.rem_size());
7567 let size = element.layout_as_root(
7568 size(available_width, AvailableSpace::Definite(line_height)),
7569 window,
7570 cx,
7571 );
7572
7573 width += size.width;
7574 len += highlighted_chunk.text.len();
7575 fragments.push(LineFragment::Element {
7576 id: renderer.id,
7577 element: Some(element),
7578 size,
7579 len: highlighted_chunk.text.len(),
7580 });
7581 }
7582 ChunkReplacement::Str(x) => {
7583 let text_style = if let Some(style) = highlighted_chunk.style {
7584 Cow::Owned(text_style.clone().highlight(style))
7585 } else {
7586 Cow::Borrowed(text_style)
7587 };
7588
7589 let run = TextRun {
7590 len: x.len(),
7591 font: text_style.font(),
7592 color: text_style.color,
7593 background_color: text_style.background_color,
7594 underline: text_style.underline,
7595 strikethrough: text_style.strikethrough,
7596 };
7597 let line_layout = window
7598 .text_system()
7599 .shape_line(x, font_size, &[run], None)
7600 .with_len(highlighted_chunk.text.len());
7601
7602 width += line_layout.width;
7603 len += highlighted_chunk.text.len();
7604 fragments.push(LineFragment::Text(line_layout))
7605 }
7606 }
7607 } else {
7608 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
7609 if ix > 0 {
7610 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
7611 let text_runs = if segments.is_empty() {
7612 &styles
7613 } else {
7614 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast)
7615 };
7616 let shaped_line = window.text_system().shape_line(
7617 line.clone().into(),
7618 font_size,
7619 text_runs,
7620 None,
7621 );
7622 width += shaped_line.width;
7623 len += shaped_line.len;
7624 fragments.push(LineFragment::Text(shaped_line));
7625 layouts.push(Self {
7626 width: mem::take(&mut width),
7627 len: mem::take(&mut len),
7628 fragments: mem::take(&mut fragments),
7629 invisibles: std::mem::take(&mut invisibles),
7630 font_size,
7631 });
7632
7633 line.clear();
7634 styles.clear();
7635 row += 1;
7636 line_exceeded_max_len = false;
7637 non_whitespace_added = false;
7638 if row == max_line_count {
7639 return layouts;
7640 }
7641 }
7642
7643 if !line_chunk.is_empty() && !line_exceeded_max_len {
7644 let text_style = if let Some(style) = highlighted_chunk.style {
7645 Cow::Owned(text_style.clone().highlight(style))
7646 } else {
7647 Cow::Borrowed(text_style)
7648 };
7649
7650 if line.len() + line_chunk.len() > max_line_len {
7651 let mut chunk_len = max_line_len - line.len();
7652 while !line_chunk.is_char_boundary(chunk_len) {
7653 chunk_len -= 1;
7654 }
7655 line_chunk = &line_chunk[..chunk_len];
7656 line_exceeded_max_len = true;
7657 }
7658
7659 styles.push(TextRun {
7660 len: line_chunk.len(),
7661 font: text_style.font(),
7662 color: text_style.color,
7663 background_color: text_style.background_color,
7664 underline: text_style.underline,
7665 strikethrough: text_style.strikethrough,
7666 });
7667
7668 if editor_mode.is_full() && !highlighted_chunk.is_inlay {
7669 // Line wrap pads its contents with fake whitespaces,
7670 // avoid printing them
7671 let is_soft_wrapped = is_row_soft_wrapped(row);
7672 if highlighted_chunk.is_tab {
7673 if non_whitespace_added || !is_soft_wrapped {
7674 invisibles.push(Invisible::Tab {
7675 line_start_offset: line.len(),
7676 line_end_offset: line.len() + line_chunk.len(),
7677 });
7678 }
7679 } else {
7680 invisibles.extend(line_chunk.char_indices().filter_map(
7681 |(index, c)| {
7682 let is_whitespace = c.is_whitespace();
7683 non_whitespace_added |= !is_whitespace;
7684 if is_whitespace
7685 && (non_whitespace_added || !is_soft_wrapped)
7686 {
7687 Some(Invisible::Whitespace {
7688 line_offset: line.len() + index,
7689 })
7690 } else {
7691 None
7692 }
7693 },
7694 ))
7695 }
7696 }
7697
7698 line.push_str(line_chunk);
7699 }
7700 }
7701 }
7702 }
7703
7704 layouts
7705 }
7706
7707 /// Takes text runs and non-overlapping left-to-right background ranges with color.
7708 /// Returns new text runs with adjusted contrast as per background ranges.
7709 fn split_runs_by_bg_segments(
7710 text_runs: &[TextRun],
7711 bg_segments: &[(Range<DisplayPoint>, Hsla)],
7712 min_contrast: f32,
7713 ) -> Vec<TextRun> {
7714 let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
7715 let mut line_col = 0usize;
7716 let mut segment_ix = 0usize;
7717
7718 for text_run in text_runs.iter() {
7719 let run_start_col = line_col;
7720 let run_end_col = run_start_col + text_run.len;
7721 while segment_ix < bg_segments.len()
7722 && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
7723 {
7724 segment_ix += 1;
7725 }
7726 let mut cursor_col = run_start_col;
7727 let mut local_segment_ix = segment_ix;
7728 while local_segment_ix < bg_segments.len() {
7729 let (range, segment_color) = &bg_segments[local_segment_ix];
7730 let segment_start_col = range.start.column() as usize;
7731 let segment_end_col = range.end.column() as usize;
7732 if segment_start_col >= run_end_col {
7733 break;
7734 }
7735 if segment_start_col > cursor_col {
7736 let span_len = segment_start_col - cursor_col;
7737 output_runs.push(TextRun {
7738 len: span_len,
7739 font: text_run.font.clone(),
7740 color: text_run.color,
7741 background_color: text_run.background_color,
7742 underline: text_run.underline,
7743 strikethrough: text_run.strikethrough,
7744 });
7745 cursor_col = segment_start_col;
7746 }
7747 let segment_slice_end_col = segment_end_col.min(run_end_col);
7748 if segment_slice_end_col > cursor_col {
7749 let new_text_color =
7750 ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
7751 output_runs.push(TextRun {
7752 len: segment_slice_end_col - cursor_col,
7753 font: text_run.font.clone(),
7754 color: new_text_color,
7755 background_color: text_run.background_color,
7756 underline: text_run.underline,
7757 strikethrough: text_run.strikethrough,
7758 });
7759 cursor_col = segment_slice_end_col;
7760 }
7761 if segment_end_col >= run_end_col {
7762 break;
7763 }
7764 local_segment_ix += 1;
7765 }
7766 if cursor_col < run_end_col {
7767 output_runs.push(TextRun {
7768 len: run_end_col - cursor_col,
7769 font: text_run.font.clone(),
7770 color: text_run.color,
7771 background_color: text_run.background_color,
7772 underline: text_run.underline,
7773 strikethrough: text_run.strikethrough,
7774 });
7775 }
7776 line_col = run_end_col;
7777 segment_ix = local_segment_ix;
7778 }
7779 output_runs
7780 }
7781
7782 fn prepaint(
7783 &mut self,
7784 line_height: Pixels,
7785 scroll_pixel_position: gpui::Point<Pixels>,
7786 row: DisplayRow,
7787 content_origin: gpui::Point<Pixels>,
7788 line_elements: &mut SmallVec<[AnyElement; 1]>,
7789 window: &mut Window,
7790 cx: &mut App,
7791 ) {
7792 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
7793 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
7794 for fragment in &mut self.fragments {
7795 match fragment {
7796 LineFragment::Text(line) => {
7797 fragment_origin.x += line.width;
7798 }
7799 LineFragment::Element { element, size, .. } => {
7800 let mut element = element
7801 .take()
7802 .expect("you can't prepaint LineWithInvisibles twice");
7803
7804 // Center the element vertically within the line.
7805 let mut element_origin = fragment_origin;
7806 element_origin.y += (line_height - size.height) / 2.;
7807 element.prepaint_at(element_origin, window, cx);
7808 line_elements.push(element);
7809
7810 fragment_origin.x += size.width;
7811 }
7812 }
7813 }
7814 }
7815
7816 fn draw(
7817 &self,
7818 layout: &EditorLayout,
7819 row: DisplayRow,
7820 content_origin: gpui::Point<Pixels>,
7821 whitespace_setting: ShowWhitespaceSetting,
7822 selection_ranges: &[Range<DisplayPoint>],
7823 window: &mut Window,
7824 cx: &mut App,
7825 ) {
7826 let line_height = layout.position_map.line_height;
7827 let line_y = line_height
7828 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7829
7830 let mut fragment_origin =
7831 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7832
7833 for fragment in &self.fragments {
7834 match fragment {
7835 LineFragment::Text(line) => {
7836 line.paint(fragment_origin, line_height, window, cx)
7837 .log_err();
7838 fragment_origin.x += line.width;
7839 }
7840 LineFragment::Element { size, .. } => {
7841 fragment_origin.x += size.width;
7842 }
7843 }
7844 }
7845
7846 self.draw_invisibles(
7847 selection_ranges,
7848 layout,
7849 content_origin,
7850 line_y,
7851 row,
7852 line_height,
7853 whitespace_setting,
7854 window,
7855 cx,
7856 );
7857 }
7858
7859 fn draw_background(
7860 &self,
7861 layout: &EditorLayout,
7862 row: DisplayRow,
7863 content_origin: gpui::Point<Pixels>,
7864 window: &mut Window,
7865 cx: &mut App,
7866 ) {
7867 let line_height = layout.position_map.line_height;
7868 let line_y = line_height
7869 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7870
7871 let mut fragment_origin =
7872 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7873
7874 for fragment in &self.fragments {
7875 match fragment {
7876 LineFragment::Text(line) => {
7877 line.paint_background(fragment_origin, line_height, window, cx)
7878 .log_err();
7879 fragment_origin.x += line.width;
7880 }
7881 LineFragment::Element { size, .. } => {
7882 fragment_origin.x += size.width;
7883 }
7884 }
7885 }
7886 }
7887
7888 fn draw_invisibles(
7889 &self,
7890 selection_ranges: &[Range<DisplayPoint>],
7891 layout: &EditorLayout,
7892 content_origin: gpui::Point<Pixels>,
7893 line_y: Pixels,
7894 row: DisplayRow,
7895 line_height: Pixels,
7896 whitespace_setting: ShowWhitespaceSetting,
7897 window: &mut Window,
7898 cx: &mut App,
7899 ) {
7900 let extract_whitespace_info = |invisible: &Invisible| {
7901 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
7902 Invisible::Tab {
7903 line_start_offset,
7904 line_end_offset,
7905 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
7906 Invisible::Whitespace { line_offset } => {
7907 (*line_offset, line_offset + 1, &layout.space_invisible)
7908 }
7909 };
7910
7911 let x_offset = self.x_for_index(token_offset);
7912 let invisible_offset =
7913 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
7914 let origin = content_origin
7915 + gpui::point(
7916 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
7917 line_y,
7918 );
7919
7920 (
7921 [token_offset, token_end_offset],
7922 Box::new(move |window: &mut Window, cx: &mut App| {
7923 invisible_symbol
7924 .paint(origin, line_height, window, cx)
7925 .log_err();
7926 }),
7927 )
7928 };
7929
7930 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
7931 match whitespace_setting {
7932 ShowWhitespaceSetting::None => (),
7933 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
7934 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
7935 let invisible_point = DisplayPoint::new(row, start as u32);
7936 if !selection_ranges
7937 .iter()
7938 .any(|region| region.start <= invisible_point && invisible_point < region.end)
7939 {
7940 return;
7941 }
7942
7943 paint(window, cx);
7944 }),
7945
7946 ShowWhitespaceSetting::Trailing => {
7947 let mut previous_start = self.len;
7948 for ([start, end], paint) in invisible_iter.rev() {
7949 if previous_start != end {
7950 break;
7951 }
7952 previous_start = start;
7953 paint(window, cx);
7954 }
7955 }
7956
7957 // For a whitespace to be on a boundary, any of the following conditions need to be met:
7958 // - It is a tab
7959 // - It is adjacent to an edge (start or end)
7960 // - It is adjacent to a whitespace (left or right)
7961 ShowWhitespaceSetting::Boundary => {
7962 // 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
7963 // the above cases.
7964 // Note: We zip in the original `invisibles` to check for tab equality
7965 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
7966 for (([start, end], paint), invisible) in
7967 invisible_iter.zip_eq(self.invisibles.iter())
7968 {
7969 let should_render = match (&last_seen, invisible) {
7970 (_, Invisible::Tab { .. }) => true,
7971 (Some((_, last_end, _)), _) => *last_end == start,
7972 _ => false,
7973 };
7974
7975 if should_render || start == 0 || end == self.len {
7976 paint(window, cx);
7977
7978 // Since we are scanning from the left, we will skip over the first available whitespace that is part
7979 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
7980 if let Some((should_render_last, last_end, paint_last)) = last_seen {
7981 // Note that we need to make sure that the last one is actually adjacent
7982 if !should_render_last && last_end == start {
7983 paint_last(window, cx);
7984 }
7985 }
7986 }
7987
7988 // Manually render anything within a selection
7989 let invisible_point = DisplayPoint::new(row, start as u32);
7990 if selection_ranges.iter().any(|region| {
7991 region.start <= invisible_point && invisible_point < region.end
7992 }) {
7993 paint(window, cx);
7994 }
7995
7996 last_seen = Some((should_render, end, paint));
7997 }
7998 }
7999 }
8000 }
8001
8002 pub fn x_for_index(&self, index: usize) -> Pixels {
8003 let mut fragment_start_x = Pixels::ZERO;
8004 let mut fragment_start_index = 0;
8005
8006 for fragment in &self.fragments {
8007 match fragment {
8008 LineFragment::Text(shaped_line) => {
8009 let fragment_end_index = fragment_start_index + shaped_line.len;
8010 if index < fragment_end_index {
8011 return fragment_start_x
8012 + shaped_line.x_for_index(index - fragment_start_index);
8013 }
8014 fragment_start_x += shaped_line.width;
8015 fragment_start_index = fragment_end_index;
8016 }
8017 LineFragment::Element { len, size, .. } => {
8018 let fragment_end_index = fragment_start_index + len;
8019 if index < fragment_end_index {
8020 return fragment_start_x;
8021 }
8022 fragment_start_x += size.width;
8023 fragment_start_index = fragment_end_index;
8024 }
8025 }
8026 }
8027
8028 fragment_start_x
8029 }
8030
8031 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
8032 let mut fragment_start_x = Pixels::ZERO;
8033 let mut fragment_start_index = 0;
8034
8035 for fragment in &self.fragments {
8036 match fragment {
8037 LineFragment::Text(shaped_line) => {
8038 let fragment_end_x = fragment_start_x + shaped_line.width;
8039 if x < fragment_end_x {
8040 return Some(
8041 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
8042 );
8043 }
8044 fragment_start_x = fragment_end_x;
8045 fragment_start_index += shaped_line.len;
8046 }
8047 LineFragment::Element { len, size, .. } => {
8048 let fragment_end_x = fragment_start_x + size.width;
8049 if x < fragment_end_x {
8050 return Some(fragment_start_index);
8051 }
8052 fragment_start_index += len;
8053 fragment_start_x = fragment_end_x;
8054 }
8055 }
8056 }
8057
8058 None
8059 }
8060
8061 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
8062 let mut fragment_start_index = 0;
8063
8064 for fragment in &self.fragments {
8065 match fragment {
8066 LineFragment::Text(shaped_line) => {
8067 let fragment_end_index = fragment_start_index + shaped_line.len;
8068 if index < fragment_end_index {
8069 return shaped_line.font_id_for_index(index - fragment_start_index);
8070 }
8071 fragment_start_index = fragment_end_index;
8072 }
8073 LineFragment::Element { len, .. } => {
8074 let fragment_end_index = fragment_start_index + len;
8075 if index < fragment_end_index {
8076 return None;
8077 }
8078 fragment_start_index = fragment_end_index;
8079 }
8080 }
8081 }
8082
8083 None
8084 }
8085}
8086
8087#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8088enum Invisible {
8089 /// A tab character
8090 ///
8091 /// A tab character is internally represented by spaces (configured by the user's tab width)
8092 /// aligned to the nearest column, so it's necessary to store the start and end offset for
8093 /// adjacency checks.
8094 Tab {
8095 line_start_offset: usize,
8096 line_end_offset: usize,
8097 },
8098 Whitespace {
8099 line_offset: usize,
8100 },
8101}
8102
8103impl EditorElement {
8104 /// Returns the rem size to use when rendering the [`EditorElement`].
8105 ///
8106 /// This allows UI elements to scale based on the `buffer_font_size`.
8107 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
8108 match self.editor.read(cx).mode {
8109 EditorMode::Full {
8110 scale_ui_elements_with_buffer_font_size: true,
8111 ..
8112 }
8113 | EditorMode::Minimap { .. } => {
8114 let buffer_font_size = self.style.text.font_size;
8115 match buffer_font_size {
8116 AbsoluteLength::Pixels(pixels) => {
8117 let rem_size_scale = {
8118 // Our default UI font size is 14px on a 16px base scale.
8119 // This means the default UI font size is 0.875rems.
8120 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
8121
8122 // We then determine the delta between a single rem and the default font
8123 // size scale.
8124 let default_font_size_delta = 1. - default_font_size_scale;
8125
8126 // Finally, we add this delta to 1rem to get the scale factor that
8127 // should be used to scale up the UI.
8128 1. + default_font_size_delta
8129 };
8130
8131 Some(pixels * rem_size_scale)
8132 }
8133 AbsoluteLength::Rems(rems) => {
8134 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
8135 }
8136 }
8137 }
8138 // We currently use single-line and auto-height editors in UI contexts,
8139 // so we don't want to scale everything with the buffer font size, as it
8140 // ends up looking off.
8141 _ => None,
8142 }
8143 }
8144
8145 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
8146 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
8147 parent.upgrade()
8148 } else {
8149 Some(self.editor.clone())
8150 }
8151 }
8152}
8153
8154impl Element for EditorElement {
8155 type RequestLayoutState = ();
8156 type PrepaintState = EditorLayout;
8157
8158 fn id(&self) -> Option<ElementId> {
8159 None
8160 }
8161
8162 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
8163 None
8164 }
8165
8166 fn request_layout(
8167 &mut self,
8168 _: Option<&GlobalElementId>,
8169 _inspector_id: Option<&gpui::InspectorElementId>,
8170 window: &mut Window,
8171 cx: &mut App,
8172 ) -> (gpui::LayoutId, ()) {
8173 let rem_size = self.rem_size(cx);
8174 window.with_rem_size(rem_size, |window| {
8175 self.editor.update(cx, |editor, cx| {
8176 editor.set_style(self.style.clone(), window, cx);
8177
8178 let layout_id = match editor.mode {
8179 EditorMode::SingleLine => {
8180 let rem_size = window.rem_size();
8181 let height = self.style.text.line_height_in_pixels(rem_size);
8182 let mut style = Style::default();
8183 style.size.height = height.into();
8184 style.size.width = relative(1.).into();
8185 window.request_layout(style, None, cx)
8186 }
8187 EditorMode::AutoHeight {
8188 min_lines,
8189 max_lines,
8190 } => {
8191 let editor_handle = cx.entity();
8192 let max_line_number_width =
8193 self.max_line_number_width(&editor.snapshot(window, cx), window);
8194 window.request_measured_layout(
8195 Style::default(),
8196 move |known_dimensions, available_space, window, cx| {
8197 editor_handle
8198 .update(cx, |editor, cx| {
8199 compute_auto_height_layout(
8200 editor,
8201 min_lines,
8202 max_lines,
8203 max_line_number_width,
8204 known_dimensions,
8205 available_space.width,
8206 window,
8207 cx,
8208 )
8209 })
8210 .unwrap_or_default()
8211 },
8212 )
8213 }
8214 EditorMode::Minimap { .. } => {
8215 let mut style = Style::default();
8216 style.size.width = relative(1.).into();
8217 style.size.height = relative(1.).into();
8218 window.request_layout(style, None, cx)
8219 }
8220 EditorMode::Full {
8221 sized_by_content, ..
8222 } => {
8223 let mut style = Style::default();
8224 style.size.width = relative(1.).into();
8225 if sized_by_content {
8226 let snapshot = editor.snapshot(window, cx);
8227 let line_height =
8228 self.style.text.line_height_in_pixels(window.rem_size());
8229 let scroll_height =
8230 (snapshot.max_point().row().next_row().0 as f32) * line_height;
8231 style.size.height = scroll_height.into();
8232 } else {
8233 style.size.height = relative(1.).into();
8234 }
8235 window.request_layout(style, None, cx)
8236 }
8237 };
8238
8239 (layout_id, ())
8240 })
8241 })
8242 }
8243
8244 fn prepaint(
8245 &mut self,
8246 _: Option<&GlobalElementId>,
8247 _inspector_id: Option<&gpui::InspectorElementId>,
8248 bounds: Bounds<Pixels>,
8249 _: &mut Self::RequestLayoutState,
8250 window: &mut Window,
8251 cx: &mut App,
8252 ) -> Self::PrepaintState {
8253 let text_style = TextStyleRefinement {
8254 font_size: Some(self.style.text.font_size),
8255 line_height: Some(self.style.text.line_height),
8256 ..Default::default()
8257 };
8258
8259 let is_minimap = self.editor.read(cx).mode.is_minimap();
8260
8261 if !is_minimap {
8262 let focus_handle = self.editor.focus_handle(cx);
8263 window.set_view_id(self.editor.entity_id());
8264 window.set_focus_handle(&focus_handle, cx);
8265 }
8266
8267 let rem_size = self.rem_size(cx);
8268 window.with_rem_size(rem_size, |window| {
8269 window.with_text_style(Some(text_style), |window| {
8270 window.with_content_mask(Some(ContentMask { bounds }), |window| {
8271 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
8272 (editor.snapshot(window, cx), editor.read_only(cx))
8273 });
8274 let style = self.style.clone();
8275
8276 let rem_size = window.rem_size();
8277 let font_id = window.text_system().resolve_font(&style.text.font());
8278 let font_size = style.text.font_size.to_pixels(rem_size);
8279 let line_height = style.text.line_height_in_pixels(rem_size);
8280 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8281 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
8282 let glyph_grid_cell = size(em_advance, line_height);
8283
8284 let gutter_dimensions = snapshot
8285 .gutter_dimensions(
8286 font_id,
8287 font_size,
8288 self.max_line_number_width(&snapshot, window),
8289 cx,
8290 )
8291 .or_else(|| {
8292 self.editor.read(cx).offset_content.then(|| {
8293 GutterDimensions::default_with_margin(font_id, font_size, cx)
8294 })
8295 })
8296 .unwrap_or_default();
8297 let text_width = bounds.size.width - gutter_dimensions.width;
8298
8299 let settings = EditorSettings::get_global(cx);
8300 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
8301 let vertical_scrollbar_width = (scrollbars_shown
8302 && settings.scrollbar.axes.vertical
8303 && self.editor.read(cx).show_scrollbars.vertical)
8304 .then_some(style.scrollbar_width)
8305 .unwrap_or_default();
8306 let minimap_width = self
8307 .get_minimap_width(
8308 &settings.minimap,
8309 scrollbars_shown,
8310 text_width,
8311 em_width,
8312 font_size,
8313 rem_size,
8314 cx,
8315 )
8316 .unwrap_or_default();
8317
8318 let right_margin = minimap_width + vertical_scrollbar_width;
8319
8320 let editor_width =
8321 text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
8322 let editor_margins = EditorMargins {
8323 gutter: gutter_dimensions,
8324 right: right_margin,
8325 };
8326
8327 snapshot = self.editor.update(cx, |editor, cx| {
8328 editor.last_bounds = Some(bounds);
8329 editor.gutter_dimensions = gutter_dimensions;
8330 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
8331 editor.set_visible_column_count(editor_width / em_advance);
8332
8333 if matches!(
8334 editor.mode,
8335 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
8336 ) {
8337 snapshot
8338 } else {
8339 let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
8340 let wrap_width = match editor.soft_wrap_mode(cx) {
8341 SoftWrap::GitDiff => None,
8342 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
8343 SoftWrap::EditorWidth => Some(editor_width),
8344 SoftWrap::Column(column) => Some(wrap_width_for(column)),
8345 SoftWrap::Bounded(column) => {
8346 Some(editor_width.min(wrap_width_for(column)))
8347 }
8348 };
8349
8350 if editor.set_wrap_width(wrap_width, cx) {
8351 editor.snapshot(window, cx)
8352 } else {
8353 snapshot
8354 }
8355 }
8356 });
8357
8358 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
8359 let gutter_hitbox = window.insert_hitbox(
8360 gutter_bounds(bounds, gutter_dimensions),
8361 HitboxBehavior::Normal,
8362 );
8363 let text_hitbox = window.insert_hitbox(
8364 Bounds {
8365 origin: gutter_hitbox.top_right(),
8366 size: size(text_width, bounds.size.height),
8367 },
8368 HitboxBehavior::Normal,
8369 );
8370
8371 // Offset the content_bounds from the text_bounds by the gutter margin (which
8372 // is roughly half a character wide) to make hit testing work more like how we want.
8373 let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
8374 let content_origin = text_hitbox.origin + content_offset;
8375
8376 let height_in_lines = bounds.size.height / line_height;
8377 let max_row = snapshot.max_point().row().as_f32();
8378
8379 // The max scroll position for the top of the window
8380 let max_scroll_top = if matches!(
8381 snapshot.mode,
8382 EditorMode::SingleLine
8383 | EditorMode::AutoHeight { .. }
8384 | EditorMode::Full {
8385 sized_by_content: true,
8386 ..
8387 }
8388 ) {
8389 (max_row - height_in_lines + 1.).max(0.)
8390 } else {
8391 let settings = EditorSettings::get_global(cx);
8392 match settings.scroll_beyond_last_line {
8393 ScrollBeyondLastLine::OnePage => max_row,
8394 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
8395 ScrollBeyondLastLine::VerticalScrollMargin => {
8396 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
8397 .max(0.)
8398 }
8399 }
8400 };
8401
8402 let (
8403 autoscroll_request,
8404 autoscroll_containing_element,
8405 needs_horizontal_autoscroll,
8406 ) = self.editor.update(cx, |editor, cx| {
8407 let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
8408
8409 let autoscroll_containing_element =
8410 autoscroll_request.is_some() || editor.has_pending_selection();
8411
8412 let (needs_horizontal_autoscroll, was_scrolled) = editor
8413 .autoscroll_vertically(
8414 bounds,
8415 line_height,
8416 max_scroll_top,
8417 autoscroll_request,
8418 window,
8419 cx,
8420 );
8421 if was_scrolled.0 {
8422 snapshot = editor.snapshot(window, cx);
8423 }
8424 (
8425 autoscroll_request,
8426 autoscroll_containing_element,
8427 needs_horizontal_autoscroll,
8428 )
8429 });
8430
8431 let mut scroll_position = snapshot.scroll_position();
8432 // The scroll position is a fractional point, the whole number of which represents
8433 // the top of the window in terms of display rows.
8434 let start_row = DisplayRow(scroll_position.y as u32);
8435 let max_row = snapshot.max_point().row();
8436 let end_row = cmp::min(
8437 (scroll_position.y + height_in_lines).ceil() as u32,
8438 max_row.next_row().0,
8439 );
8440 let end_row = DisplayRow(end_row);
8441
8442 let row_infos = snapshot
8443 .row_infos(start_row)
8444 .take((start_row..end_row).len())
8445 .collect::<Vec<RowInfo>>();
8446 let is_row_soft_wrapped = |row: usize| {
8447 row_infos
8448 .get(row)
8449 .is_none_or(|info| info.buffer_row.is_none())
8450 };
8451
8452 let start_anchor = if start_row == Default::default() {
8453 Anchor::min()
8454 } else {
8455 snapshot.buffer_snapshot.anchor_before(
8456 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
8457 )
8458 };
8459 let end_anchor = if end_row > max_row {
8460 Anchor::max()
8461 } else {
8462 snapshot.buffer_snapshot.anchor_before(
8463 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
8464 )
8465 };
8466
8467 let mut highlighted_rows = self
8468 .editor
8469 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
8470
8471 let is_light = cx.theme().appearance().is_light();
8472
8473 for (ix, row_info) in row_infos.iter().enumerate() {
8474 let Some(diff_status) = row_info.diff_status else {
8475 continue;
8476 };
8477
8478 let background_color = match diff_status.kind {
8479 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
8480 DiffHunkStatusKind::Deleted => {
8481 cx.theme().colors().version_control_deleted
8482 }
8483 DiffHunkStatusKind::Modified => {
8484 debug_panic!("modified diff status for row info");
8485 continue;
8486 }
8487 };
8488
8489 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
8490
8491 let hollow_highlight = LineHighlight {
8492 background: (background_color.opacity(if is_light {
8493 0.08
8494 } else {
8495 0.06
8496 }))
8497 .into(),
8498 border: Some(if is_light {
8499 background_color.opacity(0.48)
8500 } else {
8501 background_color.opacity(0.36)
8502 }),
8503 include_gutter: true,
8504 type_id: None,
8505 };
8506
8507 let filled_highlight = LineHighlight {
8508 background: solid_background(background_color.opacity(hunk_opacity)),
8509 border: None,
8510 include_gutter: true,
8511 type_id: None,
8512 };
8513
8514 let background = if Self::diff_hunk_hollow(diff_status, cx) {
8515 hollow_highlight
8516 } else {
8517 filled_highlight
8518 };
8519
8520 highlighted_rows
8521 .entry(start_row + DisplayRow(ix as u32))
8522 .or_insert(background);
8523 }
8524
8525 let highlighted_ranges = self
8526 .editor_with_selections(cx)
8527 .map(|editor| {
8528 editor.read(cx).background_highlights_in_range(
8529 start_anchor..end_anchor,
8530 &snapshot.display_snapshot,
8531 cx.theme(),
8532 )
8533 })
8534 .unwrap_or_default();
8535 let highlighted_gutter_ranges =
8536 self.editor.read(cx).gutter_highlights_in_range(
8537 start_anchor..end_anchor,
8538 &snapshot.display_snapshot,
8539 cx,
8540 );
8541
8542 let document_colors = self
8543 .editor
8544 .read(cx)
8545 .colors
8546 .as_ref()
8547 .map(|colors| colors.editor_display_highlights(&snapshot));
8548 let redacted_ranges = self.editor.read(cx).redacted_ranges(
8549 start_anchor..end_anchor,
8550 &snapshot.display_snapshot,
8551 cx,
8552 );
8553
8554 let (local_selections, selected_buffer_ids): (
8555 Vec<Selection<Point>>,
8556 Vec<BufferId>,
8557 ) = self
8558 .editor_with_selections(cx)
8559 .map(|editor| {
8560 editor.update(cx, |editor, cx| {
8561 let all_selections = editor.selections.all::<Point>(cx);
8562 let selected_buffer_ids = if editor.is_singleton(cx) {
8563 Vec::new()
8564 } else {
8565 let mut selected_buffer_ids =
8566 Vec::with_capacity(all_selections.len());
8567
8568 for selection in all_selections {
8569 for buffer_id in snapshot
8570 .buffer_snapshot
8571 .buffer_ids_for_range(selection.range())
8572 {
8573 if selected_buffer_ids.last() != Some(&buffer_id) {
8574 selected_buffer_ids.push(buffer_id);
8575 }
8576 }
8577 }
8578
8579 selected_buffer_ids
8580 };
8581
8582 let mut selections = editor
8583 .selections
8584 .disjoint_in_range(start_anchor..end_anchor, cx);
8585 selections.extend(editor.selections.pending(cx));
8586
8587 (selections, selected_buffer_ids)
8588 })
8589 })
8590 .unwrap_or_default();
8591
8592 let (selections, mut active_rows, newest_selection_head) = self
8593 .layout_selections(
8594 start_anchor,
8595 end_anchor,
8596 &local_selections,
8597 &snapshot,
8598 start_row,
8599 end_row,
8600 window,
8601 cx,
8602 );
8603 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
8604 editor.active_breakpoints(start_row..end_row, window, cx)
8605 });
8606 for (display_row, (_, bp, state)) in &breakpoint_rows {
8607 if bp.is_enabled() && state.is_none_or(|s| s.verified) {
8608 active_rows.entry(*display_row).or_default().breakpoint = true;
8609 }
8610 }
8611
8612 let line_numbers = self.layout_line_numbers(
8613 Some(&gutter_hitbox),
8614 gutter_dimensions,
8615 line_height,
8616 scroll_position,
8617 start_row..end_row,
8618 &row_infos,
8619 &active_rows,
8620 newest_selection_head,
8621 &snapshot,
8622 window,
8623 cx,
8624 );
8625
8626 // We add the gutter breakpoint indicator to breakpoint_rows after painting
8627 // line numbers so we don't paint a line number debug accent color if a user
8628 // has their mouse over that line when a breakpoint isn't there
8629 self.editor.update(cx, |editor, _| {
8630 if let Some(phantom_breakpoint) = &mut editor
8631 .gutter_breakpoint_indicator
8632 .0
8633 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
8634 {
8635 // Is there a non-phantom breakpoint on this line?
8636 phantom_breakpoint.collides_with_existing_breakpoint = true;
8637 breakpoint_rows
8638 .entry(phantom_breakpoint.display_row)
8639 .or_insert_with(|| {
8640 let position = snapshot.display_point_to_anchor(
8641 DisplayPoint::new(phantom_breakpoint.display_row, 0),
8642 Bias::Right,
8643 );
8644 let breakpoint = Breakpoint::new_standard();
8645 phantom_breakpoint.collides_with_existing_breakpoint = false;
8646 (position, breakpoint, None)
8647 });
8648 }
8649 });
8650
8651 let mut expand_toggles =
8652 window.with_element_namespace("expand_toggles", |window| {
8653 self.layout_expand_toggles(
8654 &gutter_hitbox,
8655 gutter_dimensions,
8656 em_width,
8657 line_height,
8658 scroll_position,
8659 &row_infos,
8660 window,
8661 cx,
8662 )
8663 });
8664
8665 let mut crease_toggles =
8666 window.with_element_namespace("crease_toggles", |window| {
8667 self.layout_crease_toggles(
8668 start_row..end_row,
8669 &row_infos,
8670 &active_rows,
8671 &snapshot,
8672 window,
8673 cx,
8674 )
8675 });
8676 let crease_trailers =
8677 window.with_element_namespace("crease_trailers", |window| {
8678 self.layout_crease_trailers(
8679 row_infos.iter().copied(),
8680 &snapshot,
8681 window,
8682 cx,
8683 )
8684 });
8685
8686 let display_hunks = self.layout_gutter_diff_hunks(
8687 line_height,
8688 &gutter_hitbox,
8689 start_row..end_row,
8690 &snapshot,
8691 window,
8692 cx,
8693 );
8694
8695 let bg_segments_per_row = Self::bg_segments_per_row(
8696 start_row..end_row,
8697 &selections,
8698 &highlighted_ranges,
8699 self.style.background,
8700 );
8701
8702 let mut line_layouts = Self::layout_lines(
8703 start_row..end_row,
8704 &snapshot,
8705 &self.style,
8706 editor_width,
8707 is_row_soft_wrapped,
8708 &bg_segments_per_row,
8709 window,
8710 cx,
8711 );
8712 let new_renderer_widths = (!is_minimap).then(|| {
8713 line_layouts
8714 .iter()
8715 .flat_map(|layout| &layout.fragments)
8716 .filter_map(|fragment| {
8717 if let LineFragment::Element { id, size, .. } = fragment {
8718 Some((*id, size.width))
8719 } else {
8720 None
8721 }
8722 })
8723 });
8724 if new_renderer_widths.is_some_and(|new_renderer_widths| {
8725 self.editor.update(cx, |editor, cx| {
8726 editor.update_renderer_widths(new_renderer_widths, cx)
8727 })
8728 }) {
8729 // If the fold widths have changed, we need to prepaint
8730 // the element again to account for any changes in
8731 // wrapping.
8732 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8733 }
8734
8735 let longest_line_blame_width = self
8736 .editor
8737 .update(cx, |editor, cx| {
8738 if !editor.show_git_blame_inline {
8739 return None;
8740 }
8741 let blame = editor.blame.as_ref()?;
8742 let blame_entry = blame
8743 .update(cx, |blame, cx| {
8744 let row_infos =
8745 snapshot.row_infos(snapshot.longest_row()).next()?;
8746 blame.blame_for_rows(&[row_infos], cx).next()
8747 })
8748 .flatten()?;
8749 let mut element = render_inline_blame_entry(blame_entry, &style, cx)?;
8750 let inline_blame_padding = ProjectSettings::get_global(cx)
8751 .git
8752 .inline_blame
8753 .unwrap_or_default()
8754 .padding
8755 as f32
8756 * em_advance;
8757 Some(
8758 element
8759 .layout_as_root(AvailableSpace::min_size(), window, cx)
8760 .width
8761 + inline_blame_padding,
8762 )
8763 })
8764 .unwrap_or(Pixels::ZERO);
8765
8766 let longest_line_width = layout_line(
8767 snapshot.longest_row(),
8768 &snapshot,
8769 &style,
8770 editor_width,
8771 is_row_soft_wrapped,
8772 window,
8773 cx,
8774 )
8775 .width;
8776
8777 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
8778 text_hitbox.bounds,
8779 glyph_grid_cell,
8780 size(longest_line_width, max_row.as_f32() * line_height),
8781 longest_line_blame_width,
8782 EditorSettings::get_global(cx),
8783 );
8784
8785 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
8786
8787 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
8788 snapshot.sticky_header_excerpt(scroll_position.y)
8789 } else {
8790 None
8791 };
8792 let sticky_header_excerpt_id =
8793 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
8794
8795 let blocks = (!is_minimap)
8796 .then(|| {
8797 window.with_element_namespace("blocks", |window| {
8798 self.render_blocks(
8799 start_row..end_row,
8800 &snapshot,
8801 &hitbox,
8802 &text_hitbox,
8803 editor_width,
8804 &mut scroll_width,
8805 &editor_margins,
8806 em_width,
8807 gutter_dimensions.full_width(),
8808 line_height,
8809 &mut line_layouts,
8810 &local_selections,
8811 &selected_buffer_ids,
8812 is_row_soft_wrapped,
8813 sticky_header_excerpt_id,
8814 window,
8815 cx,
8816 )
8817 })
8818 })
8819 .unwrap_or_else(|| Ok((Vec::default(), HashMap::default())));
8820 let (mut blocks, row_block_types) = match blocks {
8821 Ok(blocks) => blocks,
8822 Err(resized_blocks) => {
8823 self.editor.update(cx, |editor, cx| {
8824 editor.resize_blocks(
8825 resized_blocks,
8826 autoscroll_request.map(|(autoscroll, _)| autoscroll),
8827 cx,
8828 )
8829 });
8830 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8831 }
8832 };
8833
8834 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
8835 window.with_element_namespace("blocks", |window| {
8836 self.layout_sticky_buffer_header(
8837 sticky_header_excerpt,
8838 scroll_position.y,
8839 line_height,
8840 right_margin,
8841 &snapshot,
8842 &hitbox,
8843 &selected_buffer_ids,
8844 &blocks,
8845 window,
8846 cx,
8847 )
8848 })
8849 });
8850
8851 let start_buffer_row =
8852 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
8853 let end_buffer_row =
8854 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
8855
8856 let scroll_max = point(
8857 ((scroll_width - editor_width) / em_advance).max(0.0),
8858 max_scroll_top,
8859 );
8860
8861 self.editor.update(cx, |editor, cx| {
8862 if editor.scroll_manager.clamp_scroll_left(scroll_max.x) {
8863 scroll_position.x = scroll_position.x.min(scroll_max.x);
8864 }
8865
8866 if needs_horizontal_autoscroll.0
8867 && let Some(new_scroll_position) = editor.autoscroll_horizontally(
8868 start_row,
8869 editor_width,
8870 scroll_width,
8871 em_advance,
8872 &line_layouts,
8873 autoscroll_request,
8874 window,
8875 cx,
8876 )
8877 {
8878 scroll_position = new_scroll_position;
8879 }
8880 });
8881
8882 let scroll_pixel_position = point(
8883 scroll_position.x * em_advance,
8884 scroll_position.y * line_height,
8885 );
8886 let indent_guides = self.layout_indent_guides(
8887 content_origin,
8888 text_hitbox.origin,
8889 start_buffer_row..end_buffer_row,
8890 scroll_pixel_position,
8891 line_height,
8892 &snapshot,
8893 window,
8894 cx,
8895 );
8896
8897 let crease_trailers =
8898 window.with_element_namespace("crease_trailers", |window| {
8899 self.prepaint_crease_trailers(
8900 crease_trailers,
8901 &line_layouts,
8902 line_height,
8903 content_origin,
8904 scroll_pixel_position,
8905 em_width,
8906 window,
8907 cx,
8908 )
8909 });
8910
8911 let (edit_prediction_popover, edit_prediction_popover_origin) = self
8912 .editor
8913 .update(cx, |editor, cx| {
8914 editor.render_edit_prediction_popover(
8915 &text_hitbox.bounds,
8916 content_origin,
8917 right_margin,
8918 &snapshot,
8919 start_row..end_row,
8920 scroll_position.y,
8921 scroll_position.y + height_in_lines,
8922 &line_layouts,
8923 line_height,
8924 scroll_pixel_position,
8925 newest_selection_head,
8926 editor_width,
8927 &style,
8928 window,
8929 cx,
8930 )
8931 })
8932 .unzip();
8933
8934 let mut inline_diagnostics = self.layout_inline_diagnostics(
8935 &line_layouts,
8936 &crease_trailers,
8937 &row_block_types,
8938 content_origin,
8939 scroll_pixel_position,
8940 edit_prediction_popover_origin,
8941 start_row,
8942 end_row,
8943 line_height,
8944 em_width,
8945 &style,
8946 window,
8947 cx,
8948 );
8949
8950 let mut inline_blame_layout = None;
8951 let mut inline_code_actions = None;
8952 if let Some(newest_selection_head) = newest_selection_head {
8953 let display_row = newest_selection_head.row();
8954 if (start_row..end_row).contains(&display_row)
8955 && !row_block_types.contains_key(&display_row)
8956 {
8957 inline_code_actions = self.layout_inline_code_actions(
8958 newest_selection_head,
8959 content_origin,
8960 scroll_pixel_position,
8961 line_height,
8962 &snapshot,
8963 window,
8964 cx,
8965 );
8966
8967 let line_ix = display_row.minus(start_row) as usize;
8968 if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
8969 row_infos.get(line_ix),
8970 line_layouts.get(line_ix),
8971 crease_trailers.get(line_ix),
8972 ) {
8973 let crease_trailer_layout = crease_trailer.as_ref();
8974 if let Some(layout) = self.layout_inline_blame(
8975 display_row,
8976 row_info,
8977 line_layout,
8978 crease_trailer_layout,
8979 em_width,
8980 content_origin,
8981 scroll_pixel_position,
8982 line_height,
8983 &text_hitbox,
8984 window,
8985 cx,
8986 ) {
8987 inline_blame_layout = Some(layout);
8988 // Blame overrides inline diagnostics
8989 inline_diagnostics.remove(&display_row);
8990 }
8991 } else {
8992 log::error!(
8993 "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
8994 line_layouts.len(): {}, \
8995 crease_trailers.len(): {}",
8996 line_ix,
8997 row_infos.len(),
8998 line_layouts.len(),
8999 crease_trailers.len(),
9000 );
9001 }
9002 }
9003 }
9004
9005 let blamed_display_rows = self.layout_blame_entries(
9006 &row_infos,
9007 em_width,
9008 scroll_position,
9009 line_height,
9010 &gutter_hitbox,
9011 gutter_dimensions.git_blame_entries_width,
9012 window,
9013 cx,
9014 );
9015
9016 let line_elements = self.prepaint_lines(
9017 start_row,
9018 &mut line_layouts,
9019 line_height,
9020 scroll_pixel_position,
9021 content_origin,
9022 window,
9023 cx,
9024 );
9025
9026 window.with_element_namespace("blocks", |window| {
9027 self.layout_blocks(
9028 &mut blocks,
9029 &hitbox,
9030 line_height,
9031 scroll_pixel_position,
9032 window,
9033 cx,
9034 );
9035 });
9036
9037 let cursors = self.collect_cursors(&snapshot, cx);
9038 let visible_row_range = start_row..end_row;
9039 let non_visible_cursors = cursors
9040 .iter()
9041 .any(|c| !visible_row_range.contains(&c.0.row()));
9042
9043 let visible_cursors = self.layout_visible_cursors(
9044 &snapshot,
9045 &selections,
9046 &row_block_types,
9047 start_row..end_row,
9048 &line_layouts,
9049 &text_hitbox,
9050 content_origin,
9051 scroll_position,
9052 scroll_pixel_position,
9053 line_height,
9054 em_width,
9055 em_advance,
9056 autoscroll_containing_element,
9057 window,
9058 cx,
9059 );
9060
9061 let scrollbars_layout = self.layout_scrollbars(
9062 &snapshot,
9063 &scrollbar_layout_information,
9064 content_offset,
9065 scroll_position,
9066 non_visible_cursors,
9067 right_margin,
9068 editor_width,
9069 window,
9070 cx,
9071 );
9072
9073 let gutter_settings = EditorSettings::get_global(cx).gutter;
9074
9075 let context_menu_layout =
9076 if let Some(newest_selection_head) = newest_selection_head {
9077 let newest_selection_point =
9078 newest_selection_head.to_point(&snapshot.display_snapshot);
9079 if (start_row..end_row).contains(&newest_selection_head.row()) {
9080 self.layout_cursor_popovers(
9081 line_height,
9082 &text_hitbox,
9083 content_origin,
9084 right_margin,
9085 start_row,
9086 scroll_pixel_position,
9087 &line_layouts,
9088 newest_selection_head,
9089 newest_selection_point,
9090 &style,
9091 window,
9092 cx,
9093 )
9094 } else {
9095 None
9096 }
9097 } else {
9098 None
9099 };
9100
9101 self.layout_gutter_menu(
9102 line_height,
9103 &text_hitbox,
9104 content_origin,
9105 right_margin,
9106 scroll_pixel_position,
9107 gutter_dimensions.width - gutter_dimensions.left_padding,
9108 window,
9109 cx,
9110 );
9111
9112 let test_indicators = if gutter_settings.runnables {
9113 self.layout_run_indicators(
9114 line_height,
9115 start_row..end_row,
9116 &row_infos,
9117 scroll_pixel_position,
9118 &gutter_dimensions,
9119 &gutter_hitbox,
9120 &display_hunks,
9121 &snapshot,
9122 &mut breakpoint_rows,
9123 window,
9124 cx,
9125 )
9126 } else {
9127 Vec::new()
9128 };
9129
9130 let show_breakpoints = snapshot
9131 .show_breakpoints
9132 .unwrap_or(gutter_settings.breakpoints);
9133 let breakpoints = if show_breakpoints {
9134 self.layout_breakpoints(
9135 line_height,
9136 start_row..end_row,
9137 scroll_pixel_position,
9138 &gutter_dimensions,
9139 &gutter_hitbox,
9140 &display_hunks,
9141 &snapshot,
9142 breakpoint_rows,
9143 &row_infos,
9144 window,
9145 cx,
9146 )
9147 } else {
9148 Vec::new()
9149 };
9150
9151 self.layout_signature_help(
9152 &hitbox,
9153 content_origin,
9154 scroll_pixel_position,
9155 newest_selection_head,
9156 start_row,
9157 &line_layouts,
9158 line_height,
9159 em_width,
9160 context_menu_layout,
9161 window,
9162 cx,
9163 );
9164
9165 if !cx.has_active_drag() {
9166 self.layout_hover_popovers(
9167 &snapshot,
9168 &hitbox,
9169 start_row..end_row,
9170 content_origin,
9171 scroll_pixel_position,
9172 &line_layouts,
9173 line_height,
9174 em_width,
9175 context_menu_layout,
9176 window,
9177 cx,
9178 );
9179 }
9180
9181 let mouse_context_menu = self.layout_mouse_context_menu(
9182 &snapshot,
9183 start_row..end_row,
9184 content_origin,
9185 window,
9186 cx,
9187 );
9188
9189 window.with_element_namespace("crease_toggles", |window| {
9190 self.prepaint_crease_toggles(
9191 &mut crease_toggles,
9192 line_height,
9193 &gutter_dimensions,
9194 gutter_settings,
9195 scroll_pixel_position,
9196 &gutter_hitbox,
9197 window,
9198 cx,
9199 )
9200 });
9201
9202 window.with_element_namespace("expand_toggles", |window| {
9203 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
9204 });
9205
9206 let wrap_guides = self.layout_wrap_guides(
9207 em_advance,
9208 scroll_position,
9209 content_origin,
9210 scrollbars_layout.as_ref(),
9211 vertical_scrollbar_width,
9212 &hitbox,
9213 window,
9214 cx,
9215 );
9216
9217 let minimap = window.with_element_namespace("minimap", |window| {
9218 self.layout_minimap(
9219 &snapshot,
9220 minimap_width,
9221 scroll_position,
9222 &scrollbar_layout_information,
9223 scrollbars_layout.as_ref(),
9224 window,
9225 cx,
9226 )
9227 });
9228
9229 let invisible_symbol_font_size = font_size / 2.;
9230 let tab_invisible = window.text_system().shape_line(
9231 "β".into(),
9232 invisible_symbol_font_size,
9233 &[TextRun {
9234 len: "β".len(),
9235 font: self.style.text.font(),
9236 color: cx.theme().colors().editor_invisible,
9237 background_color: None,
9238 underline: None,
9239 strikethrough: None,
9240 }],
9241 None,
9242 );
9243 let space_invisible = window.text_system().shape_line(
9244 "β’".into(),
9245 invisible_symbol_font_size,
9246 &[TextRun {
9247 len: "β’".len(),
9248 font: self.style.text.font(),
9249 color: cx.theme().colors().editor_invisible,
9250 background_color: None,
9251 underline: None,
9252 strikethrough: None,
9253 }],
9254 None,
9255 );
9256
9257 let mode = snapshot.mode.clone();
9258
9259 let (diff_hunk_controls, diff_hunk_control_bounds) = if is_read_only {
9260 (vec![], vec![])
9261 } else {
9262 self.layout_diff_hunk_controls(
9263 start_row..end_row,
9264 &row_infos,
9265 &text_hitbox,
9266 newest_selection_head,
9267 line_height,
9268 right_margin,
9269 scroll_pixel_position,
9270 &display_hunks,
9271 &highlighted_rows,
9272 self.editor.clone(),
9273 window,
9274 cx,
9275 )
9276 };
9277
9278 let position_map = Rc::new(PositionMap {
9279 size: bounds.size,
9280 visible_row_range,
9281 scroll_pixel_position,
9282 scroll_max,
9283 line_layouts,
9284 line_height,
9285 em_width,
9286 em_advance,
9287 snapshot,
9288 gutter_hitbox: gutter_hitbox.clone(),
9289 text_hitbox: text_hitbox.clone(),
9290 inline_blame_bounds: inline_blame_layout
9291 .as_ref()
9292 .map(|layout| (layout.bounds, layout.entry.clone())),
9293 display_hunks: display_hunks.clone(),
9294 diff_hunk_control_bounds,
9295 });
9296
9297 self.editor.update(cx, |editor, _| {
9298 editor.last_position_map = Some(position_map.clone())
9299 });
9300
9301 EditorLayout {
9302 mode,
9303 position_map,
9304 visible_display_row_range: start_row..end_row,
9305 wrap_guides,
9306 indent_guides,
9307 hitbox,
9308 gutter_hitbox,
9309 display_hunks,
9310 content_origin,
9311 scrollbars_layout,
9312 minimap,
9313 active_rows,
9314 highlighted_rows,
9315 highlighted_ranges,
9316 highlighted_gutter_ranges,
9317 redacted_ranges,
9318 document_colors,
9319 line_elements,
9320 line_numbers,
9321 blamed_display_rows,
9322 inline_diagnostics,
9323 inline_blame_layout,
9324 inline_code_actions,
9325 blocks,
9326 cursors,
9327 visible_cursors,
9328 selections,
9329 edit_prediction_popover,
9330 diff_hunk_controls,
9331 mouse_context_menu,
9332 test_indicators,
9333 breakpoints,
9334 crease_toggles,
9335 crease_trailers,
9336 tab_invisible,
9337 space_invisible,
9338 sticky_buffer_header,
9339 expand_toggles,
9340 }
9341 })
9342 })
9343 })
9344 }
9345
9346 fn paint(
9347 &mut self,
9348 _: Option<&GlobalElementId>,
9349 _inspector_id: Option<&gpui::InspectorElementId>,
9350 bounds: Bounds<gpui::Pixels>,
9351 _: &mut Self::RequestLayoutState,
9352 layout: &mut Self::PrepaintState,
9353 window: &mut Window,
9354 cx: &mut App,
9355 ) {
9356 if !layout.mode.is_minimap() {
9357 let focus_handle = self.editor.focus_handle(cx);
9358 let key_context = self
9359 .editor
9360 .update(cx, |editor, cx| editor.key_context(window, cx));
9361
9362 window.set_key_context(key_context);
9363 window.handle_input(
9364 &focus_handle,
9365 ElementInputHandler::new(bounds, self.editor.clone()),
9366 cx,
9367 );
9368 self.register_actions(window, cx);
9369 self.register_key_listeners(window, cx, layout);
9370 }
9371
9372 let text_style = TextStyleRefinement {
9373 font_size: Some(self.style.text.font_size),
9374 line_height: Some(self.style.text.line_height),
9375 ..Default::default()
9376 };
9377 let rem_size = self.rem_size(cx);
9378 window.with_rem_size(rem_size, |window| {
9379 window.with_text_style(Some(text_style), |window| {
9380 window.with_content_mask(Some(ContentMask { bounds }), |window| {
9381 self.paint_mouse_listeners(layout, window, cx);
9382 self.paint_background(layout, window, cx);
9383 self.paint_indent_guides(layout, window, cx);
9384
9385 if layout.gutter_hitbox.size.width > Pixels::ZERO {
9386 self.paint_blamed_display_rows(layout, window, cx);
9387 self.paint_line_numbers(layout, window, cx);
9388 }
9389
9390 self.paint_text(layout, window, cx);
9391
9392 if layout.gutter_hitbox.size.width > Pixels::ZERO {
9393 self.paint_gutter_highlights(layout, window, cx);
9394 self.paint_gutter_indicators(layout, window, cx);
9395 }
9396
9397 if !layout.blocks.is_empty() {
9398 window.with_element_namespace("blocks", |window| {
9399 self.paint_blocks(layout, window, cx);
9400 });
9401 }
9402
9403 window.with_element_namespace("blocks", |window| {
9404 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
9405 sticky_header.paint(window, cx)
9406 }
9407 });
9408
9409 self.paint_minimap(layout, window, cx);
9410 self.paint_scrollbars(layout, window, cx);
9411 self.paint_edit_prediction_popover(layout, window, cx);
9412 self.paint_mouse_context_menu(layout, window, cx);
9413 });
9414 })
9415 })
9416 }
9417}
9418
9419pub(super) fn gutter_bounds(
9420 editor_bounds: Bounds<Pixels>,
9421 gutter_dimensions: GutterDimensions,
9422) -> Bounds<Pixels> {
9423 Bounds {
9424 origin: editor_bounds.origin,
9425 size: size(gutter_dimensions.width, editor_bounds.size.height),
9426 }
9427}
9428
9429#[derive(Clone, Copy)]
9430struct ContextMenuLayout {
9431 y_flipped: bool,
9432 bounds: Bounds<Pixels>,
9433}
9434
9435/// Holds information required for layouting the editor scrollbars.
9436struct ScrollbarLayoutInformation {
9437 /// The bounds of the editor area (excluding the content offset).
9438 editor_bounds: Bounds<Pixels>,
9439 /// The available range to scroll within the document.
9440 scroll_range: Size<Pixels>,
9441 /// The space available for one glyph in the editor.
9442 glyph_grid_cell: Size<Pixels>,
9443}
9444
9445impl ScrollbarLayoutInformation {
9446 pub fn new(
9447 editor_bounds: Bounds<Pixels>,
9448 glyph_grid_cell: Size<Pixels>,
9449 document_size: Size<Pixels>,
9450 longest_line_blame_width: Pixels,
9451 settings: &EditorSettings,
9452 ) -> Self {
9453 let vertical_overscroll = match settings.scroll_beyond_last_line {
9454 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
9455 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
9456 ScrollBeyondLastLine::VerticalScrollMargin => {
9457 (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
9458 }
9459 };
9460
9461 let overscroll = size(longest_line_blame_width, vertical_overscroll);
9462
9463 ScrollbarLayoutInformation {
9464 editor_bounds,
9465 scroll_range: document_size + overscroll,
9466 glyph_grid_cell,
9467 }
9468 }
9469}
9470
9471impl IntoElement for EditorElement {
9472 type Element = Self;
9473
9474 fn into_element(self) -> Self::Element {
9475 self
9476 }
9477}
9478
9479pub struct EditorLayout {
9480 position_map: Rc<PositionMap>,
9481 hitbox: Hitbox,
9482 gutter_hitbox: Hitbox,
9483 content_origin: gpui::Point<Pixels>,
9484 scrollbars_layout: Option<EditorScrollbars>,
9485 minimap: Option<MinimapLayout>,
9486 mode: EditorMode,
9487 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
9488 indent_guides: Option<Vec<IndentGuideLayout>>,
9489 visible_display_row_range: Range<DisplayRow>,
9490 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
9491 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
9492 line_elements: SmallVec<[AnyElement; 1]>,
9493 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
9494 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
9495 blamed_display_rows: Option<Vec<AnyElement>>,
9496 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
9497 inline_blame_layout: Option<InlineBlameLayout>,
9498 inline_code_actions: Option<AnyElement>,
9499 blocks: Vec<BlockLayout>,
9500 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
9501 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
9502 redacted_ranges: Vec<Range<DisplayPoint>>,
9503 cursors: Vec<(DisplayPoint, Hsla)>,
9504 visible_cursors: Vec<CursorLayout>,
9505 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
9506 test_indicators: Vec<AnyElement>,
9507 breakpoints: Vec<AnyElement>,
9508 crease_toggles: Vec<Option<AnyElement>>,
9509 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
9510 diff_hunk_controls: Vec<AnyElement>,
9511 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
9512 edit_prediction_popover: Option<AnyElement>,
9513 mouse_context_menu: Option<AnyElement>,
9514 tab_invisible: ShapedLine,
9515 space_invisible: ShapedLine,
9516 sticky_buffer_header: Option<AnyElement>,
9517 document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
9518}
9519
9520impl EditorLayout {
9521 fn line_end_overshoot(&self) -> Pixels {
9522 0.15 * self.position_map.line_height
9523 }
9524}
9525
9526struct LineNumberLayout {
9527 shaped_line: ShapedLine,
9528 hitbox: Option<Hitbox>,
9529}
9530
9531struct ColoredRange<T> {
9532 start: T,
9533 end: T,
9534 color: Hsla,
9535}
9536
9537impl Along for ScrollbarAxes {
9538 type Unit = bool;
9539
9540 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
9541 match axis {
9542 ScrollbarAxis::Horizontal => self.horizontal,
9543 ScrollbarAxis::Vertical => self.vertical,
9544 }
9545 }
9546
9547 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
9548 match axis {
9549 ScrollbarAxis::Horizontal => ScrollbarAxes {
9550 horizontal: f(self.horizontal),
9551 vertical: self.vertical,
9552 },
9553 ScrollbarAxis::Vertical => ScrollbarAxes {
9554 horizontal: self.horizontal,
9555 vertical: f(self.vertical),
9556 },
9557 }
9558 }
9559}
9560
9561#[derive(Clone)]
9562struct EditorScrollbars {
9563 pub vertical: Option<ScrollbarLayout>,
9564 pub horizontal: Option<ScrollbarLayout>,
9565 pub visible: bool,
9566}
9567
9568impl EditorScrollbars {
9569 pub fn from_scrollbar_axes(
9570 show_scrollbar: ScrollbarAxes,
9571 layout_information: &ScrollbarLayoutInformation,
9572 content_offset: gpui::Point<Pixels>,
9573 scroll_position: gpui::Point<f32>,
9574 scrollbar_width: Pixels,
9575 right_margin: Pixels,
9576 editor_width: Pixels,
9577 show_scrollbars: bool,
9578 scrollbar_state: Option<&ActiveScrollbarState>,
9579 window: &mut Window,
9580 ) -> Self {
9581 let ScrollbarLayoutInformation {
9582 editor_bounds,
9583 scroll_range,
9584 glyph_grid_cell,
9585 } = layout_information;
9586
9587 let viewport_size = size(editor_width, editor_bounds.size.height);
9588
9589 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
9590 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
9591 Corner::BottomLeft,
9592 editor_bounds.bottom_left(),
9593 size(
9594 // The horizontal viewport size differs from the space available for the
9595 // horizontal scrollbar, so we have to manually stich it together here.
9596 editor_bounds.size.width - right_margin,
9597 scrollbar_width,
9598 ),
9599 ),
9600 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
9601 Corner::TopRight,
9602 editor_bounds.top_right(),
9603 size(scrollbar_width, viewport_size.height),
9604 ),
9605 };
9606
9607 let mut create_scrollbar_layout = |axis| {
9608 let viewport_size = viewport_size.along(axis);
9609 let scroll_range = scroll_range.along(axis);
9610
9611 // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
9612 (show_scrollbar.along(axis)
9613 && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
9614 .then(|| {
9615 ScrollbarLayout::new(
9616 window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
9617 viewport_size,
9618 scroll_range,
9619 glyph_grid_cell.along(axis),
9620 content_offset.along(axis),
9621 scroll_position.along(axis),
9622 show_scrollbars,
9623 axis,
9624 )
9625 .with_thumb_state(
9626 scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
9627 )
9628 })
9629 };
9630
9631 Self {
9632 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
9633 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
9634 visible: show_scrollbars,
9635 }
9636 }
9637
9638 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
9639 [
9640 (&self.vertical, ScrollbarAxis::Vertical),
9641 (&self.horizontal, ScrollbarAxis::Horizontal),
9642 ]
9643 .into_iter()
9644 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
9645 }
9646
9647 /// Returns the currently hovered scrollbar axis, if any.
9648 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
9649 self.iter_scrollbars()
9650 .find(|s| s.0.hitbox.is_hovered(window))
9651 }
9652}
9653
9654#[derive(Clone)]
9655struct ScrollbarLayout {
9656 hitbox: Hitbox,
9657 visible_range: Range<f32>,
9658 text_unit_size: Pixels,
9659 thumb_bounds: Option<Bounds<Pixels>>,
9660 thumb_state: ScrollbarThumbState,
9661}
9662
9663impl ScrollbarLayout {
9664 const BORDER_WIDTH: Pixels = px(1.0);
9665 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
9666 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
9667 const MIN_THUMB_SIZE: Pixels = px(25.0);
9668
9669 fn new(
9670 scrollbar_track_hitbox: Hitbox,
9671 viewport_size: Pixels,
9672 scroll_range: Pixels,
9673 glyph_space: Pixels,
9674 content_offset: Pixels,
9675 scroll_position: f32,
9676 show_thumb: bool,
9677 axis: ScrollbarAxis,
9678 ) -> Self {
9679 let track_bounds = scrollbar_track_hitbox.bounds;
9680 // The length of the track available to the scrollbar thumb. We deliberately
9681 // exclude the content size here so that the thumb aligns with the content.
9682 let track_length = track_bounds.size.along(axis) - content_offset;
9683
9684 Self::new_with_hitbox_and_track_length(
9685 scrollbar_track_hitbox,
9686 track_length,
9687 viewport_size,
9688 scroll_range,
9689 glyph_space,
9690 content_offset,
9691 scroll_position,
9692 show_thumb,
9693 axis,
9694 )
9695 }
9696
9697 fn for_minimap(
9698 minimap_track_hitbox: Hitbox,
9699 visible_lines: f32,
9700 total_editor_lines: f32,
9701 minimap_line_height: Pixels,
9702 scroll_position: f32,
9703 minimap_scroll_top: f32,
9704 show_thumb: bool,
9705 ) -> Self {
9706 // The scrollbar thumb size is calculated as
9707 // (visible_content/total_content) Γ scrollbar_track_length.
9708 //
9709 // For the minimap's thumb layout, we leverage this by setting the
9710 // scrollbar track length to the entire document size (using minimap line
9711 // height). This creates a thumb that exactly represents the editor
9712 // viewport scaled to minimap proportions.
9713 //
9714 // We adjust the thumb position relative to `minimap_scroll_top` to
9715 // accommodate for the deliberately oversized track.
9716 //
9717 // This approach ensures that the minimap thumb accurately reflects the
9718 // editor's current scroll position whilst nicely synchronizing the minimap
9719 // thumb and scrollbar thumb.
9720 let scroll_range = total_editor_lines * minimap_line_height;
9721 let viewport_size = visible_lines * minimap_line_height;
9722
9723 let track_top_offset = -minimap_scroll_top * minimap_line_height;
9724
9725 Self::new_with_hitbox_and_track_length(
9726 minimap_track_hitbox,
9727 scroll_range,
9728 viewport_size,
9729 scroll_range,
9730 minimap_line_height,
9731 track_top_offset,
9732 scroll_position,
9733 show_thumb,
9734 ScrollbarAxis::Vertical,
9735 )
9736 }
9737
9738 fn new_with_hitbox_and_track_length(
9739 scrollbar_track_hitbox: Hitbox,
9740 track_length: Pixels,
9741 viewport_size: Pixels,
9742 scroll_range: Pixels,
9743 glyph_space: Pixels,
9744 content_offset: Pixels,
9745 scroll_position: f32,
9746 show_thumb: bool,
9747 axis: ScrollbarAxis,
9748 ) -> Self {
9749 let text_units_per_page = viewport_size / glyph_space;
9750 let visible_range = scroll_position..scroll_position + text_units_per_page;
9751 let total_text_units = scroll_range / glyph_space;
9752
9753 let thumb_percentage = text_units_per_page / total_text_units;
9754 let thumb_size = (track_length * thumb_percentage)
9755 .max(ScrollbarLayout::MIN_THUMB_SIZE)
9756 .min(track_length);
9757
9758 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
9759
9760 let content_larger_than_viewport = text_unit_divisor > 0.;
9761
9762 let text_unit_size = if content_larger_than_viewport {
9763 (track_length - thumb_size) / text_unit_divisor
9764 } else {
9765 glyph_space
9766 };
9767
9768 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
9769 Self::thumb_bounds(
9770 &scrollbar_track_hitbox,
9771 content_offset,
9772 visible_range.start,
9773 text_unit_size,
9774 thumb_size,
9775 axis,
9776 )
9777 });
9778
9779 ScrollbarLayout {
9780 hitbox: scrollbar_track_hitbox,
9781 visible_range,
9782 text_unit_size,
9783 thumb_bounds,
9784 thumb_state: Default::default(),
9785 }
9786 }
9787
9788 fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
9789 if let Some(thumb_state) = thumb_state {
9790 Self {
9791 thumb_state,
9792 ..self
9793 }
9794 } else {
9795 self
9796 }
9797 }
9798
9799 fn thumb_bounds(
9800 scrollbar_track: &Hitbox,
9801 content_offset: Pixels,
9802 visible_range_start: f32,
9803 text_unit_size: Pixels,
9804 thumb_size: Pixels,
9805 axis: ScrollbarAxis,
9806 ) -> Bounds<Pixels> {
9807 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
9808 origin + content_offset + visible_range_start * text_unit_size
9809 });
9810 Bounds::new(
9811 thumb_origin,
9812 scrollbar_track.size.apply_along(axis, |_| thumb_size),
9813 )
9814 }
9815
9816 fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
9817 self.thumb_bounds
9818 .is_some_and(|bounds| bounds.contains(position))
9819 }
9820
9821 fn marker_quads_for_ranges(
9822 &self,
9823 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
9824 column: Option<usize>,
9825 ) -> Vec<PaintQuad> {
9826 struct MinMax {
9827 min: Pixels,
9828 max: Pixels,
9829 }
9830 let (x_range, height_limit) = if let Some(column) = column {
9831 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
9832 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
9833 let end = start + column_width;
9834 (
9835 Range { start, end },
9836 MinMax {
9837 min: Self::MIN_MARKER_HEIGHT,
9838 max: px(f32::MAX),
9839 },
9840 )
9841 } else {
9842 (
9843 Range {
9844 start: Self::BORDER_WIDTH,
9845 end: self.hitbox.size.width,
9846 },
9847 MinMax {
9848 min: Self::LINE_MARKER_HEIGHT,
9849 max: Self::LINE_MARKER_HEIGHT,
9850 },
9851 )
9852 };
9853
9854 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
9855 let mut pixel_ranges = row_ranges
9856 .into_iter()
9857 .map(|range| {
9858 let start_y = row_to_y(range.start);
9859 let end_y = row_to_y(range.end)
9860 + self
9861 .text_unit_size
9862 .max(height_limit.min)
9863 .min(height_limit.max);
9864 ColoredRange {
9865 start: start_y,
9866 end: end_y,
9867 color: range.color,
9868 }
9869 })
9870 .peekable();
9871
9872 let mut quads = Vec::new();
9873 while let Some(mut pixel_range) = pixel_ranges.next() {
9874 while let Some(next_pixel_range) = pixel_ranges.peek() {
9875 if pixel_range.end >= next_pixel_range.start - px(1.0)
9876 && pixel_range.color == next_pixel_range.color
9877 {
9878 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
9879 pixel_ranges.next();
9880 } else {
9881 break;
9882 }
9883 }
9884
9885 let bounds = Bounds::from_corners(
9886 point(x_range.start, pixel_range.start),
9887 point(x_range.end, pixel_range.end),
9888 );
9889 quads.push(quad(
9890 bounds,
9891 Corners::default(),
9892 pixel_range.color,
9893 Edges::default(),
9894 Hsla::transparent_black(),
9895 BorderStyle::default(),
9896 ));
9897 }
9898
9899 quads
9900 }
9901}
9902
9903struct MinimapLayout {
9904 pub minimap: AnyElement,
9905 pub thumb_layout: ScrollbarLayout,
9906 pub minimap_scroll_top: f32,
9907 pub minimap_line_height: Pixels,
9908 pub thumb_border_style: MinimapThumbBorder,
9909 pub max_scroll_top: f32,
9910}
9911
9912impl MinimapLayout {
9913 /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
9914 const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
9915 /// The minimap width as a percentage of the editor width.
9916 const MINIMAP_WIDTH_PCT: f32 = 0.15;
9917 /// Calculates the scroll top offset the minimap editor has to have based on the
9918 /// current scroll progress.
9919 fn calculate_minimap_top_offset(
9920 document_lines: f32,
9921 visible_editor_lines: f32,
9922 visible_minimap_lines: f32,
9923 scroll_position: f32,
9924 ) -> f32 {
9925 let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
9926 if non_visible_document_lines == 0. {
9927 0.
9928 } else {
9929 let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
9930 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
9931 }
9932 }
9933}
9934
9935struct CreaseTrailerLayout {
9936 element: AnyElement,
9937 bounds: Bounds<Pixels>,
9938}
9939
9940pub(crate) struct PositionMap {
9941 pub size: Size<Pixels>,
9942 pub line_height: Pixels,
9943 pub scroll_pixel_position: gpui::Point<Pixels>,
9944 pub scroll_max: gpui::Point<f32>,
9945 pub em_width: Pixels,
9946 pub em_advance: Pixels,
9947 pub visible_row_range: Range<DisplayRow>,
9948 pub line_layouts: Vec<LineWithInvisibles>,
9949 pub snapshot: EditorSnapshot,
9950 pub text_hitbox: Hitbox,
9951 pub gutter_hitbox: Hitbox,
9952 pub inline_blame_bounds: Option<(Bounds<Pixels>, BlameEntry)>,
9953 pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
9954 pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
9955}
9956
9957#[derive(Debug, Copy, Clone)]
9958pub struct PointForPosition {
9959 pub previous_valid: DisplayPoint,
9960 pub next_valid: DisplayPoint,
9961 pub exact_unclipped: DisplayPoint,
9962 pub column_overshoot_after_line_end: u32,
9963}
9964
9965impl PointForPosition {
9966 pub fn as_valid(&self) -> Option<DisplayPoint> {
9967 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
9968 Some(self.previous_valid)
9969 } else {
9970 None
9971 }
9972 }
9973
9974 pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
9975 let Some(valid_point) = self.as_valid() else {
9976 return false;
9977 };
9978 let range = selection.range();
9979
9980 let candidate_row = valid_point.row();
9981 let candidate_col = valid_point.column();
9982
9983 let start_row = range.start.row();
9984 let start_col = range.start.column();
9985 let end_row = range.end.row();
9986 let end_col = range.end.column();
9987
9988 if candidate_row < start_row || candidate_row > end_row {
9989 false
9990 } else if start_row == end_row {
9991 candidate_col >= start_col && candidate_col < end_col
9992 } else if candidate_row == start_row {
9993 candidate_col >= start_col
9994 } else if candidate_row == end_row {
9995 candidate_col < end_col
9996 } else {
9997 true
9998 }
9999 }
10000}
10001
10002impl PositionMap {
10003 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
10004 let text_bounds = self.text_hitbox.bounds;
10005 let scroll_position = self.snapshot.scroll_position();
10006 let position = position - text_bounds.origin;
10007 let y = position.y.max(px(0.)).min(self.size.height);
10008 let x = position.x + (scroll_position.x * self.em_advance);
10009 let row = ((y / self.line_height) + scroll_position.y) as u32;
10010
10011 let (column, x_overshoot_after_line_end) = if let Some(line) = self
10012 .line_layouts
10013 .get(row as usize - scroll_position.y as usize)
10014 {
10015 if let Some(ix) = line.index_for_x(x) {
10016 (ix as u32, px(0.))
10017 } else {
10018 (line.len as u32, px(0.).max(x - line.width))
10019 }
10020 } else {
10021 (0, x)
10022 };
10023
10024 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
10025 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
10026 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
10027
10028 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
10029 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
10030 PointForPosition {
10031 previous_valid,
10032 next_valid,
10033 exact_unclipped,
10034 column_overshoot_after_line_end,
10035 }
10036 }
10037}
10038
10039struct BlockLayout {
10040 id: BlockId,
10041 x_offset: Pixels,
10042 row: Option<DisplayRow>,
10043 element: AnyElement,
10044 available_space: Size<AvailableSpace>,
10045 style: BlockStyle,
10046 overlaps_gutter: bool,
10047 is_buffer_header: bool,
10048}
10049
10050pub fn layout_line(
10051 row: DisplayRow,
10052 snapshot: &EditorSnapshot,
10053 style: &EditorStyle,
10054 text_width: Pixels,
10055 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
10056 window: &mut Window,
10057 cx: &mut App,
10058) -> LineWithInvisibles {
10059 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
10060 LineWithInvisibles::from_chunks(
10061 chunks,
10062 style,
10063 MAX_LINE_LEN,
10064 1,
10065 &snapshot.mode,
10066 text_width,
10067 is_row_soft_wrapped,
10068 &[],
10069 window,
10070 cx,
10071 )
10072 .pop()
10073 .unwrap()
10074}
10075
10076#[derive(Debug)]
10077pub struct IndentGuideLayout {
10078 origin: gpui::Point<Pixels>,
10079 length: Pixels,
10080 single_indent_width: Pixels,
10081 depth: u32,
10082 active: bool,
10083 settings: IndentGuideSettings,
10084}
10085
10086pub struct CursorLayout {
10087 origin: gpui::Point<Pixels>,
10088 block_width: Pixels,
10089 line_height: Pixels,
10090 color: Hsla,
10091 shape: CursorShape,
10092 block_text: Option<ShapedLine>,
10093 cursor_name: Option<AnyElement>,
10094}
10095
10096#[derive(Debug)]
10097pub struct CursorName {
10098 string: SharedString,
10099 color: Hsla,
10100 is_top_row: bool,
10101}
10102
10103impl CursorLayout {
10104 pub fn new(
10105 origin: gpui::Point<Pixels>,
10106 block_width: Pixels,
10107 line_height: Pixels,
10108 color: Hsla,
10109 shape: CursorShape,
10110 block_text: Option<ShapedLine>,
10111 ) -> CursorLayout {
10112 CursorLayout {
10113 origin,
10114 block_width,
10115 line_height,
10116 color,
10117 shape,
10118 block_text,
10119 cursor_name: None,
10120 }
10121 }
10122
10123 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
10124 Bounds {
10125 origin: self.origin + origin,
10126 size: size(self.block_width, self.line_height),
10127 }
10128 }
10129
10130 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
10131 match self.shape {
10132 CursorShape::Bar => Bounds {
10133 origin: self.origin + origin,
10134 size: size(px(2.0), self.line_height),
10135 },
10136 CursorShape::Block | CursorShape::Hollow => Bounds {
10137 origin: self.origin + origin,
10138 size: size(self.block_width, self.line_height),
10139 },
10140 CursorShape::Underline => Bounds {
10141 origin: self.origin
10142 + origin
10143 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
10144 size: size(self.block_width, px(2.0)),
10145 },
10146 }
10147 }
10148
10149 pub fn layout(
10150 &mut self,
10151 origin: gpui::Point<Pixels>,
10152 cursor_name: Option<CursorName>,
10153 window: &mut Window,
10154 cx: &mut App,
10155 ) {
10156 if let Some(cursor_name) = cursor_name {
10157 let bounds = self.bounds(origin);
10158 let text_size = self.line_height / 1.5;
10159
10160 let name_origin = if cursor_name.is_top_row {
10161 point(bounds.right() - px(1.), bounds.top())
10162 } else {
10163 match self.shape {
10164 CursorShape::Bar => point(
10165 bounds.right() - px(2.),
10166 bounds.top() - text_size / 2. - px(1.),
10167 ),
10168 _ => point(
10169 bounds.right() - px(1.),
10170 bounds.top() - text_size / 2. - px(1.),
10171 ),
10172 }
10173 };
10174 let mut name_element = div()
10175 .bg(self.color)
10176 .text_size(text_size)
10177 .px_0p5()
10178 .line_height(text_size + px(2.))
10179 .text_color(cursor_name.color)
10180 .child(cursor_name.string)
10181 .into_any_element();
10182
10183 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
10184
10185 self.cursor_name = Some(name_element);
10186 }
10187 }
10188
10189 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
10190 let bounds = self.bounds(origin);
10191
10192 //Draw background or border quad
10193 let cursor = if matches!(self.shape, CursorShape::Hollow) {
10194 outline(bounds, self.color, BorderStyle::Solid)
10195 } else {
10196 fill(bounds, self.color)
10197 };
10198
10199 if let Some(name) = &mut self.cursor_name {
10200 name.paint(window, cx);
10201 }
10202
10203 window.paint_quad(cursor);
10204
10205 if let Some(block_text) = &self.block_text {
10206 block_text
10207 .paint(self.origin + origin, self.line_height, window, cx)
10208 .log_err();
10209 }
10210 }
10211
10212 pub fn shape(&self) -> CursorShape {
10213 self.shape
10214 }
10215}
10216
10217#[derive(Debug)]
10218pub struct HighlightedRange {
10219 pub start_y: Pixels,
10220 pub line_height: Pixels,
10221 pub lines: Vec<HighlightedRangeLine>,
10222 pub color: Hsla,
10223 pub corner_radius: Pixels,
10224}
10225
10226#[derive(Debug)]
10227pub struct HighlightedRangeLine {
10228 pub start_x: Pixels,
10229 pub end_x: Pixels,
10230}
10231
10232impl HighlightedRange {
10233 pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
10234 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
10235 self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
10236 self.paint_lines(
10237 self.start_y + self.line_height,
10238 &self.lines[1..],
10239 fill,
10240 bounds,
10241 window,
10242 );
10243 } else {
10244 self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
10245 }
10246 }
10247
10248 fn paint_lines(
10249 &self,
10250 start_y: Pixels,
10251 lines: &[HighlightedRangeLine],
10252 fill: bool,
10253 _bounds: Bounds<Pixels>,
10254 window: &mut Window,
10255 ) {
10256 if lines.is_empty() {
10257 return;
10258 }
10259
10260 let first_line = lines.first().unwrap();
10261 let last_line = lines.last().unwrap();
10262
10263 let first_top_left = point(first_line.start_x, start_y);
10264 let first_top_right = point(first_line.end_x, start_y);
10265
10266 let curve_height = point(Pixels::ZERO, self.corner_radius);
10267 let curve_width = |start_x: Pixels, end_x: Pixels| {
10268 let max = (end_x - start_x) / 2.;
10269 let width = if max < self.corner_radius {
10270 max
10271 } else {
10272 self.corner_radius
10273 };
10274
10275 point(width, Pixels::ZERO)
10276 };
10277
10278 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
10279 let mut builder = if fill {
10280 gpui::PathBuilder::fill()
10281 } else {
10282 gpui::PathBuilder::stroke(px(1.))
10283 };
10284 builder.move_to(first_top_right - top_curve_width);
10285 builder.curve_to(first_top_right + curve_height, first_top_right);
10286
10287 let mut iter = lines.iter().enumerate().peekable();
10288 while let Some((ix, line)) = iter.next() {
10289 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
10290
10291 if let Some((_, next_line)) = iter.peek() {
10292 let next_top_right = point(next_line.end_x, bottom_right.y);
10293
10294 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
10295 Ordering::Equal => {
10296 builder.line_to(bottom_right);
10297 }
10298 Ordering::Less => {
10299 let curve_width = curve_width(next_top_right.x, bottom_right.x);
10300 builder.line_to(bottom_right - curve_height);
10301 if self.corner_radius > Pixels::ZERO {
10302 builder.curve_to(bottom_right - curve_width, bottom_right);
10303 }
10304 builder.line_to(next_top_right + curve_width);
10305 if self.corner_radius > Pixels::ZERO {
10306 builder.curve_to(next_top_right + curve_height, next_top_right);
10307 }
10308 }
10309 Ordering::Greater => {
10310 let curve_width = curve_width(bottom_right.x, next_top_right.x);
10311 builder.line_to(bottom_right - curve_height);
10312 if self.corner_radius > Pixels::ZERO {
10313 builder.curve_to(bottom_right + curve_width, bottom_right);
10314 }
10315 builder.line_to(next_top_right - curve_width);
10316 if self.corner_radius > Pixels::ZERO {
10317 builder.curve_to(next_top_right + curve_height, next_top_right);
10318 }
10319 }
10320 }
10321 } else {
10322 let curve_width = curve_width(line.start_x, line.end_x);
10323 builder.line_to(bottom_right - curve_height);
10324 if self.corner_radius > Pixels::ZERO {
10325 builder.curve_to(bottom_right - curve_width, bottom_right);
10326 }
10327
10328 let bottom_left = point(line.start_x, bottom_right.y);
10329 builder.line_to(bottom_left + curve_width);
10330 if self.corner_radius > Pixels::ZERO {
10331 builder.curve_to(bottom_left - curve_height, bottom_left);
10332 }
10333 }
10334 }
10335
10336 if first_line.start_x > last_line.start_x {
10337 let curve_width = curve_width(last_line.start_x, first_line.start_x);
10338 let second_top_left = point(last_line.start_x, start_y + self.line_height);
10339 builder.line_to(second_top_left + curve_height);
10340 if self.corner_radius > Pixels::ZERO {
10341 builder.curve_to(second_top_left + curve_width, second_top_left);
10342 }
10343 let first_bottom_left = point(first_line.start_x, second_top_left.y);
10344 builder.line_to(first_bottom_left - curve_width);
10345 if self.corner_radius > Pixels::ZERO {
10346 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
10347 }
10348 }
10349
10350 builder.line_to(first_top_left + curve_height);
10351 if self.corner_radius > Pixels::ZERO {
10352 builder.curve_to(first_top_left + top_curve_width, first_top_left);
10353 }
10354 builder.line_to(first_top_right - top_curve_width);
10355
10356 if let Ok(path) = builder.build() {
10357 window.paint_path(path, self.color);
10358 }
10359 }
10360}
10361
10362enum CursorPopoverType {
10363 CodeContextMenu,
10364 EditPrediction,
10365}
10366
10367pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10368 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
10369}
10370
10371fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10372 (delta.pow(1.2) / 300.0).into()
10373}
10374
10375pub fn register_action<T: Action>(
10376 editor: &Entity<Editor>,
10377 window: &mut Window,
10378 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
10379) {
10380 let editor = editor.clone();
10381 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
10382 let action = action.downcast_ref().unwrap();
10383 if phase == DispatchPhase::Bubble {
10384 editor.update(cx, |editor, cx| {
10385 listener(editor, action, window, cx);
10386 })
10387 }
10388 })
10389}
10390
10391fn compute_auto_height_layout(
10392 editor: &mut Editor,
10393 min_lines: usize,
10394 max_lines: Option<usize>,
10395 max_line_number_width: Pixels,
10396 known_dimensions: Size<Option<Pixels>>,
10397 available_width: AvailableSpace,
10398 window: &mut Window,
10399 cx: &mut Context<Editor>,
10400) -> Option<Size<Pixels>> {
10401 let width = known_dimensions.width.or({
10402 if let AvailableSpace::Definite(available_width) = available_width {
10403 Some(available_width)
10404 } else {
10405 None
10406 }
10407 })?;
10408 if let Some(height) = known_dimensions.height {
10409 return Some(size(width, height));
10410 }
10411
10412 let style = editor.style.as_ref().unwrap();
10413 let font_id = window.text_system().resolve_font(&style.text.font());
10414 let font_size = style.text.font_size.to_pixels(window.rem_size());
10415 let line_height = style.text.line_height_in_pixels(window.rem_size());
10416 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
10417
10418 let mut snapshot = editor.snapshot(window, cx);
10419 let gutter_dimensions = snapshot
10420 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
10421 .or_else(|| {
10422 editor
10423 .offset_content
10424 .then(|| GutterDimensions::default_with_margin(font_id, font_size, cx))
10425 })
10426 .unwrap_or_default();
10427
10428 editor.gutter_dimensions = gutter_dimensions;
10429 let text_width = width - gutter_dimensions.width;
10430 let overscroll = size(em_width, px(0.));
10431
10432 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
10433 if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None)
10434 && editor.set_wrap_width(Some(editor_width), cx)
10435 {
10436 snapshot = editor.snapshot(window, cx);
10437 }
10438
10439 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
10440
10441 let min_height = line_height * min_lines as f32;
10442 let content_height = scroll_height.max(min_height);
10443
10444 let final_height = if let Some(max_lines) = max_lines {
10445 let max_height = line_height * max_lines as f32;
10446 content_height.min(max_height)
10447 } else {
10448 content_height
10449 };
10450
10451 Some(size(width, final_height))
10452}
10453
10454#[cfg(test)]
10455mod tests {
10456 use super::*;
10457 use crate::{
10458 Editor, MultiBuffer, SelectionEffects,
10459 display_map::{BlockPlacement, BlockProperties},
10460 editor_tests::{init_test, update_test_language_settings},
10461 };
10462 use gpui::{TestAppContext, VisualTestContext};
10463 use language::language_settings;
10464 use log::info;
10465 use std::num::NonZeroU32;
10466 use util::test::sample_text;
10467
10468 #[gpui::test]
10469 async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
10470 init_test(cx, |_| {});
10471
10472 let window = cx.add_window(|window, cx| {
10473 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
10474 let mut editor = Editor::new(
10475 EditorMode::AutoHeight {
10476 min_lines: 1,
10477 max_lines: None,
10478 },
10479 buffer,
10480 None,
10481 window,
10482 cx,
10483 );
10484 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10485 editor
10486 });
10487 let cx = &mut VisualTestContext::from_window(*window, cx);
10488 let editor = window.root(cx).unwrap();
10489 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10490
10491 for x in 1..=100 {
10492 let (_, state) = cx.draw(
10493 Default::default(),
10494 size(px(200. + 0.13 * x as f32), px(500.)),
10495 |_, _| EditorElement::new(&editor, style.clone()),
10496 );
10497
10498 assert!(
10499 state.position_map.scroll_max.x == 0.,
10500 "Soft wrapped editor should have no horizontal scrolling!"
10501 );
10502 }
10503 }
10504
10505 #[gpui::test]
10506 async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
10507 init_test(cx, |_| {});
10508
10509 let window = cx.add_window(|window, cx| {
10510 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
10511 let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
10512 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10513 editor
10514 });
10515 let cx = &mut VisualTestContext::from_window(*window, cx);
10516 let editor = window.root(cx).unwrap();
10517 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10518
10519 for x in 1..=100 {
10520 let (_, state) = cx.draw(
10521 Default::default(),
10522 size(px(200. + 0.13 * x as f32), px(500.)),
10523 |_, _| EditorElement::new(&editor, style.clone()),
10524 );
10525
10526 assert!(
10527 state.position_map.scroll_max.x == 0.,
10528 "Soft wrapped editor should have no horizontal scrolling!"
10529 );
10530 }
10531 }
10532
10533 #[gpui::test]
10534 fn test_shape_line_numbers(cx: &mut TestAppContext) {
10535 init_test(cx, |_| {});
10536 let window = cx.add_window(|window, cx| {
10537 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
10538 Editor::new(EditorMode::full(), buffer, None, window, cx)
10539 });
10540
10541 let editor = window.root(cx).unwrap();
10542 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
10543 let line_height = window
10544 .update(cx, |_, window, _| {
10545 style.text.line_height_in_pixels(window.rem_size())
10546 })
10547 .unwrap();
10548 let element = EditorElement::new(&editor, style);
10549 let snapshot = window
10550 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
10551 .unwrap();
10552
10553 let layouts = cx
10554 .update_window(*window, |_, window, cx| {
10555 element.layout_line_numbers(
10556 None,
10557 GutterDimensions {
10558 left_padding: Pixels::ZERO,
10559 right_padding: Pixels::ZERO,
10560 width: px(30.0),
10561 margin: Pixels::ZERO,
10562 git_blame_entries_width: None,
10563 },
10564 line_height,
10565 gpui::Point::default(),
10566 DisplayRow(0)..DisplayRow(6),
10567 &(0..6)
10568 .map(|row| RowInfo {
10569 buffer_row: Some(row),
10570 ..Default::default()
10571 })
10572 .collect::<Vec<_>>(),
10573 &BTreeMap::default(),
10574 Some(DisplayPoint::new(DisplayRow(0), 0)),
10575 &snapshot,
10576 window,
10577 cx,
10578 )
10579 })
10580 .unwrap();
10581 assert_eq!(layouts.len(), 6);
10582
10583 let relative_rows = window
10584 .update(cx, |editor, window, cx| {
10585 let snapshot = editor.snapshot(window, cx);
10586 element.calculate_relative_line_numbers(
10587 &snapshot,
10588 &(DisplayRow(0)..DisplayRow(6)),
10589 Some(DisplayRow(3)),
10590 )
10591 })
10592 .unwrap();
10593 assert_eq!(relative_rows[&DisplayRow(0)], 3);
10594 assert_eq!(relative_rows[&DisplayRow(1)], 2);
10595 assert_eq!(relative_rows[&DisplayRow(2)], 1);
10596 // current line has no relative number
10597 assert_eq!(relative_rows[&DisplayRow(4)], 1);
10598 assert_eq!(relative_rows[&DisplayRow(5)], 2);
10599
10600 // works if cursor is before screen
10601 let relative_rows = window
10602 .update(cx, |editor, window, cx| {
10603 let snapshot = editor.snapshot(window, cx);
10604 element.calculate_relative_line_numbers(
10605 &snapshot,
10606 &(DisplayRow(3)..DisplayRow(6)),
10607 Some(DisplayRow(1)),
10608 )
10609 })
10610 .unwrap();
10611 assert_eq!(relative_rows.len(), 3);
10612 assert_eq!(relative_rows[&DisplayRow(3)], 2);
10613 assert_eq!(relative_rows[&DisplayRow(4)], 3);
10614 assert_eq!(relative_rows[&DisplayRow(5)], 4);
10615
10616 // works if cursor is after screen
10617 let relative_rows = window
10618 .update(cx, |editor, window, cx| {
10619 let snapshot = editor.snapshot(window, cx);
10620 element.calculate_relative_line_numbers(
10621 &snapshot,
10622 &(DisplayRow(0)..DisplayRow(3)),
10623 Some(DisplayRow(6)),
10624 )
10625 })
10626 .unwrap();
10627 assert_eq!(relative_rows.len(), 3);
10628 assert_eq!(relative_rows[&DisplayRow(0)], 5);
10629 assert_eq!(relative_rows[&DisplayRow(1)], 4);
10630 assert_eq!(relative_rows[&DisplayRow(2)], 3);
10631 }
10632
10633 #[gpui::test]
10634 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
10635 init_test(cx, |_| {});
10636
10637 let window = cx.add_window(|window, cx| {
10638 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
10639 Editor::new(EditorMode::full(), buffer, None, window, cx)
10640 });
10641 let cx = &mut VisualTestContext::from_window(*window, cx);
10642 let editor = window.root(cx).unwrap();
10643 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10644
10645 window
10646 .update(cx, |editor, window, cx| {
10647 editor.cursor_shape = CursorShape::Block;
10648 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
10649 s.select_ranges([
10650 Point::new(0, 0)..Point::new(1, 0),
10651 Point::new(3, 2)..Point::new(3, 3),
10652 Point::new(5, 6)..Point::new(6, 0),
10653 ]);
10654 });
10655 })
10656 .unwrap();
10657
10658 let (_, state) = cx.draw(
10659 point(px(500.), px(500.)),
10660 size(px(500.), px(500.)),
10661 |_, _| EditorElement::new(&editor, style),
10662 );
10663
10664 assert_eq!(state.selections.len(), 1);
10665 let local_selections = &state.selections[0].1;
10666 assert_eq!(local_selections.len(), 3);
10667 // moves cursor back one line
10668 assert_eq!(
10669 local_selections[0].head,
10670 DisplayPoint::new(DisplayRow(0), 6)
10671 );
10672 assert_eq!(
10673 local_selections[0].range,
10674 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
10675 );
10676
10677 // moves cursor back one column
10678 assert_eq!(
10679 local_selections[1].range,
10680 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
10681 );
10682 assert_eq!(
10683 local_selections[1].head,
10684 DisplayPoint::new(DisplayRow(3), 2)
10685 );
10686
10687 // leaves cursor on the max point
10688 assert_eq!(
10689 local_selections[2].range,
10690 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
10691 );
10692 assert_eq!(
10693 local_selections[2].head,
10694 DisplayPoint::new(DisplayRow(6), 0)
10695 );
10696
10697 // active lines does not include 1 (even though the range of the selection does)
10698 assert_eq!(
10699 state.active_rows.keys().cloned().collect::<Vec<_>>(),
10700 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
10701 );
10702 }
10703
10704 #[gpui::test]
10705 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
10706 init_test(cx, |_| {});
10707
10708 let window = cx.add_window(|window, cx| {
10709 let buffer = MultiBuffer::build_simple("", cx);
10710 Editor::new(EditorMode::full(), buffer, None, window, cx)
10711 });
10712 let cx = &mut VisualTestContext::from_window(*window, cx);
10713 let editor = window.root(cx).unwrap();
10714 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10715 window
10716 .update(cx, |editor, window, cx| {
10717 editor.set_placeholder_text("hello", cx);
10718 editor.insert_blocks(
10719 [BlockProperties {
10720 style: BlockStyle::Fixed,
10721 placement: BlockPlacement::Above(Anchor::min()),
10722 height: Some(3),
10723 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
10724 priority: 0,
10725 }],
10726 None,
10727 cx,
10728 );
10729
10730 // Blur the editor so that it displays placeholder text.
10731 window.blur();
10732 })
10733 .unwrap();
10734
10735 let (_, state) = cx.draw(
10736 point(px(500.), px(500.)),
10737 size(px(500.), px(500.)),
10738 |_, _| EditorElement::new(&editor, style),
10739 );
10740 assert_eq!(state.position_map.line_layouts.len(), 4);
10741 assert_eq!(state.line_numbers.len(), 1);
10742 assert_eq!(
10743 state
10744 .line_numbers
10745 .get(&MultiBufferRow(0))
10746 .map(|line_number| line_number.shaped_line.text.as_ref()),
10747 Some("1")
10748 );
10749 }
10750
10751 #[gpui::test]
10752 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
10753 const TAB_SIZE: u32 = 4;
10754
10755 let input_text = "\t \t|\t| a b";
10756 let expected_invisibles = vec![
10757 Invisible::Tab {
10758 line_start_offset: 0,
10759 line_end_offset: TAB_SIZE as usize,
10760 },
10761 Invisible::Whitespace {
10762 line_offset: TAB_SIZE as usize,
10763 },
10764 Invisible::Tab {
10765 line_start_offset: TAB_SIZE as usize + 1,
10766 line_end_offset: TAB_SIZE as usize * 2,
10767 },
10768 Invisible::Tab {
10769 line_start_offset: TAB_SIZE as usize * 2 + 1,
10770 line_end_offset: TAB_SIZE as usize * 3,
10771 },
10772 Invisible::Whitespace {
10773 line_offset: TAB_SIZE as usize * 3 + 1,
10774 },
10775 Invisible::Whitespace {
10776 line_offset: TAB_SIZE as usize * 3 + 3,
10777 },
10778 ];
10779 assert_eq!(
10780 expected_invisibles.len(),
10781 input_text
10782 .chars()
10783 .filter(|initial_char| initial_char.is_whitespace())
10784 .count(),
10785 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10786 );
10787
10788 for show_line_numbers in [true, false] {
10789 init_test(cx, |s| {
10790 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10791 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
10792 });
10793
10794 let actual_invisibles = collect_invisibles_from_new_editor(
10795 cx,
10796 EditorMode::full(),
10797 input_text,
10798 px(500.0),
10799 show_line_numbers,
10800 );
10801
10802 assert_eq!(expected_invisibles, actual_invisibles);
10803 }
10804 }
10805
10806 #[gpui::test]
10807 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
10808 init_test(cx, |s| {
10809 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10810 s.defaults.tab_size = NonZeroU32::new(4);
10811 });
10812
10813 for editor_mode_without_invisibles in [
10814 EditorMode::SingleLine,
10815 EditorMode::AutoHeight {
10816 min_lines: 1,
10817 max_lines: Some(100),
10818 },
10819 ] {
10820 for show_line_numbers in [true, false] {
10821 let invisibles = collect_invisibles_from_new_editor(
10822 cx,
10823 editor_mode_without_invisibles.clone(),
10824 "\t\t\t| | a b",
10825 px(500.0),
10826 show_line_numbers,
10827 );
10828 assert!(
10829 invisibles.is_empty(),
10830 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
10831 );
10832 }
10833 }
10834 }
10835
10836 #[gpui::test]
10837 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
10838 let tab_size = 4;
10839 let input_text = "a\tbcd ".repeat(9);
10840 let repeated_invisibles = [
10841 Invisible::Tab {
10842 line_start_offset: 1,
10843 line_end_offset: tab_size as usize,
10844 },
10845 Invisible::Whitespace {
10846 line_offset: tab_size as usize + 3,
10847 },
10848 Invisible::Whitespace {
10849 line_offset: tab_size as usize + 4,
10850 },
10851 Invisible::Whitespace {
10852 line_offset: tab_size as usize + 5,
10853 },
10854 Invisible::Whitespace {
10855 line_offset: tab_size as usize + 6,
10856 },
10857 Invisible::Whitespace {
10858 line_offset: tab_size as usize + 7,
10859 },
10860 ];
10861 let expected_invisibles = std::iter::once(repeated_invisibles)
10862 .cycle()
10863 .take(9)
10864 .flatten()
10865 .collect::<Vec<_>>();
10866 assert_eq!(
10867 expected_invisibles.len(),
10868 input_text
10869 .chars()
10870 .filter(|initial_char| initial_char.is_whitespace())
10871 .count(),
10872 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10873 );
10874 info!("Expected invisibles: {expected_invisibles:?}");
10875
10876 init_test(cx, |_| {});
10877
10878 // Put the same string with repeating whitespace pattern into editors of various size,
10879 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
10880 let resize_step = 10.0;
10881 let mut editor_width = 200.0;
10882 while editor_width <= 1000.0 {
10883 for show_line_numbers in [true, false] {
10884 update_test_language_settings(cx, |s| {
10885 s.defaults.tab_size = NonZeroU32::new(tab_size);
10886 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10887 s.defaults.preferred_line_length = Some(editor_width as u32);
10888 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
10889 });
10890
10891 let actual_invisibles = collect_invisibles_from_new_editor(
10892 cx,
10893 EditorMode::full(),
10894 &input_text,
10895 px(editor_width),
10896 show_line_numbers,
10897 );
10898
10899 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
10900 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
10901 let mut i = 0;
10902 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
10903 i = actual_index;
10904 match expected_invisibles.get(i) {
10905 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
10906 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
10907 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
10908 _ => {
10909 panic!(
10910 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
10911 )
10912 }
10913 },
10914 None => {
10915 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
10916 }
10917 }
10918 }
10919 let missing_expected_invisibles = &expected_invisibles[i + 1..];
10920 assert!(
10921 missing_expected_invisibles.is_empty(),
10922 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
10923 );
10924
10925 editor_width += resize_step;
10926 }
10927 }
10928 }
10929
10930 fn collect_invisibles_from_new_editor(
10931 cx: &mut TestAppContext,
10932 editor_mode: EditorMode,
10933 input_text: &str,
10934 editor_width: Pixels,
10935 show_line_numbers: bool,
10936 ) -> Vec<Invisible> {
10937 info!(
10938 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
10939 editor_width.0
10940 );
10941 let window = cx.add_window(|window, cx| {
10942 let buffer = MultiBuffer::build_simple(input_text, cx);
10943 Editor::new(editor_mode, buffer, None, window, cx)
10944 });
10945 let cx = &mut VisualTestContext::from_window(*window, cx);
10946 let editor = window.root(cx).unwrap();
10947
10948 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10949 window
10950 .update(cx, |editor, _, cx| {
10951 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10952 editor.set_wrap_width(Some(editor_width), cx);
10953 editor.set_show_line_numbers(show_line_numbers, cx);
10954 })
10955 .unwrap();
10956 let (_, state) = cx.draw(
10957 point(px(500.), px(500.)),
10958 size(px(500.), px(500.)),
10959 |_, _| EditorElement::new(&editor, style),
10960 );
10961 state
10962 .position_map
10963 .line_layouts
10964 .iter()
10965 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
10966 .cloned()
10967 .collect()
10968 }
10969
10970 #[gpui::test]
10971 fn test_merge_overlapping_ranges() {
10972 let base_bg = Hsla::default();
10973 let color1 = Hsla {
10974 h: 0.0,
10975 s: 0.5,
10976 l: 0.5,
10977 a: 0.5,
10978 };
10979 let color2 = Hsla {
10980 h: 120.0,
10981 s: 0.5,
10982 l: 0.5,
10983 a: 0.5,
10984 };
10985
10986 let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
10987 let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
10988 v.iter()
10989 .map(|(r, _)| (r.start.column(), r.end.column()))
10990 .collect()
10991 };
10992
10993 // Test overlapping ranges blend colors
10994 let overlapping = vec![
10995 (display_point(5)..display_point(15), color1),
10996 (display_point(10)..display_point(20), color2),
10997 ];
10998 let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
10999 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
11000
11001 // Test middle segment should have blended color
11002 let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
11003 assert_eq!(result[1].1, blended);
11004
11005 // Test adjacent same-color ranges merge
11006 let adjacent_same = vec![
11007 (display_point(5)..display_point(10), color1),
11008 (display_point(10)..display_point(15), color1),
11009 ];
11010 let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
11011 assert_eq!(cols(&result), vec![(5, 15)]);
11012
11013 // Test contained range splits
11014 let contained = vec![
11015 (display_point(5)..display_point(20), color1),
11016 (display_point(10)..display_point(15), color2),
11017 ];
11018 let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
11019 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
11020
11021 // Test multiple overlaps split at every boundary
11022 let color3 = Hsla {
11023 h: 240.0,
11024 s: 0.5,
11025 l: 0.5,
11026 a: 0.5,
11027 };
11028 let complex = vec![
11029 (display_point(5)..display_point(12), color1),
11030 (display_point(8)..display_point(16), color2),
11031 (display_point(10)..display_point(14), color3),
11032 ];
11033 let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
11034 assert_eq!(
11035 cols(&result),
11036 vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
11037 );
11038 }
11039
11040 #[gpui::test]
11041 fn test_bg_segments_per_row() {
11042 let base_bg = Hsla::default();
11043
11044 // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
11045 {
11046 let selection_color = Hsla {
11047 h: 200.0,
11048 s: 0.5,
11049 l: 0.5,
11050 a: 0.5,
11051 };
11052 let player_color = PlayerColor {
11053 cursor: selection_color,
11054 background: selection_color,
11055 selection: selection_color,
11056 };
11057
11058 let spanning_selection = SelectionLayout {
11059 head: DisplayPoint::new(DisplayRow(3), 7),
11060 cursor_shape: CursorShape::Bar,
11061 is_newest: true,
11062 is_local: true,
11063 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
11064 active_rows: DisplayRow(1)..DisplayRow(4),
11065 user_name: None,
11066 };
11067
11068 let selections = vec![(player_color, vec![spanning_selection])];
11069 let result = EditorElement::bg_segments_per_row(
11070 DisplayRow(0)..DisplayRow(5),
11071 &selections,
11072 &[],
11073 base_bg,
11074 );
11075
11076 assert_eq!(result.len(), 5);
11077 assert!(result[0].is_empty());
11078 assert_eq!(result[1].len(), 1);
11079 assert_eq!(result[2].len(), 1);
11080 assert_eq!(result[3].len(), 1);
11081 assert!(result[4].is_empty());
11082
11083 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
11084 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
11085 assert_eq!(result[1][0].0.end.column(), u32::MAX);
11086 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
11087 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
11088 assert_eq!(result[2][0].0.end.column(), u32::MAX);
11089 assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
11090 assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
11091 }
11092
11093 // Case B: selection ends exactly at the start of row 3, excluding row 3
11094 {
11095 let selection_color = Hsla {
11096 h: 120.0,
11097 s: 0.5,
11098 l: 0.5,
11099 a: 0.5,
11100 };
11101 let player_color = PlayerColor {
11102 cursor: selection_color,
11103 background: selection_color,
11104 selection: selection_color,
11105 };
11106
11107 let selection = SelectionLayout {
11108 head: DisplayPoint::new(DisplayRow(2), 0),
11109 cursor_shape: CursorShape::Bar,
11110 is_newest: true,
11111 is_local: true,
11112 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
11113 active_rows: DisplayRow(1)..DisplayRow(3),
11114 user_name: None,
11115 };
11116
11117 let selections = vec![(player_color, vec![selection])];
11118 let result = EditorElement::bg_segments_per_row(
11119 DisplayRow(0)..DisplayRow(4),
11120 &selections,
11121 &[],
11122 base_bg,
11123 );
11124
11125 assert_eq!(result.len(), 4);
11126 assert!(result[0].is_empty());
11127 assert_eq!(result[1].len(), 1);
11128 assert_eq!(result[2].len(), 1);
11129 assert!(result[3].is_empty());
11130
11131 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
11132 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
11133 assert_eq!(result[1][0].0.end.column(), u32::MAX);
11134 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
11135 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
11136 assert_eq!(result[2][0].0.end.column(), u32::MAX);
11137 }
11138 }
11139
11140 #[cfg(test)]
11141 fn generate_test_run(len: usize, color: Hsla) -> TextRun {
11142 TextRun {
11143 len,
11144 font: gpui::font(".SystemUIFont"),
11145 color,
11146 background_color: None,
11147 underline: None,
11148 strikethrough: None,
11149 }
11150 }
11151
11152 #[gpui::test]
11153 fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
11154 init_test(cx, |_| {});
11155
11156 let text_color = Hsla {
11157 h: 210.0,
11158 s: 0.1,
11159 l: 0.4,
11160 a: 1.0,
11161 };
11162 let bg1 = Hsla {
11163 h: 30.0,
11164 s: 0.6,
11165 l: 0.8,
11166 a: 1.0,
11167 };
11168 let bg2 = Hsla {
11169 h: 200.0,
11170 s: 0.6,
11171 l: 0.2,
11172 a: 1.0,
11173 };
11174 let min_contrast = 45.0;
11175
11176 // Case A: single run; disjoint segments inside the run
11177 let runs = vec![generate_test_run(20, text_color)];
11178 let segs = vec![
11179 (
11180 DisplayPoint::new(DisplayRow(0), 5)..DisplayPoint::new(DisplayRow(0), 10),
11181 bg1,
11182 ),
11183 (
11184 DisplayPoint::new(DisplayRow(0), 12)..DisplayPoint::new(DisplayRow(0), 16),
11185 bg2,
11186 ),
11187 ];
11188 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast);
11189 // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
11190 assert_eq!(
11191 out.iter().map(|r| r.len).collect::<Vec<_>>(),
11192 vec![5, 5, 2, 4, 4]
11193 );
11194 assert_eq!(out[0].color, text_color);
11195 assert_eq!(
11196 out[1].color,
11197 ensure_minimum_contrast(text_color, bg1, min_contrast)
11198 );
11199 assert_eq!(out[2].color, text_color);
11200 assert_eq!(
11201 out[3].color,
11202 ensure_minimum_contrast(text_color, bg2, min_contrast)
11203 );
11204 assert_eq!(out[4].color, text_color);
11205
11206 // Case B: multiple runs; segment extends to end of line (u32::MAX)
11207 let runs = vec![
11208 generate_test_run(8, text_color),
11209 generate_test_run(7, text_color),
11210 ];
11211 let segs = vec![(
11212 DisplayPoint::new(DisplayRow(0), 6)..DisplayPoint::new(DisplayRow(0), u32::MAX),
11213 bg1,
11214 )];
11215 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast);
11216 // Expected slices across runs: [0,6) [6,8) | [0,7)
11217 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
11218 let adjusted = ensure_minimum_contrast(text_color, bg1, min_contrast);
11219 assert_eq!(out[0].color, text_color);
11220 assert_eq!(out[1].color, adjusted);
11221 assert_eq!(out[2].color, adjusted);
11222
11223 // Case C: multi-byte characters
11224 // for text: "Hello π δΈη!"
11225 let runs = vec![
11226 generate_test_run(5, text_color), // "Hello"
11227 generate_test_run(6, text_color), // " π "
11228 generate_test_run(6, text_color), // "δΈη"
11229 generate_test_run(1, text_color), // "!"
11230 ];
11231 // selecting "π δΈ"
11232 let segs = vec![(
11233 DisplayPoint::new(DisplayRow(0), 6)..DisplayPoint::new(DisplayRow(0), 14),
11234 bg1,
11235 )];
11236 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast);
11237 // "Hello" | " " | "π " | "δΈ" | "η" | "!"
11238 assert_eq!(
11239 out.iter().map(|r| r.len).collect::<Vec<_>>(),
11240 vec![5, 1, 5, 3, 3, 1]
11241 );
11242 assert_eq!(out[0].color, text_color); // "Hello"
11243 assert_eq!(
11244 out[2].color,
11245 ensure_minimum_contrast(text_color, bg1, min_contrast)
11246 ); // "π "
11247 assert_eq!(
11248 out[3].color,
11249 ensure_minimum_contrast(text_color, bg1, min_contrast)
11250 ); // "δΈ"
11251 assert_eq!(out[4].color, text_color); // "η"
11252 assert_eq!(out[5].color, text_color); // "!"
11253 }
11254}