element.rs

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