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