element.rs

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