element.rs

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