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