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