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 if !base_background.is_opaque() {
3274 // We don't actually know what color is behind this editor.
3275 return Vec::new();
3276 }
3277 let highlight_iter = highlight_ranges.iter().cloned();
3278 let selection_iter = selections.iter().flat_map(|(player_color, layouts)| {
3279 let color = player_color.selection;
3280 layouts.iter().filter_map(move |selection_layout| {
3281 if selection_layout.range.start != selection_layout.range.end {
3282 Some((selection_layout.range.clone(), color))
3283 } else {
3284 None
3285 }
3286 })
3287 });
3288 let mut per_row_map = vec![Vec::new(); rows.len()];
3289 for (range, color) in highlight_iter.chain(selection_iter) {
3290 let covered_rows = if range.end.column() == 0 {
3291 cmp::max(range.start.row(), rows.start)..cmp::min(range.end.row(), rows.end)
3292 } else {
3293 cmp::max(range.start.row(), rows.start)
3294 ..cmp::min(range.end.row().next_row(), rows.end)
3295 };
3296 for row in covered_rows.iter_rows() {
3297 let seg_start = if row == range.start.row() {
3298 range.start
3299 } else {
3300 DisplayPoint::new(row, 0)
3301 };
3302 let seg_end = if row == range.end.row() && range.end.column() != 0 {
3303 range.end
3304 } else {
3305 DisplayPoint::new(row, u32::MAX)
3306 };
3307 let ix = row.minus(rows.start) as usize;
3308 debug_assert!(row >= rows.start && row < rows.end);
3309 debug_assert!(ix < per_row_map.len());
3310 per_row_map[ix].push((seg_start..seg_end, color));
3311 }
3312 }
3313 for row_segments in per_row_map.iter_mut() {
3314 if row_segments.is_empty() {
3315 continue;
3316 }
3317 let segments = mem::take(row_segments);
3318 let merged = Self::merge_overlapping_ranges(segments, base_background);
3319 *row_segments = merged;
3320 }
3321 per_row_map
3322 }
3323
3324 /// Merge overlapping ranges by splitting at all range boundaries and blending colors where
3325 /// multiple ranges overlap. The result contains non-overlapping ranges ordered from left to right.
3326 ///
3327 /// Expects `start.row() == end.row()` for each range.
3328 fn merge_overlapping_ranges(
3329 ranges: Vec<(Range<DisplayPoint>, Hsla)>,
3330 base_background: Hsla,
3331 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
3332 struct Boundary {
3333 pos: DisplayPoint,
3334 is_start: bool,
3335 index: usize,
3336 color: Hsla,
3337 }
3338
3339 let mut boundaries: SmallVec<[Boundary; 16]> = SmallVec::with_capacity(ranges.len() * 2);
3340 for (index, (range, color)) in ranges.iter().enumerate() {
3341 debug_assert!(
3342 range.start.row() == range.end.row(),
3343 "expects single-row ranges"
3344 );
3345 if range.start < range.end {
3346 boundaries.push(Boundary {
3347 pos: range.start,
3348 is_start: true,
3349 index,
3350 color: *color,
3351 });
3352 boundaries.push(Boundary {
3353 pos: range.end,
3354 is_start: false,
3355 index,
3356 color: *color,
3357 });
3358 }
3359 }
3360
3361 if boundaries.is_empty() {
3362 return Vec::new();
3363 }
3364
3365 boundaries
3366 .sort_unstable_by(|a, b| a.pos.cmp(&b.pos).then_with(|| a.is_start.cmp(&b.is_start)));
3367
3368 let mut processed_ranges: Vec<(Range<DisplayPoint>, Hsla)> = Vec::new();
3369 let mut active_ranges: SmallVec<[(usize, Hsla); 8]> = SmallVec::new();
3370
3371 let mut i = 0;
3372 let mut start_pos = boundaries[0].pos;
3373
3374 let boundaries_len = boundaries.len();
3375 while i < boundaries_len {
3376 let current_boundary_pos = boundaries[i].pos;
3377 if start_pos < current_boundary_pos {
3378 if !active_ranges.is_empty() {
3379 let mut color = base_background;
3380 for &(_, c) in &active_ranges {
3381 color = Hsla::blend(color, c);
3382 }
3383 if let Some((last_range, last_color)) = processed_ranges.last_mut() {
3384 if *last_color == color && last_range.end == start_pos {
3385 last_range.end = current_boundary_pos;
3386 } else {
3387 processed_ranges.push((start_pos..current_boundary_pos, color));
3388 }
3389 } else {
3390 processed_ranges.push((start_pos..current_boundary_pos, color));
3391 }
3392 }
3393 }
3394 while i < boundaries_len && boundaries[i].pos == current_boundary_pos {
3395 let active_range = &boundaries[i];
3396 if active_range.is_start {
3397 let idx = active_range.index;
3398 let pos = active_ranges
3399 .binary_search_by_key(&idx, |(i, _)| *i)
3400 .unwrap_or_else(|p| p);
3401 active_ranges.insert(pos, (idx, active_range.color));
3402 } else {
3403 let idx = active_range.index;
3404 if let Ok(pos) = active_ranges.binary_search_by_key(&idx, |(i, _)| *i) {
3405 active_ranges.remove(pos);
3406 }
3407 }
3408 i += 1;
3409 }
3410 start_pos = current_boundary_pos;
3411 }
3412
3413 processed_ranges
3414 }
3415
3416 fn layout_lines(
3417 rows: Range<DisplayRow>,
3418 snapshot: &EditorSnapshot,
3419 style: &EditorStyle,
3420 editor_width: Pixels,
3421 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3422 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
3423 window: &mut Window,
3424 cx: &mut App,
3425 ) -> Vec<LineWithInvisibles> {
3426 if rows.start >= rows.end {
3427 return Vec::new();
3428 }
3429
3430 // Show the placeholder when the editor is empty
3431 if snapshot.is_empty() {
3432 let font_size = style.text.font_size.to_pixels(window.rem_size());
3433 let placeholder_color = cx.theme().colors().text_placeholder;
3434 let placeholder_text = snapshot.placeholder_text();
3435
3436 let placeholder_lines = placeholder_text
3437 .as_ref()
3438 .map_or("", AsRef::as_ref)
3439 .split('\n')
3440 .skip(rows.start.0 as usize)
3441 .chain(iter::repeat(""))
3442 .take(rows.len());
3443 placeholder_lines
3444 .map(move |line| {
3445 let run = TextRun {
3446 len: line.len(),
3447 font: style.text.font(),
3448 color: placeholder_color,
3449 background_color: None,
3450 underline: None,
3451 strikethrough: None,
3452 };
3453 let line = window.text_system().shape_line(
3454 line.to_string().into(),
3455 font_size,
3456 &[run],
3457 None,
3458 );
3459 LineWithInvisibles {
3460 width: line.width,
3461 len: line.len,
3462 fragments: smallvec![LineFragment::Text(line)],
3463 invisibles: Vec::new(),
3464 font_size,
3465 }
3466 })
3467 .collect()
3468 } else {
3469 let chunks = snapshot.highlighted_chunks(rows.clone(), true, style);
3470 LineWithInvisibles::from_chunks(
3471 chunks,
3472 style,
3473 MAX_LINE_LEN,
3474 rows.len(),
3475 &snapshot.mode,
3476 editor_width,
3477 is_row_soft_wrapped,
3478 bg_segments_per_row,
3479 window,
3480 cx,
3481 )
3482 }
3483 }
3484
3485 fn prepaint_lines(
3486 &self,
3487 start_row: DisplayRow,
3488 line_layouts: &mut [LineWithInvisibles],
3489 line_height: Pixels,
3490 scroll_pixel_position: gpui::Point<Pixels>,
3491 content_origin: gpui::Point<Pixels>,
3492 window: &mut Window,
3493 cx: &mut App,
3494 ) -> SmallVec<[AnyElement; 1]> {
3495 let mut line_elements = SmallVec::new();
3496 for (ix, line) in line_layouts.iter_mut().enumerate() {
3497 let row = start_row + DisplayRow(ix as u32);
3498 line.prepaint(
3499 line_height,
3500 scroll_pixel_position,
3501 row,
3502 content_origin,
3503 &mut line_elements,
3504 window,
3505 cx,
3506 );
3507 }
3508 line_elements
3509 }
3510
3511 fn render_block(
3512 &self,
3513 block: &Block,
3514 available_width: AvailableSpace,
3515 block_id: BlockId,
3516 block_row_start: DisplayRow,
3517 snapshot: &EditorSnapshot,
3518 text_x: Pixels,
3519 rows: &Range<DisplayRow>,
3520 line_layouts: &[LineWithInvisibles],
3521 editor_margins: &EditorMargins,
3522 line_height: Pixels,
3523 em_width: Pixels,
3524 text_hitbox: &Hitbox,
3525 editor_width: Pixels,
3526 scroll_width: &mut Pixels,
3527 resized_blocks: &mut HashMap<CustomBlockId, u32>,
3528 row_block_types: &mut HashMap<DisplayRow, bool>,
3529 selections: &[Selection<Point>],
3530 selected_buffer_ids: &Vec<BufferId>,
3531 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
3532 sticky_header_excerpt_id: Option<ExcerptId>,
3533 window: &mut Window,
3534 cx: &mut App,
3535 ) -> Option<(AnyElement, Size<Pixels>, DisplayRow, Pixels)> {
3536 let mut x_position = None;
3537 let mut element = match block {
3538 Block::Custom(custom) => {
3539 let block_start = custom.start().to_point(&snapshot.buffer_snapshot);
3540 let block_end = custom.end().to_point(&snapshot.buffer_snapshot);
3541 if block.place_near() && snapshot.is_line_folded(MultiBufferRow(block_start.row)) {
3542 return None;
3543 }
3544 let align_to = block_start.to_display_point(snapshot);
3545 let x_and_width = |layout: &LineWithInvisibles| {
3546 Some((
3547 text_x + layout.x_for_index(align_to.column() as usize),
3548 text_x + layout.width,
3549 ))
3550 };
3551 let line_ix = align_to.row().0.checked_sub(rows.start.0);
3552 x_position =
3553 if let Some(layout) = line_ix.and_then(|ix| line_layouts.get(ix as usize)) {
3554 x_and_width(layout)
3555 } else {
3556 x_and_width(&layout_line(
3557 align_to.row(),
3558 snapshot,
3559 &self.style,
3560 editor_width,
3561 is_row_soft_wrapped,
3562 window,
3563 cx,
3564 ))
3565 };
3566
3567 let anchor_x = x_position.unwrap().0;
3568
3569 let selected = selections
3570 .binary_search_by(|selection| {
3571 if selection.end <= block_start {
3572 Ordering::Less
3573 } else if selection.start >= block_end {
3574 Ordering::Greater
3575 } else {
3576 Ordering::Equal
3577 }
3578 })
3579 .is_ok();
3580
3581 div()
3582 .size_full()
3583 .child(custom.render(&mut BlockContext {
3584 window,
3585 app: cx,
3586 anchor_x,
3587 margins: editor_margins,
3588 line_height,
3589 em_width,
3590 block_id,
3591 selected,
3592 max_width: text_hitbox.size.width.max(*scroll_width),
3593 editor_style: &self.style,
3594 }))
3595 .into_any()
3596 }
3597
3598 Block::FoldedBuffer {
3599 first_excerpt,
3600 height,
3601 ..
3602 } => {
3603 let selected = selected_buffer_ids.contains(&first_excerpt.buffer_id);
3604 let result = v_flex().id(block_id).w_full().pr(editor_margins.right);
3605
3606 let jump_data = header_jump_data(snapshot, block_row_start, *height, first_excerpt);
3607 result
3608 .child(self.render_buffer_header(
3609 first_excerpt,
3610 true,
3611 selected,
3612 false,
3613 jump_data,
3614 window,
3615 cx,
3616 ))
3617 .into_any_element()
3618 }
3619
3620 Block::ExcerptBoundary { .. } => {
3621 let color = cx.theme().colors().clone();
3622 let mut result = v_flex().id(block_id).w_full();
3623
3624 result = result.child(
3625 h_flex().relative().child(
3626 div()
3627 .top(line_height / 2.)
3628 .absolute()
3629 .w_full()
3630 .h_px()
3631 .bg(color.border_variant),
3632 ),
3633 );
3634
3635 result.into_any()
3636 }
3637
3638 Block::BufferHeader { excerpt, height } => {
3639 let mut result = v_flex().id(block_id).w_full();
3640
3641 let jump_data = header_jump_data(snapshot, block_row_start, *height, excerpt);
3642
3643 if sticky_header_excerpt_id != Some(excerpt.id) {
3644 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
3645
3646 result = result.child(div().pr(editor_margins.right).child(
3647 self.render_buffer_header(
3648 excerpt, false, selected, false, jump_data, window, cx,
3649 ),
3650 ));
3651 } else {
3652 result =
3653 result.child(div().h(FILE_HEADER_HEIGHT as f32 * window.line_height()));
3654 }
3655
3656 result.into_any()
3657 }
3658 };
3659
3660 // Discover the element's content height, then round up to the nearest multiple of line height.
3661 let preliminary_size = element.layout_as_root(
3662 size(available_width, AvailableSpace::MinContent),
3663 window,
3664 cx,
3665 );
3666 let quantized_height = (preliminary_size.height / line_height).ceil() * line_height;
3667 let final_size = if preliminary_size.height == quantized_height {
3668 preliminary_size
3669 } else {
3670 element.layout_as_root(size(available_width, quantized_height.into()), window, cx)
3671 };
3672 let mut element_height_in_lines = ((final_size.height / line_height).ceil() as u32).max(1);
3673
3674 let mut row = block_row_start;
3675 let mut x_offset = px(0.);
3676 let mut is_block = true;
3677
3678 if let BlockId::Custom(custom_block_id) = block_id
3679 && block.has_height()
3680 {
3681 if block.place_near()
3682 && let Some((x_target, line_width)) = x_position
3683 {
3684 let margin = em_width * 2;
3685 if line_width + final_size.width + margin
3686 < editor_width + editor_margins.gutter.full_width()
3687 && !row_block_types.contains_key(&(row - 1))
3688 && element_height_in_lines == 1
3689 {
3690 x_offset = line_width + margin;
3691 row = row - 1;
3692 is_block = false;
3693 element_height_in_lines = 0;
3694 row_block_types.insert(row, is_block);
3695 } else {
3696 let max_offset =
3697 editor_width + editor_margins.gutter.full_width() - final_size.width;
3698 let min_offset = (x_target + em_width - final_size.width)
3699 .max(editor_margins.gutter.full_width());
3700 x_offset = x_target.min(max_offset).max(min_offset);
3701 }
3702 };
3703 if element_height_in_lines != block.height() {
3704 resized_blocks.insert(custom_block_id, element_height_in_lines);
3705 }
3706 }
3707 for i in 0..element_height_in_lines {
3708 row_block_types.insert(row + i, is_block);
3709 }
3710
3711 Some((element, final_size, row, x_offset))
3712 }
3713
3714 fn render_buffer_header(
3715 &self,
3716 for_excerpt: &ExcerptInfo,
3717 is_folded: bool,
3718 is_selected: bool,
3719 is_sticky: bool,
3720 jump_data: JumpData,
3721 window: &mut Window,
3722 cx: &mut App,
3723 ) -> impl IntoElement {
3724 let editor = self.editor.read(cx);
3725 let multi_buffer = editor.buffer.read(cx);
3726 let file_status = multi_buffer
3727 .all_diff_hunks_expanded()
3728 .then(|| {
3729 editor
3730 .project
3731 .as_ref()?
3732 .read(cx)
3733 .status_for_buffer_id(for_excerpt.buffer_id, cx)
3734 })
3735 .flatten();
3736 let indicator = multi_buffer
3737 .buffer(for_excerpt.buffer_id)
3738 .and_then(|buffer| {
3739 let buffer = buffer.read(cx);
3740 let indicator_color = match (buffer.has_conflict(), buffer.is_dirty()) {
3741 (true, _) => Some(Color::Warning),
3742 (_, true) => Some(Color::Accent),
3743 (false, false) => None,
3744 };
3745 indicator_color.map(|indicator_color| Indicator::dot().color(indicator_color))
3746 });
3747
3748 let include_root = editor
3749 .project
3750 .as_ref()
3751 .map(|project| project.read(cx).visible_worktrees(cx).count() > 1)
3752 .unwrap_or_default();
3753 let can_open_excerpts = Editor::can_open_excerpts_in_file(for_excerpt.buffer.file());
3754 let relative_path = for_excerpt.buffer.resolve_file_path(cx, include_root);
3755 let filename = relative_path
3756 .as_ref()
3757 .and_then(|path| Some(path.file_name()?.to_string_lossy().to_string()));
3758 let parent_path = relative_path.as_ref().and_then(|path| {
3759 Some(path.parent()?.to_string_lossy().to_string() + std::path::MAIN_SEPARATOR_STR)
3760 });
3761 let focus_handle = editor.focus_handle(cx);
3762 let colors = cx.theme().colors();
3763
3764 let header = div()
3765 .p_1()
3766 .w_full()
3767 .h(FILE_HEADER_HEIGHT as f32 * window.line_height())
3768 .child(
3769 h_flex()
3770 .size_full()
3771 .gap_2()
3772 .flex_basis(Length::Definite(DefiniteLength::Fraction(0.667)))
3773 .pl_0p5()
3774 .pr_5()
3775 .rounded_sm()
3776 .when(is_sticky, |el| el.shadow_md())
3777 .border_1()
3778 .map(|div| {
3779 let border_color = if is_selected
3780 && is_folded
3781 && focus_handle.contains_focused(window, cx)
3782 {
3783 colors.border_focused
3784 } else {
3785 colors.border
3786 };
3787 div.border_color(border_color)
3788 })
3789 .bg(colors.editor_subheader_background)
3790 .hover(|style| style.bg(colors.element_hover))
3791 .map(|header| {
3792 let editor = self.editor.clone();
3793 let buffer_id = for_excerpt.buffer_id;
3794 let toggle_chevron_icon =
3795 FileIcons::get_chevron_icon(!is_folded, cx).map(Icon::from_path);
3796 header.child(
3797 div()
3798 .hover(|style| style.bg(colors.element_selected))
3799 .rounded_xs()
3800 .child(
3801 ButtonLike::new("toggle-buffer-fold")
3802 .style(ui::ButtonStyle::Transparent)
3803 .height(px(28.).into())
3804 .width(px(28.))
3805 .children(toggle_chevron_icon)
3806 .tooltip({
3807 let focus_handle = focus_handle.clone();
3808 move |window, cx| {
3809 Tooltip::with_meta_in(
3810 "Toggle Excerpt Fold",
3811 Some(&ToggleFold),
3812 "Alt+click to toggle all",
3813 &focus_handle,
3814 window,
3815 cx,
3816 )
3817 }
3818 })
3819 .on_click(move |event, window, cx| {
3820 if event.modifiers().alt {
3821 // Alt+click toggles all buffers
3822 editor.update(cx, |editor, cx| {
3823 editor.toggle_fold_all(
3824 &ToggleFoldAll,
3825 window,
3826 cx,
3827 );
3828 });
3829 } else {
3830 // Regular click toggles single buffer
3831 if is_folded {
3832 editor.update(cx, |editor, cx| {
3833 editor.unfold_buffer(buffer_id, cx);
3834 });
3835 } else {
3836 editor.update(cx, |editor, cx| {
3837 editor.fold_buffer(buffer_id, cx);
3838 });
3839 }
3840 }
3841 }),
3842 ),
3843 )
3844 })
3845 .children(
3846 editor
3847 .addons
3848 .values()
3849 .filter_map(|addon| {
3850 addon.render_buffer_header_controls(for_excerpt, window, cx)
3851 })
3852 .take(1),
3853 )
3854 .child(
3855 h_flex()
3856 .size(Pixels(12.0))
3857 .justify_center()
3858 .children(indicator),
3859 )
3860 .child(
3861 h_flex()
3862 .cursor_pointer()
3863 .id("path header block")
3864 .size_full()
3865 .justify_between()
3866 .overflow_hidden()
3867 .child(
3868 h_flex()
3869 .gap_2()
3870 .map(|path_header| {
3871 let filename = filename
3872 .map(SharedString::from)
3873 .unwrap_or_else(|| "untitled".into());
3874
3875 path_header
3876 .when(ItemSettings::get_global(cx).file_icons, |el| {
3877 let path = path::Path::new(filename.as_str());
3878 let icon = FileIcons::get_icon(path, cx)
3879 .unwrap_or_default();
3880 let icon =
3881 Icon::from_path(icon).color(Color::Muted);
3882 el.child(icon)
3883 })
3884 .child(Label::new(filename).single_line().when_some(
3885 file_status,
3886 |el, status| {
3887 el.color(if status.is_conflicted() {
3888 Color::Conflict
3889 } else if status.is_modified() {
3890 Color::Modified
3891 } else if status.is_deleted() {
3892 Color::Disabled
3893 } else {
3894 Color::Created
3895 })
3896 .when(status.is_deleted(), |el| {
3897 el.strikethrough()
3898 })
3899 },
3900 ))
3901 })
3902 .when_some(parent_path, |then, path| {
3903 then.child(div().child(path).text_color(
3904 if file_status.is_some_and(FileStatus::is_deleted) {
3905 colors.text_disabled
3906 } else {
3907 colors.text_muted
3908 },
3909 ))
3910 }),
3911 )
3912 .when(
3913 can_open_excerpts && is_selected && relative_path.is_some(),
3914 |el| {
3915 el.child(
3916 h_flex()
3917 .id("jump-to-file-button")
3918 .gap_2p5()
3919 .child(Label::new("Jump To File"))
3920 .children(
3921 KeyBinding::for_action_in(
3922 &OpenExcerpts,
3923 &focus_handle,
3924 window,
3925 cx,
3926 )
3927 .map(|binding| binding.into_any_element()),
3928 ),
3929 )
3930 },
3931 )
3932 .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
3933 .on_click(window.listener_for(&self.editor, {
3934 move |editor, e: &ClickEvent, window, cx| {
3935 editor.open_excerpts_common(
3936 Some(jump_data.clone()),
3937 e.modifiers().secondary(),
3938 window,
3939 cx,
3940 );
3941 }
3942 })),
3943 ),
3944 );
3945
3946 let file = for_excerpt.buffer.file().cloned();
3947 let editor = self.editor.clone();
3948 right_click_menu("buffer-header-context-menu")
3949 .trigger(move |_, _, _| header)
3950 .menu(move |window, cx| {
3951 let menu_context = focus_handle.clone();
3952 let editor = editor.clone();
3953 let file = file.clone();
3954 ContextMenu::build(window, cx, move |mut menu, window, cx| {
3955 if let Some(file) = file
3956 && let Some(project) = editor.read(cx).project()
3957 && let Some(worktree) =
3958 project.read(cx).worktree_for_id(file.worktree_id(cx), cx)
3959 {
3960 let worktree = worktree.read(cx);
3961 let relative_path = file.path();
3962 let entry_for_path = worktree.entry_for_path(relative_path);
3963 let abs_path = entry_for_path.map(|e| {
3964 e.canonical_path.as_deref().map_or_else(
3965 || worktree.abs_path().join(relative_path),
3966 Path::to_path_buf,
3967 )
3968 });
3969 let has_relative_path = worktree.root_entry().is_some_and(Entry::is_dir);
3970
3971 let parent_abs_path = abs_path
3972 .as_ref()
3973 .and_then(|abs_path| Some(abs_path.parent()?.to_path_buf()));
3974 let relative_path = has_relative_path
3975 .then_some(relative_path)
3976 .map(ToOwned::to_owned);
3977
3978 let visible_in_project_panel =
3979 relative_path.is_some() && worktree.is_visible();
3980 let reveal_in_project_panel = entry_for_path
3981 .filter(|_| visible_in_project_panel)
3982 .map(|entry| entry.id);
3983 menu = menu
3984 .when_some(abs_path, |menu, abs_path| {
3985 menu.entry(
3986 "Copy Path",
3987 Some(Box::new(zed_actions::workspace::CopyPath)),
3988 window.handler_for(&editor, move |_, _, cx| {
3989 cx.write_to_clipboard(ClipboardItem::new_string(
3990 abs_path.to_string_lossy().to_string(),
3991 ));
3992 }),
3993 )
3994 })
3995 .when_some(relative_path, |menu, relative_path| {
3996 menu.entry(
3997 "Copy Relative Path",
3998 Some(Box::new(zed_actions::workspace::CopyRelativePath)),
3999 window.handler_for(&editor, move |_, _, cx| {
4000 cx.write_to_clipboard(ClipboardItem::new_string(
4001 relative_path.to_string_lossy().to_string(),
4002 ));
4003 }),
4004 )
4005 })
4006 .when(
4007 reveal_in_project_panel.is_some() || parent_abs_path.is_some(),
4008 |menu| menu.separator(),
4009 )
4010 .when_some(reveal_in_project_panel, |menu, entry_id| {
4011 menu.entry(
4012 "Reveal In Project Panel",
4013 Some(Box::new(RevealInProjectPanel::default())),
4014 window.handler_for(&editor, move |editor, _, cx| {
4015 if let Some(project) = &mut editor.project {
4016 project.update(cx, |_, cx| {
4017 cx.emit(project::Event::RevealInProjectPanel(
4018 entry_id,
4019 ))
4020 });
4021 }
4022 }),
4023 )
4024 })
4025 .when_some(parent_abs_path, |menu, parent_abs_path| {
4026 menu.entry(
4027 "Open in Terminal",
4028 Some(Box::new(OpenInTerminal)),
4029 window.handler_for(&editor, move |_, window, cx| {
4030 window.dispatch_action(
4031 OpenTerminal {
4032 working_directory: parent_abs_path.clone(),
4033 }
4034 .boxed_clone(),
4035 cx,
4036 );
4037 }),
4038 )
4039 });
4040 }
4041
4042 menu.context(menu_context)
4043 })
4044 })
4045 }
4046
4047 fn render_blocks(
4048 &self,
4049 rows: Range<DisplayRow>,
4050 snapshot: &EditorSnapshot,
4051 hitbox: &Hitbox,
4052 text_hitbox: &Hitbox,
4053 editor_width: Pixels,
4054 scroll_width: &mut Pixels,
4055 editor_margins: &EditorMargins,
4056 em_width: Pixels,
4057 text_x: Pixels,
4058 line_height: Pixels,
4059 line_layouts: &mut [LineWithInvisibles],
4060 selections: &[Selection<Point>],
4061 selected_buffer_ids: &Vec<BufferId>,
4062 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
4063 sticky_header_excerpt_id: Option<ExcerptId>,
4064 window: &mut Window,
4065 cx: &mut App,
4066 ) -> Result<(Vec<BlockLayout>, HashMap<DisplayRow, bool>), HashMap<CustomBlockId, u32>> {
4067 let (fixed_blocks, non_fixed_blocks) = snapshot
4068 .blocks_in_range(rows.clone())
4069 .partition::<Vec<_>, _>(|(_, block)| block.style() == BlockStyle::Fixed);
4070
4071 let mut focused_block = self
4072 .editor
4073 .update(cx, |editor, _| editor.take_focused_block());
4074 let mut fixed_block_max_width = Pixels::ZERO;
4075 let mut blocks = Vec::new();
4076 let mut resized_blocks = HashMap::default();
4077 let mut row_block_types = HashMap::default();
4078
4079 for (row, block) in fixed_blocks {
4080 let block_id = block.id();
4081
4082 if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
4083 focused_block = None;
4084 }
4085
4086 if let Some((element, element_size, row, x_offset)) = self.render_block(
4087 block,
4088 AvailableSpace::MinContent,
4089 block_id,
4090 row,
4091 snapshot,
4092 text_x,
4093 &rows,
4094 line_layouts,
4095 editor_margins,
4096 line_height,
4097 em_width,
4098 text_hitbox,
4099 editor_width,
4100 scroll_width,
4101 &mut resized_blocks,
4102 &mut row_block_types,
4103 selections,
4104 selected_buffer_ids,
4105 is_row_soft_wrapped,
4106 sticky_header_excerpt_id,
4107 window,
4108 cx,
4109 ) {
4110 fixed_block_max_width = fixed_block_max_width.max(element_size.width + em_width);
4111 blocks.push(BlockLayout {
4112 id: block_id,
4113 x_offset,
4114 row: Some(row),
4115 element,
4116 available_space: size(AvailableSpace::MinContent, element_size.height.into()),
4117 style: BlockStyle::Fixed,
4118 overlaps_gutter: true,
4119 is_buffer_header: block.is_buffer_header(),
4120 });
4121 }
4122 }
4123
4124 for (row, block) in non_fixed_blocks {
4125 let style = block.style();
4126 let width = match (style, block.place_near()) {
4127 (_, true) => AvailableSpace::MinContent,
4128 (BlockStyle::Sticky, _) => hitbox.size.width.into(),
4129 (BlockStyle::Flex, _) => hitbox
4130 .size
4131 .width
4132 .max(fixed_block_max_width)
4133 .max(editor_margins.gutter.width + *scroll_width)
4134 .into(),
4135 (BlockStyle::Fixed, _) => unreachable!(),
4136 };
4137 let block_id = block.id();
4138
4139 if focused_block.as_ref().is_some_and(|b| b.id == block_id) {
4140 focused_block = None;
4141 }
4142
4143 if let Some((element, element_size, row, x_offset)) = self.render_block(
4144 block,
4145 width,
4146 block_id,
4147 row,
4148 snapshot,
4149 text_x,
4150 &rows,
4151 line_layouts,
4152 editor_margins,
4153 line_height,
4154 em_width,
4155 text_hitbox,
4156 editor_width,
4157 scroll_width,
4158 &mut resized_blocks,
4159 &mut row_block_types,
4160 selections,
4161 selected_buffer_ids,
4162 is_row_soft_wrapped,
4163 sticky_header_excerpt_id,
4164 window,
4165 cx,
4166 ) {
4167 blocks.push(BlockLayout {
4168 id: block_id,
4169 x_offset,
4170 row: Some(row),
4171 element,
4172 available_space: size(width, element_size.height.into()),
4173 style,
4174 overlaps_gutter: !block.place_near(),
4175 is_buffer_header: block.is_buffer_header(),
4176 });
4177 }
4178 }
4179
4180 if let Some(focused_block) = focused_block
4181 && let Some(focus_handle) = focused_block.focus_handle.upgrade()
4182 && focus_handle.is_focused(window)
4183 && let Some(block) = snapshot.block_for_id(focused_block.id)
4184 {
4185 let style = block.style();
4186 let width = match style {
4187 BlockStyle::Fixed => AvailableSpace::MinContent,
4188 BlockStyle::Flex => AvailableSpace::Definite(
4189 hitbox
4190 .size
4191 .width
4192 .max(fixed_block_max_width)
4193 .max(editor_margins.gutter.width + *scroll_width),
4194 ),
4195 BlockStyle::Sticky => AvailableSpace::Definite(hitbox.size.width),
4196 };
4197
4198 if let Some((element, element_size, _, x_offset)) = self.render_block(
4199 &block,
4200 width,
4201 focused_block.id,
4202 rows.end,
4203 snapshot,
4204 text_x,
4205 &rows,
4206 line_layouts,
4207 editor_margins,
4208 line_height,
4209 em_width,
4210 text_hitbox,
4211 editor_width,
4212 scroll_width,
4213 &mut resized_blocks,
4214 &mut row_block_types,
4215 selections,
4216 selected_buffer_ids,
4217 is_row_soft_wrapped,
4218 sticky_header_excerpt_id,
4219 window,
4220 cx,
4221 ) {
4222 blocks.push(BlockLayout {
4223 id: block.id(),
4224 x_offset,
4225 row: None,
4226 element,
4227 available_space: size(width, element_size.height.into()),
4228 style,
4229 overlaps_gutter: true,
4230 is_buffer_header: block.is_buffer_header(),
4231 });
4232 }
4233 }
4234
4235 if resized_blocks.is_empty() {
4236 *scroll_width =
4237 (*scroll_width).max(fixed_block_max_width - editor_margins.gutter.width);
4238 Ok((blocks, row_block_types))
4239 } else {
4240 Err(resized_blocks)
4241 }
4242 }
4243
4244 fn layout_blocks(
4245 &self,
4246 blocks: &mut Vec<BlockLayout>,
4247 hitbox: &Hitbox,
4248 line_height: Pixels,
4249 scroll_pixel_position: gpui::Point<Pixels>,
4250 window: &mut Window,
4251 cx: &mut App,
4252 ) {
4253 for block in blocks {
4254 let mut origin = if let Some(row) = block.row {
4255 hitbox.origin
4256 + point(
4257 block.x_offset,
4258 row.as_f32() * line_height - scroll_pixel_position.y,
4259 )
4260 } else {
4261 // Position the block outside the visible area
4262 hitbox.origin + point(Pixels::ZERO, hitbox.size.height)
4263 };
4264
4265 if !matches!(block.style, BlockStyle::Sticky) {
4266 origin += point(-scroll_pixel_position.x, Pixels::ZERO);
4267 }
4268
4269 let focus_handle =
4270 block
4271 .element
4272 .prepaint_as_root(origin, block.available_space, window, cx);
4273
4274 if let Some(focus_handle) = focus_handle {
4275 self.editor.update(cx, |editor, _cx| {
4276 editor.set_focused_block(FocusedBlock {
4277 id: block.id,
4278 focus_handle: focus_handle.downgrade(),
4279 });
4280 });
4281 }
4282 }
4283 }
4284
4285 fn layout_sticky_buffer_header(
4286 &self,
4287 StickyHeaderExcerpt { excerpt }: StickyHeaderExcerpt<'_>,
4288 scroll_position: f32,
4289 line_height: Pixels,
4290 right_margin: Pixels,
4291 snapshot: &EditorSnapshot,
4292 hitbox: &Hitbox,
4293 selected_buffer_ids: &Vec<BufferId>,
4294 blocks: &[BlockLayout],
4295 window: &mut Window,
4296 cx: &mut App,
4297 ) -> AnyElement {
4298 let jump_data = header_jump_data(
4299 snapshot,
4300 DisplayRow(scroll_position as u32),
4301 FILE_HEADER_HEIGHT + MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
4302 excerpt,
4303 );
4304
4305 let editor_bg_color = cx.theme().colors().editor_background;
4306
4307 let selected = selected_buffer_ids.contains(&excerpt.buffer_id);
4308
4309 let available_width = hitbox.bounds.size.width - right_margin;
4310
4311 let mut header = v_flex()
4312 .w_full()
4313 .relative()
4314 .child(
4315 div()
4316 .w(available_width)
4317 .h(FILE_HEADER_HEIGHT as f32 * line_height)
4318 .bg(linear_gradient(
4319 0.,
4320 linear_color_stop(editor_bg_color.opacity(0.), 0.),
4321 linear_color_stop(editor_bg_color, 0.6),
4322 ))
4323 .absolute()
4324 .top_0(),
4325 )
4326 .child(
4327 self.render_buffer_header(excerpt, false, selected, true, jump_data, window, cx)
4328 .into_any_element(),
4329 )
4330 .into_any_element();
4331
4332 let mut origin = hitbox.origin;
4333 // Move floating header up to avoid colliding with the next buffer header.
4334 for block in blocks.iter() {
4335 if !block.is_buffer_header {
4336 continue;
4337 }
4338
4339 let Some(display_row) = block.row.filter(|row| row.0 > scroll_position as u32) else {
4340 continue;
4341 };
4342
4343 let max_row = display_row.0.saturating_sub(FILE_HEADER_HEIGHT);
4344 let offset = scroll_position - max_row as f32;
4345
4346 if offset > 0.0 {
4347 origin.y -= offset * line_height;
4348 }
4349 break;
4350 }
4351
4352 let size = size(
4353 AvailableSpace::Definite(available_width),
4354 AvailableSpace::MinContent,
4355 );
4356
4357 header.prepaint_as_root(origin, size, window, cx);
4358
4359 header
4360 }
4361
4362 fn layout_cursor_popovers(
4363 &self,
4364 line_height: Pixels,
4365 text_hitbox: &Hitbox,
4366 content_origin: gpui::Point<Pixels>,
4367 right_margin: Pixels,
4368 start_row: DisplayRow,
4369 scroll_pixel_position: gpui::Point<Pixels>,
4370 line_layouts: &[LineWithInvisibles],
4371 cursor: DisplayPoint,
4372 cursor_point: Point,
4373 style: &EditorStyle,
4374 window: &mut Window,
4375 cx: &mut App,
4376 ) -> Option<ContextMenuLayout> {
4377 let mut min_menu_height = Pixels::ZERO;
4378 let mut max_menu_height = Pixels::ZERO;
4379 let mut height_above_menu = Pixels::ZERO;
4380 let height_below_menu = Pixels::ZERO;
4381 let mut edit_prediction_popover_visible = false;
4382 let mut context_menu_visible = false;
4383 let context_menu_placement;
4384
4385 {
4386 let editor = self.editor.read(cx);
4387 if editor.edit_prediction_visible_in_cursor_popover(editor.has_active_edit_prediction())
4388 {
4389 height_above_menu +=
4390 editor.edit_prediction_cursor_popover_height() + POPOVER_Y_PADDING;
4391 edit_prediction_popover_visible = true;
4392 }
4393
4394 if editor.context_menu_visible()
4395 && let Some(crate::ContextMenuOrigin::Cursor) = editor.context_menu_origin()
4396 {
4397 let (min_height_in_lines, max_height_in_lines) = editor
4398 .context_menu_options
4399 .as_ref()
4400 .map_or((3, 12), |options| {
4401 (options.min_entries_visible, options.max_entries_visible)
4402 });
4403
4404 min_menu_height += line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4405 max_menu_height += line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4406 context_menu_visible = true;
4407 }
4408 context_menu_placement = editor
4409 .context_menu_options
4410 .as_ref()
4411 .and_then(|options| options.placement.clone());
4412 }
4413
4414 let visible = edit_prediction_popover_visible || context_menu_visible;
4415 if !visible {
4416 return None;
4417 }
4418
4419 let cursor_row_layout = &line_layouts[cursor.row().minus(start_row) as usize];
4420 let target_position = content_origin
4421 + gpui::Point {
4422 x: cmp::max(
4423 px(0.),
4424 cursor_row_layout.x_for_index(cursor.column() as usize)
4425 - scroll_pixel_position.x,
4426 ),
4427 y: cmp::max(
4428 px(0.),
4429 cursor.row().next_row().as_f32() * line_height - scroll_pixel_position.y,
4430 ),
4431 };
4432
4433 let viewport_bounds =
4434 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4435 right: -right_margin - MENU_GAP,
4436 ..Default::default()
4437 });
4438
4439 let min_height = height_above_menu + min_menu_height + height_below_menu;
4440 let max_height = height_above_menu + max_menu_height + height_below_menu;
4441 let (laid_out_popovers, y_flipped) = self.layout_popovers_above_or_below_line(
4442 target_position,
4443 line_height,
4444 min_height,
4445 max_height,
4446 context_menu_placement,
4447 text_hitbox,
4448 viewport_bounds,
4449 window,
4450 cx,
4451 |height, max_width_for_stable_x, y_flipped, window, cx| {
4452 // First layout the menu to get its size - others can be at least this wide.
4453 let context_menu = if context_menu_visible {
4454 let menu_height = if y_flipped {
4455 height - height_below_menu
4456 } else {
4457 height - height_above_menu
4458 };
4459 let mut element = self
4460 .render_context_menu(line_height, menu_height, window, cx)
4461 .expect("Visible context menu should always render.");
4462 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4463 Some((CursorPopoverType::CodeContextMenu, element, size))
4464 } else {
4465 None
4466 };
4467 let min_width = context_menu
4468 .as_ref()
4469 .map_or(px(0.), |(_, _, size)| size.width);
4470 let max_width = max_width_for_stable_x.max(
4471 context_menu
4472 .as_ref()
4473 .map_or(px(0.), |(_, _, size)| size.width),
4474 );
4475
4476 let edit_prediction = if edit_prediction_popover_visible {
4477 self.editor.update(cx, move |editor, cx| {
4478 let accept_binding =
4479 editor.accept_edit_prediction_keybind(false, window, cx);
4480 let mut element = editor.render_edit_prediction_cursor_popover(
4481 min_width,
4482 max_width,
4483 cursor_point,
4484 style,
4485 accept_binding.keystroke(),
4486 window,
4487 cx,
4488 )?;
4489 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4490 Some((CursorPopoverType::EditPrediction, element, size))
4491 })
4492 } else {
4493 None
4494 };
4495 vec![edit_prediction, context_menu]
4496 .into_iter()
4497 .flatten()
4498 .collect::<Vec<_>>()
4499 },
4500 )?;
4501
4502 let (menu_ix, (_, menu_bounds)) = laid_out_popovers
4503 .iter()
4504 .find_position(|(x, _)| matches!(x, CursorPopoverType::CodeContextMenu))?;
4505 let last_ix = laid_out_popovers.len() - 1;
4506 let menu_is_last = menu_ix == last_ix;
4507 let first_popover_bounds = laid_out_popovers[0].1;
4508 let last_popover_bounds = laid_out_popovers[last_ix].1;
4509
4510 // Bounds to layout the aside around. When y_flipped, the aside goes either above or to the
4511 // right, and otherwise it goes below or to the right.
4512 let mut target_bounds = Bounds::from_corners(
4513 first_popover_bounds.origin,
4514 last_popover_bounds.bottom_right(),
4515 );
4516 target_bounds.size.width = menu_bounds.size.width;
4517
4518 // Like `target_bounds`, but with the max height it could occupy. Choosing an aside position
4519 // based on this is preferred for layout stability.
4520 let mut max_target_bounds = target_bounds;
4521 max_target_bounds.size.height = max_height;
4522 if y_flipped {
4523 max_target_bounds.origin.y -= max_height - target_bounds.size.height;
4524 }
4525
4526 // Add spacing around `target_bounds` and `max_target_bounds`.
4527 let mut extend_amount = Edges::all(MENU_GAP);
4528 if y_flipped {
4529 extend_amount.bottom = line_height;
4530 } else {
4531 extend_amount.top = line_height;
4532 }
4533 let target_bounds = target_bounds.extend(extend_amount);
4534 let max_target_bounds = max_target_bounds.extend(extend_amount);
4535
4536 let must_place_above_or_below =
4537 if y_flipped && !menu_is_last && menu_bounds.size.height < max_menu_height {
4538 laid_out_popovers[menu_ix + 1..]
4539 .iter()
4540 .any(|(_, popover_bounds)| popover_bounds.size.width > menu_bounds.size.width)
4541 } else {
4542 false
4543 };
4544
4545 let aside_bounds = self.layout_context_menu_aside(
4546 y_flipped,
4547 *menu_bounds,
4548 target_bounds,
4549 max_target_bounds,
4550 max_menu_height,
4551 must_place_above_or_below,
4552 text_hitbox,
4553 viewport_bounds,
4554 window,
4555 cx,
4556 );
4557
4558 if let Some(menu_bounds) = laid_out_popovers.iter().find_map(|(popover_type, bounds)| {
4559 if matches!(popover_type, CursorPopoverType::CodeContextMenu) {
4560 Some(*bounds)
4561 } else {
4562 None
4563 }
4564 }) {
4565 let bounds = if let Some(aside_bounds) = aside_bounds {
4566 menu_bounds.union(&aside_bounds)
4567 } else {
4568 menu_bounds
4569 };
4570 return Some(ContextMenuLayout { y_flipped, bounds });
4571 }
4572
4573 None
4574 }
4575
4576 fn layout_gutter_menu(
4577 &self,
4578 line_height: Pixels,
4579 text_hitbox: &Hitbox,
4580 content_origin: gpui::Point<Pixels>,
4581 right_margin: Pixels,
4582 scroll_pixel_position: gpui::Point<Pixels>,
4583 gutter_overshoot: Pixels,
4584 window: &mut Window,
4585 cx: &mut App,
4586 ) {
4587 let editor = self.editor.read(cx);
4588 if !editor.context_menu_visible() {
4589 return;
4590 }
4591 let Some(crate::ContextMenuOrigin::GutterIndicator(gutter_row)) =
4592 editor.context_menu_origin()
4593 else {
4594 return;
4595 };
4596 // Context menu was spawned via a click on a gutter. Ensure it's a bit closer to the
4597 // indicator than just a plain first column of the text field.
4598 let target_position = content_origin
4599 + gpui::Point {
4600 x: -gutter_overshoot,
4601 y: gutter_row.next_row().as_f32() * line_height - scroll_pixel_position.y,
4602 };
4603
4604 let (min_height_in_lines, max_height_in_lines) = editor
4605 .context_menu_options
4606 .as_ref()
4607 .map_or((3, 12), |options| {
4608 (options.min_entries_visible, options.max_entries_visible)
4609 });
4610
4611 let min_height = line_height * min_height_in_lines as f32 + POPOVER_Y_PADDING;
4612 let max_height = line_height * max_height_in_lines as f32 + POPOVER_Y_PADDING;
4613 let viewport_bounds =
4614 Bounds::new(Default::default(), window.viewport_size()).extend(Edges {
4615 right: -right_margin - MENU_GAP,
4616 ..Default::default()
4617 });
4618 self.layout_popovers_above_or_below_line(
4619 target_position,
4620 line_height,
4621 min_height,
4622 max_height,
4623 editor
4624 .context_menu_options
4625 .as_ref()
4626 .and_then(|options| options.placement.clone()),
4627 text_hitbox,
4628 viewport_bounds,
4629 window,
4630 cx,
4631 move |height, _max_width_for_stable_x, _, window, cx| {
4632 let mut element = self
4633 .render_context_menu(line_height, height, window, cx)
4634 .expect("Visible context menu should always render.");
4635 let size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
4636 vec![(CursorPopoverType::CodeContextMenu, element, size)]
4637 },
4638 );
4639 }
4640
4641 fn layout_popovers_above_or_below_line(
4642 &self,
4643 target_position: gpui::Point<Pixels>,
4644 line_height: Pixels,
4645 min_height: Pixels,
4646 max_height: Pixels,
4647 placement: Option<ContextMenuPlacement>,
4648 text_hitbox: &Hitbox,
4649 viewport_bounds: Bounds<Pixels>,
4650 window: &mut Window,
4651 cx: &mut App,
4652 make_sized_popovers: impl FnOnce(
4653 Pixels,
4654 Pixels,
4655 bool,
4656 &mut Window,
4657 &mut App,
4658 ) -> Vec<(CursorPopoverType, AnyElement, Size<Pixels>)>,
4659 ) -> Option<(Vec<(CursorPopoverType, Bounds<Pixels>)>, bool)> {
4660 let text_style = TextStyleRefinement {
4661 line_height: Some(DefiniteLength::Fraction(
4662 BufferLineHeight::Comfortable.value(),
4663 )),
4664 ..Default::default()
4665 };
4666 window.with_text_style(Some(text_style), |window| {
4667 // If the max height won't fit below and there is more space above, put it above the line.
4668 let bottom_y_when_flipped = target_position.y - line_height;
4669 let available_above = bottom_y_when_flipped - text_hitbox.top();
4670 let available_below = text_hitbox.bottom() - target_position.y;
4671 let y_overflows_below = max_height > available_below;
4672 let mut y_flipped = match placement {
4673 Some(ContextMenuPlacement::Above) => true,
4674 Some(ContextMenuPlacement::Below) => false,
4675 None => y_overflows_below && available_above > available_below,
4676 };
4677 let mut height = cmp::min(
4678 max_height,
4679 if y_flipped {
4680 available_above
4681 } else {
4682 available_below
4683 },
4684 );
4685
4686 // If the min height doesn't fit within text bounds, instead fit within the window.
4687 if height < min_height {
4688 let available_above = bottom_y_when_flipped;
4689 let available_below = viewport_bounds.bottom() - target_position.y;
4690 let (y_flipped_override, height_override) = match placement {
4691 Some(ContextMenuPlacement::Above) => {
4692 (true, cmp::min(available_above, min_height))
4693 }
4694 Some(ContextMenuPlacement::Below) => {
4695 (false, cmp::min(available_below, min_height))
4696 }
4697 None => {
4698 if available_below > min_height {
4699 (false, min_height)
4700 } else if available_above > min_height {
4701 (true, min_height)
4702 } else if available_above > available_below {
4703 (true, available_above)
4704 } else {
4705 (false, available_below)
4706 }
4707 }
4708 };
4709 y_flipped = y_flipped_override;
4710 height = height_override;
4711 }
4712
4713 let max_width_for_stable_x = viewport_bounds.right() - target_position.x;
4714
4715 // TODO: Use viewport_bounds.width as a max width so that it doesn't get clipped on the left
4716 // for very narrow windows.
4717 let popovers =
4718 make_sized_popovers(height, max_width_for_stable_x, y_flipped, window, cx);
4719 if popovers.is_empty() {
4720 return None;
4721 }
4722
4723 let max_width = popovers
4724 .iter()
4725 .map(|(_, _, size)| size.width)
4726 .max()
4727 .unwrap_or_default();
4728
4729 let mut current_position = gpui::Point {
4730 // Snap the right edge of the list to the right edge of the window if its horizontal bounds
4731 // overflow. Include space for the scrollbar.
4732 x: target_position
4733 .x
4734 .min((viewport_bounds.right() - max_width).max(Pixels::ZERO)),
4735 y: if y_flipped {
4736 bottom_y_when_flipped
4737 } else {
4738 target_position.y
4739 },
4740 };
4741
4742 let mut laid_out_popovers = popovers
4743 .into_iter()
4744 .map(|(popover_type, element, size)| {
4745 if y_flipped {
4746 current_position.y -= size.height;
4747 }
4748 let position = current_position;
4749 window.defer_draw(element, current_position, 1);
4750 if !y_flipped {
4751 current_position.y += size.height + MENU_GAP;
4752 } else {
4753 current_position.y -= MENU_GAP;
4754 }
4755 (popover_type, Bounds::new(position, size))
4756 })
4757 .collect::<Vec<_>>();
4758
4759 if y_flipped {
4760 laid_out_popovers.reverse();
4761 }
4762
4763 Some((laid_out_popovers, y_flipped))
4764 })
4765 }
4766
4767 fn layout_context_menu_aside(
4768 &self,
4769 y_flipped: bool,
4770 menu_bounds: Bounds<Pixels>,
4771 target_bounds: Bounds<Pixels>,
4772 max_target_bounds: Bounds<Pixels>,
4773 max_height: Pixels,
4774 must_place_above_or_below: bool,
4775 text_hitbox: &Hitbox,
4776 viewport_bounds: Bounds<Pixels>,
4777 window: &mut Window,
4778 cx: &mut App,
4779 ) -> Option<Bounds<Pixels>> {
4780 let available_within_viewport = target_bounds.space_within(&viewport_bounds);
4781 let positioned_aside = if available_within_viewport.right >= MENU_ASIDE_MIN_WIDTH
4782 && !must_place_above_or_below
4783 {
4784 let max_width = cmp::min(
4785 available_within_viewport.right - px(1.),
4786 MENU_ASIDE_MAX_WIDTH,
4787 );
4788 let mut aside = self.render_context_menu_aside(
4789 size(max_width, max_height - POPOVER_Y_PADDING),
4790 window,
4791 cx,
4792 )?;
4793 let size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
4794 let right_position = point(target_bounds.right(), menu_bounds.origin.y);
4795 Some((aside, right_position, size))
4796 } else {
4797 let max_size = size(
4798 // TODO(mgsloan): Once the menu is bounded by viewport width the bound on viewport
4799 // won't be needed here.
4800 cmp::min(
4801 cmp::max(menu_bounds.size.width - px(2.), MENU_ASIDE_MIN_WIDTH),
4802 viewport_bounds.right(),
4803 ),
4804 cmp::min(
4805 max_height,
4806 cmp::max(
4807 available_within_viewport.top,
4808 available_within_viewport.bottom,
4809 ),
4810 ) - POPOVER_Y_PADDING,
4811 );
4812 let mut aside = self.render_context_menu_aside(max_size, window, cx)?;
4813 let actual_size = aside.layout_as_root(AvailableSpace::min_size(), window, cx);
4814
4815 let top_position = point(
4816 menu_bounds.origin.x,
4817 target_bounds.top() - actual_size.height,
4818 );
4819 let bottom_position = point(menu_bounds.origin.x, target_bounds.bottom());
4820
4821 let fit_within = |available: Edges<Pixels>, wanted: Size<Pixels>| {
4822 // Prefer to fit on the same side of the line as the menu, then on the other side of
4823 // the line.
4824 if !y_flipped && wanted.height < available.bottom {
4825 Some(bottom_position)
4826 } else if !y_flipped && wanted.height < available.top {
4827 Some(top_position)
4828 } else if y_flipped && wanted.height < available.top {
4829 Some(top_position)
4830 } else if y_flipped && wanted.height < available.bottom {
4831 Some(bottom_position)
4832 } else {
4833 None
4834 }
4835 };
4836
4837 // Prefer choosing a direction using max sizes rather than actual size for stability.
4838 let available_within_text = max_target_bounds.space_within(&text_hitbox.bounds);
4839 let wanted = size(MENU_ASIDE_MAX_WIDTH, max_height);
4840 let aside_position = fit_within(available_within_text, wanted)
4841 // Fallback: fit max size in window.
4842 .or_else(|| fit_within(max_target_bounds.space_within(&viewport_bounds), wanted))
4843 // Fallback: fit actual size in window.
4844 .or_else(|| fit_within(available_within_viewport, actual_size));
4845
4846 aside_position.map(|position| (aside, position, actual_size))
4847 };
4848
4849 // Skip drawing if it doesn't fit anywhere.
4850 if let Some((aside, position, size)) = positioned_aside {
4851 let aside_bounds = Bounds::new(position, size);
4852 window.defer_draw(aside, position, 2);
4853 return Some(aside_bounds);
4854 }
4855
4856 None
4857 }
4858
4859 fn render_context_menu(
4860 &self,
4861 line_height: Pixels,
4862 height: Pixels,
4863 window: &mut Window,
4864 cx: &mut App,
4865 ) -> Option<AnyElement> {
4866 let max_height_in_lines = ((height - POPOVER_Y_PADDING) / line_height).floor() as u32;
4867 self.editor.update(cx, |editor, cx| {
4868 editor.render_context_menu(&self.style, max_height_in_lines, window, cx)
4869 })
4870 }
4871
4872 fn render_context_menu_aside(
4873 &self,
4874 max_size: Size<Pixels>,
4875 window: &mut Window,
4876 cx: &mut App,
4877 ) -> Option<AnyElement> {
4878 if max_size.width < px(100.) || max_size.height < px(12.) {
4879 None
4880 } else {
4881 self.editor.update(cx, |editor, cx| {
4882 editor.render_context_menu_aside(max_size, window, cx)
4883 })
4884 }
4885 }
4886
4887 fn layout_mouse_context_menu(
4888 &self,
4889 editor_snapshot: &EditorSnapshot,
4890 visible_range: Range<DisplayRow>,
4891 content_origin: gpui::Point<Pixels>,
4892 window: &mut Window,
4893 cx: &mut App,
4894 ) -> Option<AnyElement> {
4895 let position = self.editor.update(cx, |editor, _cx| {
4896 let visible_start_point = editor.display_to_pixel_point(
4897 DisplayPoint::new(visible_range.start, 0),
4898 editor_snapshot,
4899 window,
4900 )?;
4901 let visible_end_point = editor.display_to_pixel_point(
4902 DisplayPoint::new(visible_range.end, 0),
4903 editor_snapshot,
4904 window,
4905 )?;
4906
4907 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4908 let (source_display_point, position) = match mouse_context_menu.position {
4909 MenuPosition::PinnedToScreen(point) => (None, point),
4910 MenuPosition::PinnedToEditor { source, offset } => {
4911 let source_display_point = source.to_display_point(editor_snapshot);
4912 let source_point = editor.to_pixel_point(source, editor_snapshot, window)?;
4913 let position = content_origin + source_point + offset;
4914 (Some(source_display_point), position)
4915 }
4916 };
4917
4918 let source_included = source_display_point.is_none_or(|source_display_point| {
4919 visible_range
4920 .to_inclusive()
4921 .contains(&source_display_point.row())
4922 });
4923 let position_included =
4924 visible_start_point.y <= position.y && position.y <= visible_end_point.y;
4925 if !source_included && !position_included {
4926 None
4927 } else {
4928 Some(position)
4929 }
4930 })?;
4931
4932 let text_style = TextStyleRefinement {
4933 line_height: Some(DefiniteLength::Fraction(
4934 BufferLineHeight::Comfortable.value(),
4935 )),
4936 ..Default::default()
4937 };
4938 window.with_text_style(Some(text_style), |window| {
4939 let mut element = self.editor.read_with(cx, |editor, _| {
4940 let mouse_context_menu = editor.mouse_context_menu.as_ref()?;
4941 let context_menu = mouse_context_menu.context_menu.clone();
4942
4943 Some(
4944 deferred(
4945 anchored()
4946 .position(position)
4947 .child(context_menu)
4948 .anchor(Corner::TopLeft)
4949 .snap_to_window_with_margin(px(8.)),
4950 )
4951 .with_priority(1)
4952 .into_any(),
4953 )
4954 })?;
4955
4956 element.prepaint_as_root(position, AvailableSpace::min_size(), window, cx);
4957 Some(element)
4958 })
4959 }
4960
4961 fn layout_hover_popovers(
4962 &self,
4963 snapshot: &EditorSnapshot,
4964 hitbox: &Hitbox,
4965 visible_display_row_range: Range<DisplayRow>,
4966 content_origin: gpui::Point<Pixels>,
4967 scroll_pixel_position: gpui::Point<Pixels>,
4968 line_layouts: &[LineWithInvisibles],
4969 line_height: Pixels,
4970 em_width: Pixels,
4971 context_menu_layout: Option<ContextMenuLayout>,
4972 window: &mut Window,
4973 cx: &mut App,
4974 ) {
4975 struct MeasuredHoverPopover {
4976 element: AnyElement,
4977 size: Size<Pixels>,
4978 horizontal_offset: Pixels,
4979 }
4980
4981 let max_size = size(
4982 (120. * em_width) // Default size
4983 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
4984 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
4985 (16. * line_height) // Default size
4986 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
4987 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
4988 );
4989
4990 let hover_popovers = self.editor.update(cx, |editor, cx| {
4991 editor.hover_state.render(
4992 snapshot,
4993 visible_display_row_range.clone(),
4994 max_size,
4995 window,
4996 cx,
4997 )
4998 });
4999 let Some((position, hover_popovers)) = hover_popovers else {
5000 return;
5001 };
5002
5003 // This is safe because we check on layout whether the required row is available
5004 let hovered_row_layout =
5005 &line_layouts[position.row().minus(visible_display_row_range.start) as usize];
5006
5007 // Compute Hovered Point
5008 let x =
5009 hovered_row_layout.x_for_index(position.column() as usize) - scroll_pixel_position.x;
5010 let y = position.row().as_f32() * line_height - scroll_pixel_position.y;
5011 let hovered_point = content_origin + point(x, y);
5012
5013 let mut overall_height = Pixels::ZERO;
5014 let mut measured_hover_popovers = Vec::new();
5015 for (position, mut hover_popover) in hover_popovers.into_iter().with_position() {
5016 let size = hover_popover.layout_as_root(AvailableSpace::min_size(), window, cx);
5017 let horizontal_offset =
5018 (hitbox.top_right().x - POPOVER_RIGHT_OFFSET - (hovered_point.x + size.width))
5019 .min(Pixels::ZERO);
5020 match position {
5021 itertools::Position::Middle | itertools::Position::Last => {
5022 overall_height += HOVER_POPOVER_GAP
5023 }
5024 _ => {}
5025 }
5026 overall_height += size.height;
5027 measured_hover_popovers.push(MeasuredHoverPopover {
5028 element: hover_popover,
5029 size,
5030 horizontal_offset,
5031 });
5032 }
5033
5034 fn draw_occluder(
5035 width: Pixels,
5036 origin: gpui::Point<Pixels>,
5037 window: &mut Window,
5038 cx: &mut App,
5039 ) {
5040 let mut occlusion = div()
5041 .size_full()
5042 .occlude()
5043 .on_mouse_move(|_, _, cx| cx.stop_propagation())
5044 .into_any_element();
5045 occlusion.layout_as_root(size(width, HOVER_POPOVER_GAP).into(), window, cx);
5046 window.defer_draw(occlusion, origin, 2);
5047 }
5048
5049 fn place_popovers_above(
5050 hovered_point: gpui::Point<Pixels>,
5051 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5052 window: &mut Window,
5053 cx: &mut App,
5054 ) {
5055 let mut current_y = hovered_point.y;
5056 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5057 let size = popover.size;
5058 let popover_origin = point(
5059 hovered_point.x + popover.horizontal_offset,
5060 current_y - size.height,
5061 );
5062
5063 window.defer_draw(popover.element, popover_origin, 2);
5064 if position != itertools::Position::Last {
5065 let origin = point(popover_origin.x, popover_origin.y - HOVER_POPOVER_GAP);
5066 draw_occluder(size.width, origin, window, cx);
5067 }
5068
5069 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5070 }
5071 }
5072
5073 fn place_popovers_below(
5074 hovered_point: gpui::Point<Pixels>,
5075 measured_hover_popovers: Vec<MeasuredHoverPopover>,
5076 line_height: Pixels,
5077 window: &mut Window,
5078 cx: &mut App,
5079 ) {
5080 let mut current_y = hovered_point.y + line_height;
5081 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5082 let size = popover.size;
5083 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5084
5085 window.defer_draw(popover.element, popover_origin, 2);
5086 if position != itertools::Position::Last {
5087 let origin = point(popover_origin.x, popover_origin.y + size.height);
5088 draw_occluder(size.width, origin, window, cx);
5089 }
5090
5091 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5092 }
5093 }
5094
5095 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5096 context_menu_layout
5097 .as_ref()
5098 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5099 };
5100
5101 let can_place_above = {
5102 let mut bounds_above = Vec::new();
5103 let mut current_y = hovered_point.y;
5104 for popover in &measured_hover_popovers {
5105 let size = popover.size;
5106 let popover_origin = point(
5107 hovered_point.x + popover.horizontal_offset,
5108 current_y - size.height,
5109 );
5110 bounds_above.push(Bounds::new(popover_origin, size));
5111 current_y = popover_origin.y - HOVER_POPOVER_GAP;
5112 }
5113 bounds_above
5114 .iter()
5115 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5116 };
5117
5118 let can_place_below = || {
5119 let mut bounds_below = Vec::new();
5120 let mut current_y = hovered_point.y + line_height;
5121 for popover in &measured_hover_popovers {
5122 let size = popover.size;
5123 let popover_origin = point(hovered_point.x + popover.horizontal_offset, current_y);
5124 bounds_below.push(Bounds::new(popover_origin, size));
5125 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5126 }
5127 bounds_below
5128 .iter()
5129 .all(|b| b.is_contained_within(hitbox) && !intersects_menu(*b))
5130 };
5131
5132 if can_place_above {
5133 // try placing above hovered point
5134 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5135 } else if can_place_below() {
5136 // try placing below hovered point
5137 place_popovers_below(
5138 hovered_point,
5139 measured_hover_popovers,
5140 line_height,
5141 window,
5142 cx,
5143 );
5144 } else {
5145 // try to place popovers around the context menu
5146 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5147 let total_width = measured_hover_popovers
5148 .iter()
5149 .map(|p| p.size.width)
5150 .max()
5151 .unwrap_or(Pixels::ZERO);
5152 let y_for_horizontal_positioning = if menu.y_flipped {
5153 menu.bounds.bottom() - overall_height
5154 } else {
5155 menu.bounds.top()
5156 };
5157 let possible_origins = vec![
5158 // left of context menu
5159 point(
5160 menu.bounds.left() - total_width - HOVER_POPOVER_GAP,
5161 y_for_horizontal_positioning,
5162 ),
5163 // right of context menu
5164 point(
5165 menu.bounds.right() + HOVER_POPOVER_GAP,
5166 y_for_horizontal_positioning,
5167 ),
5168 // top of context menu
5169 point(
5170 menu.bounds.left(),
5171 menu.bounds.top() - overall_height - HOVER_POPOVER_GAP,
5172 ),
5173 // bottom of context menu
5174 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5175 ];
5176 possible_origins.into_iter().find(|&origin| {
5177 Bounds::new(origin, size(total_width, overall_height))
5178 .is_contained_within(hitbox)
5179 })
5180 });
5181 if let Some(origin) = origin_surrounding_menu {
5182 let mut current_y = origin.y;
5183 for (position, popover) in measured_hover_popovers.into_iter().with_position() {
5184 let size = popover.size;
5185 let popover_origin = point(origin.x, current_y);
5186
5187 window.defer_draw(popover.element, popover_origin, 2);
5188 if position != itertools::Position::Last {
5189 let origin = point(popover_origin.x, popover_origin.y + size.height);
5190 draw_occluder(size.width, origin, window, cx);
5191 }
5192
5193 current_y = popover_origin.y + size.height + HOVER_POPOVER_GAP;
5194 }
5195 } else {
5196 // fallback to existing above/below cursor logic
5197 // this might overlap menu or overflow in rare case
5198 if can_place_above {
5199 place_popovers_above(hovered_point, measured_hover_popovers, window, cx);
5200 } else {
5201 place_popovers_below(
5202 hovered_point,
5203 measured_hover_popovers,
5204 line_height,
5205 window,
5206 cx,
5207 );
5208 }
5209 }
5210 }
5211 }
5212
5213 fn layout_diff_hunk_controls(
5214 &self,
5215 row_range: Range<DisplayRow>,
5216 row_infos: &[RowInfo],
5217 text_hitbox: &Hitbox,
5218 newest_cursor_position: Option<DisplayPoint>,
5219 line_height: Pixels,
5220 right_margin: Pixels,
5221 scroll_pixel_position: gpui::Point<Pixels>,
5222 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
5223 highlighted_rows: &BTreeMap<DisplayRow, LineHighlight>,
5224 editor: Entity<Editor>,
5225 window: &mut Window,
5226 cx: &mut App,
5227 ) -> (Vec<AnyElement>, Vec<(DisplayRow, Bounds<Pixels>)>) {
5228 let render_diff_hunk_controls = editor.read(cx).render_diff_hunk_controls.clone();
5229 let hovered_diff_hunk_row = editor.read(cx).hovered_diff_hunk_row;
5230
5231 let mut controls = vec![];
5232 let mut control_bounds = vec![];
5233
5234 let active_positions = [
5235 hovered_diff_hunk_row.map(|row| DisplayPoint::new(row, 0)),
5236 newest_cursor_position,
5237 ];
5238
5239 for (hunk, _) in display_hunks {
5240 if let DisplayDiffHunk::Unfolded {
5241 display_row_range,
5242 multi_buffer_range,
5243 status,
5244 is_created_file,
5245 ..
5246 } = &hunk
5247 {
5248 if display_row_range.start < row_range.start
5249 || display_row_range.start >= row_range.end
5250 {
5251 continue;
5252 }
5253 if highlighted_rows
5254 .get(&display_row_range.start)
5255 .and_then(|highlight| highlight.type_id)
5256 .is_some_and(|type_id| {
5257 [
5258 TypeId::of::<ConflictsOuter>(),
5259 TypeId::of::<ConflictsOursMarker>(),
5260 TypeId::of::<ConflictsOurs>(),
5261 TypeId::of::<ConflictsTheirs>(),
5262 TypeId::of::<ConflictsTheirsMarker>(),
5263 ]
5264 .contains(&type_id)
5265 })
5266 {
5267 continue;
5268 }
5269 let row_ix = (display_row_range.start - row_range.start).0 as usize;
5270 if row_infos[row_ix].diff_status.is_none() {
5271 continue;
5272 }
5273 if row_infos[row_ix]
5274 .diff_status
5275 .is_some_and(|status| status.is_added())
5276 && !status.is_added()
5277 {
5278 continue;
5279 }
5280
5281 if active_positions
5282 .iter()
5283 .any(|p| p.is_some_and(|p| display_row_range.contains(&p.row())))
5284 {
5285 let y = display_row_range.start.as_f32() * line_height
5286 + text_hitbox.bounds.top()
5287 - scroll_pixel_position.y;
5288
5289 let mut element = render_diff_hunk_controls(
5290 display_row_range.start.0,
5291 status,
5292 multi_buffer_range.clone(),
5293 *is_created_file,
5294 line_height,
5295 &editor,
5296 window,
5297 cx,
5298 );
5299 let size =
5300 element.layout_as_root(size(px(100.0), line_height).into(), window, cx);
5301
5302 let x = text_hitbox.bounds.right() - right_margin - px(10.) - size.width;
5303
5304 let bounds = Bounds::new(gpui::Point::new(x, y), size);
5305 control_bounds.push((display_row_range.start, bounds));
5306
5307 window.with_absolute_element_offset(gpui::Point::new(x, y), |window| {
5308 element.prepaint(window, cx)
5309 });
5310 controls.push(element);
5311 }
5312 }
5313 }
5314
5315 (controls, control_bounds)
5316 }
5317
5318 fn layout_signature_help(
5319 &self,
5320 hitbox: &Hitbox,
5321 content_origin: gpui::Point<Pixels>,
5322 scroll_pixel_position: gpui::Point<Pixels>,
5323 newest_selection_head: Option<DisplayPoint>,
5324 start_row: DisplayRow,
5325 line_layouts: &[LineWithInvisibles],
5326 line_height: Pixels,
5327 em_width: Pixels,
5328 context_menu_layout: Option<ContextMenuLayout>,
5329 window: &mut Window,
5330 cx: &mut App,
5331 ) {
5332 if !self.editor.focus_handle(cx).is_focused(window) {
5333 return;
5334 }
5335 let Some(newest_selection_head) = newest_selection_head else {
5336 return;
5337 };
5338
5339 let max_size = size(
5340 (120. * em_width) // Default size
5341 .min(hitbox.size.width / 2.) // Shrink to half of the editor width
5342 .max(MIN_POPOVER_CHARACTER_WIDTH * em_width), // Apply minimum width of 20 characters
5343 (16. * line_height) // Default size
5344 .min(hitbox.size.height / 2.) // Shrink to half of the editor height
5345 .max(MIN_POPOVER_LINE_HEIGHT * line_height), // Apply minimum height of 4 lines
5346 );
5347
5348 let maybe_element = self.editor.update(cx, |editor, cx| {
5349 if let Some(popover) = editor.signature_help_state.popover_mut() {
5350 let element = popover.render(max_size, window, cx);
5351 Some(element)
5352 } else {
5353 None
5354 }
5355 });
5356 let Some(mut element) = maybe_element else {
5357 return;
5358 };
5359
5360 let selection_row = newest_selection_head.row();
5361 let Some(cursor_row_layout) = (selection_row >= start_row)
5362 .then(|| line_layouts.get(selection_row.minus(start_row) as usize))
5363 .flatten()
5364 else {
5365 return;
5366 };
5367
5368 let target_x = cursor_row_layout.x_for_index(newest_selection_head.column() as usize)
5369 - scroll_pixel_position.x;
5370 let target_y = selection_row.as_f32() * line_height - scroll_pixel_position.y;
5371 let target_point = content_origin + point(target_x, target_y);
5372
5373 let actual_size = element.layout_as_root(Size::<AvailableSpace>::default(), window, cx);
5374
5375 let (popover_bounds_above, popover_bounds_below) = {
5376 let horizontal_offset = (hitbox.top_right().x
5377 - POPOVER_RIGHT_OFFSET
5378 - (target_point.x + actual_size.width))
5379 .min(Pixels::ZERO);
5380 let initial_x = target_point.x + horizontal_offset;
5381 (
5382 Bounds::new(
5383 point(initial_x, target_point.y - actual_size.height),
5384 actual_size,
5385 ),
5386 Bounds::new(
5387 point(initial_x, target_point.y + line_height + HOVER_POPOVER_GAP),
5388 actual_size,
5389 ),
5390 )
5391 };
5392
5393 let intersects_menu = |bounds: Bounds<Pixels>| -> bool {
5394 context_menu_layout
5395 .as_ref()
5396 .is_some_and(|menu| bounds.intersects(&menu.bounds))
5397 };
5398
5399 let final_origin = if popover_bounds_above.is_contained_within(hitbox)
5400 && !intersects_menu(popover_bounds_above)
5401 {
5402 // try placing above cursor
5403 popover_bounds_above.origin
5404 } else if popover_bounds_below.is_contained_within(hitbox)
5405 && !intersects_menu(popover_bounds_below)
5406 {
5407 // try placing below cursor
5408 popover_bounds_below.origin
5409 } else {
5410 // try surrounding context menu if exists
5411 let origin_surrounding_menu = context_menu_layout.as_ref().and_then(|menu| {
5412 let y_for_horizontal_positioning = if menu.y_flipped {
5413 menu.bounds.bottom() - actual_size.height
5414 } else {
5415 menu.bounds.top()
5416 };
5417 let possible_origins = vec![
5418 // left of context menu
5419 point(
5420 menu.bounds.left() - actual_size.width - HOVER_POPOVER_GAP,
5421 y_for_horizontal_positioning,
5422 ),
5423 // right of context menu
5424 point(
5425 menu.bounds.right() + HOVER_POPOVER_GAP,
5426 y_for_horizontal_positioning,
5427 ),
5428 // top of context menu
5429 point(
5430 menu.bounds.left(),
5431 menu.bounds.top() - actual_size.height - HOVER_POPOVER_GAP,
5432 ),
5433 // bottom of context menu
5434 point(menu.bounds.left(), menu.bounds.bottom() + HOVER_POPOVER_GAP),
5435 ];
5436 possible_origins
5437 .into_iter()
5438 .find(|&origin| Bounds::new(origin, actual_size).is_contained_within(hitbox))
5439 });
5440 origin_surrounding_menu.unwrap_or_else(|| {
5441 // fallback to existing above/below cursor logic
5442 // this might overlap menu or overflow in rare case
5443 if popover_bounds_above.is_contained_within(hitbox) {
5444 popover_bounds_above.origin
5445 } else {
5446 popover_bounds_below.origin
5447 }
5448 })
5449 };
5450
5451 window.defer_draw(element, final_origin, 2);
5452 }
5453
5454 fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
5455 window.paint_layer(layout.hitbox.bounds, |window| {
5456 let scroll_top = layout.position_map.snapshot.scroll_position().y;
5457 let gutter_bg = cx.theme().colors().editor_gutter_background;
5458 window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg));
5459 window.paint_quad(fill(
5460 layout.position_map.text_hitbox.bounds,
5461 self.style.background,
5462 ));
5463
5464 if matches!(
5465 layout.mode,
5466 EditorMode::Full { .. } | EditorMode::Minimap { .. }
5467 ) {
5468 let show_active_line_background = match layout.mode {
5469 EditorMode::Full {
5470 show_active_line_background,
5471 ..
5472 } => show_active_line_background,
5473 EditorMode::Minimap { .. } => true,
5474 _ => false,
5475 };
5476 let mut active_rows = layout.active_rows.iter().peekable();
5477 while let Some((start_row, contains_non_empty_selection)) = active_rows.next() {
5478 let mut end_row = start_row.0;
5479 while active_rows
5480 .peek()
5481 .is_some_and(|(active_row, has_selection)| {
5482 active_row.0 == end_row + 1
5483 && has_selection.selection == contains_non_empty_selection.selection
5484 })
5485 {
5486 active_rows.next().unwrap();
5487 end_row += 1;
5488 }
5489
5490 if show_active_line_background && !contains_non_empty_selection.selection {
5491 let highlight_h_range =
5492 match layout.position_map.snapshot.current_line_highlight {
5493 CurrentLineHighlight::Gutter => Some(Range {
5494 start: layout.hitbox.left(),
5495 end: layout.gutter_hitbox.right(),
5496 }),
5497 CurrentLineHighlight::Line => Some(Range {
5498 start: layout.position_map.text_hitbox.bounds.left(),
5499 end: layout.position_map.text_hitbox.bounds.right(),
5500 }),
5501 CurrentLineHighlight::All => Some(Range {
5502 start: layout.hitbox.left(),
5503 end: layout.hitbox.right(),
5504 }),
5505 CurrentLineHighlight::None => None,
5506 };
5507 if let Some(range) = highlight_h_range {
5508 let active_line_bg = cx.theme().colors().editor_active_line_background;
5509 let bounds = Bounds {
5510 origin: point(
5511 range.start,
5512 layout.hitbox.origin.y
5513 + (start_row.as_f32() - scroll_top)
5514 * layout.position_map.line_height,
5515 ),
5516 size: size(
5517 range.end - range.start,
5518 layout.position_map.line_height
5519 * (end_row - start_row.0 + 1) as f32,
5520 ),
5521 };
5522 window.paint_quad(fill(bounds, active_line_bg));
5523 }
5524 }
5525 }
5526
5527 let mut paint_highlight = |highlight_row_start: DisplayRow,
5528 highlight_row_end: DisplayRow,
5529 highlight: crate::LineHighlight,
5530 edges| {
5531 let mut origin_x = layout.hitbox.left();
5532 let mut width = layout.hitbox.size.width;
5533 if !highlight.include_gutter {
5534 origin_x += layout.gutter_hitbox.size.width;
5535 width -= layout.gutter_hitbox.size.width;
5536 }
5537
5538 let origin = point(
5539 origin_x,
5540 layout.hitbox.origin.y
5541 + (highlight_row_start.as_f32() - scroll_top)
5542 * layout.position_map.line_height,
5543 );
5544 let size = size(
5545 width,
5546 layout.position_map.line_height
5547 * highlight_row_end.next_row().minus(highlight_row_start) as f32,
5548 );
5549 let mut quad = fill(Bounds { origin, size }, highlight.background);
5550 if let Some(border_color) = highlight.border {
5551 quad.border_color = border_color;
5552 quad.border_widths = edges
5553 }
5554 window.paint_quad(quad);
5555 };
5556
5557 let mut current_paint: Option<(LineHighlight, Range<DisplayRow>, Edges<Pixels>)> =
5558 None;
5559 for (&new_row, &new_background) in &layout.highlighted_rows {
5560 match &mut current_paint {
5561 &mut Some((current_background, ref mut current_range, mut edges)) => {
5562 let new_range_started = current_background != new_background
5563 || current_range.end.next_row() != new_row;
5564 if new_range_started {
5565 if current_range.end.next_row() == new_row {
5566 edges.bottom = px(0.);
5567 };
5568 paint_highlight(
5569 current_range.start,
5570 current_range.end,
5571 current_background,
5572 edges,
5573 );
5574 let edges = Edges {
5575 top: if current_range.end.next_row() != new_row {
5576 px(1.)
5577 } else {
5578 px(0.)
5579 },
5580 bottom: px(1.),
5581 ..Default::default()
5582 };
5583 current_paint = Some((new_background, new_row..new_row, edges));
5584 continue;
5585 } else {
5586 current_range.end = current_range.end.next_row();
5587 }
5588 }
5589 None => {
5590 let edges = Edges {
5591 top: px(1.),
5592 bottom: px(1.),
5593 ..Default::default()
5594 };
5595 current_paint = Some((new_background, new_row..new_row, edges))
5596 }
5597 };
5598 }
5599 if let Some((color, range, edges)) = current_paint {
5600 paint_highlight(range.start, range.end, color, edges);
5601 }
5602
5603 for (guide_x, active) in layout.wrap_guides.iter() {
5604 let color = if *active {
5605 cx.theme().colors().editor_active_wrap_guide
5606 } else {
5607 cx.theme().colors().editor_wrap_guide
5608 };
5609 window.paint_quad(fill(
5610 Bounds {
5611 origin: point(*guide_x, layout.position_map.text_hitbox.origin.y),
5612 size: size(px(1.), layout.position_map.text_hitbox.size.height),
5613 },
5614 color,
5615 ));
5616 }
5617 }
5618 })
5619 }
5620
5621 fn paint_indent_guides(
5622 &mut self,
5623 layout: &mut EditorLayout,
5624 window: &mut Window,
5625 cx: &mut App,
5626 ) {
5627 let Some(indent_guides) = &layout.indent_guides else {
5628 return;
5629 };
5630
5631 let faded_color = |color: Hsla, alpha: f32| {
5632 let mut faded = color;
5633 faded.a = alpha;
5634 faded
5635 };
5636
5637 for indent_guide in indent_guides {
5638 let indent_accent_colors = cx.theme().accents().color_for_index(indent_guide.depth);
5639 let settings = indent_guide.settings;
5640
5641 // TODO fixed for now, expose them through themes later
5642 const INDENT_AWARE_ALPHA: f32 = 0.2;
5643 const INDENT_AWARE_ACTIVE_ALPHA: f32 = 0.4;
5644 const INDENT_AWARE_BACKGROUND_ALPHA: f32 = 0.1;
5645 const INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA: f32 = 0.2;
5646
5647 let line_color = match (settings.coloring, indent_guide.active) {
5648 (IndentGuideColoring::Disabled, _) => None,
5649 (IndentGuideColoring::Fixed, false) => {
5650 Some(cx.theme().colors().editor_indent_guide)
5651 }
5652 (IndentGuideColoring::Fixed, true) => {
5653 Some(cx.theme().colors().editor_indent_guide_active)
5654 }
5655 (IndentGuideColoring::IndentAware, false) => {
5656 Some(faded_color(indent_accent_colors, INDENT_AWARE_ALPHA))
5657 }
5658 (IndentGuideColoring::IndentAware, true) => {
5659 Some(faded_color(indent_accent_colors, INDENT_AWARE_ACTIVE_ALPHA))
5660 }
5661 };
5662
5663 let background_color = match (settings.background_coloring, indent_guide.active) {
5664 (IndentGuideBackgroundColoring::Disabled, _) => None,
5665 (IndentGuideBackgroundColoring::IndentAware, false) => Some(faded_color(
5666 indent_accent_colors,
5667 INDENT_AWARE_BACKGROUND_ALPHA,
5668 )),
5669 (IndentGuideBackgroundColoring::IndentAware, true) => Some(faded_color(
5670 indent_accent_colors,
5671 INDENT_AWARE_BACKGROUND_ACTIVE_ALPHA,
5672 )),
5673 };
5674
5675 let requested_line_width = if indent_guide.active {
5676 settings.active_line_width
5677 } else {
5678 settings.line_width
5679 }
5680 .clamp(1, 10);
5681 let mut line_indicator_width = 0.;
5682 if let Some(color) = line_color {
5683 window.paint_quad(fill(
5684 Bounds {
5685 origin: indent_guide.origin,
5686 size: size(px(requested_line_width as f32), indent_guide.length),
5687 },
5688 color,
5689 ));
5690 line_indicator_width = requested_line_width as f32;
5691 }
5692
5693 if let Some(color) = background_color {
5694 let width = indent_guide.single_indent_width - px(line_indicator_width);
5695 window.paint_quad(fill(
5696 Bounds {
5697 origin: point(
5698 indent_guide.origin.x + px(line_indicator_width),
5699 indent_guide.origin.y,
5700 ),
5701 size: size(width, indent_guide.length),
5702 },
5703 color,
5704 ));
5705 }
5706 }
5707 }
5708
5709 fn paint_line_numbers(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5710 let is_singleton = self.editor.read(cx).is_singleton(cx);
5711
5712 let line_height = layout.position_map.line_height;
5713 window.set_cursor_style(CursorStyle::Arrow, &layout.gutter_hitbox);
5714
5715 for LineNumberLayout {
5716 shaped_line,
5717 hitbox,
5718 } in layout.line_numbers.values()
5719 {
5720 let Some(hitbox) = hitbox else {
5721 continue;
5722 };
5723
5724 let Some(()) = (if !is_singleton && hitbox.is_hovered(window) {
5725 let color = cx.theme().colors().editor_hover_line_number;
5726
5727 let line = self.shape_line_number(shaped_line.text.clone(), color, window);
5728 line.paint(hitbox.origin, line_height, window, cx).log_err()
5729 } else {
5730 shaped_line
5731 .paint(hitbox.origin, line_height, window, cx)
5732 .log_err()
5733 }) else {
5734 continue;
5735 };
5736
5737 // In singleton buffers, we select corresponding lines on the line number click, so use | -like cursor.
5738 // In multi buffers, we open file at the line number clicked, so use a pointing hand cursor.
5739 if is_singleton {
5740 window.set_cursor_style(CursorStyle::IBeam, hitbox);
5741 } else {
5742 window.set_cursor_style(CursorStyle::PointingHand, hitbox);
5743 }
5744 }
5745 }
5746
5747 fn paint_gutter_diff_hunks(layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
5748 if layout.display_hunks.is_empty() {
5749 return;
5750 }
5751
5752 let line_height = layout.position_map.line_height;
5753 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5754 for (hunk, hitbox) in &layout.display_hunks {
5755 let hunk_to_paint = match hunk {
5756 DisplayDiffHunk::Folded { .. } => {
5757 let hunk_bounds = Self::diff_hunk_bounds(
5758 &layout.position_map.snapshot,
5759 line_height,
5760 layout.gutter_hitbox.bounds,
5761 hunk,
5762 );
5763 Some((
5764 hunk_bounds,
5765 cx.theme().colors().version_control_modified,
5766 Corners::all(px(0.)),
5767 DiffHunkStatus::modified_none(),
5768 ))
5769 }
5770 DisplayDiffHunk::Unfolded {
5771 status,
5772 display_row_range,
5773 ..
5774 } => hitbox.as_ref().map(|hunk_hitbox| match status.kind {
5775 DiffHunkStatusKind::Added => (
5776 hunk_hitbox.bounds,
5777 cx.theme().colors().version_control_added,
5778 Corners::all(px(0.)),
5779 *status,
5780 ),
5781 DiffHunkStatusKind::Modified => (
5782 hunk_hitbox.bounds,
5783 cx.theme().colors().version_control_modified,
5784 Corners::all(px(0.)),
5785 *status,
5786 ),
5787 DiffHunkStatusKind::Deleted if !display_row_range.is_empty() => (
5788 hunk_hitbox.bounds,
5789 cx.theme().colors().version_control_deleted,
5790 Corners::all(px(0.)),
5791 *status,
5792 ),
5793 DiffHunkStatusKind::Deleted => (
5794 Bounds::new(
5795 point(
5796 hunk_hitbox.origin.x - hunk_hitbox.size.width,
5797 hunk_hitbox.origin.y,
5798 ),
5799 size(hunk_hitbox.size.width * 2., hunk_hitbox.size.height),
5800 ),
5801 cx.theme().colors().version_control_deleted,
5802 Corners::all(1. * line_height),
5803 *status,
5804 ),
5805 }),
5806 };
5807
5808 if let Some((hunk_bounds, background_color, corner_radii, status)) = hunk_to_paint {
5809 // Flatten the background color with the editor color to prevent
5810 // elements below transparent hunks from showing through
5811 let flattened_background_color = cx
5812 .theme()
5813 .colors()
5814 .editor_background
5815 .blend(background_color);
5816
5817 if !Self::diff_hunk_hollow(status, cx) {
5818 window.paint_quad(quad(
5819 hunk_bounds,
5820 corner_radii,
5821 flattened_background_color,
5822 Edges::default(),
5823 transparent_black(),
5824 BorderStyle::default(),
5825 ));
5826 } else {
5827 let flattened_unstaged_background_color = cx
5828 .theme()
5829 .colors()
5830 .editor_background
5831 .blend(background_color.opacity(0.3));
5832
5833 window.paint_quad(quad(
5834 hunk_bounds,
5835 corner_radii,
5836 flattened_unstaged_background_color,
5837 Edges::all(Pixels(1.0)),
5838 flattened_background_color,
5839 BorderStyle::Solid,
5840 ));
5841 }
5842 }
5843 }
5844 });
5845 }
5846
5847 fn gutter_strip_width(line_height: Pixels) -> Pixels {
5848 (0.275 * line_height).floor()
5849 }
5850
5851 fn diff_hunk_bounds(
5852 snapshot: &EditorSnapshot,
5853 line_height: Pixels,
5854 gutter_bounds: Bounds<Pixels>,
5855 hunk: &DisplayDiffHunk,
5856 ) -> Bounds<Pixels> {
5857 let scroll_position = snapshot.scroll_position();
5858 let scroll_top = scroll_position.y * line_height;
5859 let gutter_strip_width = Self::gutter_strip_width(line_height);
5860
5861 match hunk {
5862 DisplayDiffHunk::Folded { display_row, .. } => {
5863 let start_y = display_row.as_f32() * line_height - scroll_top;
5864 let end_y = start_y + line_height;
5865 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5866 let highlight_size = size(gutter_strip_width, end_y - start_y);
5867 Bounds::new(highlight_origin, highlight_size)
5868 }
5869 DisplayDiffHunk::Unfolded {
5870 display_row_range,
5871 status,
5872 ..
5873 } => {
5874 if status.is_deleted() && display_row_range.is_empty() {
5875 let row = display_row_range.start;
5876
5877 let offset = line_height / 2.;
5878 let start_y = row.as_f32() * line_height - offset - scroll_top;
5879 let end_y = start_y + line_height;
5880
5881 let width = (0.35 * line_height).floor();
5882 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5883 let highlight_size = size(width, end_y - start_y);
5884 Bounds::new(highlight_origin, highlight_size)
5885 } else {
5886 let start_row = display_row_range.start;
5887 let end_row = display_row_range.end;
5888 // If we're in a multibuffer, row range span might include an
5889 // excerpt header, so if we were to draw the marker straight away,
5890 // the hunk might include the rows of that header.
5891 // Making the range inclusive doesn't quite cut it, as we rely on the exclusivity for the soft wrap.
5892 // Instead, we simply check whether the range we're dealing with includes
5893 // any excerpt headers and if so, we stop painting the diff hunk on the first row of that header.
5894 let end_row_in_current_excerpt = snapshot
5895 .blocks_in_range(start_row..end_row)
5896 .find_map(|(start_row, block)| {
5897 if matches!(
5898 block,
5899 Block::ExcerptBoundary { .. } | Block::BufferHeader { .. }
5900 ) {
5901 Some(start_row)
5902 } else {
5903 None
5904 }
5905 })
5906 .unwrap_or(end_row);
5907
5908 let start_y = start_row.as_f32() * line_height - scroll_top;
5909 let end_y = end_row_in_current_excerpt.as_f32() * line_height - scroll_top;
5910
5911 let highlight_origin = gutter_bounds.origin + point(px(0.), start_y);
5912 let highlight_size = size(gutter_strip_width, end_y - start_y);
5913 Bounds::new(highlight_origin, highlight_size)
5914 }
5915 }
5916 }
5917 }
5918
5919 fn paint_gutter_indicators(
5920 &self,
5921 layout: &mut EditorLayout,
5922 window: &mut Window,
5923 cx: &mut App,
5924 ) {
5925 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5926 window.with_element_namespace("crease_toggles", |window| {
5927 for crease_toggle in layout.crease_toggles.iter_mut().flatten() {
5928 crease_toggle.paint(window, cx);
5929 }
5930 });
5931
5932 window.with_element_namespace("expand_toggles", |window| {
5933 for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() {
5934 expand_toggle.paint(window, cx);
5935 }
5936 });
5937
5938 for breakpoint in layout.breakpoints.iter_mut() {
5939 breakpoint.paint(window, cx);
5940 }
5941
5942 for test_indicator in layout.test_indicators.iter_mut() {
5943 test_indicator.paint(window, cx);
5944 }
5945 });
5946 }
5947
5948 fn paint_gutter_highlights(
5949 &self,
5950 layout: &mut EditorLayout,
5951 window: &mut Window,
5952 cx: &mut App,
5953 ) {
5954 for (_, hunk_hitbox) in &layout.display_hunks {
5955 if let Some(hunk_hitbox) = hunk_hitbox
5956 && !self
5957 .editor
5958 .read(cx)
5959 .buffer()
5960 .read(cx)
5961 .all_diff_hunks_expanded()
5962 {
5963 window.set_cursor_style(CursorStyle::PointingHand, hunk_hitbox);
5964 }
5965 }
5966
5967 let show_git_gutter = layout
5968 .position_map
5969 .snapshot
5970 .show_git_diff_gutter
5971 .unwrap_or_else(|| {
5972 matches!(
5973 ProjectSettings::get_global(cx).git.git_gutter,
5974 Some(GitGutterSetting::TrackedFiles)
5975 )
5976 });
5977 if show_git_gutter {
5978 Self::paint_gutter_diff_hunks(layout, window, cx)
5979 }
5980
5981 let highlight_width = 0.275 * layout.position_map.line_height;
5982 let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height);
5983 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
5984 for (range, color) in &layout.highlighted_gutter_ranges {
5985 let start_row = if range.start.row() < layout.visible_display_row_range.start {
5986 layout.visible_display_row_range.start - DisplayRow(1)
5987 } else {
5988 range.start.row()
5989 };
5990 let end_row = if range.end.row() > layout.visible_display_row_range.end {
5991 layout.visible_display_row_range.end + DisplayRow(1)
5992 } else {
5993 range.end.row()
5994 };
5995
5996 let start_y = layout.gutter_hitbox.top()
5997 + start_row.0 as f32 * layout.position_map.line_height
5998 - layout.position_map.scroll_pixel_position.y;
5999 let end_y = layout.gutter_hitbox.top()
6000 + (end_row.0 + 1) as f32 * layout.position_map.line_height
6001 - layout.position_map.scroll_pixel_position.y;
6002 let bounds = Bounds::from_corners(
6003 point(layout.gutter_hitbox.left(), start_y),
6004 point(layout.gutter_hitbox.left() + highlight_width, end_y),
6005 );
6006 window.paint_quad(fill(bounds, *color).corner_radii(highlight_corner_radii));
6007 }
6008 });
6009 }
6010
6011 fn paint_blamed_display_rows(
6012 &self,
6013 layout: &mut EditorLayout,
6014 window: &mut Window,
6015 cx: &mut App,
6016 ) {
6017 let Some(blamed_display_rows) = layout.blamed_display_rows.take() else {
6018 return;
6019 };
6020
6021 window.paint_layer(layout.gutter_hitbox.bounds, |window| {
6022 for mut blame_element in blamed_display_rows.into_iter() {
6023 blame_element.paint(window, cx);
6024 }
6025 })
6026 }
6027
6028 fn paint_text(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6029 window.with_content_mask(
6030 Some(ContentMask {
6031 bounds: layout.position_map.text_hitbox.bounds,
6032 }),
6033 |window| {
6034 let editor = self.editor.read(cx);
6035 if editor.mouse_cursor_hidden {
6036 window.set_window_cursor_style(CursorStyle::None);
6037 } else if let SelectionDragState::ReadyToDrag {
6038 mouse_down_time, ..
6039 } = &editor.selection_drag_state
6040 {
6041 let drag_and_drop_delay = Duration::from_millis(
6042 EditorSettings::get_global(cx).drag_and_drop_selection.delay,
6043 );
6044 if mouse_down_time.elapsed() >= drag_and_drop_delay {
6045 window.set_cursor_style(
6046 CursorStyle::DragCopy,
6047 &layout.position_map.text_hitbox,
6048 );
6049 }
6050 } else if matches!(
6051 editor.selection_drag_state,
6052 SelectionDragState::Dragging { .. }
6053 ) {
6054 window
6055 .set_cursor_style(CursorStyle::DragCopy, &layout.position_map.text_hitbox);
6056 } else if editor
6057 .hovered_link_state
6058 .as_ref()
6059 .is_some_and(|hovered_link_state| !hovered_link_state.links.is_empty())
6060 {
6061 window.set_cursor_style(
6062 CursorStyle::PointingHand,
6063 &layout.position_map.text_hitbox,
6064 );
6065 } else {
6066 window.set_cursor_style(CursorStyle::IBeam, &layout.position_map.text_hitbox);
6067 };
6068
6069 self.paint_lines_background(layout, window, cx);
6070 let invisible_display_ranges = self.paint_highlights(layout, window, cx);
6071 self.paint_document_colors(layout, window);
6072 self.paint_lines(&invisible_display_ranges, layout, window, cx);
6073 self.paint_redactions(layout, window);
6074 self.paint_cursors(layout, window, cx);
6075 self.paint_inline_diagnostics(layout, window, cx);
6076 self.paint_inline_blame(layout, window, cx);
6077 self.paint_inline_code_actions(layout, window, cx);
6078 self.paint_diff_hunk_controls(layout, window, cx);
6079 window.with_element_namespace("crease_trailers", |window| {
6080 for trailer in layout.crease_trailers.iter_mut().flatten() {
6081 trailer.element.paint(window, cx);
6082 }
6083 });
6084 },
6085 )
6086 }
6087
6088 fn paint_highlights(
6089 &mut self,
6090 layout: &mut EditorLayout,
6091 window: &mut Window,
6092 cx: &mut App,
6093 ) -> SmallVec<[Range<DisplayPoint>; 32]> {
6094 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6095 let mut invisible_display_ranges = SmallVec::<[Range<DisplayPoint>; 32]>::new();
6096 let line_end_overshoot = 0.15 * layout.position_map.line_height;
6097 for (range, color) in &layout.highlighted_ranges {
6098 self.paint_highlighted_range(
6099 range.clone(),
6100 true,
6101 *color,
6102 Pixels::ZERO,
6103 line_end_overshoot,
6104 layout,
6105 window,
6106 );
6107 }
6108
6109 let corner_radius = if EditorSettings::get_global(cx).rounded_selection {
6110 0.15 * layout.position_map.line_height
6111 } else {
6112 Pixels::ZERO
6113 };
6114
6115 for (player_color, selections) in &layout.selections {
6116 for selection in selections.iter() {
6117 self.paint_highlighted_range(
6118 selection.range.clone(),
6119 true,
6120 player_color.selection,
6121 corner_radius,
6122 corner_radius * 2.,
6123 layout,
6124 window,
6125 );
6126
6127 if selection.is_local && !selection.range.is_empty() {
6128 invisible_display_ranges.push(selection.range.clone());
6129 }
6130 }
6131 }
6132 invisible_display_ranges
6133 })
6134 }
6135
6136 fn paint_lines(
6137 &mut self,
6138 invisible_display_ranges: &[Range<DisplayPoint>],
6139 layout: &mut EditorLayout,
6140 window: &mut Window,
6141 cx: &mut App,
6142 ) {
6143 let whitespace_setting = self
6144 .editor
6145 .read(cx)
6146 .buffer
6147 .read(cx)
6148 .language_settings(cx)
6149 .show_whitespaces;
6150
6151 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6152 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6153 line_with_invisibles.draw(
6154 layout,
6155 row,
6156 layout.content_origin,
6157 whitespace_setting,
6158 invisible_display_ranges,
6159 window,
6160 cx,
6161 )
6162 }
6163
6164 for line_element in &mut layout.line_elements {
6165 line_element.paint(window, cx);
6166 }
6167 }
6168
6169 fn paint_lines_background(
6170 &mut self,
6171 layout: &mut EditorLayout,
6172 window: &mut Window,
6173 cx: &mut App,
6174 ) {
6175 for (ix, line_with_invisibles) in layout.position_map.line_layouts.iter().enumerate() {
6176 let row = DisplayRow(layout.visible_display_row_range.start.0 + ix as u32);
6177 line_with_invisibles.draw_background(layout, row, layout.content_origin, window, cx);
6178 }
6179 }
6180
6181 fn paint_redactions(&mut self, layout: &EditorLayout, window: &mut Window) {
6182 if layout.redacted_ranges.is_empty() {
6183 return;
6184 }
6185
6186 let line_end_overshoot = layout.line_end_overshoot();
6187
6188 // A softer than perfect black
6189 let redaction_color = gpui::rgb(0x0e1111);
6190
6191 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6192 for range in layout.redacted_ranges.iter() {
6193 self.paint_highlighted_range(
6194 range.clone(),
6195 true,
6196 redaction_color.into(),
6197 Pixels::ZERO,
6198 line_end_overshoot,
6199 layout,
6200 window,
6201 );
6202 }
6203 });
6204 }
6205
6206 fn paint_document_colors(&self, layout: &mut EditorLayout, window: &mut Window) {
6207 let Some((colors_render_mode, image_colors)) = &layout.document_colors else {
6208 return;
6209 };
6210 if image_colors.is_empty()
6211 || colors_render_mode == &DocumentColorsRenderMode::None
6212 || colors_render_mode == &DocumentColorsRenderMode::Inlay
6213 {
6214 return;
6215 }
6216
6217 let line_end_overshoot = layout.line_end_overshoot();
6218
6219 for (range, color) in image_colors {
6220 match colors_render_mode {
6221 DocumentColorsRenderMode::Inlay | DocumentColorsRenderMode::None => return,
6222 DocumentColorsRenderMode::Background => {
6223 self.paint_highlighted_range(
6224 range.clone(),
6225 true,
6226 *color,
6227 Pixels::ZERO,
6228 line_end_overshoot,
6229 layout,
6230 window,
6231 );
6232 }
6233 DocumentColorsRenderMode::Border => {
6234 self.paint_highlighted_range(
6235 range.clone(),
6236 false,
6237 *color,
6238 Pixels::ZERO,
6239 line_end_overshoot,
6240 layout,
6241 window,
6242 );
6243 }
6244 }
6245 }
6246 }
6247
6248 fn paint_cursors(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6249 for cursor in &mut layout.visible_cursors {
6250 cursor.paint(layout.content_origin, window, cx);
6251 }
6252 }
6253
6254 fn paint_scrollbars(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6255 let Some(scrollbars_layout) = layout.scrollbars_layout.take() else {
6256 return;
6257 };
6258 let any_scrollbar_dragged = self.editor.read(cx).scroll_manager.any_scrollbar_dragged();
6259
6260 for (scrollbar_layout, axis) in scrollbars_layout.iter_scrollbars() {
6261 let hitbox = &scrollbar_layout.hitbox;
6262 if scrollbars_layout.visible {
6263 let scrollbar_edges = match axis {
6264 ScrollbarAxis::Horizontal => Edges {
6265 top: Pixels::ZERO,
6266 right: Pixels::ZERO,
6267 bottom: Pixels::ZERO,
6268 left: Pixels::ZERO,
6269 },
6270 ScrollbarAxis::Vertical => Edges {
6271 top: Pixels::ZERO,
6272 right: Pixels::ZERO,
6273 bottom: Pixels::ZERO,
6274 left: ScrollbarLayout::BORDER_WIDTH,
6275 },
6276 };
6277
6278 window.paint_layer(hitbox.bounds, |window| {
6279 window.paint_quad(quad(
6280 hitbox.bounds,
6281 Corners::default(),
6282 cx.theme().colors().scrollbar_track_background,
6283 scrollbar_edges,
6284 cx.theme().colors().scrollbar_track_border,
6285 BorderStyle::Solid,
6286 ));
6287
6288 if axis == ScrollbarAxis::Vertical {
6289 let fast_markers =
6290 self.collect_fast_scrollbar_markers(layout, scrollbar_layout, cx);
6291 // Refresh slow scrollbar markers in the background. Below, we
6292 // paint whatever markers have already been computed.
6293 self.refresh_slow_scrollbar_markers(layout, scrollbar_layout, window, cx);
6294
6295 let markers = self.editor.read(cx).scrollbar_marker_state.markers.clone();
6296 for marker in markers.iter().chain(&fast_markers) {
6297 let mut marker = marker.clone();
6298 marker.bounds.origin += hitbox.origin;
6299 window.paint_quad(marker);
6300 }
6301 }
6302
6303 if let Some(thumb_bounds) = scrollbar_layout.thumb_bounds {
6304 let scrollbar_thumb_color = match scrollbar_layout.thumb_state {
6305 ScrollbarThumbState::Dragging => {
6306 cx.theme().colors().scrollbar_thumb_active_background
6307 }
6308 ScrollbarThumbState::Hovered => {
6309 cx.theme().colors().scrollbar_thumb_hover_background
6310 }
6311 ScrollbarThumbState::Idle => {
6312 cx.theme().colors().scrollbar_thumb_background
6313 }
6314 };
6315 window.paint_quad(quad(
6316 thumb_bounds,
6317 Corners::default(),
6318 scrollbar_thumb_color,
6319 scrollbar_edges,
6320 cx.theme().colors().scrollbar_thumb_border,
6321 BorderStyle::Solid,
6322 ));
6323
6324 if any_scrollbar_dragged {
6325 window.set_window_cursor_style(CursorStyle::Arrow);
6326 } else {
6327 window.set_cursor_style(CursorStyle::Arrow, hitbox);
6328 }
6329 }
6330 })
6331 }
6332 }
6333
6334 window.on_mouse_event({
6335 let editor = self.editor.clone();
6336 let scrollbars_layout = scrollbars_layout.clone();
6337
6338 let mut mouse_position = window.mouse_position();
6339 move |event: &MouseMoveEvent, phase, window, cx| {
6340 if phase == DispatchPhase::Capture {
6341 return;
6342 }
6343
6344 editor.update(cx, |editor, cx| {
6345 if let Some((scrollbar_layout, axis)) = event
6346 .pressed_button
6347 .filter(|button| *button == MouseButton::Left)
6348 .and(editor.scroll_manager.dragging_scrollbar_axis())
6349 .and_then(|axis| {
6350 scrollbars_layout
6351 .iter_scrollbars()
6352 .find(|(_, a)| *a == axis)
6353 })
6354 {
6355 let ScrollbarLayout {
6356 hitbox,
6357 text_unit_size,
6358 ..
6359 } = scrollbar_layout;
6360
6361 let old_position = mouse_position.along(axis);
6362 let new_position = event.position.along(axis);
6363 if (hitbox.origin.along(axis)..hitbox.bottom_right().along(axis))
6364 .contains(&old_position)
6365 {
6366 let position = editor.scroll_position(cx).apply_along(axis, |p| {
6367 (p + (new_position - old_position) / *text_unit_size).max(0.)
6368 });
6369 editor.set_scroll_position(position, window, cx);
6370 }
6371
6372 editor.scroll_manager.show_scrollbars(window, cx);
6373 cx.stop_propagation();
6374 } else if let Some((layout, axis)) = scrollbars_layout
6375 .get_hovered_axis(window)
6376 .filter(|_| !event.dragging())
6377 {
6378 if layout.thumb_hovered(&event.position) {
6379 editor
6380 .scroll_manager
6381 .set_hovered_scroll_thumb_axis(axis, cx);
6382 } else {
6383 editor.scroll_manager.reset_scrollbar_state(cx);
6384 }
6385
6386 editor.scroll_manager.show_scrollbars(window, cx);
6387 } else {
6388 editor.scroll_manager.reset_scrollbar_state(cx);
6389 }
6390
6391 mouse_position = event.position;
6392 })
6393 }
6394 });
6395
6396 if any_scrollbar_dragged {
6397 window.on_mouse_event({
6398 let editor = self.editor.clone();
6399 move |_: &MouseUpEvent, phase, window, cx| {
6400 if phase == DispatchPhase::Capture {
6401 return;
6402 }
6403
6404 editor.update(cx, |editor, cx| {
6405 if let Some((_, axis)) = scrollbars_layout.get_hovered_axis(window) {
6406 editor
6407 .scroll_manager
6408 .set_hovered_scroll_thumb_axis(axis, cx);
6409 } else {
6410 editor.scroll_manager.reset_scrollbar_state(cx);
6411 }
6412 cx.stop_propagation();
6413 });
6414 }
6415 });
6416 } else {
6417 window.on_mouse_event({
6418 let editor = self.editor.clone();
6419
6420 move |event: &MouseDownEvent, phase, window, cx| {
6421 if phase == DispatchPhase::Capture {
6422 return;
6423 }
6424 let Some((scrollbar_layout, axis)) = scrollbars_layout.get_hovered_axis(window)
6425 else {
6426 return;
6427 };
6428
6429 let ScrollbarLayout {
6430 hitbox,
6431 visible_range,
6432 text_unit_size,
6433 thumb_bounds,
6434 ..
6435 } = scrollbar_layout;
6436
6437 let Some(thumb_bounds) = thumb_bounds else {
6438 return;
6439 };
6440
6441 editor.update(cx, |editor, cx| {
6442 editor
6443 .scroll_manager
6444 .set_dragged_scroll_thumb_axis(axis, cx);
6445
6446 let event_position = event.position.along(axis);
6447
6448 if event_position < thumb_bounds.origin.along(axis)
6449 || thumb_bounds.bottom_right().along(axis) < event_position
6450 {
6451 let center_position = ((event_position - hitbox.origin.along(axis))
6452 / *text_unit_size)
6453 .round() as u32;
6454 let start_position = center_position.saturating_sub(
6455 (visible_range.end - visible_range.start) as u32 / 2,
6456 );
6457
6458 let position = editor
6459 .scroll_position(cx)
6460 .apply_along(axis, |_| start_position as f32);
6461
6462 editor.set_scroll_position(position, window, cx);
6463 } else {
6464 editor.scroll_manager.show_scrollbars(window, cx);
6465 }
6466
6467 cx.stop_propagation();
6468 });
6469 }
6470 });
6471 }
6472 }
6473
6474 fn collect_fast_scrollbar_markers(
6475 &self,
6476 layout: &EditorLayout,
6477 scrollbar_layout: &ScrollbarLayout,
6478 cx: &mut App,
6479 ) -> Vec<PaintQuad> {
6480 const LIMIT: usize = 100;
6481 if !EditorSettings::get_global(cx).scrollbar.cursors || layout.cursors.len() > LIMIT {
6482 return vec![];
6483 }
6484 let cursor_ranges = layout
6485 .cursors
6486 .iter()
6487 .map(|(point, color)| ColoredRange {
6488 start: point.row(),
6489 end: point.row(),
6490 color: *color,
6491 })
6492 .collect_vec();
6493 scrollbar_layout.marker_quads_for_ranges(cursor_ranges, None)
6494 }
6495
6496 fn refresh_slow_scrollbar_markers(
6497 &self,
6498 layout: &EditorLayout,
6499 scrollbar_layout: &ScrollbarLayout,
6500 window: &mut Window,
6501 cx: &mut App,
6502 ) {
6503 self.editor.update(cx, |editor, cx| {
6504 if !editor.is_singleton(cx)
6505 || !editor
6506 .scrollbar_marker_state
6507 .should_refresh(scrollbar_layout.hitbox.size)
6508 {
6509 return;
6510 }
6511
6512 let scrollbar_layout = scrollbar_layout.clone();
6513 let background_highlights = editor.background_highlights.clone();
6514 let snapshot = layout.position_map.snapshot.clone();
6515 let theme = cx.theme().clone();
6516 let scrollbar_settings = EditorSettings::get_global(cx).scrollbar;
6517
6518 editor.scrollbar_marker_state.dirty = false;
6519 editor.scrollbar_marker_state.pending_refresh =
6520 Some(cx.spawn_in(window, async move |editor, cx| {
6521 let scrollbar_size = scrollbar_layout.hitbox.size;
6522 let scrollbar_markers = cx
6523 .background_spawn(async move {
6524 let max_point = snapshot.display_snapshot.buffer_snapshot.max_point();
6525 let mut marker_quads = Vec::new();
6526 if scrollbar_settings.git_diff {
6527 let marker_row_ranges =
6528 snapshot.buffer_snapshot.diff_hunks().map(|hunk| {
6529 let start_display_row =
6530 MultiBufferPoint::new(hunk.row_range.start.0, 0)
6531 .to_display_point(&snapshot.display_snapshot)
6532 .row();
6533 let mut end_display_row =
6534 MultiBufferPoint::new(hunk.row_range.end.0, 0)
6535 .to_display_point(&snapshot.display_snapshot)
6536 .row();
6537 if end_display_row != start_display_row {
6538 end_display_row.0 -= 1;
6539 }
6540 let color = match &hunk.status().kind {
6541 DiffHunkStatusKind::Added => {
6542 theme.colors().version_control_added
6543 }
6544 DiffHunkStatusKind::Modified => {
6545 theme.colors().version_control_modified
6546 }
6547 DiffHunkStatusKind::Deleted => {
6548 theme.colors().version_control_deleted
6549 }
6550 };
6551 ColoredRange {
6552 start: start_display_row,
6553 end: end_display_row,
6554 color,
6555 }
6556 });
6557
6558 marker_quads.extend(
6559 scrollbar_layout
6560 .marker_quads_for_ranges(marker_row_ranges, Some(0)),
6561 );
6562 }
6563
6564 for (background_highlight_id, (_, background_ranges)) in
6565 background_highlights.iter()
6566 {
6567 let is_search_highlights = *background_highlight_id
6568 == HighlightKey::Type(TypeId::of::<BufferSearchHighlights>());
6569 let is_text_highlights = *background_highlight_id
6570 == HighlightKey::Type(TypeId::of::<SelectedTextHighlight>());
6571 let is_symbol_occurrences = *background_highlight_id
6572 == HighlightKey::Type(TypeId::of::<DocumentHighlightRead>())
6573 || *background_highlight_id
6574 == HighlightKey::Type(
6575 TypeId::of::<DocumentHighlightWrite>(),
6576 );
6577 if (is_search_highlights && scrollbar_settings.search_results)
6578 || (is_text_highlights && scrollbar_settings.selected_text)
6579 || (is_symbol_occurrences && scrollbar_settings.selected_symbol)
6580 {
6581 let mut color = theme.status().info;
6582 if is_symbol_occurrences {
6583 color.fade_out(0.5);
6584 }
6585 let marker_row_ranges = background_ranges.iter().map(|range| {
6586 let display_start = range
6587 .start
6588 .to_display_point(&snapshot.display_snapshot);
6589 let display_end =
6590 range.end.to_display_point(&snapshot.display_snapshot);
6591 ColoredRange {
6592 start: display_start.row(),
6593 end: display_end.row(),
6594 color,
6595 }
6596 });
6597 marker_quads.extend(
6598 scrollbar_layout
6599 .marker_quads_for_ranges(marker_row_ranges, Some(1)),
6600 );
6601 }
6602 }
6603
6604 if scrollbar_settings.diagnostics != ScrollbarDiagnostics::None {
6605 let diagnostics = snapshot
6606 .buffer_snapshot
6607 .diagnostics_in_range::<Point>(Point::zero()..max_point)
6608 // Don't show diagnostics the user doesn't care about
6609 .filter(|diagnostic| {
6610 match (
6611 scrollbar_settings.diagnostics,
6612 diagnostic.diagnostic.severity,
6613 ) {
6614 (ScrollbarDiagnostics::All, _) => true,
6615 (
6616 ScrollbarDiagnostics::Error,
6617 lsp::DiagnosticSeverity::ERROR,
6618 ) => true,
6619 (
6620 ScrollbarDiagnostics::Warning,
6621 lsp::DiagnosticSeverity::ERROR
6622 | lsp::DiagnosticSeverity::WARNING,
6623 ) => true,
6624 (
6625 ScrollbarDiagnostics::Information,
6626 lsp::DiagnosticSeverity::ERROR
6627 | lsp::DiagnosticSeverity::WARNING
6628 | lsp::DiagnosticSeverity::INFORMATION,
6629 ) => true,
6630 (_, _) => false,
6631 }
6632 })
6633 // We want to sort by severity, in order to paint the most severe diagnostics last.
6634 .sorted_by_key(|diagnostic| {
6635 std::cmp::Reverse(diagnostic.diagnostic.severity)
6636 });
6637
6638 let marker_row_ranges = diagnostics.into_iter().map(|diagnostic| {
6639 let start_display = diagnostic
6640 .range
6641 .start
6642 .to_display_point(&snapshot.display_snapshot);
6643 let end_display = diagnostic
6644 .range
6645 .end
6646 .to_display_point(&snapshot.display_snapshot);
6647 let color = match diagnostic.diagnostic.severity {
6648 lsp::DiagnosticSeverity::ERROR => theme.status().error,
6649 lsp::DiagnosticSeverity::WARNING => theme.status().warning,
6650 lsp::DiagnosticSeverity::INFORMATION => theme.status().info,
6651 _ => theme.status().hint,
6652 };
6653 ColoredRange {
6654 start: start_display.row(),
6655 end: end_display.row(),
6656 color,
6657 }
6658 });
6659 marker_quads.extend(
6660 scrollbar_layout
6661 .marker_quads_for_ranges(marker_row_ranges, Some(2)),
6662 );
6663 }
6664
6665 Arc::from(marker_quads)
6666 })
6667 .await;
6668
6669 editor.update(cx, |editor, cx| {
6670 editor.scrollbar_marker_state.markers = scrollbar_markers;
6671 editor.scrollbar_marker_state.scrollbar_size = scrollbar_size;
6672 editor.scrollbar_marker_state.pending_refresh = None;
6673 cx.notify();
6674 })?;
6675
6676 Ok(())
6677 }));
6678 });
6679 }
6680
6681 fn paint_highlighted_range(
6682 &self,
6683 range: Range<DisplayPoint>,
6684 fill: bool,
6685 color: Hsla,
6686 corner_radius: Pixels,
6687 line_end_overshoot: Pixels,
6688 layout: &EditorLayout,
6689 window: &mut Window,
6690 ) {
6691 let start_row = layout.visible_display_row_range.start;
6692 let end_row = layout.visible_display_row_range.end;
6693 if range.start != range.end {
6694 let row_range = if range.end.column() == 0 {
6695 cmp::max(range.start.row(), start_row)..cmp::min(range.end.row(), end_row)
6696 } else {
6697 cmp::max(range.start.row(), start_row)
6698 ..cmp::min(range.end.row().next_row(), end_row)
6699 };
6700
6701 let highlighted_range = HighlightedRange {
6702 color,
6703 line_height: layout.position_map.line_height,
6704 corner_radius,
6705 start_y: layout.content_origin.y
6706 + row_range.start.as_f32() * layout.position_map.line_height
6707 - layout.position_map.scroll_pixel_position.y,
6708 lines: row_range
6709 .iter_rows()
6710 .map(|row| {
6711 let line_layout =
6712 &layout.position_map.line_layouts[row.minus(start_row) as usize];
6713 HighlightedRangeLine {
6714 start_x: if row == range.start.row() {
6715 layout.content_origin.x
6716 + line_layout.x_for_index(range.start.column() as usize)
6717 - layout.position_map.scroll_pixel_position.x
6718 } else {
6719 layout.content_origin.x
6720 - layout.position_map.scroll_pixel_position.x
6721 },
6722 end_x: if row == range.end.row() {
6723 layout.content_origin.x
6724 + line_layout.x_for_index(range.end.column() as usize)
6725 - layout.position_map.scroll_pixel_position.x
6726 } else {
6727 layout.content_origin.x + line_layout.width + line_end_overshoot
6728 - layout.position_map.scroll_pixel_position.x
6729 },
6730 }
6731 })
6732 .collect(),
6733 };
6734
6735 highlighted_range.paint(fill, layout.position_map.text_hitbox.bounds, window);
6736 }
6737 }
6738
6739 fn paint_inline_diagnostics(
6740 &mut self,
6741 layout: &mut EditorLayout,
6742 window: &mut Window,
6743 cx: &mut App,
6744 ) {
6745 for mut inline_diagnostic in layout.inline_diagnostics.drain() {
6746 inline_diagnostic.1.paint(window, cx);
6747 }
6748 }
6749
6750 fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6751 if let Some(mut blame_layout) = layout.inline_blame_layout.take() {
6752 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6753 blame_layout.element.paint(window, cx);
6754 })
6755 }
6756 }
6757
6758 fn paint_inline_code_actions(
6759 &mut self,
6760 layout: &mut EditorLayout,
6761 window: &mut Window,
6762 cx: &mut App,
6763 ) {
6764 if let Some(mut inline_code_actions) = layout.inline_code_actions.take() {
6765 window.paint_layer(layout.position_map.text_hitbox.bounds, |window| {
6766 inline_code_actions.paint(window, cx);
6767 })
6768 }
6769 }
6770
6771 fn paint_diff_hunk_controls(
6772 &mut self,
6773 layout: &mut EditorLayout,
6774 window: &mut Window,
6775 cx: &mut App,
6776 ) {
6777 for mut diff_hunk_control in layout.diff_hunk_controls.drain(..) {
6778 diff_hunk_control.paint(window, cx);
6779 }
6780 }
6781
6782 fn paint_minimap(&self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6783 if let Some(mut layout) = layout.minimap.take() {
6784 let minimap_hitbox = layout.thumb_layout.hitbox.clone();
6785 let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap();
6786
6787 window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| {
6788 window.with_element_namespace("minimap", |window| {
6789 layout.minimap.paint(window, cx);
6790 if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds {
6791 let minimap_thumb_color = match layout.thumb_layout.thumb_state {
6792 ScrollbarThumbState::Idle => {
6793 cx.theme().colors().minimap_thumb_background
6794 }
6795 ScrollbarThumbState::Hovered => {
6796 cx.theme().colors().minimap_thumb_hover_background
6797 }
6798 ScrollbarThumbState::Dragging => {
6799 cx.theme().colors().minimap_thumb_active_background
6800 }
6801 };
6802 let minimap_thumb_border = match layout.thumb_border_style {
6803 MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH),
6804 MinimapThumbBorder::LeftOnly => Edges {
6805 left: ScrollbarLayout::BORDER_WIDTH,
6806 ..Default::default()
6807 },
6808 MinimapThumbBorder::LeftOpen => Edges {
6809 right: ScrollbarLayout::BORDER_WIDTH,
6810 top: ScrollbarLayout::BORDER_WIDTH,
6811 bottom: ScrollbarLayout::BORDER_WIDTH,
6812 ..Default::default()
6813 },
6814 MinimapThumbBorder::RightOpen => Edges {
6815 left: ScrollbarLayout::BORDER_WIDTH,
6816 top: ScrollbarLayout::BORDER_WIDTH,
6817 bottom: ScrollbarLayout::BORDER_WIDTH,
6818 ..Default::default()
6819 },
6820 MinimapThumbBorder::None => Default::default(),
6821 };
6822
6823 window.paint_layer(minimap_hitbox.bounds, |window| {
6824 window.paint_quad(quad(
6825 thumb_bounds,
6826 Corners::default(),
6827 minimap_thumb_color,
6828 minimap_thumb_border,
6829 cx.theme().colors().minimap_thumb_border,
6830 BorderStyle::Solid,
6831 ));
6832 });
6833 }
6834 });
6835 });
6836
6837 if dragging_minimap {
6838 window.set_window_cursor_style(CursorStyle::Arrow);
6839 } else {
6840 window.set_cursor_style(CursorStyle::Arrow, &minimap_hitbox);
6841 }
6842
6843 let minimap_axis = ScrollbarAxis::Vertical;
6844 let pixels_per_line = (minimap_hitbox.size.height / layout.max_scroll_top)
6845 .min(layout.minimap_line_height);
6846
6847 let mut mouse_position = window.mouse_position();
6848
6849 window.on_mouse_event({
6850 let editor = self.editor.clone();
6851
6852 let minimap_hitbox = minimap_hitbox.clone();
6853
6854 move |event: &MouseMoveEvent, phase, window, cx| {
6855 if phase == DispatchPhase::Capture {
6856 return;
6857 }
6858
6859 editor.update(cx, |editor, cx| {
6860 if event.pressed_button == Some(MouseButton::Left)
6861 && editor.scroll_manager.is_dragging_minimap()
6862 {
6863 let old_position = mouse_position.along(minimap_axis);
6864 let new_position = event.position.along(minimap_axis);
6865 if (minimap_hitbox.origin.along(minimap_axis)
6866 ..minimap_hitbox.bottom_right().along(minimap_axis))
6867 .contains(&old_position)
6868 {
6869 let position =
6870 editor.scroll_position(cx).apply_along(minimap_axis, |p| {
6871 (p + (new_position - old_position) / pixels_per_line)
6872 .max(0.)
6873 });
6874 editor.set_scroll_position(position, window, cx);
6875 }
6876 cx.stop_propagation();
6877 } else if minimap_hitbox.is_hovered(window) {
6878 editor.scroll_manager.set_is_hovering_minimap_thumb(
6879 !event.dragging()
6880 && layout
6881 .thumb_layout
6882 .thumb_bounds
6883 .is_some_and(|bounds| bounds.contains(&event.position)),
6884 cx,
6885 );
6886
6887 // Stop hover events from propagating to the
6888 // underlying editor if the minimap hitbox is hovered
6889 if !event.dragging() {
6890 cx.stop_propagation();
6891 }
6892 } else {
6893 editor.scroll_manager.hide_minimap_thumb(cx);
6894 }
6895 mouse_position = event.position;
6896 });
6897 }
6898 });
6899
6900 if dragging_minimap {
6901 window.on_mouse_event({
6902 let editor = self.editor.clone();
6903 move |event: &MouseUpEvent, phase, window, cx| {
6904 if phase == DispatchPhase::Capture {
6905 return;
6906 }
6907
6908 editor.update(cx, |editor, cx| {
6909 if minimap_hitbox.is_hovered(window) {
6910 editor.scroll_manager.set_is_hovering_minimap_thumb(
6911 layout
6912 .thumb_layout
6913 .thumb_bounds
6914 .is_some_and(|bounds| bounds.contains(&event.position)),
6915 cx,
6916 );
6917 } else {
6918 editor.scroll_manager.hide_minimap_thumb(cx);
6919 }
6920 cx.stop_propagation();
6921 });
6922 }
6923 });
6924 } else {
6925 window.on_mouse_event({
6926 let editor = self.editor.clone();
6927
6928 move |event: &MouseDownEvent, phase, window, cx| {
6929 if phase == DispatchPhase::Capture || !minimap_hitbox.is_hovered(window) {
6930 return;
6931 }
6932
6933 let event_position = event.position;
6934
6935 let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds else {
6936 return;
6937 };
6938
6939 editor.update(cx, |editor, cx| {
6940 if !thumb_bounds.contains(&event_position) {
6941 let click_position =
6942 event_position.relative_to(&minimap_hitbox.origin).y;
6943
6944 let top_position = (click_position
6945 - thumb_bounds.size.along(minimap_axis) / 2.0)
6946 .max(Pixels::ZERO);
6947
6948 let scroll_offset = (layout.minimap_scroll_top
6949 + top_position / layout.minimap_line_height)
6950 .min(layout.max_scroll_top);
6951
6952 let scroll_position = editor
6953 .scroll_position(cx)
6954 .apply_along(minimap_axis, |_| scroll_offset);
6955 editor.set_scroll_position(scroll_position, window, cx);
6956 }
6957
6958 editor.scroll_manager.set_is_dragging_minimap(cx);
6959 cx.stop_propagation();
6960 });
6961 }
6962 });
6963 }
6964 }
6965 }
6966
6967 fn paint_blocks(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) {
6968 for mut block in layout.blocks.drain(..) {
6969 if block.overlaps_gutter {
6970 block.element.paint(window, cx);
6971 } else {
6972 let mut bounds = layout.hitbox.bounds;
6973 bounds.origin.x += layout.gutter_hitbox.bounds.size.width;
6974 window.with_content_mask(Some(ContentMask { bounds }), |window| {
6975 block.element.paint(window, cx);
6976 })
6977 }
6978 }
6979 }
6980
6981 fn paint_edit_prediction_popover(
6982 &mut self,
6983 layout: &mut EditorLayout,
6984 window: &mut Window,
6985 cx: &mut App,
6986 ) {
6987 if let Some(edit_prediction_popover) = layout.edit_prediction_popover.as_mut() {
6988 edit_prediction_popover.paint(window, cx);
6989 }
6990 }
6991
6992 fn paint_mouse_context_menu(
6993 &mut self,
6994 layout: &mut EditorLayout,
6995 window: &mut Window,
6996 cx: &mut App,
6997 ) {
6998 if let Some(mouse_context_menu) = layout.mouse_context_menu.as_mut() {
6999 mouse_context_menu.paint(window, cx);
7000 }
7001 }
7002
7003 fn paint_scroll_wheel_listener(
7004 &mut self,
7005 layout: &EditorLayout,
7006 window: &mut Window,
7007 cx: &mut App,
7008 ) {
7009 window.on_mouse_event({
7010 let position_map = layout.position_map.clone();
7011 let editor = self.editor.clone();
7012 let hitbox = layout.hitbox.clone();
7013 let mut delta = ScrollDelta::default();
7014
7015 // Set a minimum scroll_sensitivity of 0.01 to make sure the user doesn't
7016 // accidentally turn off their scrolling.
7017 let base_scroll_sensitivity =
7018 EditorSettings::get_global(cx).scroll_sensitivity.max(0.01);
7019
7020 // Use a minimum fast_scroll_sensitivity for same reason above
7021 let fast_scroll_sensitivity = EditorSettings::get_global(cx)
7022 .fast_scroll_sensitivity
7023 .max(0.01);
7024
7025 move |event: &ScrollWheelEvent, phase, window, cx| {
7026 let scroll_sensitivity = {
7027 if event.modifiers.alt {
7028 fast_scroll_sensitivity
7029 } else {
7030 base_scroll_sensitivity
7031 }
7032 };
7033
7034 if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
7035 delta = delta.coalesce(event.delta);
7036 editor.update(cx, |editor, cx| {
7037 let position_map: &PositionMap = &position_map;
7038
7039 let line_height = position_map.line_height;
7040 let max_glyph_advance = position_map.em_advance;
7041 let (delta, axis) = match delta {
7042 gpui::ScrollDelta::Pixels(mut pixels) => {
7043 //Trackpad
7044 let axis = position_map.snapshot.ongoing_scroll.filter(&mut pixels);
7045 (pixels, axis)
7046 }
7047
7048 gpui::ScrollDelta::Lines(lines) => {
7049 //Not trackpad
7050 let pixels =
7051 point(lines.x * max_glyph_advance, lines.y * line_height);
7052 (pixels, None)
7053 }
7054 };
7055
7056 let current_scroll_position = position_map.snapshot.scroll_position();
7057 let x = (current_scroll_position.x * max_glyph_advance
7058 - (delta.x * scroll_sensitivity))
7059 / max_glyph_advance;
7060 let y = (current_scroll_position.y * line_height
7061 - (delta.y * scroll_sensitivity))
7062 / line_height;
7063 let mut scroll_position =
7064 point(x, y).clamp(&point(0., 0.), &position_map.scroll_max);
7065 let forbid_vertical_scroll = editor.scroll_manager.forbid_vertical_scroll();
7066 if forbid_vertical_scroll {
7067 scroll_position.y = current_scroll_position.y;
7068 }
7069
7070 if scroll_position != current_scroll_position {
7071 editor.scroll(scroll_position, axis, window, cx);
7072 cx.stop_propagation();
7073 } else if y < 0. {
7074 // Due to clamping, we may fail to detect cases of overscroll to the top;
7075 // We want the scroll manager to get an update in such cases and detect the change of direction
7076 // on the next frame.
7077 cx.notify();
7078 }
7079 });
7080 }
7081 }
7082 });
7083 }
7084
7085 fn paint_mouse_listeners(&mut self, layout: &EditorLayout, window: &mut Window, cx: &mut App) {
7086 if layout.mode.is_minimap() {
7087 return;
7088 }
7089
7090 self.paint_scroll_wheel_listener(layout, window, cx);
7091
7092 window.on_mouse_event({
7093 let position_map = layout.position_map.clone();
7094 let editor = self.editor.clone();
7095 let diff_hunk_range =
7096 layout
7097 .display_hunks
7098 .iter()
7099 .find_map(|(hunk, hunk_hitbox)| match hunk {
7100 DisplayDiffHunk::Folded { .. } => None,
7101 DisplayDiffHunk::Unfolded {
7102 multi_buffer_range, ..
7103 } => {
7104 if hunk_hitbox
7105 .as_ref()
7106 .map(|hitbox| hitbox.is_hovered(window))
7107 .unwrap_or(false)
7108 {
7109 Some(multi_buffer_range.clone())
7110 } else {
7111 None
7112 }
7113 }
7114 });
7115 let line_numbers = layout.line_numbers.clone();
7116
7117 move |event: &MouseDownEvent, phase, window, cx| {
7118 if phase == DispatchPhase::Bubble {
7119 match event.button {
7120 MouseButton::Left => editor.update(cx, |editor, cx| {
7121 let pending_mouse_down = editor
7122 .pending_mouse_down
7123 .get_or_insert_with(Default::default)
7124 .clone();
7125
7126 *pending_mouse_down.borrow_mut() = Some(event.clone());
7127
7128 Self::mouse_left_down(
7129 editor,
7130 event,
7131 diff_hunk_range.clone(),
7132 &position_map,
7133 line_numbers.as_ref(),
7134 window,
7135 cx,
7136 );
7137 }),
7138 MouseButton::Right => editor.update(cx, |editor, cx| {
7139 Self::mouse_right_down(editor, event, &position_map, window, cx);
7140 }),
7141 MouseButton::Middle => editor.update(cx, |editor, cx| {
7142 Self::mouse_middle_down(editor, event, &position_map, window, cx);
7143 }),
7144 _ => {}
7145 };
7146 }
7147 }
7148 });
7149
7150 window.on_mouse_event({
7151 let editor = self.editor.clone();
7152 let position_map = layout.position_map.clone();
7153
7154 move |event: &MouseUpEvent, phase, window, cx| {
7155 if phase == DispatchPhase::Bubble {
7156 editor.update(cx, |editor, cx| {
7157 Self::mouse_up(editor, event, &position_map, window, cx)
7158 });
7159 }
7160 }
7161 });
7162
7163 window.on_mouse_event({
7164 let editor = self.editor.clone();
7165 let position_map = layout.position_map.clone();
7166 let mut captured_mouse_down = None;
7167
7168 move |event: &MouseUpEvent, phase, window, cx| match phase {
7169 // Clear the pending mouse down during the capture phase,
7170 // so that it happens even if another event handler stops
7171 // propagation.
7172 DispatchPhase::Capture => editor.update(cx, |editor, _cx| {
7173 let pending_mouse_down = editor
7174 .pending_mouse_down
7175 .get_or_insert_with(Default::default)
7176 .clone();
7177
7178 let mut pending_mouse_down = pending_mouse_down.borrow_mut();
7179 if pending_mouse_down.is_some() && position_map.text_hitbox.is_hovered(window) {
7180 captured_mouse_down = pending_mouse_down.take();
7181 window.refresh();
7182 }
7183 }),
7184 // Fire click handlers during the bubble phase.
7185 DispatchPhase::Bubble => editor.update(cx, |editor, cx| {
7186 if let Some(mouse_down) = captured_mouse_down.take() {
7187 let event = ClickEvent::Mouse(MouseClickEvent {
7188 down: mouse_down,
7189 up: event.clone(),
7190 });
7191 Self::click(editor, &event, &position_map, window, cx);
7192 }
7193 }),
7194 }
7195 });
7196
7197 window.on_mouse_event({
7198 let position_map = layout.position_map.clone();
7199 let editor = self.editor.clone();
7200
7201 move |event: &MouseMoveEvent, phase, window, cx| {
7202 if phase == DispatchPhase::Bubble {
7203 editor.update(cx, |editor, cx| {
7204 if editor.hover_state.focused(window, cx) {
7205 return;
7206 }
7207 if event.pressed_button == Some(MouseButton::Left)
7208 || event.pressed_button == Some(MouseButton::Middle)
7209 {
7210 Self::mouse_dragged(editor, event, &position_map, window, cx)
7211 }
7212
7213 Self::mouse_moved(editor, event, &position_map, window, cx)
7214 });
7215 }
7216 }
7217 });
7218 }
7219
7220 fn column_pixels(&self, column: usize, window: &Window) -> Pixels {
7221 let style = &self.style;
7222 let font_size = style.text.font_size.to_pixels(window.rem_size());
7223 let layout = window.text_system().shape_line(
7224 SharedString::from(" ".repeat(column)),
7225 font_size,
7226 &[TextRun {
7227 len: column,
7228 font: style.text.font(),
7229 color: Hsla::default(),
7230 background_color: None,
7231 underline: None,
7232 strikethrough: None,
7233 }],
7234 None,
7235 );
7236
7237 layout.width
7238 }
7239
7240 fn max_line_number_width(&self, snapshot: &EditorSnapshot, window: &mut Window) -> Pixels {
7241 let digit_count = snapshot.widest_line_number().ilog10() + 1;
7242 self.column_pixels(digit_count as usize, window)
7243 }
7244
7245 fn shape_line_number(
7246 &self,
7247 text: SharedString,
7248 color: Hsla,
7249 window: &mut Window,
7250 ) -> ShapedLine {
7251 let run = TextRun {
7252 len: text.len(),
7253 font: self.style.text.font(),
7254 color,
7255 background_color: None,
7256 underline: None,
7257 strikethrough: None,
7258 };
7259 window.text_system().shape_line(
7260 text,
7261 self.style.text.font_size.to_pixels(window.rem_size()),
7262 &[run],
7263 None,
7264 )
7265 }
7266
7267 fn diff_hunk_hollow(status: DiffHunkStatus, cx: &mut App) -> bool {
7268 let unstaged = status.has_secondary_hunk();
7269 let unstaged_hollow = ProjectSettings::get_global(cx)
7270 .git
7271 .hunk_style
7272 .is_some_and(|style| matches!(style, GitHunkStyleSetting::UnstagedHollow));
7273
7274 unstaged == unstaged_hollow
7275 }
7276}
7277
7278fn header_jump_data(
7279 snapshot: &EditorSnapshot,
7280 block_row_start: DisplayRow,
7281 height: u32,
7282 for_excerpt: &ExcerptInfo,
7283) -> JumpData {
7284 let range = &for_excerpt.range;
7285 let buffer = &for_excerpt.buffer;
7286 let jump_anchor = range.primary.start;
7287
7288 let excerpt_start = range.context.start;
7289 let jump_position = language::ToPoint::to_point(&jump_anchor, buffer);
7290 let rows_from_excerpt_start = if jump_anchor == excerpt_start {
7291 0
7292 } else {
7293 let excerpt_start_point = language::ToPoint::to_point(&excerpt_start, buffer);
7294 jump_position.row.saturating_sub(excerpt_start_point.row)
7295 };
7296
7297 let line_offset_from_top = (block_row_start.0 + height + rows_from_excerpt_start)
7298 .saturating_sub(
7299 snapshot
7300 .scroll_anchor
7301 .scroll_position(&snapshot.display_snapshot)
7302 .y as u32,
7303 );
7304
7305 JumpData::MultiBufferPoint {
7306 excerpt_id: for_excerpt.id,
7307 anchor: jump_anchor,
7308 position: jump_position,
7309 line_offset_from_top,
7310 }
7311}
7312
7313pub struct AcceptEditPredictionBinding(pub(crate) Option<gpui::KeyBinding>);
7314
7315impl AcceptEditPredictionBinding {
7316 pub fn keystroke(&self) -> Option<&KeybindingKeystroke> {
7317 if let Some(binding) = self.0.as_ref() {
7318 match &binding.keystrokes() {
7319 [keystroke, ..] => Some(keystroke),
7320 _ => None,
7321 }
7322 } else {
7323 None
7324 }
7325 }
7326}
7327
7328fn prepaint_gutter_button(
7329 button: IconButton,
7330 row: DisplayRow,
7331 line_height: Pixels,
7332 gutter_dimensions: &GutterDimensions,
7333 scroll_pixel_position: gpui::Point<Pixels>,
7334 gutter_hitbox: &Hitbox,
7335 display_hunks: &[(DisplayDiffHunk, Option<Hitbox>)],
7336 window: &mut Window,
7337 cx: &mut App,
7338) -> AnyElement {
7339 let mut button = button.into_any_element();
7340
7341 let available_space = size(
7342 AvailableSpace::MinContent,
7343 AvailableSpace::Definite(line_height),
7344 );
7345 let indicator_size = button.layout_as_root(available_space, window, cx);
7346
7347 let blame_width = gutter_dimensions.git_blame_entries_width;
7348 let gutter_width = display_hunks
7349 .binary_search_by(|(hunk, _)| match hunk {
7350 DisplayDiffHunk::Folded { display_row } => display_row.cmp(&row),
7351 DisplayDiffHunk::Unfolded {
7352 display_row_range, ..
7353 } => {
7354 if display_row_range.end <= row {
7355 Ordering::Less
7356 } else if display_row_range.start > row {
7357 Ordering::Greater
7358 } else {
7359 Ordering::Equal
7360 }
7361 }
7362 })
7363 .ok()
7364 .and_then(|ix| Some(display_hunks[ix].1.as_ref()?.size.width));
7365 let left_offset = blame_width.max(gutter_width).unwrap_or_default();
7366
7367 let mut x = left_offset;
7368 let available_width = gutter_dimensions.margin + gutter_dimensions.left_padding
7369 - indicator_size.width
7370 - left_offset;
7371 x += available_width / 2.;
7372
7373 let mut y = row.as_f32() * line_height - scroll_pixel_position.y;
7374 y += (line_height - indicator_size.height) / 2.;
7375
7376 button.prepaint_as_root(
7377 gutter_hitbox.origin + point(x, y),
7378 available_space,
7379 window,
7380 cx,
7381 );
7382 button
7383}
7384
7385fn render_inline_blame_entry(
7386 blame_entry: BlameEntry,
7387 style: &EditorStyle,
7388 cx: &mut App,
7389) -> Option<AnyElement> {
7390 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7391 renderer.render_inline_blame_entry(&style.text, blame_entry, cx)
7392}
7393
7394fn render_blame_entry_popover(
7395 blame_entry: BlameEntry,
7396 scroll_handle: ScrollHandle,
7397 commit_message: Option<ParsedCommitMessage>,
7398 markdown: Entity<Markdown>,
7399 workspace: WeakEntity<Workspace>,
7400 blame: &Entity<GitBlame>,
7401 window: &mut Window,
7402 cx: &mut App,
7403) -> Option<AnyElement> {
7404 let renderer = cx.global::<GlobalBlameRenderer>().0.clone();
7405 let blame = blame.read(cx);
7406 let repository = blame.repository(cx)?;
7407 renderer.render_blame_entry_popover(
7408 blame_entry,
7409 scroll_handle,
7410 commit_message,
7411 markdown,
7412 repository,
7413 workspace,
7414 window,
7415 cx,
7416 )
7417}
7418
7419fn render_blame_entry(
7420 ix: usize,
7421 blame: &Entity<GitBlame>,
7422 blame_entry: BlameEntry,
7423 style: &EditorStyle,
7424 last_used_color: &mut Option<(PlayerColor, Oid)>,
7425 editor: Entity<Editor>,
7426 workspace: Entity<Workspace>,
7427 renderer: Arc<dyn BlameRenderer>,
7428 cx: &mut App,
7429) -> Option<AnyElement> {
7430 let mut sha_color = cx
7431 .theme()
7432 .players()
7433 .color_for_participant(blame_entry.sha.into());
7434
7435 // If the last color we used is the same as the one we get for this line, but
7436 // the commit SHAs are different, then we try again to get a different color.
7437 match *last_used_color {
7438 Some((color, sha)) if sha != blame_entry.sha && color.cursor == sha_color.cursor => {
7439 let index: u32 = blame_entry.sha.into();
7440 sha_color = cx.theme().players().color_for_participant(index + 1);
7441 }
7442 _ => {}
7443 };
7444 last_used_color.replace((sha_color, blame_entry.sha));
7445
7446 let blame = blame.read(cx);
7447 let details = blame.details_for_entry(&blame_entry);
7448 let repository = blame.repository(cx)?;
7449 renderer.render_blame_entry(
7450 &style.text,
7451 blame_entry,
7452 details,
7453 repository,
7454 workspace.downgrade(),
7455 editor,
7456 ix,
7457 sha_color.cursor,
7458 cx,
7459 )
7460}
7461
7462#[derive(Debug)]
7463pub(crate) struct LineWithInvisibles {
7464 fragments: SmallVec<[LineFragment; 1]>,
7465 invisibles: Vec<Invisible>,
7466 len: usize,
7467 pub(crate) width: Pixels,
7468 font_size: Pixels,
7469}
7470
7471enum LineFragment {
7472 Text(ShapedLine),
7473 Element {
7474 id: ChunkRendererId,
7475 element: Option<AnyElement>,
7476 size: Size<Pixels>,
7477 len: usize,
7478 },
7479}
7480
7481impl fmt::Debug for LineFragment {
7482 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
7483 match self {
7484 LineFragment::Text(shaped_line) => f.debug_tuple("Text").field(shaped_line).finish(),
7485 LineFragment::Element { size, len, .. } => f
7486 .debug_struct("Element")
7487 .field("size", size)
7488 .field("len", len)
7489 .finish(),
7490 }
7491 }
7492}
7493
7494impl LineWithInvisibles {
7495 fn from_chunks<'a>(
7496 chunks: impl Iterator<Item = HighlightedChunk<'a>>,
7497 editor_style: &EditorStyle,
7498 max_line_len: usize,
7499 max_line_count: usize,
7500 editor_mode: &EditorMode,
7501 text_width: Pixels,
7502 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
7503 bg_segments_per_row: &[Vec<(Range<DisplayPoint>, Hsla)>],
7504 window: &mut Window,
7505 cx: &mut App,
7506 ) -> Vec<Self> {
7507 let text_style = &editor_style.text;
7508 let mut layouts = Vec::with_capacity(max_line_count);
7509 let mut fragments: SmallVec<[LineFragment; 1]> = SmallVec::new();
7510 let mut line = String::new();
7511 let mut invisibles = Vec::new();
7512 let mut width = Pixels::ZERO;
7513 let mut len = 0;
7514 let mut styles = Vec::new();
7515 let mut non_whitespace_added = false;
7516 let mut row = 0;
7517 let mut line_exceeded_max_len = false;
7518 let font_size = text_style.font_size.to_pixels(window.rem_size());
7519 let min_contrast = EditorSettings::get_global(cx).minimum_contrast_for_highlights;
7520
7521 let ellipsis = SharedString::from("β―");
7522
7523 for highlighted_chunk in chunks.chain([HighlightedChunk {
7524 text: "\n",
7525 style: None,
7526 is_tab: false,
7527 is_inlay: false,
7528 replacement: None,
7529 }]) {
7530 if let Some(replacement) = highlighted_chunk.replacement {
7531 if !line.is_empty() {
7532 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
7533 let text_runs: &[TextRun] = if segments.is_empty() {
7534 &styles
7535 } else {
7536 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast)
7537 };
7538 let shaped_line = window.text_system().shape_line(
7539 line.clone().into(),
7540 font_size,
7541 text_runs,
7542 None,
7543 );
7544 width += shaped_line.width;
7545 len += shaped_line.len;
7546 fragments.push(LineFragment::Text(shaped_line));
7547 line.clear();
7548 styles.clear();
7549 }
7550
7551 match replacement {
7552 ChunkReplacement::Renderer(renderer) => {
7553 let available_width = if renderer.constrain_width {
7554 let chunk = if highlighted_chunk.text == ellipsis.as_ref() {
7555 ellipsis.clone()
7556 } else {
7557 SharedString::from(Arc::from(highlighted_chunk.text))
7558 };
7559 let shaped_line = window.text_system().shape_line(
7560 chunk,
7561 font_size,
7562 &[text_style.to_run(highlighted_chunk.text.len())],
7563 None,
7564 );
7565 AvailableSpace::Definite(shaped_line.width)
7566 } else {
7567 AvailableSpace::MinContent
7568 };
7569
7570 let mut element = (renderer.render)(&mut ChunkRendererContext {
7571 context: cx,
7572 window,
7573 max_width: text_width,
7574 });
7575 let line_height = text_style.line_height_in_pixels(window.rem_size());
7576 let size = element.layout_as_root(
7577 size(available_width, AvailableSpace::Definite(line_height)),
7578 window,
7579 cx,
7580 );
7581
7582 width += size.width;
7583 len += highlighted_chunk.text.len();
7584 fragments.push(LineFragment::Element {
7585 id: renderer.id,
7586 element: Some(element),
7587 size,
7588 len: highlighted_chunk.text.len(),
7589 });
7590 }
7591 ChunkReplacement::Str(x) => {
7592 let text_style = if let Some(style) = highlighted_chunk.style {
7593 Cow::Owned(text_style.clone().highlight(style))
7594 } else {
7595 Cow::Borrowed(text_style)
7596 };
7597
7598 let run = TextRun {
7599 len: x.len(),
7600 font: text_style.font(),
7601 color: text_style.color,
7602 background_color: text_style.background_color,
7603 underline: text_style.underline,
7604 strikethrough: text_style.strikethrough,
7605 };
7606 let line_layout = window
7607 .text_system()
7608 .shape_line(x, font_size, &[run], None)
7609 .with_len(highlighted_chunk.text.len());
7610
7611 width += line_layout.width;
7612 len += highlighted_chunk.text.len();
7613 fragments.push(LineFragment::Text(line_layout))
7614 }
7615 }
7616 } else {
7617 for (ix, mut line_chunk) in highlighted_chunk.text.split('\n').enumerate() {
7618 if ix > 0 {
7619 let segments = bg_segments_per_row.get(row).map(|v| &v[..]).unwrap_or(&[]);
7620 let text_runs = if segments.is_empty() {
7621 &styles
7622 } else {
7623 &Self::split_runs_by_bg_segments(&styles, segments, min_contrast)
7624 };
7625 let shaped_line = window.text_system().shape_line(
7626 line.clone().into(),
7627 font_size,
7628 text_runs,
7629 None,
7630 );
7631 width += shaped_line.width;
7632 len += shaped_line.len;
7633 fragments.push(LineFragment::Text(shaped_line));
7634 layouts.push(Self {
7635 width: mem::take(&mut width),
7636 len: mem::take(&mut len),
7637 fragments: mem::take(&mut fragments),
7638 invisibles: std::mem::take(&mut invisibles),
7639 font_size,
7640 });
7641
7642 line.clear();
7643 styles.clear();
7644 row += 1;
7645 line_exceeded_max_len = false;
7646 non_whitespace_added = false;
7647 if row == max_line_count {
7648 return layouts;
7649 }
7650 }
7651
7652 if !line_chunk.is_empty() && !line_exceeded_max_len {
7653 let text_style = if let Some(style) = highlighted_chunk.style {
7654 Cow::Owned(text_style.clone().highlight(style))
7655 } else {
7656 Cow::Borrowed(text_style)
7657 };
7658
7659 if line.len() + line_chunk.len() > max_line_len {
7660 let mut chunk_len = max_line_len - line.len();
7661 while !line_chunk.is_char_boundary(chunk_len) {
7662 chunk_len -= 1;
7663 }
7664 line_chunk = &line_chunk[..chunk_len];
7665 line_exceeded_max_len = true;
7666 }
7667
7668 styles.push(TextRun {
7669 len: line_chunk.len(),
7670 font: text_style.font(),
7671 color: text_style.color,
7672 background_color: text_style.background_color,
7673 underline: text_style.underline,
7674 strikethrough: text_style.strikethrough,
7675 });
7676
7677 if editor_mode.is_full() && !highlighted_chunk.is_inlay {
7678 // Line wrap pads its contents with fake whitespaces,
7679 // avoid printing them
7680 let is_soft_wrapped = is_row_soft_wrapped(row);
7681 if highlighted_chunk.is_tab {
7682 if non_whitespace_added || !is_soft_wrapped {
7683 invisibles.push(Invisible::Tab {
7684 line_start_offset: line.len(),
7685 line_end_offset: line.len() + line_chunk.len(),
7686 });
7687 }
7688 } else {
7689 invisibles.extend(line_chunk.char_indices().filter_map(
7690 |(index, c)| {
7691 let is_whitespace = c.is_whitespace();
7692 non_whitespace_added |= !is_whitespace;
7693 if is_whitespace
7694 && (non_whitespace_added || !is_soft_wrapped)
7695 {
7696 Some(Invisible::Whitespace {
7697 line_offset: line.len() + index,
7698 })
7699 } else {
7700 None
7701 }
7702 },
7703 ))
7704 }
7705 }
7706
7707 line.push_str(line_chunk);
7708 }
7709 }
7710 }
7711 }
7712
7713 layouts
7714 }
7715
7716 /// Takes text runs and non-overlapping left-to-right background ranges with color.
7717 /// Returns new text runs with adjusted contrast as per background ranges.
7718 fn split_runs_by_bg_segments(
7719 text_runs: &[TextRun],
7720 bg_segments: &[(Range<DisplayPoint>, Hsla)],
7721 min_contrast: f32,
7722 ) -> Vec<TextRun> {
7723 let mut output_runs: Vec<TextRun> = Vec::with_capacity(text_runs.len());
7724 let mut line_col = 0usize;
7725 let mut segment_ix = 0usize;
7726
7727 for text_run in text_runs.iter() {
7728 let run_start_col = line_col;
7729 let run_end_col = run_start_col + text_run.len;
7730 while segment_ix < bg_segments.len()
7731 && (bg_segments[segment_ix].0.end.column() as usize) <= run_start_col
7732 {
7733 segment_ix += 1;
7734 }
7735 let mut cursor_col = run_start_col;
7736 let mut local_segment_ix = segment_ix;
7737 while local_segment_ix < bg_segments.len() {
7738 let (range, segment_color) = &bg_segments[local_segment_ix];
7739 let segment_start_col = range.start.column() as usize;
7740 let segment_end_col = range.end.column() as usize;
7741 if segment_start_col >= run_end_col {
7742 break;
7743 }
7744 if segment_start_col > cursor_col {
7745 let span_len = segment_start_col - cursor_col;
7746 output_runs.push(TextRun {
7747 len: span_len,
7748 font: text_run.font.clone(),
7749 color: text_run.color,
7750 background_color: text_run.background_color,
7751 underline: text_run.underline,
7752 strikethrough: text_run.strikethrough,
7753 });
7754 cursor_col = segment_start_col;
7755 }
7756 let segment_slice_end_col = segment_end_col.min(run_end_col);
7757 if segment_slice_end_col > cursor_col {
7758 let new_text_color =
7759 ensure_minimum_contrast(text_run.color, *segment_color, min_contrast);
7760 output_runs.push(TextRun {
7761 len: segment_slice_end_col - cursor_col,
7762 font: text_run.font.clone(),
7763 color: new_text_color,
7764 background_color: text_run.background_color,
7765 underline: text_run.underline,
7766 strikethrough: text_run.strikethrough,
7767 });
7768 cursor_col = segment_slice_end_col;
7769 }
7770 if segment_end_col >= run_end_col {
7771 break;
7772 }
7773 local_segment_ix += 1;
7774 }
7775 if cursor_col < run_end_col {
7776 output_runs.push(TextRun {
7777 len: run_end_col - cursor_col,
7778 font: text_run.font.clone(),
7779 color: text_run.color,
7780 background_color: text_run.background_color,
7781 underline: text_run.underline,
7782 strikethrough: text_run.strikethrough,
7783 });
7784 }
7785 line_col = run_end_col;
7786 segment_ix = local_segment_ix;
7787 }
7788 output_runs
7789 }
7790
7791 fn prepaint(
7792 &mut self,
7793 line_height: Pixels,
7794 scroll_pixel_position: gpui::Point<Pixels>,
7795 row: DisplayRow,
7796 content_origin: gpui::Point<Pixels>,
7797 line_elements: &mut SmallVec<[AnyElement; 1]>,
7798 window: &mut Window,
7799 cx: &mut App,
7800 ) {
7801 let line_y = line_height * (row.as_f32() - scroll_pixel_position.y / line_height);
7802 let mut fragment_origin = content_origin + gpui::point(-scroll_pixel_position.x, line_y);
7803 for fragment in &mut self.fragments {
7804 match fragment {
7805 LineFragment::Text(line) => {
7806 fragment_origin.x += line.width;
7807 }
7808 LineFragment::Element { element, size, .. } => {
7809 let mut element = element
7810 .take()
7811 .expect("you can't prepaint LineWithInvisibles twice");
7812
7813 // Center the element vertically within the line.
7814 let mut element_origin = fragment_origin;
7815 element_origin.y += (line_height - size.height) / 2.;
7816 element.prepaint_at(element_origin, window, cx);
7817 line_elements.push(element);
7818
7819 fragment_origin.x += size.width;
7820 }
7821 }
7822 }
7823 }
7824
7825 fn draw(
7826 &self,
7827 layout: &EditorLayout,
7828 row: DisplayRow,
7829 content_origin: gpui::Point<Pixels>,
7830 whitespace_setting: ShowWhitespaceSetting,
7831 selection_ranges: &[Range<DisplayPoint>],
7832 window: &mut Window,
7833 cx: &mut App,
7834 ) {
7835 let line_height = layout.position_map.line_height;
7836 let line_y = line_height
7837 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7838
7839 let mut fragment_origin =
7840 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7841
7842 for fragment in &self.fragments {
7843 match fragment {
7844 LineFragment::Text(line) => {
7845 line.paint(fragment_origin, line_height, window, cx)
7846 .log_err();
7847 fragment_origin.x += line.width;
7848 }
7849 LineFragment::Element { size, .. } => {
7850 fragment_origin.x += size.width;
7851 }
7852 }
7853 }
7854
7855 self.draw_invisibles(
7856 selection_ranges,
7857 layout,
7858 content_origin,
7859 line_y,
7860 row,
7861 line_height,
7862 whitespace_setting,
7863 window,
7864 cx,
7865 );
7866 }
7867
7868 fn draw_background(
7869 &self,
7870 layout: &EditorLayout,
7871 row: DisplayRow,
7872 content_origin: gpui::Point<Pixels>,
7873 window: &mut Window,
7874 cx: &mut App,
7875 ) {
7876 let line_height = layout.position_map.line_height;
7877 let line_y = line_height
7878 * (row.as_f32() - layout.position_map.scroll_pixel_position.y / line_height);
7879
7880 let mut fragment_origin =
7881 content_origin + gpui::point(-layout.position_map.scroll_pixel_position.x, line_y);
7882
7883 for fragment in &self.fragments {
7884 match fragment {
7885 LineFragment::Text(line) => {
7886 line.paint_background(fragment_origin, line_height, window, cx)
7887 .log_err();
7888 fragment_origin.x += line.width;
7889 }
7890 LineFragment::Element { size, .. } => {
7891 fragment_origin.x += size.width;
7892 }
7893 }
7894 }
7895 }
7896
7897 fn draw_invisibles(
7898 &self,
7899 selection_ranges: &[Range<DisplayPoint>],
7900 layout: &EditorLayout,
7901 content_origin: gpui::Point<Pixels>,
7902 line_y: Pixels,
7903 row: DisplayRow,
7904 line_height: Pixels,
7905 whitespace_setting: ShowWhitespaceSetting,
7906 window: &mut Window,
7907 cx: &mut App,
7908 ) {
7909 let extract_whitespace_info = |invisible: &Invisible| {
7910 let (token_offset, token_end_offset, invisible_symbol) = match invisible {
7911 Invisible::Tab {
7912 line_start_offset,
7913 line_end_offset,
7914 } => (*line_start_offset, *line_end_offset, &layout.tab_invisible),
7915 Invisible::Whitespace { line_offset } => {
7916 (*line_offset, line_offset + 1, &layout.space_invisible)
7917 }
7918 };
7919
7920 let x_offset = self.x_for_index(token_offset);
7921 let invisible_offset =
7922 (layout.position_map.em_width - invisible_symbol.width).max(Pixels::ZERO) / 2.0;
7923 let origin = content_origin
7924 + gpui::point(
7925 x_offset + invisible_offset - layout.position_map.scroll_pixel_position.x,
7926 line_y,
7927 );
7928
7929 (
7930 [token_offset, token_end_offset],
7931 Box::new(move |window: &mut Window, cx: &mut App| {
7932 invisible_symbol
7933 .paint(origin, line_height, window, cx)
7934 .log_err();
7935 }),
7936 )
7937 };
7938
7939 let invisible_iter = self.invisibles.iter().map(extract_whitespace_info);
7940 match whitespace_setting {
7941 ShowWhitespaceSetting::None => (),
7942 ShowWhitespaceSetting::All => invisible_iter.for_each(|(_, paint)| paint(window, cx)),
7943 ShowWhitespaceSetting::Selection => invisible_iter.for_each(|([start, _], paint)| {
7944 let invisible_point = DisplayPoint::new(row, start as u32);
7945 if !selection_ranges
7946 .iter()
7947 .any(|region| region.start <= invisible_point && invisible_point < region.end)
7948 {
7949 return;
7950 }
7951
7952 paint(window, cx);
7953 }),
7954
7955 ShowWhitespaceSetting::Trailing => {
7956 let mut previous_start = self.len;
7957 for ([start, end], paint) in invisible_iter.rev() {
7958 if previous_start != end {
7959 break;
7960 }
7961 previous_start = start;
7962 paint(window, cx);
7963 }
7964 }
7965
7966 // For a whitespace to be on a boundary, any of the following conditions need to be met:
7967 // - It is a tab
7968 // - It is adjacent to an edge (start or end)
7969 // - It is adjacent to a whitespace (left or right)
7970 ShowWhitespaceSetting::Boundary => {
7971 // 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
7972 // the above cases.
7973 // Note: We zip in the original `invisibles` to check for tab equality
7974 let mut last_seen: Option<(bool, usize, Box<dyn Fn(&mut Window, &mut App)>)> = None;
7975 for (([start, end], paint), invisible) in
7976 invisible_iter.zip_eq(self.invisibles.iter())
7977 {
7978 let should_render = match (&last_seen, invisible) {
7979 (_, Invisible::Tab { .. }) => true,
7980 (Some((_, last_end, _)), _) => *last_end == start,
7981 _ => false,
7982 };
7983
7984 if should_render || start == 0 || end == self.len {
7985 paint(window, cx);
7986
7987 // Since we are scanning from the left, we will skip over the first available whitespace that is part
7988 // of a boundary between non-whitespace segments, so we correct by manually redrawing it if needed.
7989 if let Some((should_render_last, last_end, paint_last)) = last_seen {
7990 // Note that we need to make sure that the last one is actually adjacent
7991 if !should_render_last && last_end == start {
7992 paint_last(window, cx);
7993 }
7994 }
7995 }
7996
7997 // Manually render anything within a selection
7998 let invisible_point = DisplayPoint::new(row, start as u32);
7999 if selection_ranges.iter().any(|region| {
8000 region.start <= invisible_point && invisible_point < region.end
8001 }) {
8002 paint(window, cx);
8003 }
8004
8005 last_seen = Some((should_render, end, paint));
8006 }
8007 }
8008 }
8009 }
8010
8011 pub fn x_for_index(&self, index: usize) -> Pixels {
8012 let mut fragment_start_x = Pixels::ZERO;
8013 let mut fragment_start_index = 0;
8014
8015 for fragment in &self.fragments {
8016 match fragment {
8017 LineFragment::Text(shaped_line) => {
8018 let fragment_end_index = fragment_start_index + shaped_line.len;
8019 if index < fragment_end_index {
8020 return fragment_start_x
8021 + shaped_line.x_for_index(index - fragment_start_index);
8022 }
8023 fragment_start_x += shaped_line.width;
8024 fragment_start_index = fragment_end_index;
8025 }
8026 LineFragment::Element { len, size, .. } => {
8027 let fragment_end_index = fragment_start_index + len;
8028 if index < fragment_end_index {
8029 return fragment_start_x;
8030 }
8031 fragment_start_x += size.width;
8032 fragment_start_index = fragment_end_index;
8033 }
8034 }
8035 }
8036
8037 fragment_start_x
8038 }
8039
8040 pub fn index_for_x(&self, x: Pixels) -> Option<usize> {
8041 let mut fragment_start_x = Pixels::ZERO;
8042 let mut fragment_start_index = 0;
8043
8044 for fragment in &self.fragments {
8045 match fragment {
8046 LineFragment::Text(shaped_line) => {
8047 let fragment_end_x = fragment_start_x + shaped_line.width;
8048 if x < fragment_end_x {
8049 return Some(
8050 fragment_start_index + shaped_line.index_for_x(x - fragment_start_x)?,
8051 );
8052 }
8053 fragment_start_x = fragment_end_x;
8054 fragment_start_index += shaped_line.len;
8055 }
8056 LineFragment::Element { len, size, .. } => {
8057 let fragment_end_x = fragment_start_x + size.width;
8058 if x < fragment_end_x {
8059 return Some(fragment_start_index);
8060 }
8061 fragment_start_index += len;
8062 fragment_start_x = fragment_end_x;
8063 }
8064 }
8065 }
8066
8067 None
8068 }
8069
8070 pub fn font_id_for_index(&self, index: usize) -> Option<FontId> {
8071 let mut fragment_start_index = 0;
8072
8073 for fragment in &self.fragments {
8074 match fragment {
8075 LineFragment::Text(shaped_line) => {
8076 let fragment_end_index = fragment_start_index + shaped_line.len;
8077 if index < fragment_end_index {
8078 return shaped_line.font_id_for_index(index - fragment_start_index);
8079 }
8080 fragment_start_index = fragment_end_index;
8081 }
8082 LineFragment::Element { len, .. } => {
8083 let fragment_end_index = fragment_start_index + len;
8084 if index < fragment_end_index {
8085 return None;
8086 }
8087 fragment_start_index = fragment_end_index;
8088 }
8089 }
8090 }
8091
8092 None
8093 }
8094}
8095
8096#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8097enum Invisible {
8098 /// A tab character
8099 ///
8100 /// A tab character is internally represented by spaces (configured by the user's tab width)
8101 /// aligned to the nearest column, so it's necessary to store the start and end offset for
8102 /// adjacency checks.
8103 Tab {
8104 line_start_offset: usize,
8105 line_end_offset: usize,
8106 },
8107 Whitespace {
8108 line_offset: usize,
8109 },
8110}
8111
8112impl EditorElement {
8113 /// Returns the rem size to use when rendering the [`EditorElement`].
8114 ///
8115 /// This allows UI elements to scale based on the `buffer_font_size`.
8116 fn rem_size(&self, cx: &mut App) -> Option<Pixels> {
8117 match self.editor.read(cx).mode {
8118 EditorMode::Full {
8119 scale_ui_elements_with_buffer_font_size: true,
8120 ..
8121 }
8122 | EditorMode::Minimap { .. } => {
8123 let buffer_font_size = self.style.text.font_size;
8124 match buffer_font_size {
8125 AbsoluteLength::Pixels(pixels) => {
8126 let rem_size_scale = {
8127 // Our default UI font size is 14px on a 16px base scale.
8128 // This means the default UI font size is 0.875rems.
8129 let default_font_size_scale = 14. / ui::BASE_REM_SIZE_IN_PX;
8130
8131 // We then determine the delta between a single rem and the default font
8132 // size scale.
8133 let default_font_size_delta = 1. - default_font_size_scale;
8134
8135 // Finally, we add this delta to 1rem to get the scale factor that
8136 // should be used to scale up the UI.
8137 1. + default_font_size_delta
8138 };
8139
8140 Some(pixels * rem_size_scale)
8141 }
8142 AbsoluteLength::Rems(rems) => {
8143 Some(rems.to_pixels(ui::BASE_REM_SIZE_IN_PX.into()))
8144 }
8145 }
8146 }
8147 // We currently use single-line and auto-height editors in UI contexts,
8148 // so we don't want to scale everything with the buffer font size, as it
8149 // ends up looking off.
8150 _ => None,
8151 }
8152 }
8153
8154 fn editor_with_selections(&self, cx: &App) -> Option<Entity<Editor>> {
8155 if let EditorMode::Minimap { parent } = self.editor.read(cx).mode() {
8156 parent.upgrade()
8157 } else {
8158 Some(self.editor.clone())
8159 }
8160 }
8161}
8162
8163impl Element for EditorElement {
8164 type RequestLayoutState = ();
8165 type PrepaintState = EditorLayout;
8166
8167 fn id(&self) -> Option<ElementId> {
8168 None
8169 }
8170
8171 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
8172 None
8173 }
8174
8175 fn request_layout(
8176 &mut self,
8177 _: Option<&GlobalElementId>,
8178 _inspector_id: Option<&gpui::InspectorElementId>,
8179 window: &mut Window,
8180 cx: &mut App,
8181 ) -> (gpui::LayoutId, ()) {
8182 let rem_size = self.rem_size(cx);
8183 window.with_rem_size(rem_size, |window| {
8184 self.editor.update(cx, |editor, cx| {
8185 editor.set_style(self.style.clone(), window, cx);
8186
8187 let layout_id = match editor.mode {
8188 EditorMode::SingleLine => {
8189 let rem_size = window.rem_size();
8190 let height = self.style.text.line_height_in_pixels(rem_size);
8191 let mut style = Style::default();
8192 style.size.height = height.into();
8193 style.size.width = relative(1.).into();
8194 window.request_layout(style, None, cx)
8195 }
8196 EditorMode::AutoHeight {
8197 min_lines,
8198 max_lines,
8199 } => {
8200 let editor_handle = cx.entity();
8201 let max_line_number_width =
8202 self.max_line_number_width(&editor.snapshot(window, cx), window);
8203 window.request_measured_layout(
8204 Style::default(),
8205 move |known_dimensions, available_space, window, cx| {
8206 editor_handle
8207 .update(cx, |editor, cx| {
8208 compute_auto_height_layout(
8209 editor,
8210 min_lines,
8211 max_lines,
8212 max_line_number_width,
8213 known_dimensions,
8214 available_space.width,
8215 window,
8216 cx,
8217 )
8218 })
8219 .unwrap_or_default()
8220 },
8221 )
8222 }
8223 EditorMode::Minimap { .. } => {
8224 let mut style = Style::default();
8225 style.size.width = relative(1.).into();
8226 style.size.height = relative(1.).into();
8227 window.request_layout(style, None, cx)
8228 }
8229 EditorMode::Full {
8230 sized_by_content, ..
8231 } => {
8232 let mut style = Style::default();
8233 style.size.width = relative(1.).into();
8234 if sized_by_content {
8235 let snapshot = editor.snapshot(window, cx);
8236 let line_height =
8237 self.style.text.line_height_in_pixels(window.rem_size());
8238 let scroll_height =
8239 (snapshot.max_point().row().next_row().0 as f32) * line_height;
8240 style.size.height = scroll_height.into();
8241 } else {
8242 style.size.height = relative(1.).into();
8243 }
8244 window.request_layout(style, None, cx)
8245 }
8246 };
8247
8248 (layout_id, ())
8249 })
8250 })
8251 }
8252
8253 fn prepaint(
8254 &mut self,
8255 _: Option<&GlobalElementId>,
8256 _inspector_id: Option<&gpui::InspectorElementId>,
8257 bounds: Bounds<Pixels>,
8258 _: &mut Self::RequestLayoutState,
8259 window: &mut Window,
8260 cx: &mut App,
8261 ) -> Self::PrepaintState {
8262 let text_style = TextStyleRefinement {
8263 font_size: Some(self.style.text.font_size),
8264 line_height: Some(self.style.text.line_height),
8265 ..Default::default()
8266 };
8267
8268 let is_minimap = self.editor.read(cx).mode.is_minimap();
8269
8270 if !is_minimap {
8271 let focus_handle = self.editor.focus_handle(cx);
8272 window.set_view_id(self.editor.entity_id());
8273 window.set_focus_handle(&focus_handle, cx);
8274 }
8275
8276 let rem_size = self.rem_size(cx);
8277 window.with_rem_size(rem_size, |window| {
8278 window.with_text_style(Some(text_style), |window| {
8279 window.with_content_mask(Some(ContentMask { bounds }), |window| {
8280 let (mut snapshot, is_read_only) = self.editor.update(cx, |editor, cx| {
8281 (editor.snapshot(window, cx), editor.read_only(cx))
8282 });
8283 let style = self.style.clone();
8284
8285 let rem_size = window.rem_size();
8286 let font_id = window.text_system().resolve_font(&style.text.font());
8287 let font_size = style.text.font_size.to_pixels(rem_size);
8288 let line_height = style.text.line_height_in_pixels(rem_size);
8289 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
8290 let em_advance = window.text_system().em_advance(font_id, font_size).unwrap();
8291 let glyph_grid_cell = size(em_advance, line_height);
8292
8293 let gutter_dimensions = snapshot
8294 .gutter_dimensions(
8295 font_id,
8296 font_size,
8297 self.max_line_number_width(&snapshot, window),
8298 cx,
8299 )
8300 .or_else(|| {
8301 self.editor.read(cx).offset_content.then(|| {
8302 GutterDimensions::default_with_margin(font_id, font_size, cx)
8303 })
8304 })
8305 .unwrap_or_default();
8306 let text_width = bounds.size.width - gutter_dimensions.width;
8307
8308 let settings = EditorSettings::get_global(cx);
8309 let scrollbars_shown = settings.scrollbar.show != ShowScrollbar::Never;
8310 let vertical_scrollbar_width = (scrollbars_shown
8311 && settings.scrollbar.axes.vertical
8312 && self.editor.read(cx).show_scrollbars.vertical)
8313 .then_some(style.scrollbar_width)
8314 .unwrap_or_default();
8315 let minimap_width = self
8316 .get_minimap_width(
8317 &settings.minimap,
8318 scrollbars_shown,
8319 text_width,
8320 em_width,
8321 font_size,
8322 rem_size,
8323 cx,
8324 )
8325 .unwrap_or_default();
8326
8327 let right_margin = minimap_width + vertical_scrollbar_width;
8328
8329 let editor_width =
8330 text_width - gutter_dimensions.margin - 2 * em_width - right_margin;
8331 let editor_margins = EditorMargins {
8332 gutter: gutter_dimensions,
8333 right: right_margin,
8334 };
8335
8336 snapshot = self.editor.update(cx, |editor, cx| {
8337 editor.last_bounds = Some(bounds);
8338 editor.gutter_dimensions = gutter_dimensions;
8339 editor.set_visible_line_count(bounds.size.height / line_height, window, cx);
8340 editor.set_visible_column_count(editor_width / em_advance);
8341
8342 if matches!(
8343 editor.mode,
8344 EditorMode::AutoHeight { .. } | EditorMode::Minimap { .. }
8345 ) {
8346 snapshot
8347 } else {
8348 let wrap_width_for = |column: u32| (column as f32 * em_advance).ceil();
8349 let wrap_width = match editor.soft_wrap_mode(cx) {
8350 SoftWrap::GitDiff => None,
8351 SoftWrap::None => Some(wrap_width_for(MAX_LINE_LEN as u32 / 2)),
8352 SoftWrap::EditorWidth => Some(editor_width),
8353 SoftWrap::Column(column) => Some(wrap_width_for(column)),
8354 SoftWrap::Bounded(column) => {
8355 Some(editor_width.min(wrap_width_for(column)))
8356 }
8357 };
8358
8359 if editor.set_wrap_width(wrap_width, cx) {
8360 editor.snapshot(window, cx)
8361 } else {
8362 snapshot
8363 }
8364 }
8365 });
8366
8367 let hitbox = window.insert_hitbox(bounds, HitboxBehavior::Normal);
8368 let gutter_hitbox = window.insert_hitbox(
8369 gutter_bounds(bounds, gutter_dimensions),
8370 HitboxBehavior::Normal,
8371 );
8372 let text_hitbox = window.insert_hitbox(
8373 Bounds {
8374 origin: gutter_hitbox.top_right(),
8375 size: size(text_width, bounds.size.height),
8376 },
8377 HitboxBehavior::Normal,
8378 );
8379
8380 // Offset the content_bounds from the text_bounds by the gutter margin (which
8381 // is roughly half a character wide) to make hit testing work more like how we want.
8382 let content_offset = point(editor_margins.gutter.margin, Pixels::ZERO);
8383 let content_origin = text_hitbox.origin + content_offset;
8384
8385 let height_in_lines = bounds.size.height / line_height;
8386 let max_row = snapshot.max_point().row().as_f32();
8387
8388 // The max scroll position for the top of the window
8389 let max_scroll_top = if matches!(
8390 snapshot.mode,
8391 EditorMode::SingleLine
8392 | EditorMode::AutoHeight { .. }
8393 | EditorMode::Full {
8394 sized_by_content: true,
8395 ..
8396 }
8397 ) {
8398 (max_row - height_in_lines + 1.).max(0.)
8399 } else {
8400 let settings = EditorSettings::get_global(cx);
8401 match settings.scroll_beyond_last_line {
8402 ScrollBeyondLastLine::OnePage => max_row,
8403 ScrollBeyondLastLine::Off => (max_row - height_in_lines + 1.).max(0.),
8404 ScrollBeyondLastLine::VerticalScrollMargin => {
8405 (max_row - height_in_lines + 1. + settings.vertical_scroll_margin)
8406 .max(0.)
8407 }
8408 }
8409 };
8410
8411 let (
8412 autoscroll_request,
8413 autoscroll_containing_element,
8414 needs_horizontal_autoscroll,
8415 ) = self.editor.update(cx, |editor, cx| {
8416 let autoscroll_request = editor.scroll_manager.take_autoscroll_request();
8417
8418 let autoscroll_containing_element =
8419 autoscroll_request.is_some() || editor.has_pending_selection();
8420
8421 let (needs_horizontal_autoscroll, was_scrolled) = editor
8422 .autoscroll_vertically(
8423 bounds,
8424 line_height,
8425 max_scroll_top,
8426 autoscroll_request,
8427 window,
8428 cx,
8429 );
8430 if was_scrolled.0 {
8431 snapshot = editor.snapshot(window, cx);
8432 }
8433 (
8434 autoscroll_request,
8435 autoscroll_containing_element,
8436 needs_horizontal_autoscroll,
8437 )
8438 });
8439
8440 let mut scroll_position = snapshot.scroll_position();
8441 // The scroll position is a fractional point, the whole number of which represents
8442 // the top of the window in terms of display rows.
8443 let start_row = DisplayRow(scroll_position.y as u32);
8444 let max_row = snapshot.max_point().row();
8445 let end_row = cmp::min(
8446 (scroll_position.y + height_in_lines).ceil() as u32,
8447 max_row.next_row().0,
8448 );
8449 let end_row = DisplayRow(end_row);
8450
8451 let row_infos = snapshot
8452 .row_infos(start_row)
8453 .take((start_row..end_row).len())
8454 .collect::<Vec<RowInfo>>();
8455 let is_row_soft_wrapped = |row: usize| {
8456 row_infos
8457 .get(row)
8458 .is_none_or(|info| info.buffer_row.is_none())
8459 };
8460
8461 let start_anchor = if start_row == Default::default() {
8462 Anchor::min()
8463 } else {
8464 snapshot.buffer_snapshot.anchor_before(
8465 DisplayPoint::new(start_row, 0).to_offset(&snapshot, Bias::Left),
8466 )
8467 };
8468 let end_anchor = if end_row > max_row {
8469 Anchor::max()
8470 } else {
8471 snapshot.buffer_snapshot.anchor_before(
8472 DisplayPoint::new(end_row, 0).to_offset(&snapshot, Bias::Right),
8473 )
8474 };
8475
8476 let mut highlighted_rows = self
8477 .editor
8478 .update(cx, |editor, cx| editor.highlighted_display_rows(window, cx));
8479
8480 let is_light = cx.theme().appearance().is_light();
8481
8482 for (ix, row_info) in row_infos.iter().enumerate() {
8483 let Some(diff_status) = row_info.diff_status else {
8484 continue;
8485 };
8486
8487 let background_color = match diff_status.kind {
8488 DiffHunkStatusKind::Added => cx.theme().colors().version_control_added,
8489 DiffHunkStatusKind::Deleted => {
8490 cx.theme().colors().version_control_deleted
8491 }
8492 DiffHunkStatusKind::Modified => {
8493 debug_panic!("modified diff status for row info");
8494 continue;
8495 }
8496 };
8497
8498 let hunk_opacity = if is_light { 0.16 } else { 0.12 };
8499
8500 let hollow_highlight = LineHighlight {
8501 background: (background_color.opacity(if is_light {
8502 0.08
8503 } else {
8504 0.06
8505 }))
8506 .into(),
8507 border: Some(if is_light {
8508 background_color.opacity(0.48)
8509 } else {
8510 background_color.opacity(0.36)
8511 }),
8512 include_gutter: true,
8513 type_id: None,
8514 };
8515
8516 let filled_highlight = LineHighlight {
8517 background: solid_background(background_color.opacity(hunk_opacity)),
8518 border: None,
8519 include_gutter: true,
8520 type_id: None,
8521 };
8522
8523 let background = if Self::diff_hunk_hollow(diff_status, cx) {
8524 hollow_highlight
8525 } else {
8526 filled_highlight
8527 };
8528
8529 highlighted_rows
8530 .entry(start_row + DisplayRow(ix as u32))
8531 .or_insert(background);
8532 }
8533
8534 let highlighted_ranges = self
8535 .editor_with_selections(cx)
8536 .map(|editor| {
8537 editor.read(cx).background_highlights_in_range(
8538 start_anchor..end_anchor,
8539 &snapshot.display_snapshot,
8540 cx.theme(),
8541 )
8542 })
8543 .unwrap_or_default();
8544 let highlighted_gutter_ranges =
8545 self.editor.read(cx).gutter_highlights_in_range(
8546 start_anchor..end_anchor,
8547 &snapshot.display_snapshot,
8548 cx,
8549 );
8550
8551 let document_colors = self
8552 .editor
8553 .read(cx)
8554 .colors
8555 .as_ref()
8556 .map(|colors| colors.editor_display_highlights(&snapshot));
8557 let redacted_ranges = self.editor.read(cx).redacted_ranges(
8558 start_anchor..end_anchor,
8559 &snapshot.display_snapshot,
8560 cx,
8561 );
8562
8563 let (local_selections, selected_buffer_ids): (
8564 Vec<Selection<Point>>,
8565 Vec<BufferId>,
8566 ) = self
8567 .editor_with_selections(cx)
8568 .map(|editor| {
8569 editor.update(cx, |editor, cx| {
8570 let all_selections = editor.selections.all::<Point>(cx);
8571 let selected_buffer_ids = if editor.is_singleton(cx) {
8572 Vec::new()
8573 } else {
8574 let mut selected_buffer_ids =
8575 Vec::with_capacity(all_selections.len());
8576
8577 for selection in all_selections {
8578 for buffer_id in snapshot
8579 .buffer_snapshot
8580 .buffer_ids_for_range(selection.range())
8581 {
8582 if selected_buffer_ids.last() != Some(&buffer_id) {
8583 selected_buffer_ids.push(buffer_id);
8584 }
8585 }
8586 }
8587
8588 selected_buffer_ids
8589 };
8590
8591 let mut selections = editor
8592 .selections
8593 .disjoint_in_range(start_anchor..end_anchor, cx);
8594 selections.extend(editor.selections.pending(cx));
8595
8596 (selections, selected_buffer_ids)
8597 })
8598 })
8599 .unwrap_or_default();
8600
8601 let (selections, mut active_rows, newest_selection_head) = self
8602 .layout_selections(
8603 start_anchor,
8604 end_anchor,
8605 &local_selections,
8606 &snapshot,
8607 start_row,
8608 end_row,
8609 window,
8610 cx,
8611 );
8612 let mut breakpoint_rows = self.editor.update(cx, |editor, cx| {
8613 editor.active_breakpoints(start_row..end_row, window, cx)
8614 });
8615 for (display_row, (_, bp, state)) in &breakpoint_rows {
8616 if bp.is_enabled() && state.is_none_or(|s| s.verified) {
8617 active_rows.entry(*display_row).or_default().breakpoint = true;
8618 }
8619 }
8620
8621 let line_numbers = self.layout_line_numbers(
8622 Some(&gutter_hitbox),
8623 gutter_dimensions,
8624 line_height,
8625 scroll_position,
8626 start_row..end_row,
8627 &row_infos,
8628 &active_rows,
8629 newest_selection_head,
8630 &snapshot,
8631 window,
8632 cx,
8633 );
8634
8635 // We add the gutter breakpoint indicator to breakpoint_rows after painting
8636 // line numbers so we don't paint a line number debug accent color if a user
8637 // has their mouse over that line when a breakpoint isn't there
8638 self.editor.update(cx, |editor, _| {
8639 if let Some(phantom_breakpoint) = &mut editor
8640 .gutter_breakpoint_indicator
8641 .0
8642 .filter(|phantom_breakpoint| phantom_breakpoint.is_active)
8643 {
8644 // Is there a non-phantom breakpoint on this line?
8645 phantom_breakpoint.collides_with_existing_breakpoint = true;
8646 breakpoint_rows
8647 .entry(phantom_breakpoint.display_row)
8648 .or_insert_with(|| {
8649 let position = snapshot.display_point_to_anchor(
8650 DisplayPoint::new(phantom_breakpoint.display_row, 0),
8651 Bias::Right,
8652 );
8653 let breakpoint = Breakpoint::new_standard();
8654 phantom_breakpoint.collides_with_existing_breakpoint = false;
8655 (position, breakpoint, None)
8656 });
8657 }
8658 });
8659
8660 let mut expand_toggles =
8661 window.with_element_namespace("expand_toggles", |window| {
8662 self.layout_expand_toggles(
8663 &gutter_hitbox,
8664 gutter_dimensions,
8665 em_width,
8666 line_height,
8667 scroll_position,
8668 &row_infos,
8669 window,
8670 cx,
8671 )
8672 });
8673
8674 let mut crease_toggles =
8675 window.with_element_namespace("crease_toggles", |window| {
8676 self.layout_crease_toggles(
8677 start_row..end_row,
8678 &row_infos,
8679 &active_rows,
8680 &snapshot,
8681 window,
8682 cx,
8683 )
8684 });
8685 let crease_trailers =
8686 window.with_element_namespace("crease_trailers", |window| {
8687 self.layout_crease_trailers(
8688 row_infos.iter().copied(),
8689 &snapshot,
8690 window,
8691 cx,
8692 )
8693 });
8694
8695 let display_hunks = self.layout_gutter_diff_hunks(
8696 line_height,
8697 &gutter_hitbox,
8698 start_row..end_row,
8699 &snapshot,
8700 window,
8701 cx,
8702 );
8703
8704 let bg_segments_per_row = Self::bg_segments_per_row(
8705 start_row..end_row,
8706 &selections,
8707 &highlighted_ranges,
8708 self.style.background,
8709 );
8710
8711 let mut line_layouts = Self::layout_lines(
8712 start_row..end_row,
8713 &snapshot,
8714 &self.style,
8715 editor_width,
8716 is_row_soft_wrapped,
8717 &bg_segments_per_row,
8718 window,
8719 cx,
8720 );
8721 let new_renderer_widths = (!is_minimap).then(|| {
8722 line_layouts
8723 .iter()
8724 .flat_map(|layout| &layout.fragments)
8725 .filter_map(|fragment| {
8726 if let LineFragment::Element { id, size, .. } = fragment {
8727 Some((*id, size.width))
8728 } else {
8729 None
8730 }
8731 })
8732 });
8733 if new_renderer_widths.is_some_and(|new_renderer_widths| {
8734 self.editor.update(cx, |editor, cx| {
8735 editor.update_renderer_widths(new_renderer_widths, cx)
8736 })
8737 }) {
8738 // If the fold widths have changed, we need to prepaint
8739 // the element again to account for any changes in
8740 // wrapping.
8741 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8742 }
8743
8744 let longest_line_blame_width = self
8745 .editor
8746 .update(cx, |editor, cx| {
8747 if !editor.show_git_blame_inline {
8748 return None;
8749 }
8750 let blame = editor.blame.as_ref()?;
8751 let blame_entry = blame
8752 .update(cx, |blame, cx| {
8753 let row_infos =
8754 snapshot.row_infos(snapshot.longest_row()).next()?;
8755 blame.blame_for_rows(&[row_infos], cx).next()
8756 })
8757 .flatten()?;
8758 let mut element = render_inline_blame_entry(blame_entry, &style, cx)?;
8759 let inline_blame_padding = ProjectSettings::get_global(cx)
8760 .git
8761 .inline_blame
8762 .unwrap_or_default()
8763 .padding
8764 as f32
8765 * em_advance;
8766 Some(
8767 element
8768 .layout_as_root(AvailableSpace::min_size(), window, cx)
8769 .width
8770 + inline_blame_padding,
8771 )
8772 })
8773 .unwrap_or(Pixels::ZERO);
8774
8775 let longest_line_width = layout_line(
8776 snapshot.longest_row(),
8777 &snapshot,
8778 &style,
8779 editor_width,
8780 is_row_soft_wrapped,
8781 window,
8782 cx,
8783 )
8784 .width;
8785
8786 let scrollbar_layout_information = ScrollbarLayoutInformation::new(
8787 text_hitbox.bounds,
8788 glyph_grid_cell,
8789 size(longest_line_width, max_row.as_f32() * line_height),
8790 longest_line_blame_width,
8791 EditorSettings::get_global(cx),
8792 );
8793
8794 let mut scroll_width = scrollbar_layout_information.scroll_range.width;
8795
8796 let sticky_header_excerpt = if snapshot.buffer_snapshot.show_headers() {
8797 snapshot.sticky_header_excerpt(scroll_position.y)
8798 } else {
8799 None
8800 };
8801 let sticky_header_excerpt_id =
8802 sticky_header_excerpt.as_ref().map(|top| top.excerpt.id);
8803
8804 let blocks = (!is_minimap)
8805 .then(|| {
8806 window.with_element_namespace("blocks", |window| {
8807 self.render_blocks(
8808 start_row..end_row,
8809 &snapshot,
8810 &hitbox,
8811 &text_hitbox,
8812 editor_width,
8813 &mut scroll_width,
8814 &editor_margins,
8815 em_width,
8816 gutter_dimensions.full_width(),
8817 line_height,
8818 &mut line_layouts,
8819 &local_selections,
8820 &selected_buffer_ids,
8821 is_row_soft_wrapped,
8822 sticky_header_excerpt_id,
8823 window,
8824 cx,
8825 )
8826 })
8827 })
8828 .unwrap_or_else(|| Ok((Vec::default(), HashMap::default())));
8829 let (mut blocks, row_block_types) = match blocks {
8830 Ok(blocks) => blocks,
8831 Err(resized_blocks) => {
8832 self.editor.update(cx, |editor, cx| {
8833 editor.resize_blocks(
8834 resized_blocks,
8835 autoscroll_request.map(|(autoscroll, _)| autoscroll),
8836 cx,
8837 )
8838 });
8839 return self.prepaint(None, _inspector_id, bounds, &mut (), window, cx);
8840 }
8841 };
8842
8843 let sticky_buffer_header = sticky_header_excerpt.map(|sticky_header_excerpt| {
8844 window.with_element_namespace("blocks", |window| {
8845 self.layout_sticky_buffer_header(
8846 sticky_header_excerpt,
8847 scroll_position.y,
8848 line_height,
8849 right_margin,
8850 &snapshot,
8851 &hitbox,
8852 &selected_buffer_ids,
8853 &blocks,
8854 window,
8855 cx,
8856 )
8857 })
8858 });
8859
8860 let start_buffer_row =
8861 MultiBufferRow(start_anchor.to_point(&snapshot.buffer_snapshot).row);
8862 let end_buffer_row =
8863 MultiBufferRow(end_anchor.to_point(&snapshot.buffer_snapshot).row);
8864
8865 let scroll_max = point(
8866 ((scroll_width - editor_width) / em_advance).max(0.0),
8867 max_scroll_top,
8868 );
8869
8870 self.editor.update(cx, |editor, cx| {
8871 if editor.scroll_manager.clamp_scroll_left(scroll_max.x) {
8872 scroll_position.x = scroll_position.x.min(scroll_max.x);
8873 }
8874
8875 if needs_horizontal_autoscroll.0
8876 && let Some(new_scroll_position) = editor.autoscroll_horizontally(
8877 start_row,
8878 editor_width,
8879 scroll_width,
8880 em_advance,
8881 &line_layouts,
8882 autoscroll_request,
8883 window,
8884 cx,
8885 )
8886 {
8887 scroll_position = new_scroll_position;
8888 }
8889 });
8890
8891 let scroll_pixel_position = point(
8892 scroll_position.x * em_advance,
8893 scroll_position.y * line_height,
8894 );
8895 let indent_guides = self.layout_indent_guides(
8896 content_origin,
8897 text_hitbox.origin,
8898 start_buffer_row..end_buffer_row,
8899 scroll_pixel_position,
8900 line_height,
8901 &snapshot,
8902 window,
8903 cx,
8904 );
8905
8906 let crease_trailers =
8907 window.with_element_namespace("crease_trailers", |window| {
8908 self.prepaint_crease_trailers(
8909 crease_trailers,
8910 &line_layouts,
8911 line_height,
8912 content_origin,
8913 scroll_pixel_position,
8914 em_width,
8915 window,
8916 cx,
8917 )
8918 });
8919
8920 let (edit_prediction_popover, edit_prediction_popover_origin) = self
8921 .editor
8922 .update(cx, |editor, cx| {
8923 editor.render_edit_prediction_popover(
8924 &text_hitbox.bounds,
8925 content_origin,
8926 right_margin,
8927 &snapshot,
8928 start_row..end_row,
8929 scroll_position.y,
8930 scroll_position.y + height_in_lines,
8931 &line_layouts,
8932 line_height,
8933 scroll_pixel_position,
8934 newest_selection_head,
8935 editor_width,
8936 &style,
8937 window,
8938 cx,
8939 )
8940 })
8941 .unzip();
8942
8943 let mut inline_diagnostics = self.layout_inline_diagnostics(
8944 &line_layouts,
8945 &crease_trailers,
8946 &row_block_types,
8947 content_origin,
8948 scroll_pixel_position,
8949 edit_prediction_popover_origin,
8950 start_row,
8951 end_row,
8952 line_height,
8953 em_width,
8954 &style,
8955 window,
8956 cx,
8957 );
8958
8959 let mut inline_blame_layout = None;
8960 let mut inline_code_actions = None;
8961 if let Some(newest_selection_head) = newest_selection_head {
8962 let display_row = newest_selection_head.row();
8963 if (start_row..end_row).contains(&display_row)
8964 && !row_block_types.contains_key(&display_row)
8965 {
8966 inline_code_actions = self.layout_inline_code_actions(
8967 newest_selection_head,
8968 content_origin,
8969 scroll_pixel_position,
8970 line_height,
8971 &snapshot,
8972 window,
8973 cx,
8974 );
8975
8976 let line_ix = display_row.minus(start_row) as usize;
8977 if let (Some(row_info), Some(line_layout), Some(crease_trailer)) = (
8978 row_infos.get(line_ix),
8979 line_layouts.get(line_ix),
8980 crease_trailers.get(line_ix),
8981 ) {
8982 let crease_trailer_layout = crease_trailer.as_ref();
8983 if let Some(layout) = self.layout_inline_blame(
8984 display_row,
8985 row_info,
8986 line_layout,
8987 crease_trailer_layout,
8988 em_width,
8989 content_origin,
8990 scroll_pixel_position,
8991 line_height,
8992 &text_hitbox,
8993 window,
8994 cx,
8995 ) {
8996 inline_blame_layout = Some(layout);
8997 // Blame overrides inline diagnostics
8998 inline_diagnostics.remove(&display_row);
8999 }
9000 } else {
9001 log::error!(
9002 "bug: line_ix {} is out of bounds - row_infos.len(): {}, \
9003 line_layouts.len(): {}, \
9004 crease_trailers.len(): {}",
9005 line_ix,
9006 row_infos.len(),
9007 line_layouts.len(),
9008 crease_trailers.len(),
9009 );
9010 }
9011 }
9012 }
9013
9014 let blamed_display_rows = self.layout_blame_entries(
9015 &row_infos,
9016 em_width,
9017 scroll_position,
9018 line_height,
9019 &gutter_hitbox,
9020 gutter_dimensions.git_blame_entries_width,
9021 window,
9022 cx,
9023 );
9024
9025 let line_elements = self.prepaint_lines(
9026 start_row,
9027 &mut line_layouts,
9028 line_height,
9029 scroll_pixel_position,
9030 content_origin,
9031 window,
9032 cx,
9033 );
9034
9035 window.with_element_namespace("blocks", |window| {
9036 self.layout_blocks(
9037 &mut blocks,
9038 &hitbox,
9039 line_height,
9040 scroll_pixel_position,
9041 window,
9042 cx,
9043 );
9044 });
9045
9046 let cursors = self.collect_cursors(&snapshot, cx);
9047 let visible_row_range = start_row..end_row;
9048 let non_visible_cursors = cursors
9049 .iter()
9050 .any(|c| !visible_row_range.contains(&c.0.row()));
9051
9052 let visible_cursors = self.layout_visible_cursors(
9053 &snapshot,
9054 &selections,
9055 &row_block_types,
9056 start_row..end_row,
9057 &line_layouts,
9058 &text_hitbox,
9059 content_origin,
9060 scroll_position,
9061 scroll_pixel_position,
9062 line_height,
9063 em_width,
9064 em_advance,
9065 autoscroll_containing_element,
9066 window,
9067 cx,
9068 );
9069
9070 let scrollbars_layout = self.layout_scrollbars(
9071 &snapshot,
9072 &scrollbar_layout_information,
9073 content_offset,
9074 scroll_position,
9075 non_visible_cursors,
9076 right_margin,
9077 editor_width,
9078 window,
9079 cx,
9080 );
9081
9082 let gutter_settings = EditorSettings::get_global(cx).gutter;
9083
9084 let context_menu_layout =
9085 if let Some(newest_selection_head) = newest_selection_head {
9086 let newest_selection_point =
9087 newest_selection_head.to_point(&snapshot.display_snapshot);
9088 if (start_row..end_row).contains(&newest_selection_head.row()) {
9089 self.layout_cursor_popovers(
9090 line_height,
9091 &text_hitbox,
9092 content_origin,
9093 right_margin,
9094 start_row,
9095 scroll_pixel_position,
9096 &line_layouts,
9097 newest_selection_head,
9098 newest_selection_point,
9099 &style,
9100 window,
9101 cx,
9102 )
9103 } else {
9104 None
9105 }
9106 } else {
9107 None
9108 };
9109
9110 self.layout_gutter_menu(
9111 line_height,
9112 &text_hitbox,
9113 content_origin,
9114 right_margin,
9115 scroll_pixel_position,
9116 gutter_dimensions.width - gutter_dimensions.left_padding,
9117 window,
9118 cx,
9119 );
9120
9121 let test_indicators = if gutter_settings.runnables {
9122 self.layout_run_indicators(
9123 line_height,
9124 start_row..end_row,
9125 &row_infos,
9126 scroll_pixel_position,
9127 &gutter_dimensions,
9128 &gutter_hitbox,
9129 &display_hunks,
9130 &snapshot,
9131 &mut breakpoint_rows,
9132 window,
9133 cx,
9134 )
9135 } else {
9136 Vec::new()
9137 };
9138
9139 let show_breakpoints = snapshot
9140 .show_breakpoints
9141 .unwrap_or(gutter_settings.breakpoints);
9142 let breakpoints = if show_breakpoints {
9143 self.layout_breakpoints(
9144 line_height,
9145 start_row..end_row,
9146 scroll_pixel_position,
9147 &gutter_dimensions,
9148 &gutter_hitbox,
9149 &display_hunks,
9150 &snapshot,
9151 breakpoint_rows,
9152 &row_infos,
9153 window,
9154 cx,
9155 )
9156 } else {
9157 Vec::new()
9158 };
9159
9160 self.layout_signature_help(
9161 &hitbox,
9162 content_origin,
9163 scroll_pixel_position,
9164 newest_selection_head,
9165 start_row,
9166 &line_layouts,
9167 line_height,
9168 em_width,
9169 context_menu_layout,
9170 window,
9171 cx,
9172 );
9173
9174 if !cx.has_active_drag() {
9175 self.layout_hover_popovers(
9176 &snapshot,
9177 &hitbox,
9178 start_row..end_row,
9179 content_origin,
9180 scroll_pixel_position,
9181 &line_layouts,
9182 line_height,
9183 em_width,
9184 context_menu_layout,
9185 window,
9186 cx,
9187 );
9188 }
9189
9190 let mouse_context_menu = self.layout_mouse_context_menu(
9191 &snapshot,
9192 start_row..end_row,
9193 content_origin,
9194 window,
9195 cx,
9196 );
9197
9198 window.with_element_namespace("crease_toggles", |window| {
9199 self.prepaint_crease_toggles(
9200 &mut crease_toggles,
9201 line_height,
9202 &gutter_dimensions,
9203 gutter_settings,
9204 scroll_pixel_position,
9205 &gutter_hitbox,
9206 window,
9207 cx,
9208 )
9209 });
9210
9211 window.with_element_namespace("expand_toggles", |window| {
9212 self.prepaint_expand_toggles(&mut expand_toggles, window, cx)
9213 });
9214
9215 let wrap_guides = self.layout_wrap_guides(
9216 em_advance,
9217 scroll_position,
9218 content_origin,
9219 scrollbars_layout.as_ref(),
9220 vertical_scrollbar_width,
9221 &hitbox,
9222 window,
9223 cx,
9224 );
9225
9226 let minimap = window.with_element_namespace("minimap", |window| {
9227 self.layout_minimap(
9228 &snapshot,
9229 minimap_width,
9230 scroll_position,
9231 &scrollbar_layout_information,
9232 scrollbars_layout.as_ref(),
9233 window,
9234 cx,
9235 )
9236 });
9237
9238 let invisible_symbol_font_size = font_size / 2.;
9239 let tab_invisible = window.text_system().shape_line(
9240 "β".into(),
9241 invisible_symbol_font_size,
9242 &[TextRun {
9243 len: "β".len(),
9244 font: self.style.text.font(),
9245 color: cx.theme().colors().editor_invisible,
9246 background_color: None,
9247 underline: None,
9248 strikethrough: None,
9249 }],
9250 None,
9251 );
9252 let space_invisible = window.text_system().shape_line(
9253 "β’".into(),
9254 invisible_symbol_font_size,
9255 &[TextRun {
9256 len: "β’".len(),
9257 font: self.style.text.font(),
9258 color: cx.theme().colors().editor_invisible,
9259 background_color: None,
9260 underline: None,
9261 strikethrough: None,
9262 }],
9263 None,
9264 );
9265
9266 let mode = snapshot.mode.clone();
9267
9268 let (diff_hunk_controls, diff_hunk_control_bounds) = if is_read_only {
9269 (vec![], vec![])
9270 } else {
9271 self.layout_diff_hunk_controls(
9272 start_row..end_row,
9273 &row_infos,
9274 &text_hitbox,
9275 newest_selection_head,
9276 line_height,
9277 right_margin,
9278 scroll_pixel_position,
9279 &display_hunks,
9280 &highlighted_rows,
9281 self.editor.clone(),
9282 window,
9283 cx,
9284 )
9285 };
9286
9287 let position_map = Rc::new(PositionMap {
9288 size: bounds.size,
9289 visible_row_range,
9290 scroll_pixel_position,
9291 scroll_max,
9292 line_layouts,
9293 line_height,
9294 em_width,
9295 em_advance,
9296 snapshot,
9297 gutter_hitbox: gutter_hitbox.clone(),
9298 text_hitbox: text_hitbox.clone(),
9299 inline_blame_bounds: inline_blame_layout
9300 .as_ref()
9301 .map(|layout| (layout.bounds, layout.entry.clone())),
9302 display_hunks: display_hunks.clone(),
9303 diff_hunk_control_bounds,
9304 });
9305
9306 self.editor.update(cx, |editor, _| {
9307 editor.last_position_map = Some(position_map.clone())
9308 });
9309
9310 EditorLayout {
9311 mode,
9312 position_map,
9313 visible_display_row_range: start_row..end_row,
9314 wrap_guides,
9315 indent_guides,
9316 hitbox,
9317 gutter_hitbox,
9318 display_hunks,
9319 content_origin,
9320 scrollbars_layout,
9321 minimap,
9322 active_rows,
9323 highlighted_rows,
9324 highlighted_ranges,
9325 highlighted_gutter_ranges,
9326 redacted_ranges,
9327 document_colors,
9328 line_elements,
9329 line_numbers,
9330 blamed_display_rows,
9331 inline_diagnostics,
9332 inline_blame_layout,
9333 inline_code_actions,
9334 blocks,
9335 cursors,
9336 visible_cursors,
9337 selections,
9338 edit_prediction_popover,
9339 diff_hunk_controls,
9340 mouse_context_menu,
9341 test_indicators,
9342 breakpoints,
9343 crease_toggles,
9344 crease_trailers,
9345 tab_invisible,
9346 space_invisible,
9347 sticky_buffer_header,
9348 expand_toggles,
9349 }
9350 })
9351 })
9352 })
9353 }
9354
9355 fn paint(
9356 &mut self,
9357 _: Option<&GlobalElementId>,
9358 _inspector_id: Option<&gpui::InspectorElementId>,
9359 bounds: Bounds<gpui::Pixels>,
9360 _: &mut Self::RequestLayoutState,
9361 layout: &mut Self::PrepaintState,
9362 window: &mut Window,
9363 cx: &mut App,
9364 ) {
9365 if !layout.mode.is_minimap() {
9366 let focus_handle = self.editor.focus_handle(cx);
9367 let key_context = self
9368 .editor
9369 .update(cx, |editor, cx| editor.key_context(window, cx));
9370
9371 window.set_key_context(key_context);
9372 window.handle_input(
9373 &focus_handle,
9374 ElementInputHandler::new(bounds, self.editor.clone()),
9375 cx,
9376 );
9377 self.register_actions(window, cx);
9378 self.register_key_listeners(window, cx, layout);
9379 }
9380
9381 let text_style = TextStyleRefinement {
9382 font_size: Some(self.style.text.font_size),
9383 line_height: Some(self.style.text.line_height),
9384 ..Default::default()
9385 };
9386 let rem_size = self.rem_size(cx);
9387 window.with_rem_size(rem_size, |window| {
9388 window.with_text_style(Some(text_style), |window| {
9389 window.with_content_mask(Some(ContentMask { bounds }), |window| {
9390 self.paint_mouse_listeners(layout, window, cx);
9391 self.paint_background(layout, window, cx);
9392 self.paint_indent_guides(layout, window, cx);
9393
9394 if layout.gutter_hitbox.size.width > Pixels::ZERO {
9395 self.paint_blamed_display_rows(layout, window, cx);
9396 self.paint_line_numbers(layout, window, cx);
9397 }
9398
9399 self.paint_text(layout, window, cx);
9400
9401 if layout.gutter_hitbox.size.width > Pixels::ZERO {
9402 self.paint_gutter_highlights(layout, window, cx);
9403 self.paint_gutter_indicators(layout, window, cx);
9404 }
9405
9406 if !layout.blocks.is_empty() {
9407 window.with_element_namespace("blocks", |window| {
9408 self.paint_blocks(layout, window, cx);
9409 });
9410 }
9411
9412 window.with_element_namespace("blocks", |window| {
9413 if let Some(mut sticky_header) = layout.sticky_buffer_header.take() {
9414 sticky_header.paint(window, cx)
9415 }
9416 });
9417
9418 self.paint_minimap(layout, window, cx);
9419 self.paint_scrollbars(layout, window, cx);
9420 self.paint_edit_prediction_popover(layout, window, cx);
9421 self.paint_mouse_context_menu(layout, window, cx);
9422 });
9423 })
9424 })
9425 }
9426}
9427
9428pub(super) fn gutter_bounds(
9429 editor_bounds: Bounds<Pixels>,
9430 gutter_dimensions: GutterDimensions,
9431) -> Bounds<Pixels> {
9432 Bounds {
9433 origin: editor_bounds.origin,
9434 size: size(gutter_dimensions.width, editor_bounds.size.height),
9435 }
9436}
9437
9438#[derive(Clone, Copy)]
9439struct ContextMenuLayout {
9440 y_flipped: bool,
9441 bounds: Bounds<Pixels>,
9442}
9443
9444/// Holds information required for layouting the editor scrollbars.
9445struct ScrollbarLayoutInformation {
9446 /// The bounds of the editor area (excluding the content offset).
9447 editor_bounds: Bounds<Pixels>,
9448 /// The available range to scroll within the document.
9449 scroll_range: Size<Pixels>,
9450 /// The space available for one glyph in the editor.
9451 glyph_grid_cell: Size<Pixels>,
9452}
9453
9454impl ScrollbarLayoutInformation {
9455 pub fn new(
9456 editor_bounds: Bounds<Pixels>,
9457 glyph_grid_cell: Size<Pixels>,
9458 document_size: Size<Pixels>,
9459 longest_line_blame_width: Pixels,
9460 settings: &EditorSettings,
9461 ) -> Self {
9462 let vertical_overscroll = match settings.scroll_beyond_last_line {
9463 ScrollBeyondLastLine::OnePage => editor_bounds.size.height,
9464 ScrollBeyondLastLine::Off => glyph_grid_cell.height,
9465 ScrollBeyondLastLine::VerticalScrollMargin => {
9466 (1.0 + settings.vertical_scroll_margin) * glyph_grid_cell.height
9467 }
9468 };
9469
9470 let overscroll = size(longest_line_blame_width, vertical_overscroll);
9471
9472 ScrollbarLayoutInformation {
9473 editor_bounds,
9474 scroll_range: document_size + overscroll,
9475 glyph_grid_cell,
9476 }
9477 }
9478}
9479
9480impl IntoElement for EditorElement {
9481 type Element = Self;
9482
9483 fn into_element(self) -> Self::Element {
9484 self
9485 }
9486}
9487
9488pub struct EditorLayout {
9489 position_map: Rc<PositionMap>,
9490 hitbox: Hitbox,
9491 gutter_hitbox: Hitbox,
9492 content_origin: gpui::Point<Pixels>,
9493 scrollbars_layout: Option<EditorScrollbars>,
9494 minimap: Option<MinimapLayout>,
9495 mode: EditorMode,
9496 wrap_guides: SmallVec<[(Pixels, bool); 2]>,
9497 indent_guides: Option<Vec<IndentGuideLayout>>,
9498 visible_display_row_range: Range<DisplayRow>,
9499 active_rows: BTreeMap<DisplayRow, LineHighlightSpec>,
9500 highlighted_rows: BTreeMap<DisplayRow, LineHighlight>,
9501 line_elements: SmallVec<[AnyElement; 1]>,
9502 line_numbers: Arc<HashMap<MultiBufferRow, LineNumberLayout>>,
9503 display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
9504 blamed_display_rows: Option<Vec<AnyElement>>,
9505 inline_diagnostics: HashMap<DisplayRow, AnyElement>,
9506 inline_blame_layout: Option<InlineBlameLayout>,
9507 inline_code_actions: Option<AnyElement>,
9508 blocks: Vec<BlockLayout>,
9509 highlighted_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
9510 highlighted_gutter_ranges: Vec<(Range<DisplayPoint>, Hsla)>,
9511 redacted_ranges: Vec<Range<DisplayPoint>>,
9512 cursors: Vec<(DisplayPoint, Hsla)>,
9513 visible_cursors: Vec<CursorLayout>,
9514 selections: Vec<(PlayerColor, Vec<SelectionLayout>)>,
9515 test_indicators: Vec<AnyElement>,
9516 breakpoints: Vec<AnyElement>,
9517 crease_toggles: Vec<Option<AnyElement>>,
9518 expand_toggles: Vec<Option<(AnyElement, gpui::Point<Pixels>)>>,
9519 diff_hunk_controls: Vec<AnyElement>,
9520 crease_trailers: Vec<Option<CreaseTrailerLayout>>,
9521 edit_prediction_popover: Option<AnyElement>,
9522 mouse_context_menu: Option<AnyElement>,
9523 tab_invisible: ShapedLine,
9524 space_invisible: ShapedLine,
9525 sticky_buffer_header: Option<AnyElement>,
9526 document_colors: Option<(DocumentColorsRenderMode, Vec<(Range<DisplayPoint>, Hsla)>)>,
9527}
9528
9529impl EditorLayout {
9530 fn line_end_overshoot(&self) -> Pixels {
9531 0.15 * self.position_map.line_height
9532 }
9533}
9534
9535struct LineNumberLayout {
9536 shaped_line: ShapedLine,
9537 hitbox: Option<Hitbox>,
9538}
9539
9540struct ColoredRange<T> {
9541 start: T,
9542 end: T,
9543 color: Hsla,
9544}
9545
9546impl Along for ScrollbarAxes {
9547 type Unit = bool;
9548
9549 fn along(&self, axis: ScrollbarAxis) -> Self::Unit {
9550 match axis {
9551 ScrollbarAxis::Horizontal => self.horizontal,
9552 ScrollbarAxis::Vertical => self.vertical,
9553 }
9554 }
9555
9556 fn apply_along(&self, axis: ScrollbarAxis, f: impl FnOnce(Self::Unit) -> Self::Unit) -> Self {
9557 match axis {
9558 ScrollbarAxis::Horizontal => ScrollbarAxes {
9559 horizontal: f(self.horizontal),
9560 vertical: self.vertical,
9561 },
9562 ScrollbarAxis::Vertical => ScrollbarAxes {
9563 horizontal: self.horizontal,
9564 vertical: f(self.vertical),
9565 },
9566 }
9567 }
9568}
9569
9570#[derive(Clone)]
9571struct EditorScrollbars {
9572 pub vertical: Option<ScrollbarLayout>,
9573 pub horizontal: Option<ScrollbarLayout>,
9574 pub visible: bool,
9575}
9576
9577impl EditorScrollbars {
9578 pub fn from_scrollbar_axes(
9579 show_scrollbar: ScrollbarAxes,
9580 layout_information: &ScrollbarLayoutInformation,
9581 content_offset: gpui::Point<Pixels>,
9582 scroll_position: gpui::Point<f32>,
9583 scrollbar_width: Pixels,
9584 right_margin: Pixels,
9585 editor_width: Pixels,
9586 show_scrollbars: bool,
9587 scrollbar_state: Option<&ActiveScrollbarState>,
9588 window: &mut Window,
9589 ) -> Self {
9590 let ScrollbarLayoutInformation {
9591 editor_bounds,
9592 scroll_range,
9593 glyph_grid_cell,
9594 } = layout_information;
9595
9596 let viewport_size = size(editor_width, editor_bounds.size.height);
9597
9598 let scrollbar_bounds_for = |axis: ScrollbarAxis| match axis {
9599 ScrollbarAxis::Horizontal => Bounds::from_corner_and_size(
9600 Corner::BottomLeft,
9601 editor_bounds.bottom_left(),
9602 size(
9603 // The horizontal viewport size differs from the space available for the
9604 // horizontal scrollbar, so we have to manually stich it together here.
9605 editor_bounds.size.width - right_margin,
9606 scrollbar_width,
9607 ),
9608 ),
9609 ScrollbarAxis::Vertical => Bounds::from_corner_and_size(
9610 Corner::TopRight,
9611 editor_bounds.top_right(),
9612 size(scrollbar_width, viewport_size.height),
9613 ),
9614 };
9615
9616 let mut create_scrollbar_layout = |axis| {
9617 let viewport_size = viewport_size.along(axis);
9618 let scroll_range = scroll_range.along(axis);
9619
9620 // We always want a vertical scrollbar track for scrollbar diagnostic visibility.
9621 (show_scrollbar.along(axis)
9622 && (axis == ScrollbarAxis::Vertical || scroll_range > viewport_size))
9623 .then(|| {
9624 ScrollbarLayout::new(
9625 window.insert_hitbox(scrollbar_bounds_for(axis), HitboxBehavior::Normal),
9626 viewport_size,
9627 scroll_range,
9628 glyph_grid_cell.along(axis),
9629 content_offset.along(axis),
9630 scroll_position.along(axis),
9631 show_scrollbars,
9632 axis,
9633 )
9634 .with_thumb_state(
9635 scrollbar_state.and_then(|state| state.thumb_state_for_axis(axis)),
9636 )
9637 })
9638 };
9639
9640 Self {
9641 vertical: create_scrollbar_layout(ScrollbarAxis::Vertical),
9642 horizontal: create_scrollbar_layout(ScrollbarAxis::Horizontal),
9643 visible: show_scrollbars,
9644 }
9645 }
9646
9647 pub fn iter_scrollbars(&self) -> impl Iterator<Item = (&ScrollbarLayout, ScrollbarAxis)> + '_ {
9648 [
9649 (&self.vertical, ScrollbarAxis::Vertical),
9650 (&self.horizontal, ScrollbarAxis::Horizontal),
9651 ]
9652 .into_iter()
9653 .filter_map(|(scrollbar, axis)| scrollbar.as_ref().map(|s| (s, axis)))
9654 }
9655
9656 /// Returns the currently hovered scrollbar axis, if any.
9657 pub fn get_hovered_axis(&self, window: &Window) -> Option<(&ScrollbarLayout, ScrollbarAxis)> {
9658 self.iter_scrollbars()
9659 .find(|s| s.0.hitbox.is_hovered(window))
9660 }
9661}
9662
9663#[derive(Clone)]
9664struct ScrollbarLayout {
9665 hitbox: Hitbox,
9666 visible_range: Range<f32>,
9667 text_unit_size: Pixels,
9668 thumb_bounds: Option<Bounds<Pixels>>,
9669 thumb_state: ScrollbarThumbState,
9670}
9671
9672impl ScrollbarLayout {
9673 const BORDER_WIDTH: Pixels = px(1.0);
9674 const LINE_MARKER_HEIGHT: Pixels = px(2.0);
9675 const MIN_MARKER_HEIGHT: Pixels = px(5.0);
9676 const MIN_THUMB_SIZE: Pixels = px(25.0);
9677
9678 fn new(
9679 scrollbar_track_hitbox: Hitbox,
9680 viewport_size: Pixels,
9681 scroll_range: Pixels,
9682 glyph_space: Pixels,
9683 content_offset: Pixels,
9684 scroll_position: f32,
9685 show_thumb: bool,
9686 axis: ScrollbarAxis,
9687 ) -> Self {
9688 let track_bounds = scrollbar_track_hitbox.bounds;
9689 // The length of the track available to the scrollbar thumb. We deliberately
9690 // exclude the content size here so that the thumb aligns with the content.
9691 let track_length = track_bounds.size.along(axis) - content_offset;
9692
9693 Self::new_with_hitbox_and_track_length(
9694 scrollbar_track_hitbox,
9695 track_length,
9696 viewport_size,
9697 scroll_range,
9698 glyph_space,
9699 content_offset,
9700 scroll_position,
9701 show_thumb,
9702 axis,
9703 )
9704 }
9705
9706 fn for_minimap(
9707 minimap_track_hitbox: Hitbox,
9708 visible_lines: f32,
9709 total_editor_lines: f32,
9710 minimap_line_height: Pixels,
9711 scroll_position: f32,
9712 minimap_scroll_top: f32,
9713 show_thumb: bool,
9714 ) -> Self {
9715 // The scrollbar thumb size is calculated as
9716 // (visible_content/total_content) Γ scrollbar_track_length.
9717 //
9718 // For the minimap's thumb layout, we leverage this by setting the
9719 // scrollbar track length to the entire document size (using minimap line
9720 // height). This creates a thumb that exactly represents the editor
9721 // viewport scaled to minimap proportions.
9722 //
9723 // We adjust the thumb position relative to `minimap_scroll_top` to
9724 // accommodate for the deliberately oversized track.
9725 //
9726 // This approach ensures that the minimap thumb accurately reflects the
9727 // editor's current scroll position whilst nicely synchronizing the minimap
9728 // thumb and scrollbar thumb.
9729 let scroll_range = total_editor_lines * minimap_line_height;
9730 let viewport_size = visible_lines * minimap_line_height;
9731
9732 let track_top_offset = -minimap_scroll_top * minimap_line_height;
9733
9734 Self::new_with_hitbox_and_track_length(
9735 minimap_track_hitbox,
9736 scroll_range,
9737 viewport_size,
9738 scroll_range,
9739 minimap_line_height,
9740 track_top_offset,
9741 scroll_position,
9742 show_thumb,
9743 ScrollbarAxis::Vertical,
9744 )
9745 }
9746
9747 fn new_with_hitbox_and_track_length(
9748 scrollbar_track_hitbox: Hitbox,
9749 track_length: Pixels,
9750 viewport_size: Pixels,
9751 scroll_range: Pixels,
9752 glyph_space: Pixels,
9753 content_offset: Pixels,
9754 scroll_position: f32,
9755 show_thumb: bool,
9756 axis: ScrollbarAxis,
9757 ) -> Self {
9758 let text_units_per_page = viewport_size / glyph_space;
9759 let visible_range = scroll_position..scroll_position + text_units_per_page;
9760 let total_text_units = scroll_range / glyph_space;
9761
9762 let thumb_percentage = text_units_per_page / total_text_units;
9763 let thumb_size = (track_length * thumb_percentage)
9764 .max(ScrollbarLayout::MIN_THUMB_SIZE)
9765 .min(track_length);
9766
9767 let text_unit_divisor = (total_text_units - text_units_per_page).max(0.);
9768
9769 let content_larger_than_viewport = text_unit_divisor > 0.;
9770
9771 let text_unit_size = if content_larger_than_viewport {
9772 (track_length - thumb_size) / text_unit_divisor
9773 } else {
9774 glyph_space
9775 };
9776
9777 let thumb_bounds = (show_thumb && content_larger_than_viewport).then(|| {
9778 Self::thumb_bounds(
9779 &scrollbar_track_hitbox,
9780 content_offset,
9781 visible_range.start,
9782 text_unit_size,
9783 thumb_size,
9784 axis,
9785 )
9786 });
9787
9788 ScrollbarLayout {
9789 hitbox: scrollbar_track_hitbox,
9790 visible_range,
9791 text_unit_size,
9792 thumb_bounds,
9793 thumb_state: Default::default(),
9794 }
9795 }
9796
9797 fn with_thumb_state(self, thumb_state: Option<ScrollbarThumbState>) -> Self {
9798 if let Some(thumb_state) = thumb_state {
9799 Self {
9800 thumb_state,
9801 ..self
9802 }
9803 } else {
9804 self
9805 }
9806 }
9807
9808 fn thumb_bounds(
9809 scrollbar_track: &Hitbox,
9810 content_offset: Pixels,
9811 visible_range_start: f32,
9812 text_unit_size: Pixels,
9813 thumb_size: Pixels,
9814 axis: ScrollbarAxis,
9815 ) -> Bounds<Pixels> {
9816 let thumb_origin = scrollbar_track.origin.apply_along(axis, |origin| {
9817 origin + content_offset + visible_range_start * text_unit_size
9818 });
9819 Bounds::new(
9820 thumb_origin,
9821 scrollbar_track.size.apply_along(axis, |_| thumb_size),
9822 )
9823 }
9824
9825 fn thumb_hovered(&self, position: &gpui::Point<Pixels>) -> bool {
9826 self.thumb_bounds
9827 .is_some_and(|bounds| bounds.contains(position))
9828 }
9829
9830 fn marker_quads_for_ranges(
9831 &self,
9832 row_ranges: impl IntoIterator<Item = ColoredRange<DisplayRow>>,
9833 column: Option<usize>,
9834 ) -> Vec<PaintQuad> {
9835 struct MinMax {
9836 min: Pixels,
9837 max: Pixels,
9838 }
9839 let (x_range, height_limit) = if let Some(column) = column {
9840 let column_width = px(((self.hitbox.size.width - Self::BORDER_WIDTH).0 / 3.0).floor());
9841 let start = Self::BORDER_WIDTH + (column as f32 * column_width);
9842 let end = start + column_width;
9843 (
9844 Range { start, end },
9845 MinMax {
9846 min: Self::MIN_MARKER_HEIGHT,
9847 max: px(f32::MAX),
9848 },
9849 )
9850 } else {
9851 (
9852 Range {
9853 start: Self::BORDER_WIDTH,
9854 end: self.hitbox.size.width,
9855 },
9856 MinMax {
9857 min: Self::LINE_MARKER_HEIGHT,
9858 max: Self::LINE_MARKER_HEIGHT,
9859 },
9860 )
9861 };
9862
9863 let row_to_y = |row: DisplayRow| row.as_f32() * self.text_unit_size;
9864 let mut pixel_ranges = row_ranges
9865 .into_iter()
9866 .map(|range| {
9867 let start_y = row_to_y(range.start);
9868 let end_y = row_to_y(range.end)
9869 + self
9870 .text_unit_size
9871 .max(height_limit.min)
9872 .min(height_limit.max);
9873 ColoredRange {
9874 start: start_y,
9875 end: end_y,
9876 color: range.color,
9877 }
9878 })
9879 .peekable();
9880
9881 let mut quads = Vec::new();
9882 while let Some(mut pixel_range) = pixel_ranges.next() {
9883 while let Some(next_pixel_range) = pixel_ranges.peek() {
9884 if pixel_range.end >= next_pixel_range.start - px(1.0)
9885 && pixel_range.color == next_pixel_range.color
9886 {
9887 pixel_range.end = next_pixel_range.end.max(pixel_range.end);
9888 pixel_ranges.next();
9889 } else {
9890 break;
9891 }
9892 }
9893
9894 let bounds = Bounds::from_corners(
9895 point(x_range.start, pixel_range.start),
9896 point(x_range.end, pixel_range.end),
9897 );
9898 quads.push(quad(
9899 bounds,
9900 Corners::default(),
9901 pixel_range.color,
9902 Edges::default(),
9903 Hsla::transparent_black(),
9904 BorderStyle::default(),
9905 ));
9906 }
9907
9908 quads
9909 }
9910}
9911
9912struct MinimapLayout {
9913 pub minimap: AnyElement,
9914 pub thumb_layout: ScrollbarLayout,
9915 pub minimap_scroll_top: f32,
9916 pub minimap_line_height: Pixels,
9917 pub thumb_border_style: MinimapThumbBorder,
9918 pub max_scroll_top: f32,
9919}
9920
9921impl MinimapLayout {
9922 /// The minimum width of the minimap in columns. If the minimap is smaller than this, it will be hidden.
9923 const MINIMAP_MIN_WIDTH_COLUMNS: f32 = 20.;
9924 /// The minimap width as a percentage of the editor width.
9925 const MINIMAP_WIDTH_PCT: f32 = 0.15;
9926 /// Calculates the scroll top offset the minimap editor has to have based on the
9927 /// current scroll progress.
9928 fn calculate_minimap_top_offset(
9929 document_lines: f32,
9930 visible_editor_lines: f32,
9931 visible_minimap_lines: f32,
9932 scroll_position: f32,
9933 ) -> f32 {
9934 let non_visible_document_lines = (document_lines - visible_editor_lines).max(0.);
9935 if non_visible_document_lines == 0. {
9936 0.
9937 } else {
9938 let scroll_percentage = (scroll_position / non_visible_document_lines).clamp(0., 1.);
9939 scroll_percentage * (document_lines - visible_minimap_lines).max(0.)
9940 }
9941 }
9942}
9943
9944struct CreaseTrailerLayout {
9945 element: AnyElement,
9946 bounds: Bounds<Pixels>,
9947}
9948
9949pub(crate) struct PositionMap {
9950 pub size: Size<Pixels>,
9951 pub line_height: Pixels,
9952 pub scroll_pixel_position: gpui::Point<Pixels>,
9953 pub scroll_max: gpui::Point<f32>,
9954 pub em_width: Pixels,
9955 pub em_advance: Pixels,
9956 pub visible_row_range: Range<DisplayRow>,
9957 pub line_layouts: Vec<LineWithInvisibles>,
9958 pub snapshot: EditorSnapshot,
9959 pub text_hitbox: Hitbox,
9960 pub gutter_hitbox: Hitbox,
9961 pub inline_blame_bounds: Option<(Bounds<Pixels>, BlameEntry)>,
9962 pub display_hunks: Vec<(DisplayDiffHunk, Option<Hitbox>)>,
9963 pub diff_hunk_control_bounds: Vec<(DisplayRow, Bounds<Pixels>)>,
9964}
9965
9966#[derive(Debug, Copy, Clone)]
9967pub struct PointForPosition {
9968 pub previous_valid: DisplayPoint,
9969 pub next_valid: DisplayPoint,
9970 pub exact_unclipped: DisplayPoint,
9971 pub column_overshoot_after_line_end: u32,
9972}
9973
9974impl PointForPosition {
9975 pub fn as_valid(&self) -> Option<DisplayPoint> {
9976 if self.previous_valid == self.exact_unclipped && self.next_valid == self.exact_unclipped {
9977 Some(self.previous_valid)
9978 } else {
9979 None
9980 }
9981 }
9982
9983 pub fn intersects_selection(&self, selection: &Selection<DisplayPoint>) -> bool {
9984 let Some(valid_point) = self.as_valid() else {
9985 return false;
9986 };
9987 let range = selection.range();
9988
9989 let candidate_row = valid_point.row();
9990 let candidate_col = valid_point.column();
9991
9992 let start_row = range.start.row();
9993 let start_col = range.start.column();
9994 let end_row = range.end.row();
9995 let end_col = range.end.column();
9996
9997 if candidate_row < start_row || candidate_row > end_row {
9998 false
9999 } else if start_row == end_row {
10000 candidate_col >= start_col && candidate_col < end_col
10001 } else if candidate_row == start_row {
10002 candidate_col >= start_col
10003 } else if candidate_row == end_row {
10004 candidate_col < end_col
10005 } else {
10006 true
10007 }
10008 }
10009}
10010
10011impl PositionMap {
10012 pub(crate) fn point_for_position(&self, position: gpui::Point<Pixels>) -> PointForPosition {
10013 let text_bounds = self.text_hitbox.bounds;
10014 let scroll_position = self.snapshot.scroll_position();
10015 let position = position - text_bounds.origin;
10016 let y = position.y.max(px(0.)).min(self.size.height);
10017 let x = position.x + (scroll_position.x * self.em_advance);
10018 let row = ((y / self.line_height) + scroll_position.y) as u32;
10019
10020 let (column, x_overshoot_after_line_end) = if let Some(line) = self
10021 .line_layouts
10022 .get(row as usize - scroll_position.y as usize)
10023 {
10024 if let Some(ix) = line.index_for_x(x) {
10025 (ix as u32, px(0.))
10026 } else {
10027 (line.len as u32, px(0.).max(x - line.width))
10028 }
10029 } else {
10030 (0, x)
10031 };
10032
10033 let mut exact_unclipped = DisplayPoint::new(DisplayRow(row), column);
10034 let previous_valid = self.snapshot.clip_point(exact_unclipped, Bias::Left);
10035 let next_valid = self.snapshot.clip_point(exact_unclipped, Bias::Right);
10036
10037 let column_overshoot_after_line_end = (x_overshoot_after_line_end / self.em_advance) as u32;
10038 *exact_unclipped.column_mut() += column_overshoot_after_line_end;
10039 PointForPosition {
10040 previous_valid,
10041 next_valid,
10042 exact_unclipped,
10043 column_overshoot_after_line_end,
10044 }
10045 }
10046}
10047
10048struct BlockLayout {
10049 id: BlockId,
10050 x_offset: Pixels,
10051 row: Option<DisplayRow>,
10052 element: AnyElement,
10053 available_space: Size<AvailableSpace>,
10054 style: BlockStyle,
10055 overlaps_gutter: bool,
10056 is_buffer_header: bool,
10057}
10058
10059pub fn layout_line(
10060 row: DisplayRow,
10061 snapshot: &EditorSnapshot,
10062 style: &EditorStyle,
10063 text_width: Pixels,
10064 is_row_soft_wrapped: impl Copy + Fn(usize) -> bool,
10065 window: &mut Window,
10066 cx: &mut App,
10067) -> LineWithInvisibles {
10068 let chunks = snapshot.highlighted_chunks(row..row + DisplayRow(1), true, style);
10069 LineWithInvisibles::from_chunks(
10070 chunks,
10071 style,
10072 MAX_LINE_LEN,
10073 1,
10074 &snapshot.mode,
10075 text_width,
10076 is_row_soft_wrapped,
10077 &[],
10078 window,
10079 cx,
10080 )
10081 .pop()
10082 .unwrap()
10083}
10084
10085#[derive(Debug)]
10086pub struct IndentGuideLayout {
10087 origin: gpui::Point<Pixels>,
10088 length: Pixels,
10089 single_indent_width: Pixels,
10090 depth: u32,
10091 active: bool,
10092 settings: IndentGuideSettings,
10093}
10094
10095pub struct CursorLayout {
10096 origin: gpui::Point<Pixels>,
10097 block_width: Pixels,
10098 line_height: Pixels,
10099 color: Hsla,
10100 shape: CursorShape,
10101 block_text: Option<ShapedLine>,
10102 cursor_name: Option<AnyElement>,
10103}
10104
10105#[derive(Debug)]
10106pub struct CursorName {
10107 string: SharedString,
10108 color: Hsla,
10109 is_top_row: bool,
10110}
10111
10112impl CursorLayout {
10113 pub fn new(
10114 origin: gpui::Point<Pixels>,
10115 block_width: Pixels,
10116 line_height: Pixels,
10117 color: Hsla,
10118 shape: CursorShape,
10119 block_text: Option<ShapedLine>,
10120 ) -> CursorLayout {
10121 CursorLayout {
10122 origin,
10123 block_width,
10124 line_height,
10125 color,
10126 shape,
10127 block_text,
10128 cursor_name: None,
10129 }
10130 }
10131
10132 pub fn bounding_rect(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
10133 Bounds {
10134 origin: self.origin + origin,
10135 size: size(self.block_width, self.line_height),
10136 }
10137 }
10138
10139 fn bounds(&self, origin: gpui::Point<Pixels>) -> Bounds<Pixels> {
10140 match self.shape {
10141 CursorShape::Bar => Bounds {
10142 origin: self.origin + origin,
10143 size: size(px(2.0), self.line_height),
10144 },
10145 CursorShape::Block | CursorShape::Hollow => Bounds {
10146 origin: self.origin + origin,
10147 size: size(self.block_width, self.line_height),
10148 },
10149 CursorShape::Underline => Bounds {
10150 origin: self.origin
10151 + origin
10152 + gpui::Point::new(Pixels::ZERO, self.line_height - px(2.0)),
10153 size: size(self.block_width, px(2.0)),
10154 },
10155 }
10156 }
10157
10158 pub fn layout(
10159 &mut self,
10160 origin: gpui::Point<Pixels>,
10161 cursor_name: Option<CursorName>,
10162 window: &mut Window,
10163 cx: &mut App,
10164 ) {
10165 if let Some(cursor_name) = cursor_name {
10166 let bounds = self.bounds(origin);
10167 let text_size = self.line_height / 1.5;
10168
10169 let name_origin = if cursor_name.is_top_row {
10170 point(bounds.right() - px(1.), bounds.top())
10171 } else {
10172 match self.shape {
10173 CursorShape::Bar => point(
10174 bounds.right() - px(2.),
10175 bounds.top() - text_size / 2. - px(1.),
10176 ),
10177 _ => point(
10178 bounds.right() - px(1.),
10179 bounds.top() - text_size / 2. - px(1.),
10180 ),
10181 }
10182 };
10183 let mut name_element = div()
10184 .bg(self.color)
10185 .text_size(text_size)
10186 .px_0p5()
10187 .line_height(text_size + px(2.))
10188 .text_color(cursor_name.color)
10189 .child(cursor_name.string)
10190 .into_any_element();
10191
10192 name_element.prepaint_as_root(name_origin, AvailableSpace::min_size(), window, cx);
10193
10194 self.cursor_name = Some(name_element);
10195 }
10196 }
10197
10198 pub fn paint(&mut self, origin: gpui::Point<Pixels>, window: &mut Window, cx: &mut App) {
10199 let bounds = self.bounds(origin);
10200
10201 //Draw background or border quad
10202 let cursor = if matches!(self.shape, CursorShape::Hollow) {
10203 outline(bounds, self.color, BorderStyle::Solid)
10204 } else {
10205 fill(bounds, self.color)
10206 };
10207
10208 if let Some(name) = &mut self.cursor_name {
10209 name.paint(window, cx);
10210 }
10211
10212 window.paint_quad(cursor);
10213
10214 if let Some(block_text) = &self.block_text {
10215 block_text
10216 .paint(self.origin + origin, self.line_height, window, cx)
10217 .log_err();
10218 }
10219 }
10220
10221 pub fn shape(&self) -> CursorShape {
10222 self.shape
10223 }
10224}
10225
10226#[derive(Debug)]
10227pub struct HighlightedRange {
10228 pub start_y: Pixels,
10229 pub line_height: Pixels,
10230 pub lines: Vec<HighlightedRangeLine>,
10231 pub color: Hsla,
10232 pub corner_radius: Pixels,
10233}
10234
10235#[derive(Debug)]
10236pub struct HighlightedRangeLine {
10237 pub start_x: Pixels,
10238 pub end_x: Pixels,
10239}
10240
10241impl HighlightedRange {
10242 pub fn paint(&self, fill: bool, bounds: Bounds<Pixels>, window: &mut Window) {
10243 if self.lines.len() >= 2 && self.lines[0].start_x > self.lines[1].end_x {
10244 self.paint_lines(self.start_y, &self.lines[0..1], fill, bounds, window);
10245 self.paint_lines(
10246 self.start_y + self.line_height,
10247 &self.lines[1..],
10248 fill,
10249 bounds,
10250 window,
10251 );
10252 } else {
10253 self.paint_lines(self.start_y, &self.lines, fill, bounds, window);
10254 }
10255 }
10256
10257 fn paint_lines(
10258 &self,
10259 start_y: Pixels,
10260 lines: &[HighlightedRangeLine],
10261 fill: bool,
10262 _bounds: Bounds<Pixels>,
10263 window: &mut Window,
10264 ) {
10265 if lines.is_empty() {
10266 return;
10267 }
10268
10269 let first_line = lines.first().unwrap();
10270 let last_line = lines.last().unwrap();
10271
10272 let first_top_left = point(first_line.start_x, start_y);
10273 let first_top_right = point(first_line.end_x, start_y);
10274
10275 let curve_height = point(Pixels::ZERO, self.corner_radius);
10276 let curve_width = |start_x: Pixels, end_x: Pixels| {
10277 let max = (end_x - start_x) / 2.;
10278 let width = if max < self.corner_radius {
10279 max
10280 } else {
10281 self.corner_radius
10282 };
10283
10284 point(width, Pixels::ZERO)
10285 };
10286
10287 let top_curve_width = curve_width(first_line.start_x, first_line.end_x);
10288 let mut builder = if fill {
10289 gpui::PathBuilder::fill()
10290 } else {
10291 gpui::PathBuilder::stroke(px(1.))
10292 };
10293 builder.move_to(first_top_right - top_curve_width);
10294 builder.curve_to(first_top_right + curve_height, first_top_right);
10295
10296 let mut iter = lines.iter().enumerate().peekable();
10297 while let Some((ix, line)) = iter.next() {
10298 let bottom_right = point(line.end_x, start_y + (ix + 1) as f32 * self.line_height);
10299
10300 if let Some((_, next_line)) = iter.peek() {
10301 let next_top_right = point(next_line.end_x, bottom_right.y);
10302
10303 match next_top_right.x.partial_cmp(&bottom_right.x).unwrap() {
10304 Ordering::Equal => {
10305 builder.line_to(bottom_right);
10306 }
10307 Ordering::Less => {
10308 let curve_width = curve_width(next_top_right.x, bottom_right.x);
10309 builder.line_to(bottom_right - curve_height);
10310 if self.corner_radius > Pixels::ZERO {
10311 builder.curve_to(bottom_right - curve_width, bottom_right);
10312 }
10313 builder.line_to(next_top_right + curve_width);
10314 if self.corner_radius > Pixels::ZERO {
10315 builder.curve_to(next_top_right + curve_height, next_top_right);
10316 }
10317 }
10318 Ordering::Greater => {
10319 let curve_width = curve_width(bottom_right.x, next_top_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 }
10330 } else {
10331 let curve_width = curve_width(line.start_x, line.end_x);
10332 builder.line_to(bottom_right - curve_height);
10333 if self.corner_radius > Pixels::ZERO {
10334 builder.curve_to(bottom_right - curve_width, bottom_right);
10335 }
10336
10337 let bottom_left = point(line.start_x, bottom_right.y);
10338 builder.line_to(bottom_left + curve_width);
10339 if self.corner_radius > Pixels::ZERO {
10340 builder.curve_to(bottom_left - curve_height, bottom_left);
10341 }
10342 }
10343 }
10344
10345 if first_line.start_x > last_line.start_x {
10346 let curve_width = curve_width(last_line.start_x, first_line.start_x);
10347 let second_top_left = point(last_line.start_x, start_y + self.line_height);
10348 builder.line_to(second_top_left + curve_height);
10349 if self.corner_radius > Pixels::ZERO {
10350 builder.curve_to(second_top_left + curve_width, second_top_left);
10351 }
10352 let first_bottom_left = point(first_line.start_x, second_top_left.y);
10353 builder.line_to(first_bottom_left - curve_width);
10354 if self.corner_radius > Pixels::ZERO {
10355 builder.curve_to(first_bottom_left - curve_height, first_bottom_left);
10356 }
10357 }
10358
10359 builder.line_to(first_top_left + curve_height);
10360 if self.corner_radius > Pixels::ZERO {
10361 builder.curve_to(first_top_left + top_curve_width, first_top_left);
10362 }
10363 builder.line_to(first_top_right - top_curve_width);
10364
10365 if let Ok(path) = builder.build() {
10366 window.paint_path(path, self.color);
10367 }
10368 }
10369}
10370
10371enum CursorPopoverType {
10372 CodeContextMenu,
10373 EditPrediction,
10374}
10375
10376pub fn scale_vertical_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10377 (delta.pow(1.2) / 100.0).min(px(3.0)).into()
10378}
10379
10380fn scale_horizontal_mouse_autoscroll_delta(delta: Pixels) -> f32 {
10381 (delta.pow(1.2) / 300.0).into()
10382}
10383
10384pub fn register_action<T: Action>(
10385 editor: &Entity<Editor>,
10386 window: &mut Window,
10387 listener: impl Fn(&mut Editor, &T, &mut Window, &mut Context<Editor>) + 'static,
10388) {
10389 let editor = editor.clone();
10390 window.on_action(TypeId::of::<T>(), move |action, phase, window, cx| {
10391 let action = action.downcast_ref().unwrap();
10392 if phase == DispatchPhase::Bubble {
10393 editor.update(cx, |editor, cx| {
10394 listener(editor, action, window, cx);
10395 })
10396 }
10397 })
10398}
10399
10400fn compute_auto_height_layout(
10401 editor: &mut Editor,
10402 min_lines: usize,
10403 max_lines: Option<usize>,
10404 max_line_number_width: Pixels,
10405 known_dimensions: Size<Option<Pixels>>,
10406 available_width: AvailableSpace,
10407 window: &mut Window,
10408 cx: &mut Context<Editor>,
10409) -> Option<Size<Pixels>> {
10410 let width = known_dimensions.width.or({
10411 if let AvailableSpace::Definite(available_width) = available_width {
10412 Some(available_width)
10413 } else {
10414 None
10415 }
10416 })?;
10417 if let Some(height) = known_dimensions.height {
10418 return Some(size(width, height));
10419 }
10420
10421 let style = editor.style.as_ref().unwrap();
10422 let font_id = window.text_system().resolve_font(&style.text.font());
10423 let font_size = style.text.font_size.to_pixels(window.rem_size());
10424 let line_height = style.text.line_height_in_pixels(window.rem_size());
10425 let em_width = window.text_system().em_width(font_id, font_size).unwrap();
10426
10427 let mut snapshot = editor.snapshot(window, cx);
10428 let gutter_dimensions = snapshot
10429 .gutter_dimensions(font_id, font_size, max_line_number_width, cx)
10430 .or_else(|| {
10431 editor
10432 .offset_content
10433 .then(|| GutterDimensions::default_with_margin(font_id, font_size, cx))
10434 })
10435 .unwrap_or_default();
10436
10437 editor.gutter_dimensions = gutter_dimensions;
10438 let text_width = width - gutter_dimensions.width;
10439 let overscroll = size(em_width, px(0.));
10440
10441 let editor_width = text_width - gutter_dimensions.margin - overscroll.width - em_width;
10442 if !matches!(editor.soft_wrap_mode(cx), SoftWrap::None)
10443 && editor.set_wrap_width(Some(editor_width), cx)
10444 {
10445 snapshot = editor.snapshot(window, cx);
10446 }
10447
10448 let scroll_height = (snapshot.max_point().row().next_row().0 as f32) * line_height;
10449
10450 let min_height = line_height * min_lines as f32;
10451 let content_height = scroll_height.max(min_height);
10452
10453 let final_height = if let Some(max_lines) = max_lines {
10454 let max_height = line_height * max_lines as f32;
10455 content_height.min(max_height)
10456 } else {
10457 content_height
10458 };
10459
10460 Some(size(width, final_height))
10461}
10462
10463#[cfg(test)]
10464mod tests {
10465 use super::*;
10466 use crate::{
10467 Editor, MultiBuffer, SelectionEffects,
10468 display_map::{BlockPlacement, BlockProperties},
10469 editor_tests::{init_test, update_test_language_settings},
10470 };
10471 use gpui::{TestAppContext, VisualTestContext};
10472 use language::language_settings;
10473 use log::info;
10474 use std::num::NonZeroU32;
10475 use util::test::sample_text;
10476
10477 #[gpui::test]
10478 async fn test_soft_wrap_editor_width_auto_height_editor(cx: &mut TestAppContext) {
10479 init_test(cx, |_| {});
10480
10481 let window = cx.add_window(|window, cx| {
10482 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
10483 let mut editor = Editor::new(
10484 EditorMode::AutoHeight {
10485 min_lines: 1,
10486 max_lines: None,
10487 },
10488 buffer,
10489 None,
10490 window,
10491 cx,
10492 );
10493 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10494 editor
10495 });
10496 let cx = &mut VisualTestContext::from_window(*window, cx);
10497 let editor = window.root(cx).unwrap();
10498 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10499
10500 for x in 1..=100 {
10501 let (_, state) = cx.draw(
10502 Default::default(),
10503 size(px(200. + 0.13 * x as f32), px(500.)),
10504 |_, _| EditorElement::new(&editor, style.clone()),
10505 );
10506
10507 assert!(
10508 state.position_map.scroll_max.x == 0.,
10509 "Soft wrapped editor should have no horizontal scrolling!"
10510 );
10511 }
10512 }
10513
10514 #[gpui::test]
10515 async fn test_soft_wrap_editor_width_full_editor(cx: &mut TestAppContext) {
10516 init_test(cx, |_| {});
10517
10518 let window = cx.add_window(|window, cx| {
10519 let buffer = MultiBuffer::build_simple(&"a ".to_string().repeat(100), cx);
10520 let mut editor = Editor::new(EditorMode::full(), buffer, None, window, cx);
10521 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10522 editor
10523 });
10524 let cx = &mut VisualTestContext::from_window(*window, cx);
10525 let editor = window.root(cx).unwrap();
10526 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10527
10528 for x in 1..=100 {
10529 let (_, state) = cx.draw(
10530 Default::default(),
10531 size(px(200. + 0.13 * x as f32), px(500.)),
10532 |_, _| EditorElement::new(&editor, style.clone()),
10533 );
10534
10535 assert!(
10536 state.position_map.scroll_max.x == 0.,
10537 "Soft wrapped editor should have no horizontal scrolling!"
10538 );
10539 }
10540 }
10541
10542 #[gpui::test]
10543 fn test_shape_line_numbers(cx: &mut TestAppContext) {
10544 init_test(cx, |_| {});
10545 let window = cx.add_window(|window, cx| {
10546 let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
10547 Editor::new(EditorMode::full(), buffer, None, window, cx)
10548 });
10549
10550 let editor = window.root(cx).unwrap();
10551 let style = cx.update(|cx| editor.read(cx).style().unwrap().clone());
10552 let line_height = window
10553 .update(cx, |_, window, _| {
10554 style.text.line_height_in_pixels(window.rem_size())
10555 })
10556 .unwrap();
10557 let element = EditorElement::new(&editor, style);
10558 let snapshot = window
10559 .update(cx, |editor, window, cx| editor.snapshot(window, cx))
10560 .unwrap();
10561
10562 let layouts = cx
10563 .update_window(*window, |_, window, cx| {
10564 element.layout_line_numbers(
10565 None,
10566 GutterDimensions {
10567 left_padding: Pixels::ZERO,
10568 right_padding: Pixels::ZERO,
10569 width: px(30.0),
10570 margin: Pixels::ZERO,
10571 git_blame_entries_width: None,
10572 },
10573 line_height,
10574 gpui::Point::default(),
10575 DisplayRow(0)..DisplayRow(6),
10576 &(0..6)
10577 .map(|row| RowInfo {
10578 buffer_row: Some(row),
10579 ..Default::default()
10580 })
10581 .collect::<Vec<_>>(),
10582 &BTreeMap::default(),
10583 Some(DisplayPoint::new(DisplayRow(0), 0)),
10584 &snapshot,
10585 window,
10586 cx,
10587 )
10588 })
10589 .unwrap();
10590 assert_eq!(layouts.len(), 6);
10591
10592 let relative_rows = window
10593 .update(cx, |editor, window, cx| {
10594 let snapshot = editor.snapshot(window, cx);
10595 element.calculate_relative_line_numbers(
10596 &snapshot,
10597 &(DisplayRow(0)..DisplayRow(6)),
10598 Some(DisplayRow(3)),
10599 )
10600 })
10601 .unwrap();
10602 assert_eq!(relative_rows[&DisplayRow(0)], 3);
10603 assert_eq!(relative_rows[&DisplayRow(1)], 2);
10604 assert_eq!(relative_rows[&DisplayRow(2)], 1);
10605 // current line has no relative number
10606 assert_eq!(relative_rows[&DisplayRow(4)], 1);
10607 assert_eq!(relative_rows[&DisplayRow(5)], 2);
10608
10609 // works if cursor is before screen
10610 let relative_rows = window
10611 .update(cx, |editor, window, cx| {
10612 let snapshot = editor.snapshot(window, cx);
10613 element.calculate_relative_line_numbers(
10614 &snapshot,
10615 &(DisplayRow(3)..DisplayRow(6)),
10616 Some(DisplayRow(1)),
10617 )
10618 })
10619 .unwrap();
10620 assert_eq!(relative_rows.len(), 3);
10621 assert_eq!(relative_rows[&DisplayRow(3)], 2);
10622 assert_eq!(relative_rows[&DisplayRow(4)], 3);
10623 assert_eq!(relative_rows[&DisplayRow(5)], 4);
10624
10625 // works if cursor is after screen
10626 let relative_rows = window
10627 .update(cx, |editor, window, cx| {
10628 let snapshot = editor.snapshot(window, cx);
10629 element.calculate_relative_line_numbers(
10630 &snapshot,
10631 &(DisplayRow(0)..DisplayRow(3)),
10632 Some(DisplayRow(6)),
10633 )
10634 })
10635 .unwrap();
10636 assert_eq!(relative_rows.len(), 3);
10637 assert_eq!(relative_rows[&DisplayRow(0)], 5);
10638 assert_eq!(relative_rows[&DisplayRow(1)], 4);
10639 assert_eq!(relative_rows[&DisplayRow(2)], 3);
10640 }
10641
10642 #[gpui::test]
10643 async fn test_vim_visual_selections(cx: &mut TestAppContext) {
10644 init_test(cx, |_| {});
10645
10646 let window = cx.add_window(|window, cx| {
10647 let buffer = MultiBuffer::build_simple(&(sample_text(6, 6, 'a') + "\n"), cx);
10648 Editor::new(EditorMode::full(), buffer, None, window, cx)
10649 });
10650 let cx = &mut VisualTestContext::from_window(*window, cx);
10651 let editor = window.root(cx).unwrap();
10652 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10653
10654 window
10655 .update(cx, |editor, window, cx| {
10656 editor.cursor_shape = CursorShape::Block;
10657 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
10658 s.select_ranges([
10659 Point::new(0, 0)..Point::new(1, 0),
10660 Point::new(3, 2)..Point::new(3, 3),
10661 Point::new(5, 6)..Point::new(6, 0),
10662 ]);
10663 });
10664 })
10665 .unwrap();
10666
10667 let (_, state) = cx.draw(
10668 point(px(500.), px(500.)),
10669 size(px(500.), px(500.)),
10670 |_, _| EditorElement::new(&editor, style),
10671 );
10672
10673 assert_eq!(state.selections.len(), 1);
10674 let local_selections = &state.selections[0].1;
10675 assert_eq!(local_selections.len(), 3);
10676 // moves cursor back one line
10677 assert_eq!(
10678 local_selections[0].head,
10679 DisplayPoint::new(DisplayRow(0), 6)
10680 );
10681 assert_eq!(
10682 local_selections[0].range,
10683 DisplayPoint::new(DisplayRow(0), 0)..DisplayPoint::new(DisplayRow(1), 0)
10684 );
10685
10686 // moves cursor back one column
10687 assert_eq!(
10688 local_selections[1].range,
10689 DisplayPoint::new(DisplayRow(3), 2)..DisplayPoint::new(DisplayRow(3), 3)
10690 );
10691 assert_eq!(
10692 local_selections[1].head,
10693 DisplayPoint::new(DisplayRow(3), 2)
10694 );
10695
10696 // leaves cursor on the max point
10697 assert_eq!(
10698 local_selections[2].range,
10699 DisplayPoint::new(DisplayRow(5), 6)..DisplayPoint::new(DisplayRow(6), 0)
10700 );
10701 assert_eq!(
10702 local_selections[2].head,
10703 DisplayPoint::new(DisplayRow(6), 0)
10704 );
10705
10706 // active lines does not include 1 (even though the range of the selection does)
10707 assert_eq!(
10708 state.active_rows.keys().cloned().collect::<Vec<_>>(),
10709 vec![DisplayRow(0), DisplayRow(3), DisplayRow(5), DisplayRow(6)]
10710 );
10711 }
10712
10713 #[gpui::test]
10714 fn test_layout_with_placeholder_text_and_blocks(cx: &mut TestAppContext) {
10715 init_test(cx, |_| {});
10716
10717 let window = cx.add_window(|window, cx| {
10718 let buffer = MultiBuffer::build_simple("", cx);
10719 Editor::new(EditorMode::full(), buffer, None, window, cx)
10720 });
10721 let cx = &mut VisualTestContext::from_window(*window, cx);
10722 let editor = window.root(cx).unwrap();
10723 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10724 window
10725 .update(cx, |editor, window, cx| {
10726 editor.set_placeholder_text("hello", cx);
10727 editor.insert_blocks(
10728 [BlockProperties {
10729 style: BlockStyle::Fixed,
10730 placement: BlockPlacement::Above(Anchor::min()),
10731 height: Some(3),
10732 render: Arc::new(|cx| div().h(3. * cx.window.line_height()).into_any()),
10733 priority: 0,
10734 }],
10735 None,
10736 cx,
10737 );
10738
10739 // Blur the editor so that it displays placeholder text.
10740 window.blur();
10741 })
10742 .unwrap();
10743
10744 let (_, state) = cx.draw(
10745 point(px(500.), px(500.)),
10746 size(px(500.), px(500.)),
10747 |_, _| EditorElement::new(&editor, style),
10748 );
10749 assert_eq!(state.position_map.line_layouts.len(), 4);
10750 assert_eq!(state.line_numbers.len(), 1);
10751 assert_eq!(
10752 state
10753 .line_numbers
10754 .get(&MultiBufferRow(0))
10755 .map(|line_number| line_number.shaped_line.text.as_ref()),
10756 Some("1")
10757 );
10758 }
10759
10760 #[gpui::test]
10761 fn test_all_invisibles_drawing(cx: &mut TestAppContext) {
10762 const TAB_SIZE: u32 = 4;
10763
10764 let input_text = "\t \t|\t| a b";
10765 let expected_invisibles = vec![
10766 Invisible::Tab {
10767 line_start_offset: 0,
10768 line_end_offset: TAB_SIZE as usize,
10769 },
10770 Invisible::Whitespace {
10771 line_offset: TAB_SIZE as usize,
10772 },
10773 Invisible::Tab {
10774 line_start_offset: TAB_SIZE as usize + 1,
10775 line_end_offset: TAB_SIZE as usize * 2,
10776 },
10777 Invisible::Tab {
10778 line_start_offset: TAB_SIZE as usize * 2 + 1,
10779 line_end_offset: TAB_SIZE as usize * 3,
10780 },
10781 Invisible::Whitespace {
10782 line_offset: TAB_SIZE as usize * 3 + 1,
10783 },
10784 Invisible::Whitespace {
10785 line_offset: TAB_SIZE as usize * 3 + 3,
10786 },
10787 ];
10788 assert_eq!(
10789 expected_invisibles.len(),
10790 input_text
10791 .chars()
10792 .filter(|initial_char| initial_char.is_whitespace())
10793 .count(),
10794 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10795 );
10796
10797 for show_line_numbers in [true, false] {
10798 init_test(cx, |s| {
10799 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10800 s.defaults.tab_size = NonZeroU32::new(TAB_SIZE);
10801 });
10802
10803 let actual_invisibles = collect_invisibles_from_new_editor(
10804 cx,
10805 EditorMode::full(),
10806 input_text,
10807 px(500.0),
10808 show_line_numbers,
10809 );
10810
10811 assert_eq!(expected_invisibles, actual_invisibles);
10812 }
10813 }
10814
10815 #[gpui::test]
10816 fn test_invisibles_dont_appear_in_certain_editors(cx: &mut TestAppContext) {
10817 init_test(cx, |s| {
10818 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10819 s.defaults.tab_size = NonZeroU32::new(4);
10820 });
10821
10822 for editor_mode_without_invisibles in [
10823 EditorMode::SingleLine,
10824 EditorMode::AutoHeight {
10825 min_lines: 1,
10826 max_lines: Some(100),
10827 },
10828 ] {
10829 for show_line_numbers in [true, false] {
10830 let invisibles = collect_invisibles_from_new_editor(
10831 cx,
10832 editor_mode_without_invisibles.clone(),
10833 "\t\t\t| | a b",
10834 px(500.0),
10835 show_line_numbers,
10836 );
10837 assert!(
10838 invisibles.is_empty(),
10839 "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
10840 );
10841 }
10842 }
10843 }
10844
10845 #[gpui::test]
10846 fn test_wrapped_invisibles_drawing(cx: &mut TestAppContext) {
10847 let tab_size = 4;
10848 let input_text = "a\tbcd ".repeat(9);
10849 let repeated_invisibles = [
10850 Invisible::Tab {
10851 line_start_offset: 1,
10852 line_end_offset: tab_size as usize,
10853 },
10854 Invisible::Whitespace {
10855 line_offset: tab_size as usize + 3,
10856 },
10857 Invisible::Whitespace {
10858 line_offset: tab_size as usize + 4,
10859 },
10860 Invisible::Whitespace {
10861 line_offset: tab_size as usize + 5,
10862 },
10863 Invisible::Whitespace {
10864 line_offset: tab_size as usize + 6,
10865 },
10866 Invisible::Whitespace {
10867 line_offset: tab_size as usize + 7,
10868 },
10869 ];
10870 let expected_invisibles = std::iter::once(repeated_invisibles)
10871 .cycle()
10872 .take(9)
10873 .flatten()
10874 .collect::<Vec<_>>();
10875 assert_eq!(
10876 expected_invisibles.len(),
10877 input_text
10878 .chars()
10879 .filter(|initial_char| initial_char.is_whitespace())
10880 .count(),
10881 "Hardcoded expected invisibles differ from the actual ones in '{input_text}'"
10882 );
10883 info!("Expected invisibles: {expected_invisibles:?}");
10884
10885 init_test(cx, |_| {});
10886
10887 // Put the same string with repeating whitespace pattern into editors of various size,
10888 // take deliberately small steps during resizing, to put all whitespace kinds near the wrap point.
10889 let resize_step = 10.0;
10890 let mut editor_width = 200.0;
10891 while editor_width <= 1000.0 {
10892 for show_line_numbers in [true, false] {
10893 update_test_language_settings(cx, |s| {
10894 s.defaults.tab_size = NonZeroU32::new(tab_size);
10895 s.defaults.show_whitespaces = Some(ShowWhitespaceSetting::All);
10896 s.defaults.preferred_line_length = Some(editor_width as u32);
10897 s.defaults.soft_wrap = Some(language_settings::SoftWrap::PreferredLineLength);
10898 });
10899
10900 let actual_invisibles = collect_invisibles_from_new_editor(
10901 cx,
10902 EditorMode::full(),
10903 &input_text,
10904 px(editor_width),
10905 show_line_numbers,
10906 );
10907
10908 // Whatever the editor size is, ensure it has the same invisible kinds in the same order
10909 // (no good guarantees about the offsets: wrapping could trigger padding and its tests should check the offsets).
10910 let mut i = 0;
10911 for (actual_index, actual_invisible) in actual_invisibles.iter().enumerate() {
10912 i = actual_index;
10913 match expected_invisibles.get(i) {
10914 Some(expected_invisible) => match (expected_invisible, actual_invisible) {
10915 (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
10916 | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
10917 _ => {
10918 panic!(
10919 "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
10920 )
10921 }
10922 },
10923 None => {
10924 panic!("Unexpected extra invisible {actual_invisible:?} at index {i}")
10925 }
10926 }
10927 }
10928 let missing_expected_invisibles = &expected_invisibles[i + 1..];
10929 assert!(
10930 missing_expected_invisibles.is_empty(),
10931 "Missing expected invisibles after index {i}: {missing_expected_invisibles:?}"
10932 );
10933
10934 editor_width += resize_step;
10935 }
10936 }
10937 }
10938
10939 fn collect_invisibles_from_new_editor(
10940 cx: &mut TestAppContext,
10941 editor_mode: EditorMode,
10942 input_text: &str,
10943 editor_width: Pixels,
10944 show_line_numbers: bool,
10945 ) -> Vec<Invisible> {
10946 info!(
10947 "Creating editor with mode {editor_mode:?}, width {}px and text '{input_text}'",
10948 editor_width.0
10949 );
10950 let window = cx.add_window(|window, cx| {
10951 let buffer = MultiBuffer::build_simple(input_text, cx);
10952 Editor::new(editor_mode, buffer, None, window, cx)
10953 });
10954 let cx = &mut VisualTestContext::from_window(*window, cx);
10955 let editor = window.root(cx).unwrap();
10956
10957 let style = cx.update(|_, cx| editor.read(cx).style().unwrap().clone());
10958 window
10959 .update(cx, |editor, _, cx| {
10960 editor.set_soft_wrap_mode(language_settings::SoftWrap::EditorWidth, cx);
10961 editor.set_wrap_width(Some(editor_width), cx);
10962 editor.set_show_line_numbers(show_line_numbers, cx);
10963 })
10964 .unwrap();
10965 let (_, state) = cx.draw(
10966 point(px(500.), px(500.)),
10967 size(px(500.), px(500.)),
10968 |_, _| EditorElement::new(&editor, style),
10969 );
10970 state
10971 .position_map
10972 .line_layouts
10973 .iter()
10974 .flat_map(|line_with_invisibles| &line_with_invisibles.invisibles)
10975 .cloned()
10976 .collect()
10977 }
10978
10979 #[gpui::test]
10980 fn test_merge_overlapping_ranges() {
10981 let base_bg = Hsla::white();
10982 let color1 = Hsla {
10983 h: 0.0,
10984 s: 0.5,
10985 l: 0.5,
10986 a: 0.5,
10987 };
10988 let color2 = Hsla {
10989 h: 120.0,
10990 s: 0.5,
10991 l: 0.5,
10992 a: 0.5,
10993 };
10994
10995 let display_point = |col| DisplayPoint::new(DisplayRow(0), col);
10996 let cols = |v: &Vec<(Range<DisplayPoint>, Hsla)>| -> Vec<(u32, u32)> {
10997 v.iter()
10998 .map(|(r, _)| (r.start.column(), r.end.column()))
10999 .collect()
11000 };
11001
11002 // Test overlapping ranges blend colors
11003 let overlapping = vec![
11004 (display_point(5)..display_point(15), color1),
11005 (display_point(10)..display_point(20), color2),
11006 ];
11007 let result = EditorElement::merge_overlapping_ranges(overlapping, base_bg);
11008 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
11009
11010 // Test middle segment should have blended color
11011 let blended = Hsla::blend(Hsla::blend(base_bg, color1), color2);
11012 assert_eq!(result[1].1, blended);
11013
11014 // Test adjacent same-color ranges merge
11015 let adjacent_same = vec![
11016 (display_point(5)..display_point(10), color1),
11017 (display_point(10)..display_point(15), color1),
11018 ];
11019 let result = EditorElement::merge_overlapping_ranges(adjacent_same, base_bg);
11020 assert_eq!(cols(&result), vec![(5, 15)]);
11021
11022 // Test contained range splits
11023 let contained = vec![
11024 (display_point(5)..display_point(20), color1),
11025 (display_point(10)..display_point(15), color2),
11026 ];
11027 let result = EditorElement::merge_overlapping_ranges(contained, base_bg);
11028 assert_eq!(cols(&result), vec![(5, 10), (10, 15), (15, 20)]);
11029
11030 // Test multiple overlaps split at every boundary
11031 let color3 = Hsla {
11032 h: 240.0,
11033 s: 0.5,
11034 l: 0.5,
11035 a: 0.5,
11036 };
11037 let complex = vec![
11038 (display_point(5)..display_point(12), color1),
11039 (display_point(8)..display_point(16), color2),
11040 (display_point(10)..display_point(14), color3),
11041 ];
11042 let result = EditorElement::merge_overlapping_ranges(complex, base_bg);
11043 assert_eq!(
11044 cols(&result),
11045 vec![(5, 8), (8, 10), (10, 12), (12, 14), (14, 16)]
11046 );
11047 }
11048
11049 #[gpui::test]
11050 fn test_bg_segments_per_row() {
11051 let base_bg = Hsla::white();
11052
11053 // Case A: selection spans three display rows: row 1 [5, end), full row 2, row 3 [0, 7)
11054 {
11055 let selection_color = Hsla {
11056 h: 200.0,
11057 s: 0.5,
11058 l: 0.5,
11059 a: 0.5,
11060 };
11061 let player_color = PlayerColor {
11062 cursor: selection_color,
11063 background: selection_color,
11064 selection: selection_color,
11065 };
11066
11067 let spanning_selection = SelectionLayout {
11068 head: DisplayPoint::new(DisplayRow(3), 7),
11069 cursor_shape: CursorShape::Bar,
11070 is_newest: true,
11071 is_local: true,
11072 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 7),
11073 active_rows: DisplayRow(1)..DisplayRow(4),
11074 user_name: None,
11075 };
11076
11077 let selections = vec![(player_color, vec![spanning_selection])];
11078 let result = EditorElement::bg_segments_per_row(
11079 DisplayRow(0)..DisplayRow(5),
11080 &selections,
11081 &[],
11082 base_bg,
11083 );
11084
11085 assert_eq!(result.len(), 5);
11086 assert!(result[0].is_empty());
11087 assert_eq!(result[1].len(), 1);
11088 assert_eq!(result[2].len(), 1);
11089 assert_eq!(result[3].len(), 1);
11090 assert!(result[4].is_empty());
11091
11092 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
11093 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
11094 assert_eq!(result[1][0].0.end.column(), u32::MAX);
11095 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
11096 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
11097 assert_eq!(result[2][0].0.end.column(), u32::MAX);
11098 assert_eq!(result[3][0].0.start, DisplayPoint::new(DisplayRow(3), 0));
11099 assert_eq!(result[3][0].0.end, DisplayPoint::new(DisplayRow(3), 7));
11100 }
11101
11102 // Case B: selection ends exactly at the start of row 3, excluding row 3
11103 {
11104 let selection_color = Hsla {
11105 h: 120.0,
11106 s: 0.5,
11107 l: 0.5,
11108 a: 0.5,
11109 };
11110 let player_color = PlayerColor {
11111 cursor: selection_color,
11112 background: selection_color,
11113 selection: selection_color,
11114 };
11115
11116 let selection = SelectionLayout {
11117 head: DisplayPoint::new(DisplayRow(2), 0),
11118 cursor_shape: CursorShape::Bar,
11119 is_newest: true,
11120 is_local: true,
11121 range: DisplayPoint::new(DisplayRow(1), 5)..DisplayPoint::new(DisplayRow(3), 0),
11122 active_rows: DisplayRow(1)..DisplayRow(3),
11123 user_name: None,
11124 };
11125
11126 let selections = vec![(player_color, vec![selection])];
11127 let result = EditorElement::bg_segments_per_row(
11128 DisplayRow(0)..DisplayRow(4),
11129 &selections,
11130 &[],
11131 base_bg,
11132 );
11133
11134 assert_eq!(result.len(), 4);
11135 assert!(result[0].is_empty());
11136 assert_eq!(result[1].len(), 1);
11137 assert_eq!(result[2].len(), 1);
11138 assert!(result[3].is_empty());
11139
11140 assert_eq!(result[1][0].0.start, DisplayPoint::new(DisplayRow(1), 5));
11141 assert_eq!(result[1][0].0.end.row(), DisplayRow(1));
11142 assert_eq!(result[1][0].0.end.column(), u32::MAX);
11143 assert_eq!(result[2][0].0.start, DisplayPoint::new(DisplayRow(2), 0));
11144 assert_eq!(result[2][0].0.end.row(), DisplayRow(2));
11145 assert_eq!(result[2][0].0.end.column(), u32::MAX);
11146 }
11147 }
11148
11149 #[cfg(test)]
11150 fn generate_test_run(len: usize, color: Hsla) -> TextRun {
11151 TextRun {
11152 len,
11153 font: gpui::font(".SystemUIFont"),
11154 color,
11155 background_color: None,
11156 underline: None,
11157 strikethrough: None,
11158 }
11159 }
11160
11161 #[gpui::test]
11162 fn test_split_runs_by_bg_segments(cx: &mut gpui::TestAppContext) {
11163 init_test(cx, |_| {});
11164
11165 let text_color = Hsla {
11166 h: 210.0,
11167 s: 0.1,
11168 l: 0.4,
11169 a: 1.0,
11170 };
11171 let bg1 = Hsla {
11172 h: 30.0,
11173 s: 0.6,
11174 l: 0.8,
11175 a: 1.0,
11176 };
11177 let bg2 = Hsla {
11178 h: 200.0,
11179 s: 0.6,
11180 l: 0.2,
11181 a: 1.0,
11182 };
11183 let min_contrast = 45.0;
11184
11185 // Case A: single run; disjoint segments inside the run
11186 let runs = vec![generate_test_run(20, text_color)];
11187 let segs = vec![
11188 (
11189 DisplayPoint::new(DisplayRow(0), 5)..DisplayPoint::new(DisplayRow(0), 10),
11190 bg1,
11191 ),
11192 (
11193 DisplayPoint::new(DisplayRow(0), 12)..DisplayPoint::new(DisplayRow(0), 16),
11194 bg2,
11195 ),
11196 ];
11197 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast);
11198 // Expected slices: [0,5) [5,10) [10,12) [12,16) [16,20)
11199 assert_eq!(
11200 out.iter().map(|r| r.len).collect::<Vec<_>>(),
11201 vec![5, 5, 2, 4, 4]
11202 );
11203 assert_eq!(out[0].color, text_color);
11204 assert_eq!(
11205 out[1].color,
11206 ensure_minimum_contrast(text_color, bg1, min_contrast)
11207 );
11208 assert_eq!(out[2].color, text_color);
11209 assert_eq!(
11210 out[3].color,
11211 ensure_minimum_contrast(text_color, bg2, min_contrast)
11212 );
11213 assert_eq!(out[4].color, text_color);
11214
11215 // Case B: multiple runs; segment extends to end of line (u32::MAX)
11216 let runs = vec![
11217 generate_test_run(8, text_color),
11218 generate_test_run(7, text_color),
11219 ];
11220 let segs = vec![(
11221 DisplayPoint::new(DisplayRow(0), 6)..DisplayPoint::new(DisplayRow(0), u32::MAX),
11222 bg1,
11223 )];
11224 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast);
11225 // Expected slices across runs: [0,6) [6,8) | [0,7)
11226 assert_eq!(out.iter().map(|r| r.len).collect::<Vec<_>>(), vec![6, 2, 7]);
11227 let adjusted = ensure_minimum_contrast(text_color, bg1, min_contrast);
11228 assert_eq!(out[0].color, text_color);
11229 assert_eq!(out[1].color, adjusted);
11230 assert_eq!(out[2].color, adjusted);
11231
11232 // Case C: multi-byte characters
11233 // for text: "Hello π δΈη!"
11234 let runs = vec![
11235 generate_test_run(5, text_color), // "Hello"
11236 generate_test_run(6, text_color), // " π "
11237 generate_test_run(6, text_color), // "δΈη"
11238 generate_test_run(1, text_color), // "!"
11239 ];
11240 // selecting "π δΈ"
11241 let segs = vec![(
11242 DisplayPoint::new(DisplayRow(0), 6)..DisplayPoint::new(DisplayRow(0), 14),
11243 bg1,
11244 )];
11245 let out = LineWithInvisibles::split_runs_by_bg_segments(&runs, &segs, min_contrast);
11246 // "Hello" | " " | "π " | "δΈ" | "η" | "!"
11247 assert_eq!(
11248 out.iter().map(|r| r.len).collect::<Vec<_>>(),
11249 vec![5, 1, 5, 3, 3, 1]
11250 );
11251 assert_eq!(out[0].color, text_color); // "Hello"
11252 assert_eq!(
11253 out[2].color,
11254 ensure_minimum_contrast(text_color, bg1, min_contrast)
11255 ); // "π "
11256 assert_eq!(
11257 out[3].color,
11258 ensure_minimum_contrast(text_color, bg1, min_contrast)
11259 ); // "δΈ"
11260 assert_eq!(out[4].color, text_color); // "η"
11261 assert_eq!(out[5].color, text_color); // "!"
11262 }
11263}